How To Write A Slack Bot — End to End

Image for post
Image for post
Cyclone Bass Bot image by David J under a Creative Commons License.

Updated for 2020 on 6/02/20.

If you use Slack at your company and like automation, this post is for you. No intermediaries are required to follow this guide (well, besides Slack).

The idea is, by following this guide, the code examples, and Slack’s documentation, you’ll be able to get a bot up and running, rapidly, using knowledge you either already have or can get from the Internet.

Every programming article has to make assumptions to avoid book-sized bloat. This article assumes you know or learned Python reasonably well, but to give some context, at the time I wrote this, this was my most serious foray into Python, besides 100-lines scripts. While I’m a developer, I usually use JavaScript (see: javascriptpage.com), not Python.

If you don’t know Python, never fear. You can still build a bot, using this guide; the Python is pretty intuitive. The idea is to get you to a place, knowledge-wise, where Stack Overflow and the like can carry you the rest of the way, once you have the core down.

So, what kinds of bots are we talking about? There are many kinds, and while you can build different bots up from the baseline structure described here, this tutorial would work best for distributing messages to chat rooms that your bot has been invited into.

So for example, if you wanted your bot to make announcements to various chatrooms periodically, this bot tutorial would be a good fit.

It’s also worth pausing for a moment to explain how your bot runs — what this article, and bot, can’t do, or won’t explain.

Basically, the bot methods described here could most naturally be used with a bot running on your computer. If you turned your computer off, it would stop running.

So your options are to either have a bot that runs when you’re using your computer, when you execute it, or to install it on another computer — a server, somewhere — to run on a schedule (like a cron job) or around the clock, 24–7.

For more details, see “Figure out how your bot should respond” below, or another article on this topic. For now, this is something you should consider when thinking about how to build a bot.

So without further ado, here’s how to create your own bot using Python.

0. Go through the configuration process, decide the permissions for your bot, and install it to your ‘chat room’ or workspace.

Slack’s procedure has evolved here, as it started off being a plain API key (deprecated) and then became part of an OAuth flow. It’s been well-defined now, with good surrounding documentation.

Basically though, you want to create an app, then give it the right permissions — meaning, scopes (so your app can ‘read’ and especially ‘speak’) — then install it your ‘workplace’, or chat rooms.

The general process, including integrating the token(s) you’ll need to proceed, is described at the link.

Note: the app described in the python-slackclient example uses a whole Python framework (Flask) and is event-driven. The bot methods shown below are simpler and operate when executed —except for f), they’re not sitting around waiting for the user to ask something.

  1. Use Slack’s Python library.

This library was produced by the people who made the product so it’s the one I used, using my “as few intermediaries as possible” rule.

From what I can tell, this one includes all the necessary functionality; I haven’t found anything I wanted to but couldn’t do with it.

2. Figure out how your bot should respond.

Your bot has a couple of possible modes. It can:

I) Respond when you start it, as in the example of a pre-meeting information-gathering bot; it initiates conversation, gathers the necessary material, and then stops. Call this sequential.

II) Be on at all times, as in the example of Q&A-type bot (“bot lunch”, “Hello! Here are some good options in our neighborhood…”); it sits around listening to events, and springs into action whenever you say the magic key word (“hello bot” or “tipbot send 1 bit to @ben”). Call this event-driven.

Note that sequential is easy to implement: whenever I want to run it, I execute “python script.py” at the command line. Presto, it runs. You could run this from your computer, assuming it’ll be available at those times.

Event-driven is only going to be running when the machine of the owner is running it in the background, or (more likely) it’s uploaded to a server where it can run 24–7 and all employees can access the bot’s functionality at any time.

The latter process is a little bit complicated, but if you want a walkthrough, the Slack library Bolt explains the procedure pretty well.

3. How Slack’s API ‘thinks’

Bookmark the API methods page, because it is your most important reference.

You might think that everything in Slack is a room, or a channel, and that the only difference between channels is in their name & permission level (public, private). That’s a reasonable assumption; I made it. Alas, it’s wrong.

In Slack, all rooms are not created equal; permissions are so important that rooms with different permissions belong to completely different categories.

The one that’s closest to our intuition is the channel. Groups are like private channels, as I see it.

IM’s are in a different category: when you and the bot have a conversation, made up exclusively of direct messages, that is an IM.

These distinctions are important because they dictate which of the methods at the link above you’ll be using, and can assist you as you reason through your bot’s interactions.

4. Less Talk, More Action!

What are the most important things you need to know? They are:

a) For every method, there’s a tester — use it!

b) Slack’s Python library follows the syntax method extremely closely, so much so that you can look at the method name and guess almost every time exactly what to call.

c) Here’s the method to post to rooms:

Here’s a Python example of it in action:

sc.api_call(“chat.postMessage”, as_user=”true”, channel=”D0X8ZEXAX”, text=”whatever you want to say”)

d) Here’s the method to post to individuals:

You can run your bot script using this method to “open” a user, then get the channel you use chat.postMessage with to message the individual.

Here’s an example of this in action:

print sc.api_call(“im.open”, user=”U07QKAOLB”)

e) You can use this endpoint to get the ID’s of any user in the company. One use for this would be to find out a user’s ID, then to feed it to the chat.postMessage method listed above.

You can use the tester in the browser to retrieve all of this information. While I could’ve written http request scripts to get this information, my go-to method was the tester because it’s so convenient.

f) For a real-time event-driven bot that’s always listening and responding to certain things, see the example given on the Python-slackclient GitHub page (with a fake token, naturally).

import time
from slackclient import SlackClient

token = "xoxo-89234987234987234798098"
sc = SlackClient(token)
if sc.rtm_connect():
while True:
print sc.rtm_read()
time.sleep(1)
else:
print "Connection Failed, invalid token?"

This code is adapted from my own bot:

import time, json, yaml, re, os
from slackclient import SlackClient
while True:
new_evts = sc.rtm_read()
for evt in new_evts:
print(evt)
if "type" in evt:
if evt["type"] == "message" and "text" in evt:
message=evt["text"]
time.sleep(3)

Hopefully, this will get you started. With these methods, you can make a useful bot.

Due to space constraints, I left out a lot, but these are the basics, and they’re tested to work as written.

There’s plenty of potential in the area of productivity enhancements, at the intersection of third-party tools, admin configuration, domain knowledge, and computer programming. As the US Bureau of Labor Statistics says, “employment of software developers is projected to grow 21 percent from 2018 to 2028, much faster than the average for all occupations.”

In 2015, when I first wrote this article, Slack was valued at 2.8 billion. Today the company has IPO’d, and Slack has a much more concrete valuation, based on its stock market value: $20 billion, as of June 1st 2020.

No matter how you look at it, Slack is big business. Making your own slack bot can add value to any business or company — and with numbers like this, building with Slack will continue to be a profitable bet.

My name is Julian Martinez and I’m a consultant and developer. You can find more tutorials like this on javascriptpage.com. To discuss a project, use my contact form.

For more content like this, follow me on Twitter.

This article was originally part of a series. The original Part I has been archived, as this version is newer and more accurate. Part II goes into more detail about how you can get a user list and interact with individual users, using a plain API key (deprecated). Part III links to and explains the actual Python code, on GitHub, for a standup-style bot, that asks questions of users through DM’s (privately) and prints the answers (publicly) to a room.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store