How to Create and Implement a Bot Using Python?
Yes, there is an innovative way to deal with that problem - creating a simple bot. Let us present our step-by-step guide how to do it.
What is a chatbot and how can it benefit us?
By definition, a chatbot is a computer program and/or an artificial intelligence which conducts a conversation via textual methods and acts appropriately to the context. Imagine that you want to book a flight to some place on exact dates and you know where do you want to stay (or want to list the 5 cheapest 5-star hotels in Venice). You can go the airline’s page, find the flight, choose the dates, buy the tickets, then google the hotels and read their reviews (each on a different site), check their pages for some photos… a 15-minute job will take you like 2-3 hours and you still need to pack your bag! Alternatively, you could ask your personal assistant: “Hey Bob The Bot, can you book me a flight to Venice from 10th to 15th May and show me the cheapest 5-star hotels” and be presented with hotel descriptions and photos - all you need to do is give your credit cards details. This is not the future. This kinds of bots are here and in fact they are pretty easy to write.
Why to choose Python to create a bot?
Python as a programming language is the first choice for both beginners and professionals. It’s easy to use, easy to learn, and its large community provides tons of ready to use libraries and frameworks. It has some fancy frameworks like TextBlob or spaCy which help you create really advanced AI with some natural language processing skills. You can use the ChatterBot framework which allows you to create a conversational machine-learning-based bot within just couple of minutes! On the other hand, if you just need a simple tool using Python, it will take you around 2 hours (coffee making included) and you don’t need to be an expert nor a developer (basic programming skills are required still).
Everyone is busy, including developers. They also hate boring, repetitive task such as standups! Each morning they have to answer the same questions. Daily meetups are often indicated as a major interruptions for programmers. To make it easy, we can allow them to give their feedback without leaving their keyboards - it will just require a couple of seconds to write a personal message in the Slack client.
Meet Bob The Standup Bot!
Let’s make our lives easier and create a robot for answering and recording questions in the simplest way possible.
Here at Netguru we use and love Slack for our day-to-day communications. It’s free, very intuitive, and it has some nice features like an API for 3rd party integrations.
Ready, steady, Python! Creating a bot step by step
First, we start with creating our working environment. We will use virtualenv and virtualenvwrapper as they are the tools which helps us keep our dependencies clean and maintainable. Please check the installation guides (virtualenv and virtualenvwrapper) of your OS of choice. You can also use PyCharm IDE which has virtualenv built in.
Now we can register our bot in the Slack namespace so the app will know where to send all the notifications. To do this, go to https://api.slack.com/apps?new_app=1 and fill in the app name and select a workspace.
Then go the Bot Users page under the Features section of your newly created bot and create a new one. This will create a Slack-user-like object which will be later listed on your Slack users list.
Last but not least, click on Install App on the Install App page. This will ask for your permission to authorize access for the bot to your workspace. As a result, you will receive an OAuth Access Token and a Bot User OAuth Access Token. These are very important as they allow your Python code to communicate with Slack.
Give me some code!
It is time to write some Python code. As we have seen before, Slack makes available some pretty documentation and they have a dedicated section for Python integration.
Slack uses a publisher-subscriber architecture. To receive notifications we need to subscribe to the listeners queue. To do this, we are initialize the Slack client with our OAuth Token and notify it that we are ready to work https://pastebin.com/qb3tVwbT. You can now debug your code and see what kind of data (and how often) the rtm_read() method returns.
Now we should work on our first command - the bot’s actual response to our message. We will use something called Duck Typing in Python to implement a base for our all Command classes. If it can “do” it, then it is a Doable Command. We can go with a simple Help command. Every time the someone writes help to our bot, it will respond with all the commands it recognizes. https://pastebin.com/eXey19aA.
Every standup starts with the same questions: What are you working on? Did you encounter any problems? What are your plans for later? So this is our user form and the answers have to be recorded. Also, the stand up has to be started by someone and the users list can not be fixed (there are different project groups and sometimes some people may be missing). “Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.” Jamie Zawinski. We need to use a regular expression to match some patterns from the users’ messages. If the message starts with “Standup for:”, we can assume that the user wants to start a meeting for some users. Then we need to find all the emails to identify to whom we need to send private messages. https://pastebin.com/msheRUbK.
This will just start a stand up and send the first messages to each developer. But we need to record the answers and, most importantly, send them to the original poster. To do this, we create a STANDUP_CHANNELS dict collection to store the already started startups threads. RespondStandupCommand will check if the incoming message is from this channel and will then send it to the manager. https://pastebin.com/CRi6cPqt
Neverending story
The sky is the limit in every programming project. You can add as many commands as you wish. You can implement a communication feature using ChatterBot and train your bot using a corpus. This is a very trivial implementation of a Slack bot, but it works and can be very helpful. It took me about 2 hours to solve a real life problem and users can already benefit from this. Where to go next? We probably should use the thread library to make this bot non-blocking, see the official Python documentation for more details. Also, the performance can be boosted by implementing a queue for storing incoming events. We could then implement more workers so we could support more users. Feel free to fork & reuse the full code listed on Github.
Within a couple of code lines we have created a tool for gathering a feedback from the whole team about their assignments. In addition to the fact that it makes it easier for a team to stay focused on their current jobs rather than attending meetings, it also helps managers to stay in close touch and react to any problems. There are many other bots you can create: from bots that tell a random joke (or send you a random song on demand), to ones that help you book a conference room in your building - all this with just a couple of commands in your Slack client.