Image for post
Image for post
originally published at http://www.ismail.land

How to make a Chatbot with Python (for Slack)

A Step by Step Tutorial

Ismail Elouafiq
Mar 7, 2017 · 8 min read

One amazing thing about human beings is that you would talk to them, and they would answer you back… well, most of the time.

Now, what if you could make a bot that can answer back as well. What if you could add it to your plant or dishwasher. Wouldn’t that be awesome!

While this project is not about building an amazingly intelligent chatbot it will help you setup the basic foundations using Python and Slack. So, whether it is because you want to make your own virtual assistant, change the world or if you just do not have friends and want to talk to a bot, this post is the right one for you! Enjoy :)

The Basics — How it works

The basics are the basics, and you cannot beat the basics” — Charles Poliquin

This section will introduce the basics of how the bot will work. So, without further ado, here’s what we’re going to build:

Image for post
Image for post
valet de machin

Our current chatbot, whose name from now on will be: “Valet DeMachin”, will be a ridiculously dumb bad pun assistant. But for now we will make the simplest version possible.

Valet will be able to do the following:

  • Answer with something like ‘Hello @derp !’ when greeted by user @derp.
  • Answer with a farewell when given a farewell.
  • Do nothing otherwise.
Image for post
Image for post

So for now, to get started our chatbot will be super simple so we can understand how the Slack Event API works before starting to do any more advanced stuff.

Later versions can include giving recipes on what’s for dinner, smarter answers using machine learning and ridiculously bad puns and pick up lines.

(If you want to hear about the smarter updated version join the mailing list here and I promise to keep you updated ;) )

What you need first

  • A computer, if you haven’t figured that out already.
  • Have an account on Slack. Either be already on a team in Slack or create a new team.
  • We’re going to use Python3.5.1, you can use other versions of Python.
  • Python Slack Client API slackclient. You can install using pip (which you can install from here) with the command :

Ready, set, go!

Image for post
Image for post

Practice Time whenever you see this sign, there will be some practice to do ;) So try not to skip until you’re done. And if you experience any difficulties, just let me know by leaving a comment and I’ll respond as fast as possible :D

Making the bot on Slack

Go to the Slack API Bot User page.

Image for post
Image for post

Scroll down to Custom Bot Users and click on creating a new bot user.

Enter the Username for the bot, then click on Add bot integration.

Image for post
Image for post

Now you should have an API Token that would appear on the next page and looks something like this:

Optionally you can add a picture and a real name for your slackbot.

You should already be able to see it on Slack.

Image for post
Image for post

let’s see how we can get it running on Python.

Checking that everything works correctly

Let’s start by exporting the slack name and the slack token of our bot instead of hardcoding them (sticking with the good habits, right :P )

We can do this by either typing this into the command line, in the working directory of the valet:

The way we’re going to do it is by adding a source.sh file with the following:

and then sourcing the file from the command line by using:

This way we can reuse it later (there are better ways of doing this but let’s keep it simple for now ;p )

Now let’s check that the authentication token works properly. We import the environment variables and check if we can call the slack client successfully, we make a discover.py file that contains the following:

Image for post
Image for post

Practice Time check if the print method prints the correct variables for both your bot name and token. If these do not work properly, chances are you had a problem sourcing the environment variables. If it doesn’t seem to work leave me a comment here. Now let’s move on to the good stuff…

We need to find the bot id. Just like any other user, your chatbot has a user id. To find it we add the following lines to our discover.py file:

What this does is it goes through the list of users and prints out the id of our lovely Valet De Machin.

We find out that our chatbot’s id is something like :

We change the source.sh file to include the id of the chatbot:

and, of course we need to source it again

Starting small

What would this look like if it were easy? — Tim Ferriss

Now let’s make a very simple bot that will run and respond with hello.

We create a new python file valet.py containing the following:

Notice that for now we have kept the is_for_me and handle_message as simple as we can.

We want is_for_me to understand whether the message is dedicated to our chatbot. To make it simple we consider that it can be either of the following cases:

  • The message is sent on a private chat.
  • The message is sent out on a group channel and the valet is mentioned.

Since I couldn’t find a better way to know if a channel is private, I did so by implementing a function is_private that checks if the event starts with a ‘D’ since it seems like that is what makes the difference between a private channel and others (if you find a better way, please let me know I’d be more than happy to check it out, here are the event api docs by the way: https://api.slack.com/events/)

Image for post
Image for post

Practice time Try to implement the is_for_me and handle_message function, on your own first, by checking the docs for the message events at https://api.slack.com/events/message

Note that you can find the source code on the following github repository

Here’s a way to implement the previous functions:

we first add this function that enables us to get how the chatbot is mentioned:

We then finish is_for_me as follows:

To handle a message we also use get_mention to mention the user we’re talking to when we say hi. We want to say Hi only when the user is saying Hi or Hello or something similar. And we want to say bye only when the user is giving their farewells to our chatbot.

This means that we first need to add a function that will know if the user is saying hi and a function to know if the user is saying goodbye.

We implement these two very simple functions for now by just saying that if a text contains something like hello then it is a greeting (for more interesting stuff with nltk tune in by subscribing to my mailing list at http://ismail.land)

And we also implement the following methods to answer back by either hi or goodbye:

With all of this, all that is left now is for us to finally implement our handle_message function:

Finally, we run our valet.py file from the command line using

Note : If this does not work make sure you have sourced the environment variables. If not just run sh source.sh again :)

And now we can finally get on slack and talk to our chatbot.

Either from a private chat:

Image for post
Image for post

Or from a public channel:

Image for post
Image for post

Thanks for reading! :) If you enjoyed it, hit that heart button below. Would mean a lot to me and it helps other people see the story.

Of course, we later want our chatbot to be able to do more fun stuff and be used in other ways. To tune in for a part 2 on how to make your chatbot smarter and how to connect it to facebook you can join me over here on my mailing list and I promise to keep you updated!

By the way, Python3.6 is finally out, I got some time to have my hands on it, here’s a summary of the features that I’m most excited about.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store