Home > Uncategorized > Build a quick #slack #bot in c#

Build a quick #slack #bot in c#

slackbot-featured1

I’m not actually a big fan of Slack, but personal opinions aside, creating a simple slack bot for notifications is super easy to do in C#. I built a File system watcher slack bot, that could notify a custom channel in Slack whenever a new file was uploaded to my server.

You need to log in to Slack and get a slack incoming webhook url, it should look something like this:

https://hooks.slack.com/services/T04XXX/B3HKKXXXXL/4XXXXXW

You can set the name and icon for the bot too via the Web UI, which is nice.

So, the main class, which I found on Github, is as follows

using Newtonsoft.Json;
using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;

namespace SaleWatcherApp
{
    

    //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; }
    }
}

It requires Newtonsoft nuget, which you should install now.

Then, I created a console app, that watches my folder of interest. I installed this on the server using NSSM so that the EXE ran as a service.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;

namespace SaleWatcherApp
{
    class Program
    {
        static List<string> newFiles = new List<string>();
        private static SlackClient slack = null;

        static void Main(string[] args)
        {
            slack = new SlackClient(ConfigurationManager.AppSettings["slackHook"]);
            watch();
            Console.ReadLine();
        }

        private static void watch()
        {
             var watcher = new FileSystemWatcher
            {
                Path = ConfigurationManager.AppSettings["watchPath"],
                NotifyFilter = NotifyFilters.LastWrite,
                Filter = "*.*"
            };
            watcher.Changed += (sender, args) =>
            {
                if (newFiles.All(f => f != args.Name))
                {
                    Console.WriteLine(args.Name);
                    slack.PostMessage(args.Name);
                }
                newFiles.Add(args.Name);
            };
            watcher.EnableRaisingEvents = true;
        }  
    }
}
Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: