Contact Us

Create a Slackbot in under 10 minutes using Node.js

Chatbots — they’re cool, fun and useful virtual assistants to have. In this tutorial, we’ll build a basic ChatBot that can reply to queries via Slack. We’ll be running this on our local machine and to make it even simpler, we’ll be leveraging an awesome tool called Botkit which will do most of the heavy-lifting for us.


Setting Up

Create an empty folder for your project, let's name it testApp.

Run the code – npm init -y
This command quickly generates a package.json file.

Once that’s created, run the following commands – npm install dotenv
and npm install botkit
The first package adds support for environmental variables in your Node project and the second package adds the botkit tool to your project.


Adding Bots to Slack app





Coding the SlackBot

Create a .env file inside the “testApp” folder created earlier, open it up in your editor and add your API token in it. My file looks like this:


Create an index.js file inside the same folder and open it up in your editor. Write down the following code. I've commented it so you can understand what's going on with each line:

// Add support for environmental variables

// Import botkit package
var Botkit = require('botkit');

// Create a controller for the Slackbot
var controller = Botkit.slackbot({
  debug: false

// Use the token to connect the bot to your Slack app
  token: process.env.TOKEN

// Determine behaviour of the Slackbot
controller.hears(['hello', 'hi'], ['ambient', 'direct_mention', 'mention'], function (bot, message) {
  bot.reply(message, "Hello.");

Let’s try and decode the last bit of code. FYI, this is where all the magic happens. We’ll breakdown the function hears into 3 parts:


The triggers aren’t exact matches, so if the combination of letters occurs, the bot will fire the function. You can use regex if you’d like exact matches.

The context basically means where the bot heard the message. Was the bot mentioned or did someone send the message in a channel? The list of options to choose from are:

Are you excited to see your Slackbot in action? Let’s find out together.


Lights, camera, Slackbot

If everything went well, you should see it online in the sidebar under Apps.


Bots are shy, so you need to invite them your channel. Try inviting your bot to the general channel with the /invite command in Slack. In my case I had to write: /invite @robobot

Now fire up your command line and run the node app.


Let’s send a “Hi” message in the general channel.


Well done – you’ve successfully built a Slackbot that’s capable of replying to certain trigger words. Now you can add more complex logic to the bot and get it to do much more than just saying Hello. The possibilities are endless. Thank you for reading!

Get the code

All the code for this tutorial is available in the Slack Node.js Tutorial Github repo