The Slack Bot Tutorial I Wish Existed

Open a DM with it and say, “hi.

” You’ll know it’s working when the bot replies.

Slash commandsSlash commands are probably one of the coolest features you can implement with Slack.

The possibilities are endless as to what you can achieve with them.

Let’s get into it.

In your code, add the following.

controller.

on(‘slash_command’, function(bot, message) { // LOGIC GOES HERE}This is a catch-all command.

It will listen for ALL slash commands in your application.

However, if you were to go DM your app right now, this would not work.

We’ll get into it later, but first you’ll have to add the slash command to your app as well as acceptable URLs that your Slack App recognizes.

The full slash command listener will end up looking something like this:controller.

on(‘slash_command’, function(bot, message) { bot.

replyAcknowledge() switch (message.

command) { case “/echo”: bot.

reply(message, ‘heard ya!’) break; default: bot.

reply(message, ‘Did not recognize that command, sorry!’) }}This was a HUGE gotcha for me.

Slack slash commands require a response within 3000 milliseconds or else the user will see a timeout error.

bot.

replyAcknowledge() solves for this.

The switch statement listens for the various slash commands that you can set up in your application.

Before we can test these commands, we’ve got to set up some acceptable URLs that Slack will recognize.

Localhost is okay for testing listeners, but for slash commands we’ll need an HTTPS URL.

We’ll start by generating HTTP ports using ngrok.

Using ngrokStart by following official install instructions.

Run .

/ngrok http 8765This generates a URL that will look something like this: http://xxxxxx.

ngrok.

ioNow that we’ve got a temporary URL, let’s set them up in our Slack App.

Authenticating your new URLFrom the main page, navigate to OAuth & Permissions.

Here you’ll find ‘Redirect URLs’.

Add your newly created URL like so: http://xxxxxx.

ngrok.

io/oauthIn another tab, navigate to http://xxxxxx.

ngrok.

io/loginYou should redirected to a blank page that says, “Success!” If not, time to debug.

Double-checking your environment variables would be a great place to start.

Create a new slash commandFrom the main Slack App page, navigate to Slash Commands.

Click ‘Create New Command’.

Under command, write: /echo (this is what we named our command earlier)Under Request URL, write: http://xxxxxx.

ngrok.

io/slack/receiveSave.

Let’s test it!.Back in your Slack workspace.

Go back into your DM with your app and write /echo.

If your bot responds, you’ve set it up correctly.

Interactive webhooksInteractive webhooks are needed to post to specific channels from your application.

A possible scenario is if you don’t want the bot to respond directly to you, rather having the response posted to a shared channel across your team.

From your Slack App main page, navigate to incoming webhooks and turn it on.

Click ‘Add New Webhook to Workspace’ to generate a webhook for a channel in your workspace — any channel will do!Choose a channel it can post to and ‘Authorize’.

Copy that URL and add it to the your bot definition like this:var bot = controller.

spawn({ token: process.

env.

BOT_TOKEN, incoming_webhook: { url: 'https://hooks.

slack.

com/services/xxxxxx/xxxxxxxx/xxxxxxxx' }}).

startRTM();Great, we’ve set up an incoming webhook!.Let’s see it in action.

Start by adding a new listener.

controller.

hears('webhook', 'direct_message', function(bot, message) { bot.

sendWebhook({ text: "Hey we've got the webhook!" },function(err,res) { if (err) { console.

log('web err', err) } });});Test it by typing webhook in the your app’s DM channel.

Did the webhook post to the appropriate channel?.Yes?.Good job!What if you want to dynamically update the webhook URL based on the user’s response?.You would have to update your bot’s configuration.

We’ll do a simple one using an if statement.

Start by generating a new webhook to a different channel.

Update webhook listener to listen to multiple words by swapping ‘webhook’ out for [‘webhook’, ‘webhook2’].

Add an if statement to the method block of code.

if (message.

text == 'webhook') { bot.

config.

incoming_webhook.

url = [YOUR_NEW_WEBHOOK] } else { bot.

config.

incoming_webhook.

url = [YOUR_OLD_WEBHOOK]}The full listener will look something like this:controller.

hears(['webhook', 'webhook2'], 'direct_message', function(bot, message) { if (message.

text == 'webhook') { bot.

config.

incoming_webhook.

url = 'https://hooks.

slack.

com/services/YOUR/NEW/WEBHOOK' } else { bot.

config.

incoming_webhook.

url = 'https://hooks.

slack.

com/services/YOUR/OLD/WEBHOOK' } bot.

sendWebhook({ text: "Hey we've got the webhook!" },function(err,res) { if (err) { console.

log('web err', err) } });});Test it out by DM’ing your app webhook & webhook 2.

Does it post to multiple channels based on the text?.Great.

You’ve set it up correctly.

DeploymentIt’s time to deploy the application so it’s live and ready to use!.We’ll be deploying our application to Heroku.

Specify your node version in the package.

json file.

"engines": { "node": "8.

x" },2.

Add a start script.

"scripts": { "start": "node index.

js", "test": "echo "Error: no test specified" && exit 1" },3.

Run heroku create from your command line inside the root of the project.

Heroku will give you a temporary URL for your project.

Save it.

Make sure you have the Heroku CLI installed, then run heroku login to authenticate.

³4.

Add your environment variables to Heroku.

In the Heroku online dashboard, find your new project.

There should be a tab across the top that says, ‘Settings’.

Heroku dashboard tabs.

Under the settings you’ll see ‘reveal config vars’ — add all of the variables from your .

env file.

5.

Update all of the URLs in your Slack App dashboard.

This means updating the Redirect URL AND the slash command URL prefixes to be the Heroku-generated URL.

6.

Authenticate.

Navigate to YOUR_HEROKUAPP_URL/login to authenticate your app with Slack.

Test out your commands in Slack.

If it works, you’re good to go.

A note on deployment: when your Heroku app is using a free plan, your Heroku application will fall asleep after 30 minutes of inactivity.

As a result, you’ll start to get a 500 error.

To fix that, you’ll need to upgrade to a paid plan or manually re-authenticate by navigating toYOUR_HEROKUAPP_URL/login.

That’s it!.The makings of a bare bones Slack bot.

A lot of the functionality that we’ve introduced were once stand-alone integrations that you’d add into your Slack workspace one-by-one.

With the Slack App, you can bundle all the features into one application.

This saves time and makes it super easy to find all the information you need to get your bot up and running!I hope this tutorial was helpful for you!.If you have any burning questions, feel free to comment or message me directly.

Happy bot hacking!About the AuthorHi all, I’m Faye!.Finally making my official entrance into Green Room.

I met Arlan on Twitter and I joined the Backstage Capital Crew shortly after in January 2018 as a software engineer.

I get to work on tools and projects that primarily benefit our team and Headliners (portfolio companies).

In addition to working with Backstage, I co-founded a startup called PlayLoops, a GIF engine that enables progressive organizers to run efficient digital campaigns.

ResourcesTutorial source code: https://github.

com/fhayes301/slackbot-example-appDotenv: https://github.

com/motdotla/dotenvBotkit: https://github.

com/howdyai/botkitHeroku CLI: https://devcenter.

heroku.

com/articles/heroku-cli.

. More details

Leave a Reply