Creating a Python Slack Bot — The Monkey Guide

CYE
CYESEC

--

Confession: I really like guides that spell things out for me. Monkey see, monkey do.

I like them because they allow me to focus on the real challenge I’m trying to overcome instead of the busywork or the configuration. So, I decided to create one that describes how to create a Slack bot in the most detailed and precise manner (which is more than anything I could find). Hopefully, it will save someone time.

Lead Submission Slack Bot

Like many companies, we at CYE encourage our employees to submit CVs of potential candidates — and reward them if the candidates are hired. This, however, created a problem as HR was bombarded with bits of information regarding candidates, which they had to then parse and feed into our candidate pool (sometimes finding out that the candidate was already there).

So, we realized that we needed a way to submit candidates for consideration that enforced a strict format. This format also needed to include the ability to check our candidate pool and notify the submitter if there was an issue. I went ahead and created a “PartyBot” (don’t worry about the name) for this. The main features included:

  • Enforcing a pattern for submission
  • Listing the position you are submitting for
  • Including the candidates’ LinkedIn profile URL
  • Checking the candidate pool and notifying the submitter
  • Querying extra information
  • Candidates’ CV file
  • Candidates’ phone number

Here is how we did it.

Important note: The app we’ll create here will run in Socket Mode. This mode is more appropriate for small and internal apps, which operate behind a firewall (which was the case for us) and not for production-grade public apps (e.g. the google calendar app). It also eliminates the hassle of defining request URLs for the app, so you can run the bot from anywhere, without a publicly exposed server, and it just works. Learn more about Socket Mode here.

Here we go.

Create App on Slack API

  1. Go to the Slack App API page and click the create app button
  2. Click “From scratch
  3. Give your app a name (this is how users will see it), pick the workspace where it will reside, and click Create App

Socket Mode

The first thing we’ll do is activate Socket Mode for the app. Under the Settings side menu; click Socket Mode, go down the Enable Socket Mode toggle and switch it to enabled. This will trigger the creation of an app-level token (which you will use later on). Give the token a name (app-token should be fine ;). Create a tokens.env file and copy the token into it like so SLACK_APP_TOKEN="<the app token>".

Features and Functionality

Go back to Basic information under the Settings side menu and click Add features and functionality.

You’ll now see the following menu for your app:

We’ll return to this menu for each of the following subsections.

Slash Commands

We’ll start by defining the Slash Commands which will allow users to better interact with the bot. We will define two commands:

  1. /partybot-submit [linkedin-url] [full name] — which starts the submission process
  2. /partybot-report— which shows what submissions were already made

Click Create New Command to add your commands. Don’t forget the Usage hint when needed.

Event Subscriptions

Now we’ll define the events that the bot will listen to. This allows interaction beyond the initial command format, so that the bot will be able to converse with the user. For our needs, it will allow us to ask them questions about the candidate they are submitting and notify them in case something is wrong (e.g., the candidate is already in our pool).

  1. Click the Enable Events toggle to On
  2. Go to Subscribe to Bot Events and click Add Bot User Event.
  3. Pick the message.im event which will allow us to know and read direct messages from users
  4. Save Changes

If you need to do more with your bot, just pick the required events.

Bots

This section allows you to modify your bot’s presence in Slack. You may want to enable Always Show My Bot as Online. We also clicked the “Allow users to send Slash commands and messages from the messages tab” checkbox.

Permissions

In this section, we define extra permissions we need for the app. Start by scrolling down to the Scopes section. You should see the im:history and commands permissions already there. We will also need the following:

  1. chat:write — which will allow the bot to send messages and chat with the users (not just receive)
  2. files:read — which will let the app to read the CV files being sent to it

In some cases, you will of course need to request approval from the workspace admin.

Now scroll up to OAuth Tokens for Your Workspace and click Install to Workspace.

Before we start writing code, go to OAuth & Permissions under the Features side menu, copy the Bot User OAuth Token into the tokens.env file like so SLACK_BOT_TOKEN=”<the bot token>”.

App Code

The whole app is available on Github. Here we will go over the code for the two commands we defined.

Show Submission Report

Let’s start with the easier command, showing all the submissions made so far. We start handling it by ack()ing the command so the user knows we received it, and retrieving the submitter’s user name and id from the received command.

We iterate over all finished submissions for that user which are saved in done_submissions_by_user[user_name]. From each submission we take the candidate name and add it to the result which is saved in submissions (by position):

Lastly we dump the result into a yamlformat (because we’re too lazy to format it with the markdown 😃) and send it back to the user:

Submit a Candidate

Now we move to the more complex command of submitting a lead. We start out by ack()ing the command and checking that the input isn’t too long (because we have a lot of hackers in the company that are bound to try things, and we don’t want to get caught off guard 🥴):

Next we extract the URL and lead name from the command (URL requires some special handling due to how Slack sends it to the bot):

Then we check for corner cases that prevent submission:

Then we create a unique token for the submission and link it to the user submitting. We continue the conversation to get more details about the lead using client.chat_postMessage(). Later on when we receive answers, we’ll retrieve the submission (and finalize it) from current_token_by_user_id[user_id].

And that’s it! That covers the main gist of things. See the code for more information.

Thanks for reading and enjoy your new Slack bot!

Dr. Nimrod Partush — ​ Combining years of AI research experience with deep knowledge of the cybersecurity domain, Dr. Partush leads the Data Science Department at CYE. His background includes both practical hands-on experience gained from serving in an elite IDF cybersecurity unit and academic experience amassed through his Ph.D. in Computer Science at the Technion.

--

--

CYESEC
CYESEC

Published in CYESEC

For more current and technical security insights be sure to follow CYE on Twitter and LinkedIn where you can keep up-to-date with the latest news, findings and happenings in the cyber security world.

CYE
CYE

Written by CYE

CYE’s elite team of experts bring an insightful look into the most topical cyber trends.