Creating a SlackBot with .Net

Recently our team started using slack in liue of traditional communication tools (skype, TEAMs, even email) and we love it. There’s a lot of potential to the take the collaboration to another level with bots but I looked high and low and couldnt really find a C#/.Net centric process to build my bot upon😕

C# and .Net seems foriegn in Slack Bot Land…

As always, I first like to check to see if there’s a good C# frameworks for slack bots. I couldnt find one. Not one! Theres plenty of node and python examples of course. If that’s your cup of tea (and I do dable in those also) but what’s developer to do if without picking a new language sweet to accomplish a single purpose.

Getting Started

In this tutorial. I assume you have an understanding of the C# language and creating restful services with ASP.NET MVC 5.

We’re going to create a asp.net MVC5 Web API project. We also need a internet facing IIS webserver that you have access to deploy your mvc controller.

My Example Repo: I have skeleton repo out in github (feel free to pull, fork, modify as needed)

Slack App Documentation:
Slack documentation is here. For the purpose of this tutorial, I’m just planning to handle Slack event driven chat post from slack that mention my bot.

Example: @TestBot insult me

If you have not already create your slack app and slack bot:

  • Create your app for slack workspace (link)
  • Create a bot to be used for your app (link)

Here is the input for the slack create app dialog (make sure have a logged to select your work space)

For the purpose of this, my Botname is JBOT

Setting API Validation Structure

The first step is to get slack to trust our WEP API through its tokenizer response validation

  • Fire up Visual Studio go ahead and create your MVC project if your not using the skeleton in my repo example (it should be New->Project->Web->ASP.NET Web Application),
  • In Solution explore, create a new MVC Controller (you can also use the more appropriate web api controller) by right-clicking the Controllers Folders and “New Item”. For this Demo I named mine SlackController.

Open up the cs file of the controller we just created and and create new public Method (I called mine SlackHandler).
Important: This will be “THE” method that Slack will use to verify the your event driven WEB API Method is authentic and will be use to handle other events that your bot will listen for in the slack channel

The initial SlackHandler code is this:

You may notice SlackHandler accepts one parameter called ContentRoot which is dynamic injected at into the class at invocation.

Generally a slack message will have a the following Request/Json parameters passed to your api handler

  • Type (Always populated and describes the message (Validation, event_callback, etc.)
  • Event (populated for event callbacks like chat message in the channel etc. However it will be null if the type of message is the API validation )
  • Challenge (populated for API and usually null for channel events)
  • Token is the Oauth token of your bot user essentially your identity to slack when you post messages or respond to any event. I will not be passed in but must be set during the response of chat events which we will see later.
    • Where do I get my token?
      • You can find this value buy got going to your but user and under the “OAuth&Permisison section\”Bot User Auth Access Token”

Note: its a very good idea to protect this token because it’s essentially the credentials of your slackbot bot!

Publish: After publishign your Slack Controller to your public IIS webser we can then move on Slack validation form
Slack Validation

Slack Validation

  • Navigate to https://api.slack.com/apps
  • Click your slack application
  • Choose event subscriptions and then enable subcriptions
    • Next you’ll be prompted for your we api url that will respond back in json the challenge code that was passed into it.
    • The important thing here is the verified notification next to Request URL

Success! Once verified we can expand on the SlackHandler to handle different events

Wiring your method to handle Slack events

The purpose of this to show the potential of using C# to handle events in chat room that are occur in a chat room that mentions your slack bot.

Before we go further, create a new test channel “#myTest” and invite your SlackBot to that channel (it’s generally best to test in room by yourself and your test bot avoid annoyances at first!)

Its not doing anything..what gives?

You can mention your bot in the channel and it wont reply with any response currently. Why? The API functions are setup yet to respond to input.. lets add some more code in our SlackHandler function…

//From the original code in SlackHandler we're going to update logic for event_callback
if (content.Type.Contains("event_callback"))
{
  if (content.@Event.Type == "app_mention")
  {
   string user = "<@" + content.@Event.User + ">";
   string orig_channel = content.@Event.Channel;
  bool insultRequest = content.Event.Text.ToUpper().Contains("INSULT");
   var wc = new HttpClient();
    wc.DefaultRequestHeaders.Add("Authorization", "Bearer xoxb-[your token]");
    if(insultRequest)
    {
      var t = wc.PostAsync("https://slack.com/api/chat.postMessage", new StringContent(JsonConvert.SerializeObject(ranObj), System.Text.Encoding.UTF8, "application/json"));
   var response = t.Result;
    }
  



About: raisingcode


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.