Codementor Events

Creating a Slack Bot Using Node.js

Published Jan 24, 2017
Creating a Slack Bot Using Node.js

This tutorial was originally posted by the author on his blog. This version has been edited for clarity and may appear different from the original post.


When I first came across bots when I was using Slack and HipChat, I ignored them without ever giving them a thought. I recently attended a local JavaScript group and our team exercise was to build a Slack Bot. This opened my eyes and I finally understood all the hype surrounding bots — trust me, I'm not the only one talking about bots.

The bot that we're going to talk about in this tutorial knows how to find recipes for the list of ingredients you provide it with. It will perform a Google search for recipes once it's been given a list of ingredients. Since I like to code, I thought I'd share how I did it here.

Creating the bot in Slack

In order to create the integration and generate the API token, you must log in to your team and be an administrator. You will also be able to name the bot you created:

slack bot

Once you've finished naming your bot, you must fill in API token in order to write the code later on. You can also give the bot an emoji, upload a picture, and customize your bot a little on this page:

slack bot

Now, for the code...

First, I'll be using the Botkit and Google packages — these can be installed with:

`npm botkit google --save`

    'use strict';
    var Botkit = require('botkit');
    var google = require('google');

    var controller = Botkit.slackbot({
        debug: false
    });

    // connect the bot to a stream of messages
    controller.spawn({
       token: '<insert here>',
    }).startRTM();

    controller.hears('hello',    ['direct_message','direct_mention','mention'],function(bot,message) {
        bot.reply(message,'Hello yourself.');
    });

I will be using the API token from image 2 for the token.

So what's going on here? We are requiring in the Botkit package and then creating a controller (or you can think of the controller as the bot).

We will then tell the controller to create a connection with our token and listen for messages. The controller will listen for a message with hears(). Hears takes two arguments and a callback.

The first is what to listen for - 'hello' - and the second is an array of types.

The bot.reply() will send a message back to the requesting stream.

Wrapping up

With the bot essentially being a Node.js app, the scope of what it can do is as wide as what you would expect of a Node.js app. What I'm trying to say is that this bot is a pretty strong app!

Here is a link to HestonBlumentBot, which is a fun way to find a recipe with any ingredients that you currently have.

For a related post, you can also check out this Telegram chatbot tutorial.

Discover and read more posts from Dominic Scanlan
get started
post commentsBe the first to share your opinion
Show more replies