I was recently admitted into the University of Maryland, College Park (UMCP) as a graduate student in the M.Eng. Cybersecurity program. I was also admitted into Johns Hopkins University (JHU) Security Informatics (MSSI) program. I chose not to attend JHU for various reasons but I did end up in their WhatsApp group. It was here that I was exposed to Slack.
While I was working at NetApp, other developers and QA engineers used HipChat. I'd never heard of Slack before. So, once I read about it (HipChat and Slack are basically enterprise level IM apps) I immediately created a Slack workspace (basically similar to WhatsApp groups but bundled with many more features like channels, bots, etc.) and requested my fellow UMCP classmates to join. At NetApp, I worked primarily with test automation, so of course building a Slack bot came naturally as a must-do micro-project. Without further digress, let's begin!
While I was working at NetApp, other developers and QA engineers used HipChat. I'd never heard of Slack before. So, once I read about it (HipChat and Slack are basically enterprise level IM apps) I immediately created a Slack workspace (basically similar to WhatsApp groups but bundled with many more features like channels, bots, etc.) and requested my fellow UMCP classmates to join. At NetApp, I worked primarily with test automation, so of course building a Slack bot came naturally as a must-do micro-project. Without further digress, let's begin!
Setting up and installation of the Slack app
What is the purpose of this bot?
I'm a new graduate student and naturally I was looking at the courses being offered this Fall. My fellow classmates were too. Any time someone would ask about a course, another would copy-paste the course description from Testudo in the WhatsApp group. Looks quite manual doesn't it? Automation to the rescue!
What's in a Name?
Naming anything is an insane task. It must sound good, reflect its purpose, etc. Finding names for stuff is not my forte, so I decided to go with Course Descriptions Bot. Coursedesc in short.
How do I create a Slack App?
Visit: https://api.slack.com/apps?new_app=1 Once you do, you'll be greeted with the Create a Slack App interface. Fill in the two fields and click on Create App.
On the next page,
- Click on Bot Users in the left column.
- Click on Add a Bot User.
- Fill in the two fields.
- For better usability, it is preferable not to show your bot as online always.
- Click on Add Bot User.
Now that you're done setting up the identity of your app, we need to install it in the workspace. Click on Install App in the left column. Then click on Install App to Workspace.
Click on Authorize.
On the next page, we have very important information. Take special note of Bot User OAuth Access Token. Do not share these tokens with the world. For more information on auth tokens, read the documentation of token types: https://api.slack.com/docs/token-types#bot
That's it! You're now ready with a brand new Slack App. The next step is to code the daemon which will connect with our app.
Programming the bot
Slack Client
Remember the Bot User OAuth Access Token we noted before? We need that here to create a slack client object.
from slackclient import SlackClient
slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))
Slack Real Time Messaging (RTM) API
Slack's RTM API enables us to receive events and send simple messages to Slack in almost real-time. The first step is to connect with our app:
slack_client.rtm_connect()
The above function call returns True if the connection was successfully established and False if otherwise (also results in a SlackLoginError exception).
Authentication
Now that we are connected to our app, the next step is to authenticate ourselves using the auth.test() method:
course_desc_bot_id = slack_client.api_call("auth.test")["user_id"]
The response of auth.test() is a Python dictionary which contains keys like url, user_id, user, etc. Here we'll extract the user_id. We'll use this later to check if a Slack message was sent by a user or our bot. To read more about the auth.test() method, visit https://api.slack.com/methods/auth.test
Reading events/messages sent to Slack
When we send a message to Slack, our bot will read it to determine if it is addressed to it. It will reply only if so. To read a slack event, we'll use the rtm.read() method
slack_client.rtm_read()
On successful connection (and authentication), the first event will be a simple hello message
[{u'type': u'hello'}]
When you send a message to Slack, the daemon receives an event:
[{u'client_msg_id': u'86e18aef-ac7c-4968-983c-a1a943c1c6f5', u'event_ts': u'1530900342.000367', u'text': u'<@UBHK5HHLH> help', u'ts': u'1530900342.000367', u'user': u'UBJ6NTCNT', u'team': u'TBGJ88997', u'type': u'message', u'channel': u'CBHUMNB9A'}]
The ones of interest here are the type of event, the channel from where it was sent and the text that was sent. Our bot should respond only in the case of a message event type and if it was addressed directly. To verify this, we'll use the values of type and text (a part of it). At the same time, we'll also extract the channel from where it was sent and the message text as well (in this case, help).
We have the command. Now what?
As far as the purpose of this bot goes, the code is written to handle only two scenarios:
- The student asks for a list of courses available for the term
- The student asks for the description of a specific course
In both cases, we'll be scraping the Testudo website for information.
Once we have our information, our bot will send it to Slack, through an API call, on the same channel where the message was initially received.
slack_client.api_call(
"chat.postMessage",
channel=channel,
text=course_description
)
How often to check for Slack events?
There is no fixed answer to this. The more number of times you check, the more resources you use. The RTM API is not recommended to be used by large teams. In our case, we check for events every one second.
Demo
We have a bot that is operational at this moment. However, there is development pending - most of them future enhancements. To take a sneak-peek, visit my GitHub repo: https://github.com/nikhilh-20/slack_bots
Here's a 1:14 minute demo:
That's it! You should have a live working Slack bot ready to make life easy for you!






This is awesome manh !
ReplyDeleteThanks for reading!
DeleteWonderfully written brother.. highfives
ReplyDeleteThanks for reading!
DeleteWonderfully Crafted!
ReplyDeleteThanks for reading!
Delete