Creating a slack bot with Python
In this series of posts I’m going to describe how to build a slack bot that will play a simple game.
In this first part we will create our slack bot and use it to send and receive simple messages.
There are multiple packages out there that we can use for our task such as python-rtmbot or slackbot. However, for this tutorial I wanted to use the basic Slack Real Time Messaging API.
The code from this tutorial can be found on my Github.
Step 1: Create a slack account
If you don’t have one already, create one at slack.com and start using it. … or go read something else :)
Step 2: Regsiter a slack bot
- Go to https://slack.com/apps/build and click on “Make a Custom Integration” under “Something just for my team”
- In the new page, click on “Bots”
- Choose your new slack bot name (i.e. slack_bot) and press “Add bot integration”
- In the new page, copy the API token of the new slack bot as we will need it in our script.
Step 2: Create the environment
-
Create a folder for the project
mkdir slack_bot cd slack_bot
-
Create a virtual environment for our project
mkvirtualenv slack_bot
-
Install the following requirements
pip install slackclient
-
Create a new file for our script, let’s call it “slack_bot.py”
Step 3: Send a simple message with the slack bot
In the new file, we’ll start by importing the slackclient package:
from slackclient import SlackClient
Create the slack bot instance with the token we created earlier:
sc = SlackClient(BOT_TOKEN)
Once we initialize the instance we’ll need to perform the connect action:
sc.rtm_connect()
Now we can send a simple message to the #general channel:
sc.rtm_send_message("general", "I'm ALIVE!!!")
Step 4: Interact with the slack bot
We’ll make the slack bot respond to every message on our #general channel.
Every time someone writes something, the slack bot will repond with the message ”@username wrote something…“
Annoying, I know…
We’ll perform this by running an infinite loop and making our slack bot go over all the messages that go through our slack channel. The slack bot will read the message using the rtm_read method which returns a list of messages. The script will iterate through them and send the annoying message accordingly. Between these, the bot will sleep for half a second every cycle of the loop.
The full script would look like this:
The code from this tutorial can be found on my Github.
Conclusions
In this tutorial we learned how to create a slack bot and perform a simple action.
Next time, we’ll create a simple game using this slack bot.