<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[freehunch - Medium]]></title>
        <description><![CDATA[freehunch is an initiative to help data scientist build data products from abstract ideas. We will discuss tools and technologies that will enable data scientist to build cloud-native, containerized, high-performance data products. - Medium]]></description>
        <link>https://medium.com/freehunch?source=rss----26d914342454---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>freehunch - Medium</title>
            <link>https://medium.com/freehunch?source=rss----26d914342454---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 07:41:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/freehunch" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to build a Slack Bot with Python using Slack Events API & Django under 20 minute— Code Included]]></title>
            <link>https://medium.com/freehunch/how-to-build-a-slack-bot-with-python-using-slack-events-api-django-under-20-minute-code-included-269c3a9bf64e?source=rss----26d914342454---4</link>
            <guid isPermaLink="false">https://medium.com/p/269c3a9bf64e</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Prabakaran Kumaresshan]]></dc:creator>
            <pubDate>Sat, 22 Jul 2017 07:07:24 GMT</pubDate>
            <atom:updated>2017-07-22T07:07:24.162Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QegG0tODEy3ysRO3KdYs5w.png" /><figcaption>Photo by <a href="https://unsplash.com/@danielkcheung">Daniel Cheung</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Slack is a great platform for team collaboration not just that it also has one of the best API interfaces to build Chatbots. Chatbots come in all size from reminding you to <a href="https://www.todobot.io/slack/">buy milk</a> to help you <a href="https://www.paypal.com/slack/">send or receive money</a>.</p><p>In this post, I will walk you through building a minimal Slack Bot with Python backend. The idea is to set up a Slack Bot that will greet you back when greeted, once we have it up and running then we can extend the Bots ability just by coding additional logic.</p><h4>Minute 1: Slack</h4><p>Before we start coding the bot let us understand the Slack bots life cycle:</p><ol><li>If you are new to <a href="https://slack.com/"><strong><em>Slack</em></strong></a>, it’s a messaging platform focused on team collaboration. Slack lets you create custom applications, including bots (sort of Messaging Platform as a Service). You will run the application back end to process business logic in your own server.</li><li>To startwith you need to be part of Slack team and have <strong><em>admin privilege </em></strong>to create a new Slack App. If you are not part of a Slack team you may <a href="https://slack.com/get-started">create one</a>.</li><li>We will create a <strong><em>Slack App</em></strong> for the Slack team then we will add a <strong><em>Bot User</em></strong> to the app.</li><li>We will create a Django based REST backend web application to process the <strong><em>Bot User</em></strong> requests.</li><li>Since we will be running the backend in our local system, we will use <a href="https://ngrok.com/"><strong><em>ngrok</em></strong></a> to tunnel our local network and get a public url.</li><li>Once the backend is ready we can submit the endpoint url to Slack for <strong><em>url</em></strong> <strong><em>verification by challenge</em></strong>. When you submit an endpoint for the first time Slack will send a challenge POST request with a secret token. To successfully complete the challenge you need to return the request with the challenge secret (you just have to echo the received message). This is a one time excercise for a given api endpoint.</li><li>Once verified we can <strong><em>subscribe to events</em></strong> for which we want Slack to send a message to our backend. This is the best part you dont have to pool Slack to get new events, Slack will do the heavy lifting, which makes this an excellent use case for AWS Lambda. You can find the long list of events <a href="https://api.slack.com/events">here</a>.</li><li>After setting up Slack App and have the backend ready to process events, we can write the bot logic to perform a specific task in response to an event. In this case when a user greets, our bot will respond with a greet message.</li></ol><p>Lets dive into Bot Building…</p><h4>Minute 2: Create a Slack App</h4><p>Start by creating a Slack app <a href="https://api.slack.com/apps">here</a>, click <strong><em>Create App</em></strong>.<strong> </strong>Then proceed with app creation, give it a name and select the Slack team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*ufvQ_8-720dZlYHOwOFFYA.png" /></figure><p>Then you will be taken to App configuration where you need do following to get our Bot up and running.</p><ol><li>Create a Bot User</li><li>Install Slack App to your Team</li><li>Verify Back End</li><li>Subscribe to Events</li></ol><p>On the left pane click on <strong><em>Bot User</em></strong> then choose an user name for the Bot and set “<strong><em>Always Show My Bot as Online</em></strong>” slider to on. Since we are going to use Events API only, the bot will not appeare online otherwise. Click on <strong><em>Add Bot User </em></strong>to create our hello bot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*KtJWJPJoeLGb939A5bLCOg.png" /></figure><h4>Minute 3: Install Slack App to Team</h4><p>Now on the left pane click <strong><em>Install App</em></strong> and install the app to your Slack team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*U-hy_z5tDuWS5yEZhb60OA.png" /></figure><p>Once installed you will get <strong><em>Bot User OAuth Access Token</em></strong>, note down this token we will need it later while configuring Django app. This token is the passphrase for our Bot to interact with the Slack Team. We will refer to this token as SLACK_BOT_USER_TOKEN in rest of the tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*7URX9cInQE1hgRfsZjWt4g.png" /></figure><h4>Minute 4: Slack Client <strong><em>Credentials</em></strong></h4><p>Also note down the <strong><em>App Credentials</em></strong> from <strong><em>Basic Information</em></strong> on the left pane. These credentials let us talk to Slack API, so every time we send a message to Slack we should send our Client ID(CLIENT_ID) &amp; Client Secret(CLIENT_SECRET) to identify ourselves to Slack. Similarly we can verify if an incomming message is send by Slack checking if the Verification Token (VERIFICATION_TOKEN) in the message is same as the one in App Credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*U9D5u5q4evIE2FlN3uOJqA.png" /></figure><p>Now we should have four key values with us</p><ol><li>Client ID — SLACK_CLIENT_ID</li><li>Client Secret — SLACK_CLIENT_SECRET</li><li>Verification Token — SLACK_VERIFICATION_TOKEN</li><li>Bot User Token — SLACK_BOT_USER_TOKEN</li></ol><p>We have one last step left in Slack App configuration, which is to submit our Bot’s REST API end point to Slack and get it verified.</p><p>Before we Verify our Bot and subscribe for the events, we need to have the Django app running.</p><h4>Minute 5: Environment Setup</h4><p>We will be using Python 3.5 and following packages</p><ol><li>Django</li><li>Django REST Framework</li><li><a href="https://github.com/slackapi/python-slackclient">Slack Client for Python</a></li><li><a href="https://github.com/slackapi/python-slack-events-api">Slack Events API</a></li></ol><p>We will use <a href="https://www.continuum.io/downloads"><strong><em>conda</em></strong></a> for virtual environment and <strong><em>pip</em></strong> for package management. Let us create new virtual environment “slack_bot” for our project with python version 3.5.x and activate the virtual environment.</p><pre>conda create -n slack_bot python==3.5</pre><pre><strong># windows<br></strong>activate slack_bot</pre><pre><strong># mac os, linux<br></strong>source activate slack_bot</pre><p>Now lets install required packages</p><pre>pip install django<br>pip install djangorestframework<br>pip install slackclient<br>pip install slackeventsapi</pre><h4>Minute 6: Create Django Application</h4><p>Create a django project and an app in the working directory.</p><pre>django-admin startproject slack<br>cd slack<br>django-admin startapp events</pre><p>Now your project folder structure should look like this. From now on all the file path I mention assumes slack, the project folder, as root.</p><pre>└── slack<br>    ├── events<br>    │   ├── admin.py<br>    │   ├── apps.py<br>    │   ├── __init__.py<br>    │   ├── migrations<br>    │   │   └── __init__.py<br>    │   ├── models.py<br>    │   ├── tests.py<br>    │   └── views.py<br>    ├── manage.py<br>    └── slack<br>        ├── __init__.py<br>        ├── __pycache__<br>        │   ├── __init__.cpython-35.pyc<br>        │   ├── settings.cpython-35.pyc<br>        │   ├── urls.cpython-35.pyc<br>        │   └── wsgi.cpython-35.pyc<br>        ├── settings.py<br>        ├── urls.py<br>        └── wsgi.py</pre><h4>Minute 7: Configure Django Settings</h4><p>REST Framework makes creating API end points a breeze with build-in API Views and browseable API. Lets add <strong><em>REST Framework</em></strong> as dependency in Django settings. Also we need to add our own application <strong><em>events</em></strong> as dependency. Add the two lines mentioned below in the file <strong><em>slack/settings.py</em></strong></p><pre><strong># slack/settings.py</strong></pre><pre>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br><strong>    &#39;</strong><strong>rest_framework&#39;, </strong>            <strong># &lt;== add this line</strong><br><strong>    &#39;events&#39;,     </strong>                <strong># &lt;== add this line</strong><br>]</pre><p>Then add following configurations in <strong><em>slack_bot/settings.py </em></strong>with your authentication keys from Slack.</p><pre><strong># slack/settings.py</strong></pre><pre># SLACK API Configurations<br># ----------------------------------------------<br># use your keys <br>SLACK_CLIENT_ID = &#39;20xxxxxxxxxx.20xxxxxxxxxx&#39;<br>SLACK_CLIENT_SECRET = &#39;d29fe85a95c9xxxxxxxxxxxxxxxxxxxxx&#39;<br>SLACK_VERIFICATION_TOKEN = &#39;xpxxxxxxxxxxxxxxxxxxxxxxxxx&#39;<br>SLACK_BOT_USER_TOKEN = &#39;xoxb-xxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxx&#39;</pre><p><strong><em>Please do not check in your code into any public repository like Github with these values saved. </em></strong><em>Ideally these values should be exported as environment variables and read by startup scripts.</em></p><p>Now start the Django development server</p><pre>python manage.py runserver</pre><p>Once the server is started it will print something similar to this</p><pre>Performing system checks…<br>System check identified no issues (0 silenced).</pre><pre>You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.<br>Run ‘python manage.py migrate’ to apply them.</pre><pre>July 03, 2017–17:30:32<br>Django version 1.11.3, using settings ‘slack.settings’<br>Starting development server at <a href="http://127.0.0.1:8000/"><strong>http://127.0.0.1:8000/</strong></a><br>Quit the server with CONTROL-C.</pre><p>Ignore the migration warnings and open the URL in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*VNRYg5gwmeRr4JESbs-tuQ.png" /></figure><h4>Minute 8: Create an API endpoint</h4><p>Now that we have our app server up and running we need to create an endpoint for Slack to send event messages. We will create an API view with Django Rest Framework (DRF) as follows</p><pre><strong># events/views.py</strong></pre><pre><strong>from </strong>rest_framework.views <strong>import </strong>APIView<br><strong>from </strong>rest_framework.response <strong>import </strong>Response<br><strong>from </strong>rest_framework <strong>import </strong>status<br><strong>from </strong>django.conf <strong>import </strong>settings<br><br>SLACK_VERIFICATION_TOKEN = getattr(settings, &#39;SLACK_VERIFICATION_TOKEN&#39;, <strong>None</strong>)<br><br><strong>class Events</strong>(APIView):<br>    <strong>def post</strong>(self, request, *args, **kwargs):</pre><pre>        slack_message = request.data</pre><pre>        <strong>if </strong>slack_message.get(&#39;token&#39;) != SLACK_VERIFICATION_TOKEN:<br>            <strong>return </strong>Response(status=status.HTTP_403_FORBIDDEN)</pre><pre>        <strong>return </strong>Response(status=status.HTTP_200_OK)</pre><p>In the code above we are importing the required python packages, retreiveing the token saved in configuration then defining an API view to handle POST request.</p><p>In the POST function we are checking if the token in message matches our Bot User’s verification token, this is to validate if the incomming request was actually from Slack. If there is match we are sending “<strong><em>OK</em></strong>” message else telling that the requester is “<strong><em>Forbidden</em></strong>” from accessing our server.</p><h4>Minute 9: Configure Django Routes</h4><p><em>If you are new to web applications, routing is the way to tell web server which function to invoke when an URL is hit with a request. When the URL is hit with a request message the corresponding function will be invoked, passing the requester message as parameter to the function.</em></p><p>Add following lines in <strong><em>slack/urls.py</em></strong> to tie Events API class to <a href="http://127.0.0.1:8000/events/"><em>http://localhost:8000/events/</em></a></p><pre><strong># slack/urls.py</strong></pre><pre><strong>from </strong>django.conf.urls <strong>import </strong>url<br><strong>from </strong>django.contrib <strong>import </strong>admin<br><strong>from </strong>events.views <strong>import </strong>Events                                    <strong>#</strong><br><br>urlpatterns = [<br>    url(https://medium.com/r&#39;^admin/&#39;,%20admin.site.urls),<br>    url(https://medium.com/r&#39;^events/&#39;,%20Events.as_view()),                            <strong>#</strong><br>]</pre><p>Open the server url in your browser, you will find bowserable API interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-JzfJALUMXrVaDWtPaRtgA.png" /></figure><p><strong><em>Note</em></strong><em>: Usually we will create a separate routing file for each app and register it with the project route. To keep the code simple I have defined the events app url in the project route file.</em></p><h4>Minute 10: Slack URL Verification Challenge</h4><p>In order to submit our API endpoint to Slack we need to code a logic to let Slack verify our endpoint and associate it with the Slack Bot User. In the Events API class add following code.</p><pre><strong>from </strong>rest_framework.views <strong>import </strong>APIView<br><strong>from </strong>rest_framework.response <strong>import </strong>Response<br><strong>from </strong>rest_framework <strong>import </strong>status<br><strong>from </strong>django.conf <strong>import </strong>settings<br><br>SLACK_VERIFICATION_TOKEN = getattr(settings, &#39;SLACK_VERIFICATION_TOKEN&#39;, <strong>None</strong>)<br><br><br><strong>class Events</strong>(APIView):<br>    <strong>def post</strong>(self, request, *args, **kwargs):<br><br>        slack_message = request.data<br>        <br>        <strong>if </strong>slack_message.get(&#39;token&#39;) != SLACK_VERIFICATION_TOKEN:<br>            <strong>return </strong>Response(status=status.HTTP_403_FORBIDDEN)<br><br><strong>        # verification challenge<br></strong>        <strong>if </strong>slack_message.get(&#39;type&#39;) == &#39;url_verification&#39;:        <strong>#</strong><br>            <strong>return </strong>Response(data=slack_message,                    <strong>#</strong><br>                            status=status.HTTP_200_OK)             <strong>#</strong><br><br>        <strong>return </strong>Response(status=status.HTTP_200_OK)</pre><p>What we are doing here is checking if the request is an url verification, if yes then relaying the same message back.</p><h4>Minute 11: The Greet Bot</h4><p>Lets code the greet bot, we will keep the logic simple. We are not going to use Natural Language Processing (NLP) for now, saving it for later. We will look for greet word “<strong><em>Hi</em></strong>” in user’s message if the word is found the bot will respond with a text like</p><p>In the Events API add following lines marked by <strong><em>#</em></strong></p><pre><strong>from </strong>rest_framework.views <strong>import </strong>APIView<br><strong>from </strong>rest_framework.response <strong>import </strong>Response<br><strong>from </strong>rest_framework <strong>import </strong>status<br><strong>from </strong>django.conf <strong>import </strong>settings<br><strong>from </strong>slackclient <strong>import </strong>SlackClient                               <strong>#1</strong><br><br><br>SLACK_VERIFICATION_TOKEN = getattr(settings, &#39;SLACK_VERIFICATION_TOKEN&#39;, <strong>None</strong>)<br>SLACK_BOT_USER_TOKEN = getattr(settings,                          <strong>#2</strong><br>&#39;SLACK_BOT_USER_TOKEN&#39;, <strong>None</strong>)                                     <strong>#</strong><br>Client = SlackClient(SLACK_BOT_USER_TOKEN)                        <strong>#3</strong><br><br><br><strong>class Events</strong>(APIView):<br>    <strong>def post</strong>(self, request, *args, **kwargs):<br><br>        slack_message = request.data<br><br>        <strong>if </strong>slack_message.get(&#39;token&#39;) != SLACK_VERIFICATION_TOKEN:<br>            <strong>return </strong>Response(status=status.HTTP_403_FORBIDDEN)<br><br>        # verification challenge<br>        <strong>if </strong>slack_message.get(&#39;type&#39;) == &#39;url_verification&#39;:<br>            <strong>return </strong>Response(data=slack_message,<br>                            status=status.HTTP_200_OK)<br><strong>        # greet bot</strong><br>        <strong>if </strong>&#39;event&#39; <strong>in </strong>slack_message:                              <strong>#4</strong><br>            event_message = slack_message.get(&#39;event&#39;)            <strong>#</strong><br>            <br>            # ignore bot&#39;s own message<br>            <strong>if </strong>event_message.get(&#39;subtype&#39;) == &#39;bot_message&#39;:     <strong>#5</strong><br>                <strong>return </strong>Response(status=status.HTTP_200_OK)        <strong>#</strong><br>            <br>            # process user&#39;s message<br>            user = event_message.get(&#39;user&#39;)                      <strong>#6</strong><br>            text = event_message.get(&#39;text&#39;)                      <strong>#</strong><br>            channel = event_message.get(&#39;channel&#39;)                <strong>#</strong><br>            bot_text = &#39;Hi &lt;@{}&gt; :wave:&#39;.format(user)             <strong>#</strong><br>            <strong>if </strong>&#39;hi&#39; <strong>in </strong>text.lower():                              <strong>#7</strong><br>                Client.api_call(method=&#39;chat.postMessage&#39;,        <strong>#8</strong><br>                                channel=channel,                  <strong>#</strong><br>                                text=bot_text)                    <strong>#</strong><br>                <strong>return </strong>Response(status=status.HTTP_200_OK)        <strong>#9</strong><br><br>        <strong>return </strong>Response(status=status.HTTP_200_OK)</pre><p>What we have done is</p><ol><li>Imported Slack Client package.</li><li>Retrived Slack Bot User Token from settings.</li><li>Created a Client instance to post bot response to Slack.</li><li>If event data is available in the received message, then process the message.</li><li>The message posted by bot to a channel will be received by the bot again as part of receipient. So the bot message must be ignored by bot.</li><li>If the message is from a user then process the event. Extract user id, channel id and the user message to bot. Then build the bot’s greet message with user name.</li><li>If the user message contains the greet word “<em>hi</em>”, then proceed with posting the greet message.</li><li>We are invoking Slack Client API to post the Bot response message to the channel via <a href="https://slack.com/api/chat.postMessage"><strong><em>chat.postMessage</em></strong></a><em>.</em></li><li>Once the message is posted return OK to the Slack event.</li></ol><p>Here a depiction of the bot logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*GTW6-bH1NI0-aM6GDHCoAQ.png" /></figure><h4>Minute 12: Tunneling with ngrok</h4><p>Now we need make our bot available in a public domain for Slack to make service calls. One way to do it in your local system is to user a tunneling service like <a href="https://ngrok.com/">ngrok</a>, go ahead and install <a href="https://ngrok.com/">ngrok</a> for you system.</p><p>Once you have setup ngrok</p><ol><li>Start Django server with command</li></ol><pre>python manage.py runserver 0.0.0.0:8000</pre><p>2. Use ngrok to bind your Django port to a public domain as follows</p><pre>ngrok http 8000</pre><p>ngrok will create a public URL and forward the requests to your server, you will see something like below on successful binding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqQTopvqEhBaTWvh6L2yeA.png" /></figure><p>To access your Bot API go to <strong><em>http://&lt;your-unique-id&gt;.ngrok.io/events/</em></strong></p><h4>Minute 13: Submitting URL to Slack</h4><p>Goto to <a href="https://api.slack.com/apps">Slack Apps dashboard</a> select your app and subscribe to events by giving the ngrok URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eGDillQG5zxreUxpWyE6OA.png" /></figure><p>Your URL should pass the verification challenge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*PVwIJC4yNQB1PeknFyLb1A.png" /></figure><p>Then scroll down to subscribe for channel message and direct message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*nlotvX5J135zQN1GUs9Jhg.png" /></figure><h4>Minute 14: Thats All Folks</h4><p>Your bot is up and running now, go ahead and say to it in Slack Chat.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=269c3a9bf64e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/freehunch/how-to-build-a-slack-bot-with-python-using-slack-events-api-django-under-20-minute-code-included-269c3a9bf64e">How to build a Slack Bot with Python using Slack Events API &amp; Django under 20 minute— Code Included</a> was originally published in <a href="https://medium.com/freehunch">freehunch</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>