Write your own Slack chatbot in Golang

Slack Chatbot
Chatbots are all the rage nowadays so I’ll show you how to plug one into your own Slack channel. It’s easy, fun and, best of all, completely free!

I. Preparation

Of course, you’ll need a Slack team which I’ll refer to as yourteam.slack.com throughout this post. The free plan includes up to 10 apps or service integrations & 5GB total file storage for the team which is more than enough for hooking up GitHub, your bot and your CI tool of choice: semaphore, Travis & Circle CI are all natively supported OOTB.

From there, you can create a custom integration for your Bot:
screen-shot-2016-10-22-at-17-19-39

Now, you’ve got an API token which allows your Bot to connect to Slack! Copy this and keep it handy for the next step.

II. Code

I used Norberto Lopes’ Slack API as the connector glue for my bot.

Pay particular attention how I get the Bot to only react when he’s called so it doesn’t get into any weird infinite loops (like an argument with himself).

Now for the fun part: writing your own custom commands so the Bot can do some heavy lifting for you. As a simple prototype, I’ve asked him to fetch the 10 day forecast for my town via an sw cmd trigger. Otherwise, he just repeats back what you said to him in the form of a question.

My next idea is to set a timer that will have him periodically go out and perform a task (e.g. check out how the Cubs are advancing in the Pennant Race). The possibilities are only limited by your imagination so let loose and get creative!

III. Continuous Deployment

I use CircleCI (also free for building public repos) to build and deploy my Bot as a Docker container to a DigitalOcean instance with every git push. It’s much easier than it sounds and the entire process (building a new Golang binary hosted inside a container and deployed to CoreOS) takes less than 3 minutes!

Note where the code loads the Slack API token from the environment – I’ve set this up in my CircleCI build settings.
Because sometimes tokens have undigestible characters which can get strangely escaped, I’ve base64 encoded the original Slack API one and decode it at docker runtime.

Lemme know if you have any questions or suggestions!

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

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