Black Lives Matter.

Build a Slack Bot!

Bots are taking over the world, and you can too! (on Slack of course)

Fri Nov 13 2020

🤖 Bots are taking over the world, and you can too! (on Slack of course).

Over the last few weeks, I was tasked at work to build a Slack bot to improve our bug reporting workflow. As it stood, folks would report a bug in one of our Slack channels, a dev or a manager would gather more information and ask questions, then they'd create a ticket in JIRA for it to be actioned on.

How could a bot help with this? Automation!

The idea for the bot would be to allow users to type a slash command that opens up a form asking specific questions about the bug. Once submitted, the form would gather up the questions, and create a ticket in JIRA automatically. Then just post the link to the ticket in the Slack channel.

Nothing too fancy, but a minute saved here, a minute saved there, adds up to hours.

Today, I'll be diving into how you can get started building your very own bot. You'll learn:

  • Where to start and what tools your can leverage
  • Getting around the quirks you'll likely run into
  • Deploying your bot
  • Testing it out


🏁 Ready, set, go!

STEP 1 Setup Project Scaffolding

I'm not a fan of reinventing the wheel, and believe that to move fast you should leverage tools and services that are already out there. So long as whatever you are leveraging allows for flexibility. This is where BOTKIT comes into play.

Think of Botkit as a big ole' tub of Legos (that you always wanted for Christmas). They are an open source tool allowing devs to get to building super quickly.

✔️ Steps to take now:

1 > Botkit has a base template you'll need to clone. Via the command line, run this in a directory where you keep your code: npm install -g yo generator-botkit

2 > When you run this command, you'll get asked a few questions:

  • What is your bot's name? (anything you want here)
  • Which messaging platform? (select Slack)
  • Mongo URI (ignore for now)
  • Client signing secret (ignore for now)
  • Single-team or multi-team (select single)*
  • Bot token (ignore for now)

* With regards to single-team vs multi-team: for this demo, select single-team to follow along. However, if you ever decide to create a bot you want to sell, then multi-team is the option you want.

5 > After you've answered all the prompts, Botkit will go ahead and create the scaffolding for your project. Let's go ahead an open up the project in your favourite editor.

CHECK-IN: You should have your project files downloaded.

STEP 2 Early Deployment

We're going to do things a bit backwards here, but you'll see why here shortly.
Now that you've got your project files all in one spot, let's get them saved in a repo up on Github, or wherever you like to store your code.

Once you've setup your repo, we'll need to get it deployed. For this example, and ease-of-use, let's go with Heroku.

✔️ Steps to take now:

1 > Initialise a new git repository and push up your project files

2 > Create a new app on Heroku and connect it to your Git repo.

3 > Under deploy settings, run a manual deploy.

4 > Once deployed, click "Open App". This will give you a production URL you will need for the next steps.

If you're having trouble with Heroku, there documentation is pretty good. You can also just send me an email :) 

CHECK-IN: At this point your base project file should be deployed, and you should have the URL to your hosted project.
STEP 3 - Configure your environment variables

Now that your base project is deployed, let's get back into the code. With your editor open to your project files, go ahead an open up the bot.js file. You're going to see a lot of boiler plate, but the most important area to focus on right now is the SlackAdapter. The adapter is where you'll need to set all of the configuration variables for your Slack app:



As you can see from the screenshot above, I've got everything setup using environment variables. Although not required to do start developing locally, It's best practice to add these values to a .env file, and set them up on whatever service you decide to deploy to (more on this later).

However, before you can actually set these values, you'll need create them! This is where it can get a little confusing, as there was no documentation that took me step by step of where I needed to go to configure these settings. I recommend as soon as you setup a variable, go into your code and paste into your .env file so you don't lose track of what you've done.

✔️ Steps to take now:

1 > Visit the Slack app API site (https://api.slack.com/apps), and click "New App":

  • Give your app a name
  • Select the workspace where you want this app to live
  • Click "Create app"

2 > You then get brought to a screen to setup permissions under "Basic Information". Under "Add features and functionality", click on each box and follow these steps:

Interactive Components – Should be toggled on. Set the request url to <YOUR-HEROKU-URL>/api/messages

Slash Commands – Click create new command. This will be what we use to trigger the bot in Slack. Set the form fields to these values:

  • Command: /test
  • Request URL: the exact same one you've been setting <YOUR-HEROKU-URL>/api/messages
  • Short description: Testing a bot
  • Click Save

Event Subscriptions – Should be toggled on. Set the request url to the same as you did in the step before. Directly below the url field, you'll see a panel to "Subscribe to bot events". Add Bot User Events for the following: 

  • message.channels
  • message.groups
  • message.im
  • message.mpim


You'll see two other boxes "Bots" and "Permissions". This is where the documentation gets strange on Slack and Botkits side, and one of those quirks you'll run into. Before you can set these up, you'll need to have OAuth and Permissions setup first.

3 > In the left side menu, click on "OAuth & Permissions"

4 > You'll see an option to install you app, but it should be disabled, as we'll first need to add Redirect URLs and scopes (which the bot will use)

5 > Under Redirect URLs add the following two:

  • <YOUR-HEROKU-URL>/install/auth
  • <YOUR-HEROKU-URL>/oauth

6 > Under Scopes, you'll see a section for "Bot Token Scopes". Add the following OAuth scopes:

  • app_mentions:read
  • channels:history
  • chat:write
  • commands
  • groups:history
  • im:history
  • incoming-webhook
  • mpim:history

7 > With your redirects set, and scopes added, you can now scroll to the top of OAuth & Permissions and click to "Install App to Workspace". Once you click, you'll see your app requesting the permissions you outlined in the scope. Click allow.

8 > After installing, you'll be redirected right back to OAuth & Permissions. Except this time, you should see a section at the top called "Tokens for your workspace", along with a "Bot User OAuth Access Token". Hooray! 🎉 Go ahead and jot that down somewhere. We'll use it to configure out environment variables.

9 > To verify everything is setup correctly, go into your Slack workspace and type the slash command "/test". You should see it as a suggested command in the list via your new app. (Note - it will not work yet)

10 > We're not done yet! The next step is to add all of our environment variables to Heroku! From your Slack app's "Basic Information" page, scroll down to "App Credentials". You'll see items for your App Id, Client Id, Client Secret, etc.

11 > Open a new tab or window, and visit your Heroku dashboard. Click on settings, and scroll down to Config vars. Using the values from your Slack App Credentials, add the following environment variables to Heroku:

  • BOT_TOKEN (the value taken from step 8)
  • CLIENT_ID (from the Slack app credentials dashboard)
  • CLIENT_SECRET (from the Slack app credentials dashboard)
  • CLIENT_SIGNING_SECRET ("signing secret" from the Slack app credentials dashboard)
  • VERIFICATION_TOKEN (from the Slack app credentials dashboard)

12 > Okay, last step I promise! Next you'll need to go back into your code in the bot.js file and configure the following properties with your new environment variables. This is pictured at the beginning of this section. However, for easy copy and paste:

const adapter = new SlackAdapter({
// parameters used to secure webhook endpoint
verificationToken: process.env.VERIFICATION_TOKEN,
clientSigningSecret: process.env.CLIENT_SIGNING_SECRET,
// auth token for a single-team app
botToken: process.env.BOT_TOKEN,
// credentials used to set up oauth for multi-team apps
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
scopes: ["bot"],
// for use in multi-team apps
getTokenForTeam: getTokenForTeam,
getBotUserByTeam: getBotUserByTeam,
});

CHECK-IN: At this point, your bot should have the permissions it needs, you should have the /test slack command created, your app installed to your workspace, and your environment variables added.


STEP 4 - Create the brain for your bot

Wow that was a lot. It should go much smoother than it did for me. There was literally zero step by step directions when I first went through this.

Next up, let's get our Bot doing something. We'll keep it simple, as the point of this tutorial is just to show you how to get it up and running.

Inside your code, you'll see a folder named features. These files that are scaffolded up for you are the brain for your bot. There are a few good examples in there, but for our simple use case, let's create one from scratch to help you better understand what is going on.

For sake of brevity in the newsletter and code formatting sucks, I've added the file to a gist with a ton of comments. Feel free to copy and paste to get something up and running.

✔️ Steps to take now:

1 > Grab the content from this gist, and paste it into a new file under features call test-bot.js 

2 > Read through the comments to make sure you understand what is going on.

CHECK-IN: At this point, you should have create a new file containing the contents of the gist, pasted into the features directory in your code.

STEP 5 - Test your bot!

We're almost there! Just a few more steps.

✔️ Steps to take now:

1 > You'll see in the code example, the bot will post the dialogue response to a channel called #slack-bot-test. Make sure you create that channel in your workspace and invite the Slack bot to it. This will give it permissions to post.

2 > With your new file added, let's go ahead and push those changes up to Github.

3 > Once your changes are pushed, go back to Heroku and run a manual deploy.

4 > After a few minutes you should be able to go into your app and run the `/test` command. Once you submit, a dialogue should appear asking for your name. Fill out the details and submit the form. Voilia! You should see the bot posting into the channel.

We're just scratching the surface

Bots can be a lot of fun, and really the most complicated part is just setting them up on Slack. If you found this valuable or want to learn more, let me know and I can do a more in-depth video deep dive!

Again, thank you all for taking the time today.

As always, if you like what I'm doing here, please share!

Cheers,
Christian

Thanks for tuning in,

Enjoyed the content?