Skip to content

Instantly share code, notes, and snippets.

@jogleasonjr
Last active October 20, 2023 15:54
Show Gist options
  • Save jogleasonjr/7121367 to your computer and use it in GitHub Desktop.
Save jogleasonjr/7121367 to your computer and use it in GitHub Desktop.
A simple C# class to post messages to a Slack channel. You must have the Incoming WebHooks Integration enabled. This class uses the Newtonsoft Json.NET serializer available via NuGet. Scroll down for an example test method and a LinqPad snippet. Enjoy!
using Newtonsoft.Json;
using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
//A simple C# class to post messages to a Slack channel
//Note: This class uses the Newtonsoft Json.NET serializer available via NuGet
public class SlackClient
{
private readonly Uri _uri;
private readonly Encoding _encoding = new UTF8Encoding();
public SlackClient(string urlWithAccessToken)
{
_uri = new Uri(urlWithAccessToken);
}
//Post a message using simple strings
public void PostMessage(string text, string username = null, string channel = null)
{
Payload payload = new Payload()
{
Channel = channel,
Username = username,
Text = text
};
PostMessage(payload);
}
//Post a message using a Payload object
public void PostMessage(Payload payload)
{
string payloadJson = JsonConvert.SerializeObject(payload);
using (WebClient client = new WebClient())
{
NameValueCollection data = new NameValueCollection();
data["payload"] = payloadJson;
var response = client.UploadValues(_uri, "POST", data);
//The response text is usually "ok"
string responseText = _encoding.GetString(response);
}
}
}
//This class serializes into the Json payload required by Slack Incoming WebHooks
public class Payload
{
[JsonProperty("channel")]
public string Channel { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
}
void TestPostMessage()
{
var urlWithAccessToken = "https://hooks.slack.com/services/{YOUR}/{ACCESS}/{TOKENS};
var client = new SlackClient(urlWithAccessToken);
client.PostMessage(username: "Mr. Torgue",
text: "THIS IS A TEST MESSAGE! SQUEEDLYBAMBLYFEEDLYMEEDLYMOWWWWWWWW!",
channel: "#general");
}
<Query Kind="Program">
<Reference>&lt;RuntimeDirectory&gt;\SMDiagnostics.dll</Reference>
<Reference>&lt;RuntimeDirectory&gt;\System.Configuration.dll</Reference>
<Reference>&lt;RuntimeDirectory&gt;\System.Net.Http.dll</Reference>
<Reference>&lt;RuntimeDirectory&gt;\System.Runtime.Serialization.dll</Reference>
<Reference>&lt;RuntimeDirectory&gt;\System.ServiceModel.Internals.dll</Reference>
<NuGetReference>Newtonsoft.Json</NuGetReference>
<Namespace>System.Collections.Specialized</Namespace>
<Namespace>System.Net</Namespace>
<Namespace>System.Net.Http</Namespace>
<Namespace>System.Net.Http.Headers</Namespace>
<Namespace>System.Runtime.Serialization.Json</Namespace>
<Namespace>Newtonsoft.Json</Namespace>
</Query>
void Main()
{
var urlWithAccessToken = "https://hooks.slack.com/services/{YOUR}/{ACCESS}/{TOKENS}";
var client = new SlackClient(urlWithAccessToken);
client.PostMessage(username: "Mr. Torgue",
text: "THIS IS A TEST MESSAGE! SQUEEDLYBAMBLYFEEDLYMEEDLsaMOWWWWWWWW!",
channel: "#sandbox");
}
//A simple C# class to post messages to a Slack channel
//Note: This class uses the Newtonsoft Json.NET serializer available via NuGet
public class SlackClient
{
private readonly Uri _uri;
private readonly Encoding _encoding = new UTF8Encoding();
public SlackClient(string urlWithAccessToken)
{
_uri = new Uri(urlWithAccessToken);
}
//Post a message using simple strings
public void PostMessage(string text, string username = null, string channel = null)
{
Payload payload = new Payload()
{
Channel = channel,
Username = username,
Text = text
};
PostMessage(payload);
}
//Post a message using a Payload object
public void PostMessage(Payload payload)
{
string payloadJson = JsonConvert.SerializeObject(payload);
using (WebClient client = new WebClient())
{
NameValueCollection data = new NameValueCollection();
data["payload"] = payloadJson;
var response = client.UploadValues(_uri, "POST", data);
//The response text is usually "ok"
string responseText = _encoding.GetString(response);
}
}
}
//This class serializes into the Json payload required by Slack Incoming WebHooks
public class Payload
{
[JsonProperty("channel")]
public string Channel { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
}
@babin93
Copy link

babin93 commented Apr 19, 2016

Thank you for this code example, it helped me to discover WebClient UploadValue()

@magnus-hansson
Copy link

Thanks!

@chrisbennell
Copy link

Thanks for this code and for taking the time to create a LinqPad example - that really helps.

@nqobani
Copy link

nqobani commented Jul 28, 2016

how can post images using C#. I tried to post them using markdown but I got the links(url) back...

@sshine
Copy link

sshine commented Nov 8, 2016

Following the Slack Webhook documentation, it asks to create a webhook and send a payload JSON value to it. Here is a smaller working example of that:

public sealed class SlackClient
{
    public static readonly Uri DefaultWebHookUri = new Uri("https://hooks.slack.com/services/.../.../...");

    private readonly Uri _webHookUri;

    public SlackClient(Uri webHookUri)
    {
        this._webHookUri = webHookUri;
    }

    public void SendSlackMessage(SlackMessage message)
    {
        using (WebClient webClient = new WebClient())
        {
            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            byte[] request = System.Text.Encoding.UTF8.GetBytes("payload=" + JsonConvert.SerializeObject(message));
            byte[] response = webClient.UploadData(this._webHookUri, "POST", request);

            // ...handle response...
        }
    }

    public sealed class SlackMessage
    {
        [JsonProperty("channel")]
        public string Channel { get; set; }

        [JsonProperty("username")]
        public string UserName { get; set; }

        [JsonProperty("text")]
        public string Text { get; set; }

        [JsonProperty("icon_emoji")]
        public string Icon
        {
            get { return ":computer:"; }
        }
    }
}

@sysarcher
Copy link

Thanks!! Great help.

@buinauskas
Copy link

This is amazing. Thanks @sshine!

@rodneyjoyce
Copy link

Nice, thanks

@maddisn
Copy link

maddisn commented Mar 8, 2017

What are some of the JSON properties for slack.
I want to work with attachments, colors, images and ...
Thanks much.

@tvance929
Copy link

This is great, thank you... now to just find out how to determine whether the response was a bad one or not. ( ie. response.IsSuccessStatusCode with httpclients )

@MaLKaVeS
Copy link

Up and running in just a few minutes. Thanks!

@kiquenet
Copy link

How can I get the token={your_access_token} value ?

@thecure473
Copy link

How to upload one image and message to channel?

@stevenchendan
Copy link

This is helpful. Thanks

@BrianHayes33
Copy link

is there a way to tag a user or multiple users?

@amjad
Copy link

amjad commented Feb 4, 2019

Does this work for private channels as well?

@inquisitivepanda
Copy link

I'm getting a 404 error at line 40 of the stack client. What all information on the code in this file needs to be changed to fit personal use?

@jogleasonjr
Copy link
Author

@inquisitivepanda

You just need to change the urlWithAccessToken variable. Something like https://hooks.slack.com/services/{YOUR}/{ACCESS}/{TOKENS}. If you navigate to the /apps page in your slack workspace settings on the web, find (or add) an integration for Incoming Webhooks -- your URL to use in this bit of code will be on that page.

@kalunkuo
Copy link

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment