Bots are a useful way to interact with chat services like Slack. If you’ve never built a chatbot before, this article provides a simple starter guide on how to build your first chatbot using Python in conjunction with the Slack API.
We built your development environment, got a Slack API chatbot token, and built a simple chatbot with Pyhon.
The tools we need
Our chatbot, which we call “StarterBot,” requires Python and Slack apis. To run our Python code, we need:
Python 2 或者 Python 3
PIP and VirtualEnv to handle Python application dependencies
A free Slack account with access to the API, or you can sign up for a Slack Developer Hangout Team.
The official Python Slack client codebase created by the Slack team
The Slack API tests the token
Slack API documentation is useful when you build in this tutorial.
All of the code in this tutorial is available in the Slack-StarterBot public library under the MIT license.
Build our environment
We now know what tools we need for our project, so let’s set up our development environment. First go to a terminal (or a command prompt on Windows) and switch to the directory where you want to store the project. In that directory, create a new VirtualEnv to isolate our application dependencies from other Python projects.
Activate the virtualenv:
Your prompt should now look like a screenshot:
This official Slack client API help library was built by Slack to send and receive messages over slack channels. Install the SlackClient library with this PIP command:
When the PIP command completes, you should see output similar to this and return a prompt.
We also need to get an access token for our Slack project so our chatbot can use it to connect to the Slack API.
Slack Real-time Messaging (RTM)API
Slack allows applications to access their messaging channels through a Web API. Go to the Slack Web API page and sign up to create your own Slack project. You can also log into an existing account that you have administrative access to.
Log in using the login button in the upper right corner of the Web API page and you will be sent to the chatbot user page.
Customize the Chatbot user page name your chatbot “StarterBot” and click the “Add Bot Integration” button.
Add a BOT integration and name it “Starterbot” the page will reload and you will see a newly generated access token. You can also change the logo to your own design. Take this “Full Stack Python” flag I gave you.
Copy and paste access tokens for your new Slack chatbot by clicking the “Save Integration” button at the bottom of the page. Your chatbot is now ready to connect to the Slack API.
A common practice for Python developers is to print secret tokens in environment variables. The output Slack token is named SLACK_BOT_TOKEN:
Ok, we now have the authorization to use this Slack API as a chatbot.
We need more information to set up a chatbot: the ID of our chatbot. Next we’ll write a short script to get the ID from the Slack API.
Get the ID of our chatbot
This is the last time to write some Python code! Let’s warm up by writing a short Python script to get the ID of StarterBot. This ID varies based on Slack projects.
We need this ID to verify the identity of our application when parsing messages sent to StarterBot from Slack RTM. Our script also tests whether our SLACK_BOT_TOKEN environment variable is set correctly.
Create a new file named printbotid.py and fill it with the following code:
Our code imports the SlackClient and instantiates it with the environment variable SLACK_BOT_TOKEN that we set. When the script is executed using python commands, we list all Slack users by accessing the Slack API and get an ID matching the name “satrterbot.”
We only need to run the script to get the chatbot ID once.
When it runs and gives us the chatbot ID, the script prints a simple one-line output.
Print the Slack chatbot ID with a Python script in your Slack project and copy the unique ID printed by the script. This ID is output as an environment variable BOT_ID.
This script only needs to be run once to get the chatbot ID. We can now use this ID in our Python application running StarterBot.
Code our StarterBot
Now we have everything we need to write our StarterBot code. Create a new file named starterbot.py, which contains the following code.
The imports for OS and SlackClient look familiar because we’ve already used them in theprintbotid.py.
With the dependencies we imported, we can use them to get environment variable values and instantiate the Slack client.
This code instantiates the SlackClient ‘client through us with the output environment variable SLACK_BOT_TOKEN.
Slack clients connect to Slack RTM API WebSocket and loop as messages from firehose are parsed. If there are any messages sent to StarterBot, a function called handle_Command decides what to do.
Next, add two functions to parse Slack’s output and process commands.
The parse_slack_output function receives messages from Slack and determines if they are sent to our StarterBot. The message starts with a direct command giving our chatbot ID, which is then handed over to our code to process. Currently it’s just a message via Slack pipes telling users to write more Python code!
Here’s what the entire program looks like put together (you can also view the file on GitHub) :
Now that we have our code, we can run our Starterbot code with Python Starterbot.py.
When StarterBot starts running and the output channel connected to the API creates a new channel in Slack and invites StarterBot in, or invites StarterBot into an existing channel.
Create a new channel in Slack and invite StarterBot to now send commands to StarterBot in your channel.
Send commands to your StarterBot in your Slack channel. If you’re having problems with the responses your chatbot is getting, you may need to make a change. As written in this tutorial above, the line AT_BOT = “:” requires a colon after “@starter” (the name you give your own chatbot). Removes: from the AT_BOT string. Slack seems to require a colon at the end of a @ name, but that seems incongruous.
The end of the
Well, you’ve now got a simple chatbot that you can add whatever features you want in many places in your code.
We can do a lot with Slack RTM APIS and Python. See what else you can learn from these articles:
Attach a persistent relational database or NoSQL backend such as PostgreSQL, MySQL, or SQLite to store and retrieve user data
Add another channel for interaction with the chatbot, such as text messages or phone calls
Integrate other Web apis, such as GitHub, Twilio, or api.ai
Original: fullstackpython.com
Translation: http://linux.cn
Translator: jiajia9linuxer
Source: Python development
End