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:

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 asked him to fetch the 10 day forecast for my town via the sw cmd. In the last 5 years, I’ve built out many other tasks that he helps me out with.

During baseball season, he even sends me the list of yesterday’s free-to-air MLB games. The possibilities are only limited by your imagination so let loose and get creative!

III. Continuous Deployment

I use GitHub Actions (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 Ubuntu) takes about 1 minute!

Note where the code loads the Slack API token from the environment – I’ve set this up in my build to read from my GitHub organization secrets. Because sometimes tokens have indigestible characters which can get strangely escaped, I’ve base64 encoded some secrets 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 )

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.