Slack Integration with C#

Slack

Slack is a free messaging app for teams. It is designed to help teams to improve their communication. Not just your messages, but all your files, images, PDFs, documents, and spreadsheets can be dropped right into Slack and shared with anyone you want.

Slack helps you work in the moment,  making it faster and easier to communicate with your team and with all the collective knowledge at your fingertips. Using Slack is nothing but more productivity, more transparency, and less email.

The following are the features of Slack:

  1. Group Conversation
  2. File Sharing
  3. Deep, Contextual search.
  4. Always in sync
  5. Over 80 integrations
  6. Security

Need of Integration

All your tools in one place: Connect all the tools you use to Slack and avoid all that constant switching among apps. Set up your integration so that you get all your notifications directly within Slack.

Slack integrates with over 80 external services to help you pull information from outside tools in a way that’s timely, relevant and always searchable. No more switching among apps. Bring it all together in one simple place.

How to Integrate

To integrate your application with Slack, you need to use the following procedure:

  1. If you haven’t registered an account on Slack then you need to first register on Slack. To register on Slack go to www.slack.com. And then click on Sign up for free link.

  2. To sending notifications to the Slack you must have the Incoming Webhooks integration enabled. To enable Incoming Webhooks use the following procedure:

    1. Go to the following URL and click on the Incoming Webhooks link api.slack.com as shown in the figure.




    2. Now click on the link incoming webhook integration.



    3. If you have already signed in then there is no need to sign in again otherwise to proceed further you are asked to sign in here. After signing in you will see the following window:

      sign in

    4. Now click on the choose a channel drop down list and select a channel where you want to send notifications to.

      choose a channel

    5. And click on Add Incoming Webhooks Integration.

      Add Incoming Webhooks Integration

    6. Now you get the window where you can see Setup Instructions, Message Attachments and Integration Settings options. In the Integration settings option you can change the Channel name, you can provide a descriptive label and can customize the name and the icon. Now click on Copy URL so that we can use that URL in our C# code. Finally click on the Save Settings button available at the end.

      Save Settings

  3. Now write a C# class to post messages to a Slack channel. This class uses the Newtonsoft Json.NET serializer available via NuGet.

    To install Jason.NET, open your project in Visual Studio. Then right-click on the project name in Solution Explorer and select Manage Nuget Packages. You will see a new window. In that choose Online and search for a Newtonsoft as shown in the following image. You will get Json.NET. Now click on the Install button.

    JsonNET

  4. Now write the SlackClient class as follows:
    1. using Newtonsoft.Json;  
    2. using System;  
    3. using System.Collections.Specialized;  
    4. using System.Net;  
    5. using System.Text;  
    6.   
    7. //A simple C# class to post messages to a Slack channel  
    8. //Note: This class uses the Newtonsoft Json.NET serializer available via NuGet  
    9. public class SlackClient  
    10. {  
    11.     private readonly Uri _uri;  
    12.     private readonly Encoding _encoding = new UTF8Encoding();  
    13.   
    14.     public SlackClient(string urlWithAccessToken)  
    15.     {  
    16.         _uri = new Uri(urlWithAccessToken);  
    17.     }  
    18.   
    19.     //Post a message using simple strings  
    20.     public void PostMessage(string text, string username = nullstring channel = null)  
    21.     {  
    22.         Payload payload = new Payload()  
    23.         {  
    24.             Channel = channel,  
    25.             Username = username,  
    26.             Text = text  
    27.         };  
    28.   
    29.         PostMessage(payload);  
    30.     }  
    31.   
    32.     //Post a message using a Payload object  
    33.     public void PostMessage(Payload payload)  
    34.     {  
    35.         string payloadJson = JsonConvert.SerializeObject(payload);  
    36.   
    37.         using (WebClient client = new WebClient())  
    38.         {  
    39.             NameValueCollection data = new NameValueCollection();  
    40.             data["payload"] = payloadJson;  
    41.   
    42.             var response = client.UploadValues(_uri, "POST", data);  
    43.   
    44.             //The response text is usually "ok"  
    45.             string responseText = _encoding.GetString(response);  
    46.         }  
    47.     }  
    48. }  
    49.   
    50. //This class serializes into the Json payload required by Slack Incoming WebHooks  
    51. public class Payload  
    52. {  
    53.     [JsonProperty("channel")]  
    54.     public string Channel { getset; }  
    55.   
    56.     [JsonProperty("username")]  
    57.     public string Username { getset; }  
    58.   
    59.     [JsonProperty("text")]  
    60.     Public   
  5. Now write SlackClientTest.cs as follows:
    1. void TestPostMessage()  
    2.  {  
    3.      string urlWithAccessToken = "https://{your_account}.slack.com/services/hooks/incoming-webhook?token={your_access_token}";  
    4.   
    5.      SlackClient client = new SlackClient(urlWithAccessToken);  
    6.   
    7.      client.PostMessage(username: "kamleshbhor",  
    8.                 text: "THIS IS A TEST MESSAGE!!",  
    9.                 channel: "#general");  
    10.  }  
  6. Now paste in the Webhook URL you copied instead of {your_access_token} in the TestPostMessage() method and test the code.


Similar Articles