How to build Slack Bot with Python & Django using Events API

Ronak Bansal
Chatbots Life
Published in
6 min readNov 6, 2019

--

Photo by Pankaj Patel on Unsplash

Slack is a platform for team collaboration. It is used by over 12 million users on a daily basis. Bots are the useful way to interact with people. Slack is a great platform to build chatbots because of its world class API interfaces. 95% of Slack user base say Slack apps make the parent software more valuable.

With this post, I will quickly walk you through how to build a simple Slack bot using Python & Django with Slack’s event based API.

To start with, we need to create a slack workspace. If you don’t have, you can create one here. Once we have a workspace ready where you have access to build apps, we can start the process of slack bot/app building.

Let’s start by creating a slack app. Visit https://api.slack.com/apps/new and fill in the relevant details, give a name to your app and choose your newly created workspace in the Development Slack Workspace.

You will be directed to the basic configuration page where we can start by navigating to Bot Users tab in the sidebar. Click on Add a Bot User button and fill the necessary button and save the changes.

Next, move to Install App from the side bar navigation and click on Install App to Workspace.

You will get OAuth Access Token and Bot User OAuth Access Token for your team. Lets refer them as OAUTH_ACCESS_TOKEN and BOT_USER_ACCESS_TOKEN in rest of the tutorial.

Now, take a note of App Credentials from Basic Information page.

Keep a note of Client ID, Client Secret and Verification Token and we will refer them as CLIENT_ID, CLIENT_SECRET and VERIFICATION_TOKEN further.

Now, lets start with Python Environment setup. We will use Python 3.7, virtualenv for virtual environment and pip for python package management. Let us create a new virtual environment for our project with name env and source that environment.

#install pip
pip3 install virtualenv
#create a new folder
mkdir sample_app
cd sample_app
#create the environment
virtualenv env -p python3
#source the created environment
source env/bin/activate

Its time to install rest required packages

pip install django
pip install slackclient #slack python package

Next, create a django project and app

django-admin startproject slackapp
cd slackapp/
django-admin startapp actions

We will need to add our app actions in the INSTALLED_APPS in slackapp/settings.py. We will also need to add the required slack tokens in this file.

#slackapp/settings.pyINSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'actions',
]
ALLOWED_HOSTS = ['*']#Replace correct values of your token here
VERIFICATION_TOKEN = '********'
OAUTH_ACCESS_TOKEN = '************'
BOT_USER_ACCESS_TOKEN = '****-******-******'
CLIENT_ID = '**********'
CLIENT_SECRET = '******'

Now we can test the django development server by starting it and verifying that it is running successfully.

./manage.py runserver

We will see that that the server is up and running by visiting http://127.0.0.1:8000/

Lets start by creating an API endpoint where slack will send all event messages. Lets configure django routes.

#slackapp/urls.pyfrom django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('actions/', include('actions.urls')),
]
#actions/urls.pyfrom django.urls import include, path
from . import views
urlpatterns = [
path('event/hook/', views.event_hook, name='event_hook'),
]

Slack asks for API endpoint where it will post messages sent by the bot users. This is a verification process where we have to verify the endpoint we are submitting to slack. This can be verified by returning the challenge code shared by the slack in request parameters. Here is the views.py code for the same.

# actions/views.pyfrom django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
import json
from django.http import HttpResponse, JsonResponse
@csrf_exempt
def event_hook(request):

json_dict = json.loads(request.body.decode('utf-8'))
if json_dict['token'] != settings.VERIFICATION_TOKEN:
return HttpResponse(status=403)
#return the challenge code here
if 'type' in json_dict:
if json_dict['type'] == 'url_verification':
response_dict = {"challenge": json_dict['challenge']}
return JsonResponse(response_dict, safe=False)
return HttpResponse(status=500)

We now have our API endpoint ready http://127.0.0.1:8000/actions/event/hook/ . We need this API endpoint to be available in a public domain. For this, we will be using ngrok, which will provide us with a public URL and forward the requests to our django server at the defined 8000 port.

Trending Articles on Chatbot Marketing:

1. How to Get to 1 Million Users for your Chatbot

2. How to Get Users for Free using a Viral Loop

3. How I grew JokeBot from 26k subscribers to 117k subscribers

4. Chatbot Conference 2020

Install ngrok and use it to bind to port 8000 of your django app and get the public URL for the same as below

As you can see on the above screen, ngrok has provided us with the https public domain (highlighted in the above image). We will now use this domain and thus the final Events API endpoint in our case looks like https://6d65a987.ngrok.io/actions/event/hook/

Lets submit this URL to the app settings page. Navigate to Event Subscriptions in the sidebar and Enable Events.

Lastly, scroll down to subscribe to direct messages. This is achieved by adding message.im event to bot events.

Now the slack app configuration is done and ready to use. Next, lets handle this event in our views code and respond to any message posted by user.

#actions/views.pyfrom django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
import json
from django.http import HttpResponse, JsonResponse
import slack
@csrf_exempt
def event_hook(request):

client = slack.WebClient(token=settings.BOT_USER_ACCESS_TOKEN)
json_dict = json.loads(request.body.decode('utf-8'))
if json_dict['token'] != settings.VERIFICATION_TOKEN:
return HttpResponse(status=403)
if 'type' in json_dict:
if json_dict['type'] == 'url_verification':
response_dict = {"challenge": json_dict['challenge']}
return JsonResponse(response_dict, safe=False)
if 'event' in json_dict:
event_msg = json_dict['event']
if ('subtype' in event_msg) and (event_msg['subtype'] == 'bot_message'):
return HttpResponse(status=200)
if event_msg['type'] == 'message':
user = event_msg['user']
channel = event_msg['channel']
response_msg = ":wave:, Hello <@%s>" % user
client.chat_postMessage(channel=channel, text=response_msg)
return HttpResponse(status=200)

return HttpResponse(status=200)

Finally, lets start your app development server and go to your workspace on slack. Find the app we just installed, and send a message to the app.

Hurray, we see bot responding to the hi message of the user. Now, you can play around with the code and write logic for other events you want to support.

Complete Code of the above sample app can be found here.

Note: Please do not push your code into any public repository with private information like tokens or secrets stored in it. Ideally these values should be exported as environment variables.

Don’t forget to give us your 👏 !

--

--