Home > Article > Backend Development > Detailed example of how to implement a chatbot using Python+Slack API
Chatbot (Bot) is a practical interactive chat service like Slack. If you’ve never built a chatbot before, this article provides a simple introductory guide on how to build your first chatbot using Python and the Slack API.
We build your development environment, obtain a Slack API chatbot token, and use Pyhon Develop a simple chatbot.
Tools we need
Our chatbot we’ll call it “StarterBot” requires Python and Slack API. To run our Python code we need:
Python 2 or Python 3
pip and virtualenv to handle Python application dependencies
A free Slack account with API access, or you can sign up for a Slack Developer Hangout team.
Official Python Slack client code base built by the Slack team
##Slack API Test Token
The Slack API documentation will be helpful as you build in this tutorial.
All the code in this tutorial is placed in the slack-starterbot public library and is open sourced under the MIT license.
Set up our environment
We now know what tools we need for our project, so let’s Let’s set up our development environment. First go to Terminal (or Command Prompt on Windows) and change to the directory where you want to store this project. In that directory, create a new virtualenv to isolate our application dependencies from other Python projects.
Your prompt should now look like the screenshot: Command prompt of activated starterbot's virtualenv This official slack client API help library is built by Slack, which can send and receive messages through Slack channels. Install the slackclient library via this pip command: When the pip command completes, you should see something like this output and returns the prompt. We also need to get the output of installing slackclient with pip in the activated virtualenv for our Slack project An access token so that our chatbot can use it to connect to the Slack API. Slack Real-Time Messaging (RTM) API Slack allows programs to access their messages through a Web API Delivery channel. Go to this Slack Web API page to register and build your own Slack project. You can also log in to an existing account that you have administrative rights for. After logging in using the login button in the upper right corner of the Web API page you will arrive at the chatbot user page. Customize Chatbot User Page Name your chatbot "starterbot" and click "Add bot integration" button. Add a bot integration and name it "starterbot" The page will reload and you will see a newly generated visit Token. You can also change the logo to one of your own design. For example I gave this "Full Stack Python" flag. A common practice among Python developers is to export the secret token as an environment variable. The name of the output Slack token is SLACK_BOT_TOKEN: We need one more piece of information to build our chatbot: our chatbot’s ID. Next we'll write a short script to get that ID from the Slack API. Getting the ID of our chatbot It’s finally time to write some Python code! Let’s write a A short Python script to get the StarterBot's ID to warm up. This ID varies based on the Slack project. We need this ID to authenticate our application when parsing messages sent to StarterBot from Slack RTM. Our script will also test whether our SLACK_BOT_TOKEN environment variable is set correctly. Create a new file named printbotid.py and fill in the following code: Our code imports SlackClient and instantiates it with the environment variable SLACK_BOT_TOKEN we set. When the script is executed via the python command, we access the Slack API to list all Slack users and get an ID matching the name "satrterbot". We only need to run this script to get the ID of the chatbot once. Coding our StarterBot Now we have everything we need to write the code for our StarterBot. Create a new file named starterbot.py and include the following code. Through the dependency packages we imported, we can use them to obtain environment variable values and instantiate the Slack client. Next add two functions to parse Slack’s output and process commands. This is how the entire program looks together (you can also view the file in GitHub) : When StarterBot starts running and the output channel connected to the API creates a new channel in Slack and puts Invite StarterBot in, or invite StarterBot into an existing channel. End Okay, you now have a simple chatbot that you can do a lot in code place to add any features you want to create. We can do a lot of things using the Slack RTM API and Python. See what else you can learn through these articles: #Attach a persistent relational database or NoSQL backend such as PostgreSQL, MySQL or SQLite to save and Retrieve user data Add another channel to interact with the chatbot, such as text message or phone call Integrate other web APIs, such as GitHub, Twilio or api.ai
Copy and paste the access token for your new Slack chatbot Click at the bottom of the page "Save Integration" button. Your chatbot is now ready to connect to the Slack API.
Okay, we now have authorization to use this Slack API as a chatbot.
When it runs giving us the ID of the chatbot, the script prints out a simple one line of output.
Use a Python script in your Slack project to print the ID of the Slack chatbot. Copy the unique ID printed by this script. And output the ID as an environment variable BOT_ID.
This script only needs to be run once to get the chatbot’s ID. We can now use this ID in our Python application running StarterBot.
The import of os and SlackClient looks familiar because we have already used them in theprintbotid.py.
This code instantiates the SlackClient` client through the environment variable SLACK_BOT_TOKEN we exported.
The Slack client connects to the Slack RTM API WebSocket and then loops continuously while parsing messages from firehose. If there are any messages sent to the StarterBot, a function called handle_command determines what to do.
The parse_slack_output function accepts messages from Slack and determines if they were sent to our StarterBot. The message starts with a direct command to our chatbot ID and is then handed off to our code for processing. Currently, I just publish a message through the Slack pipeline to tell the user to write more Python code!
##Now that our code is there, we can run our StarterBot through python starterbot.py code.
Create a new channel in the Slack interface and invite StarterBot. Now send commands to StarterBot in your channel.
Send commands to your StarterBot in your Slack channel If you are having issues getting responses from your chatbot, you may A modification needs to be made. As written above for this tutorial, the line AT_BOT = “:” requires a colon after “@starter” (the name you gave your own chatbot). Remove: from the end of the AT_BOT string. Slack seems to require a colon after @ a person's name, but this seems a bit incongruous.
The above is the detailed content of Detailed example of how to implement a chatbot using Python+Slack API. For more information, please follow other related articles on the PHP Chinese website!