Full Stack Python logo Full Stack Python

全部主题 | Blog | 时讯 | @fullstackpython | Facebook | 源码 # How to Build Your First Slack Bot with Python Posted by Matt Makai on 六月 04, 2016. Last updated 十月 27, 2016.

Bots are a useful way to interact with chat services such as Slack. If you have never built a bot before, this post provides an easy starter tutorial for combining the Slack API with Python to create your first bot.

We will walk through setting up your development environment, obtaining a Slack API bot token and coding our simple bot in Python.

Tools We Need

Our bot, which we will name "StarterBot", requires Python and the Slack API. To run our Python code we need:

It is also useful to have the Slack API docs handy while you're building this tutorial.

All the code for this tutorial is available open source under the MIT license in the slack-starterbot public repository.

Establishing Our Environment

We now know what tools we need for our project so let's get our development environment set up. Go to the terminal (or Command Prompt on Windows) and change into the directory where you want to store this project. Within that directory, create a new virtualenv to isolate our application dependencies from other Python projects.

  1. virtualenv starterbot

Activate the virtualenv:

  1. source starterbot/bin/activate

Your prompt should now look like the one in this screenshot.

Command prompt with starterbot's virtualenv activated.

The official slackclient API helper library built by Slack can send and receive messages from a Slack channel. Install the slackclient library with the pip command:

  1. pip install slackclient

When pip is finished you should see output like this and you'll be back at the prompt.

Output from using the pip install slackclient command with a virtualenv activated.

We also need to obtain an access token for our Slack team so our bot can use it to connect to the Slack API.

Slack Real Time Messaging (RTM) API

Slack grants programmatic access to their messaging channels via a web API. Go to the Slack web API page and sign up to create your own Slack team. You can also sign into an existing account where you have administrative privileges.

Use the sign in button on the top right corner of the Slack API page.

After you have signed in go to the Bot Users page.

Custom bot users webpage.

Name your bot "starterbot" then click the “Add bot integration” button.

Add a bot integration named starterbot.

The page will reload and you will see a newly-generated access token. You can also change the logo to a custom design. For example, I gave this bot the Full Stack Python logo.

Copy and paste the access token for your new Slack bot.

Click the "Save Integration" button at the bottom of the page. Your bot is now ready to connect to Slack's API.

A common practice for Python developers is to export secret tokens as environment variables. Export the Slack token with the name SLACK_BOT_TOKEN:

  1. export SLACK_BOT_TOKEN='your slack token pasted here'

Nice, now we are authorized to use the Slack API as a bot.

There is one more piece of information we need to build our bot: our bot's ID. Next we will write a short script to obtain that ID from the Slack API.

Obtaining Our Bot’s ID

It is finally time to write some Python code! We'll get warmed up by coding a short Python script to obtain StarterBot's ID. The ID varies based on the Slack team.

We need the ID because it allows our application to determine if messages parsed from the Slack RTM are directed at StarterBot. Our script also tests that our SLACK_BOT_TOKEN environment variable is properly set.

Create a new file named print_bot_id.py and fill it with the following code.

  1. import os
  2. from slackclient import SlackClient
  3.  
  4.  
  5. BOT_NAME = 'starterbot'
  6.  
  7. slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))
  8.  
  9.  
  10. if __name__ == "__main__":
  11. api_call = slack_client.api_call("users.list")
  12. if api_call.get('ok'):
  13. # retrieve all users so we can find our bot
  14. users = api_call.get('members')
  15. for user in users:
  16. if 'name' in user and user.get('name') == BOT_NAME:
  17. print("Bot ID for '" + user['name'] + "' is " + user.get('id'))
  18. else:
  19. print("could not find bot user with the name " + BOT_NAME)

Our code imports the SlackClient and instantiates it with our SLACK_BOT_TOKEN, which we set as an environment variable. When the script is executed by the python command we call the Slack API to list all Slack users and get the ID for the one that matches the name "starterbot".

We only need to run this script once to obtain our bot’s ID.

  1. python print_bot_id.py

The script prints a single line of output when it is run that provides us with our bot's ID.

Use the Python script to print the Slack bot's ID in your Slack team.

Copy the unique ID that your script prints out. Export the ID as an environment variable named BOT_ID.

  1. (starterbot)$ export BOT_ID='bot id returned by script'

The script only needs to be run once to get the bot ID. We can now use that ID in our Python application that will run StarterBot.

Coding Our StarterBot

We've got everything we need to write the StarterBot code. Create a new file named starterbot.py and include the following code in it.

  1. import os
  2. import time
  3. from slackclient import SlackClient

The os and SlackClient imports will look familiar because we used them in the print_bot_id.py program.

With our dependencies imported we can use them to obtain the environment variable values and then instantiate the Slack client.

  1. # starterbot's ID as an environment variable
  2. BOT_ID = os.environ.get("BOT_ID")
  3.  
  4. # constants
  5. AT_BOT = "<@" + BOT_ID + ">"
  6. EXAMPLE_COMMAND = "do"
  7.  
  8. # instantiate Slack & Twilio clients
  9. slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))

The code instantiates the SlackClient client with our SLACK_BOT_TOKEN exported as an environment variable.

  1. if __name__ == "__main__":
  2. READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose
  3. if slack_client.rtm_connect():
  4. print("StarterBot connected and running!")
  5. while True:
  6. command, channel = parse_slack_output(slack_client.rtm_read())
  7. if command and channel:
  8. handle_command(command, channel)
  9. time.sleep(READ_WEBSOCKET_DELAY)
  10. else:
  11. print("Connection failed. Invalid Slack token or bot ID?")

The Slack client connects to the Slack RTM API WebSocket then constantly loops while parsing messages from the firehose. If any of those messages are directed at StarterBot, a function named handle_command determines what to do.

Next add two new functions to parse Slack output and handle commands.

  1. def handle_command(command, channel):
  2. """
  3. Receives commands directed at the bot and determines if they
  4. are valid commands. If so, then acts on the commands. If not,
  5. returns back what it needs for clarification.
  6. """
  7. response = "Not sure what you mean. Use the *" + EXAMPLE_COMMAND + \
  8. "* command with numbers, delimited by spaces."
  9. if command.startswith(EXAMPLE_COMMAND):
  10. response = "Sure...write some more code then I can do that!"
  11. slack_client.api_call("chat.postMessage", channel=channel,
  12. text=response, as_user=True)
  13.  
  14.  
  15. def parse_slack_output(slack_rtm_output):
  16. """
  17. The Slack Real Time Messaging API is an events firehose.
  18. this parsing function returns None unless a message is
  19. directed at the Bot, based on its ID.
  20. """
  21. output_list = slack_rtm_output
  22. if output_list and len(output_list) > 0:
  23. for output in output_list:
  24. if output and 'text' in output and AT_BOT in output['text']:
  25. # return text after the @ mention, whitespace removed
  26. return output['text'].split(AT_BOT)[1].strip().lower(), \
  27. output['channel']
  28. return None, None

The parse_slack_output function takes messages from Slack and determines if they are directed at our StarterBot. Messages that start with a direct command to our bot ID are then handled by our code - which is currently just posts a message back in the Slack channel telling the user to write some more Python code!

Here is how the entire program should look when it's all put together (you can also view the file in GitHub):

  1. import os
  2. import time
  3. from slackclient import SlackClient
  4.  
  5.  
  6. # starterbot's ID as an environment variable
  7. BOT_ID = os.environ.get("BOT_ID")
  8.  
  9. # constants
  10. AT_BOT = "<@" + BOT_ID + ">"
  11. EXAMPLE_COMMAND = "do"
  12.  
  13. # instantiate Slack & Twilio clients
  14. slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))
  15.  
  16.  
  17. def handle_command(command, channel):
  18. """
  19. Receives commands directed at the bot and determines if they
  20. are valid commands. If so, then acts on the commands. If not,
  21. returns back what it needs for clarification.
  22. """
  23. response = "Not sure what you mean. Use the *" + EXAMPLE_COMMAND + \
  24. "* command with numbers, delimited by spaces."
  25. if command.startswith(EXAMPLE_COMMAND):
  26. response = "Sure...write some more code then I can do that!"
  27. slack_client.api_call("chat.postMessage", channel=channel,
  28. text=response, as_user=True)
  29.  
  30.  
  31. def parse_slack_output(slack_rtm_output):
  32. """
  33. The Slack Real Time Messaging API is an events firehose.
  34. this parsing function returns None unless a message is
  35. directed at the Bot, based on its ID.
  36. """
  37. output_list = slack_rtm_output
  38. if output_list and len(output_list) > 0:
  39. for output in output_list:
  40. if output and 'text' in output and AT_BOT in output['text']:
  41. # return text after the @ mention, whitespace removed
  42. return output['text'].split(AT_BOT)[1].strip().lower(), \
  43. output['channel']
  44. return None, None
  45.  
  46.  
  47. if __name__ == "__main__":
  48. READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose
  49. if slack_client.rtm_connect():
  50. print("StarterBot connected and running!")
  51. while True:
  52. command, channel = parse_slack_output(slack_client.rtm_read())
  53. if command and channel:
  54. handle_command(command, channel)
  55. time.sleep(READ_WEBSOCKET_DELAY)
  56. else:
  57. print("Connection failed. Invalid Slack token or bot ID?")

Now that all of our code is in place we can run our StarterBot on the command line with the python starterbot.py command.

Console output when the StarterBot is running and connected to the API.

In Slack, create a new channel and invite StarterBot or invite it to an existing channel.

In the Slack user interface create a new channel and invite StarterBot.

Now start giving StarterBot commands in your channel.

Give StarterBot commands in your Slack channel.

As it is currently written above in this tutorial, the line AT_BOT = "<@" + BOT_ID + ">" does not require a colon after the "@starter" (or whatever you named your particular bot) mention. Previous versions of this tutorial did have a colon because Slack clients would auto-insert the ":" but that is no longer the case.

Wrapping Up

Alright, now you've got a simple StarterBot with a bunch of places in the code you can add whatever features you want to build.

There is a whole lot more that could be done using the Slack RTM API and Python. Check out these posts to learn what you could do:

Questions? Contact me via Twitter @fullstackpython or @mattmakai. I'm also on GitHub with the username mattmakai.

Something wrong with this post? Fork this page's source on GitHub.


#### 在这里注册以便每月能收到一份邮件资料,内容包含本站的主要更新、教程和 Python 书籍的打折码等。

Learn more about these concepts

Slack and Python logos. Copyright their respective owners. Learning Python Bots …or view all topics.


This site is based on Matt Makai's project Full Stack Python, thanks for his excellent work!

此网站由 @haiiiiiyun开源爱好者们 共同维护。 若发现错误或想贡献,请访问: Github fullstackpython.cn 项目