Provides a simple .Net client for using Slack's Incoming Webhooks URL's to send messages to a slack channel of your choosing.
The Webhooks API is pretty simple, but it always preferable to have a typed interface to use rather than an untyped (and undocumented) JSON object. So using this library should make it simpler to build a slack message and send it using a webhook URL.
See changelog for version history.
First install the nuget package:
PM> Install-Package SlackWebhook
Next simply use the SlackClient
class to send a message:
await new SlackClient(webhookUrl).SendAsync(b => b
.WithUsername("Slack Bot Name")
.WithIcon(IconType.Url, "http://my.host/bot_icon.png")
.WithText("Something very interesting just happened")
);
In the above example i used the webhookUrl
which you obtain by adding the Incoming WebHooks app configuration
to the channel you want to send messages to (each url is tied to a specific channel, so if you want to sent to
different channels, just add multiple configurations).
- Open slack.com/services/new/incoming-webhook
- Under Post to Channel select the channel you want to send to
- Press Add Incoming WebHooks integration
- Now copy the Webhook URL
Besides the message, the Slack hook also allows attachments which are pretty neat.
In the above example I used a few attachments and fields to illustrate some of the uses. Especially the attachment
fields are a good way to include extra detail in a table-like structure (by setting short
flag on field, two fields
will be shown in the attachment side-by-side for each row).
My example was generated by this code:
await new SlackClient(webhookUrl).SendAsync(b => b
.WithText("Hello from *SlackWebhook*")
.WithUsername("SlackWebhook")
.WithIcon(IconType.Url, "https://raw.githubusercontent.com/micdah/SlackWebhook/master/icon.png")
.WithAttachment(a => a
.WithTitle("How to install")
.WithText("`PM> Install-Package SlackWebhook`")
.WithColor(Color.DarkSlateBlue))
.WithAttachment(a => a
.WithTitle("Find out more")
.WithText("Find out more by taking a look at github.com/micdah/SlackWebhook")
.WithLink("https://github.com/micdah/SlackWebhook")
.WithField(
"Use builder pattern",
"```\n" +
"await slackClient.SendASync(b => b\n" +
" .WithUsername(\"My Bot\")\n" +
" .WithText(\"Hello *World*\"));\n" +
"```")
.WithField(
"Use object initializer",
"```\n" +
"await slackClient.SendAsync(new SlackMessage {\n" +
" Username = \"My Bot\",\n" +
" Text = \"Hello *World*\"\n" +
"});\n" +
"```")));
You can find the documentation in SlackWebhook, of particular interest are these:
ISlackClient
: Interface of theSlackClient
implementation used to send messageISlackMessageBuilder
: Inteface of the message builder used to configure your messageISlackAttachmentBuilder
: Interface of the attachment builder used to configure attachments added to your message