Make a Slack WebHook plugin with C# .Net, Nancy, and Ngrok.

This blog article will walk you through making a C# webhook plugin for Slack. We’ll be using Nancy to setup a small web service, and ngrok to expose our service publicly so Slack can call it.

First, make a new C# console application with Visual Studio, and install a few nuget packages. The interesting packages are Nancy, Nancy.Hosting.Self, and Slack.Webhooks.

Next, we need to create a NancyHost and start it up. You’ll want your console application’s main to look roughly like this:

        static void Main()
        {
            JsConfig.EmitLowercaseUnderscoreNames = true;
            JsConfig.IncludeNullValues = false;
            JsConfig.PropertyConvention = JsonPropertyConvention.Lenient;
            using (var host = new NancyHost(new Uri("http://localhost:1234")))
            {
                host.Start();
                Console.ReadLine();
            }
            return;
        }

When our application runs, it launches a service that listens on localhost:1234 for requests.

Of course, you’ll need some using statements like this:

using Nancy;
using Nancy.Hosting.Self;
using Nancy.ModelBinding;
using Newtonsoft.Json;
using ServiceStack.Text;
using Slack.Webhooks;

Since our application will be listening on localhost:1234, we need to add request handlers. For our slack webhook plugin examlpe, we just need to handle a post. We’ll create a WebhookModule class that inherrits from NancyModule, and has a Post handler like this code:

public class WebhookModule : NancyModule
{
public WebhookModule()
{
Post["/"] = _ =>
{
var model = this.Bind<HookMessage>();
var message = string.Empty;
SlackAttachment attachment = null;
message = string.Format("@{0} Hello", model.UserName);
if (!string.IsNullOrWhiteSpace(message))
{
SlackMessage sm = new SlackMessage { Text = message, Username = "MyChat.Bot.Greeting", IconEmoji = Emoji.Ghost };
if(attachment != null)
{
sm.Attachments = new List<SlackAttachment>();
sm.Attachments.Add(attachment);
}
return sm;
}
return null;
};
}
}

When Post is received, this will receive a HookMessage and respond with a “Hello User” message. That response will be received by Slack and should output the “Hello User” message to your slack chat channel.

Here are a few other classes you’ll need that define the HookMessage and some other Nancy boiler plate configuration:

    public class HookMessage
    {
        public string Token { get; set; }
        public string TeamId { get; set; }
        public string ChannelId { get; set; }
        public string ChannelName { get; set; }
        public string UserId { get; set; }
        public string UserName { get; set; }
        public string Text { get; set; }
        public string TriggerWord { get; set; }
    }
    public class TitleCaseFieldNameConverter : IFieldNameConverter
    {
        public string Convert(string fieldName)
        {
            return fieldName.ToTitleCase();
        }
    }
    public class Bootstrapper : DefaultNancyBootstrapper
    {
        protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines)
        {
            container.Register<IFieldNameConverter, TitleCaseFieldNameConverter>();
            base.ApplicationStartup(container, pipelines);
        }
    }

At this point, you should be able to run your C# console application and be listening for Post requests on localhost:1234. Next, follow my ngrok block article to setup ngrok to expose your localhost:1234 service to a public address:

http://blog.novelessay.com/post/make-local-mysql-instance-publicly-available-for-a-mvc-net-website-with-ngrok

When your ngrok is ready to run, you can make your service publicly available by starting the ngrok service like this:

ngrok.exe http 1234

Lastly, you’ll need to go in to your Slack configuration, and setup an Outgoing Webhook. Look in the “Browse Apps” -> “Custom Integrations” -> “Outgoing WebHooks” section. You will probably discover it more tricky to find where it was than to actually configure it.

You need to configure which channels you want your webhook to interact with, set the ngrok address that your service is serving on, and provide a token that Slack will send. You should update your C# console application to check the token value, but that’s not entirely necessary for this system to work.

Here’s an example of how I have an Outgoing WebHook configured in Slack:

That’s everything! Give your Slack Bot a try. 

Leave a Reply

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