How To Write A Slack Bot — End to End
Updated for 2021 on 10/23/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.
If you don’t know Python, you can still try, since 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 using 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 a bot to make announcements to a chatroom periodically, this bot would be a good fit.
It’s also worth pausing for a moment to explain how your bot runs.
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.
Basic app setup
This guide explains how to craft a new Slack app from the ground up. To get started, create a new Slack app with this…
The general process, including integrating the token(s) you’ll need to proceed, is described at the link.
💡 Build useful apps, internal tools, simplified workflows, or brilliant bots for just your team or Slack's millions of…
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.
- Use Slack’s Python library.
Contribute to python-slackclient development by creating an account on GitHub.
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.
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. 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.
API Methods | Slack
Get info on your team's Slack channels, create or archive channels, invite users, set the topic and purpose, and mark a…
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).
from slackclient import SlackClient
token = "xoxo-89234987234987234798098"
sc = SlackClient(token)
print "Connection Failed, invalid token?"
This code is adapted from my own bot:
import time, json, yaml, re, os
from slackclient import SlackClientwhile True:
new_evts = sc.rtm_read()
for evt in new_evts:
if "type" in evt:
if evt["type"] == "message" and "text" in evt:
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, domain knowledge, and computer programming.
In 2015, when I first wrote this article, Slack was valued at 2.8 billion. After that it IPO’d, and ‘exited’ when it was acquired by SalesForce, for 27.7 billion.
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.
This article was originally part of a series. The original Part I has been archived. 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 by DM and posts the answers to a common room.