Create a Slack Bot with NodeJS and Slack Bolt API

Create a Slack Bot with NodeJS and Slack Bolt API

A Step by Step beginner's guide

Introduction

For developers, creating something using API that will automate our boring tasks is always a matter of excitement. And using Slack Bolt API we can make a bot for such boring tasks in Slack.

In this article, we will make a Slack Bot using Slack Bolt API and NodeJS and will also add some functionalities.

Excited right?

Me too :)

So let’s dive into it!

Keep It Going Lets Go GIF by The Tonight Show Starring Jimmy Fallon

What is Slack?

slack

Slack is a popular communication platform used by many organizations, businesses, and development teams.

If you explore Slack, you will see that it has Slack Bot which helps to streamline workflows and enhance team collaboration through automated processes.

Now let’s answer the most common question: What are the prerequisites for making a Slack Bot?

Prerequisites

  • NodeJS and NPM installed on your machine.

    For reference, you can check my blog: All About NPM.

  • A basic understanding of JavaScript and NodeJS.

With these, you are all set to go for this project!

thumbs up GIFs | Tenor

Project Setup

Here we will be discussing the steps to install a bot app in a Slack workspace.

At first, we will create a new workspace and then we will create a new Slack app for this workspace.

Create a new Slack workspace

We will go through the following steps to create a new Slack workspace

  1. Visit the Slack website.

  2. Click on Create a new workspace.

  3. Now enter your email address.

  4. Follow all the instructions and steps to create a workspace.

  5. You can now create channels, and invite team members in your newly created workspace. You can also send direct messages.

I have created this workspace named Personal_Server for which I will create the Slack bot.

Personal_Server

Note: You can also go with any existing workspace without creating a new workspace

Create a new Slack app

We will be following the following steps to create a new Slack app i.e. our Slack bot

  1. Go to the Slack API website.

  2. Now, click on Your Apps.

    Slack API Website

  3. Next click on Create New App.

    Create New App

  4. Click on From Scratch.

Now give the app name, pick up the workspace you recently created, and then click on Create App.

Note: You can also select any existing workspace without creating a new workspace

Create workspace

  1. Now you will be redirected to the App credentials page.

  2. You need to set permissions before your app starts communicating with your Slack. For this, go to the OAuth and Permissions page and scroll down to the scopes part.

    Now, add the following scopes.

    Scopes

    Okay! Want to avoid a future bug? Then also enable the chat:write scope.

    scope

  3. In the left sidebar, Go to Settings → Install apps → Install to workspace.

    You will get the Bot User OAuth Token!

For now, let’s leave this Slack API page and now let’s do our server setup with NodeJS.

Slackbot Server Setup

We need to configure a server for Slackbot that can handle requests sent to Slackbot. So now it’s coding time!

Create a directory with the name SLACK-BOT and initiate the npm:

mkdir SLACK-BOT 
cd SLACK-BOT
npm init -y

Note: -y answers all the questions of setting up by itself.

Now we need to install the following packages:

  • slack/bolt - Used to connect Slack to the Server.

  • dotenv - Used to store API Keys and Database Passwords.

  • nodemon - It is used to run the server.

To install these packages run the following command

npm i @slack/bolt dotenv nodemon

Now, nodemon helps you prevent restarting the server whenever you make any changes. It restarts the server automatically on changes.

Write the following command for nodemon setup in your package.json file.

nodemon setup

Create an app.js file under the root directory which will serve as the main starting point of our project.

Authentication of the Bot with Tokens

Now comes the Authentication part. Before communicating with the bot, Slack first needs to verify your bot with SIGNING_SECRET and a BOT_TOKEN.

Both are stored in .env file so that they are not exposed on GitHub.

Now how to get the SIGNING_SECRET and a BOT_TOKEN?

SIGNING_SECRET → Go to the basic information page and there you will get the signing secret.

Singing Secret

BOT_TOKEN → Go to the OAuth and Permissions page and there you will get the OAuth token.

OAuth Token

Now, create a .env file under the root directory where you will store the Signing secret and OAuth token which will not be published on GitHub.

SIGNING_SECRET="YOUR SIGNING SECRET"
BOT_TOKEN="YOUR BOT TOKEN"

Server Setup

Now, write the following code in app.js file.

const { App } = require("@slack/bolt");
require("dotenv").config();
//Initializing the app with tokens
const app = new App({
  token: process.env.BOT_TOKEN,
  signingSecret: process.env.SIGNING_SECRET,
});
(async () => {
  const port = 3000;
  await app.start(process.env.PORT || port);
  console.log("Bolt app started!!");
})();

Now, run the command npm run dev and you will get the following message in the terminal.

Terminal message

This indicates everything is on point till now!

Now, the biggest question is How will the server and Slackbot communicate?

Let’s dive into that.

How will the server and Slackbot communicate?

Slack has a feature called socket mode that allows Slack to use the WebSockets to connect to your application server.

  1. Go to Settings → Basic Info → App Level Tokens.

  2. Click the Generate Tokens and Scopes button.

  3. Give your token a name and allot your app two available scopes:

    • connections:write

    • authorizations:read

Generating app level token

Click the Generate button. Then copy the APP_TOKEN from the next page and put it in .env file.

Now, the .env file looks like this

SIGNING_SECRET="YOUR SIGNING SECRET"
BOT_TOKEN="YOUR BOT TOKEN"
APP_TOKEN="YOUR APP TOKEN"

Next Go to SettingsSocket Mode and enable the “Enable Socket Mode” switch.

After that update the app configuration in the app.js file with socketMode:true and your appToken.

The app.js file will now look like:

 const { App } = require("@slack/bolt");
require("dotenv").config();
const app = new App({
  token: process.env.BOT_TOKEN,
  signingSecret: process.env.SIGNING_SECRET,
  socketMode: true,
  appToken: process.env.APP_TOKEN,
});
(async () => {
  const port = 3000;
  await app.start(process.env.PORT || port);
  console.log("Bolt app started!!");
})();

On running the file, you will see something like this on your terminal.

Terminal message

Adding Functionality

The setup is more or less done. Now it’s the time to add the functionality and make our Slackbot work in real.

Excited?

So let’s do it together!

Replying to a Message:

In Slack, you can send messages to the bot by mentioning the bot using @Bot_name (for me it’s Personal_Bot).

In Slack, app mentions are an event. You can also listen to other events like when a new user joins a channel, a new channel is created, etc. To allow your bot to listen to events, you need to set up an event subscription.

Click the subscribe to bot events dropdown menu and add the following events.

Events

And then click on Save Changes located at the end of the page.

If it asks to reinstall the app, then do reinstall it.

Now we will write code to see if the app responds correctly to a message that it receives.

Add the following code to the app.js.

app.message("hello", async ({ message, say }) => {
    try {
      say(`Hello <@${message.user}>!`);
    } catch (error) {
        console.log("err")
      console.error(error);
    }
});

According to the above code, app.message is used to define that the app will respond with a “Hello @ username “ to a “hello“ message if sent.

But there’s still a problem. You will see the message like “You can’t send message to this app” when you click on the bot in the Apps tab of Slack. To resolve this, turn the feature on!

Now go back to the App settings page.

Then go to App Home under features. Now scroll down to Show Tabs section. Scroll down and check the box with allow users to send slash commands and messages from the Messages tab.

Show Tabs

Now, reload Slack using the ctrl + r command.

Try sending a message like @ Personal_Bot hello and you will see it will respond with Hello @Olibhia Ghosh.

message

Taking a real situation the message cannot be exactly the same as we provide. For that, Slack allows us to use regex expressions where the bot can respond to a message that contains a keyword or some part of it.

app.message(/hi/, async ({ message , say }) => {
    try {
      say(`Hello <@${message.user}>!`);
    } catch (error) {
        console.log("err")
      console.error(error);
    }
});

If you send any message like hi personal bot, the bot will respond as it contains the word hi in it.

Bot message

This was all about how I built my Slack Bot. You can add more features by referring to the Slack Bolt API Documentation.

Here’s the link to the source code of the Slack Bot I made : GitHub Repository.

Conclusion

I hope you’ve built your first Slack Bot by following this step-by-step guide. Now keep on exploring the API and adding more functionalities to your chatbot to enhance its functionalities.

I hope I made it simple for all.

If you found this blog useful and insightful, share it and comment down your views on it.

Do follow for more such content.

Here's how you can connect with me.

Email - olibhia0712@gmail.com

Socials: Twitter , LinkedIn and GitHub

Thanks for giving it a read !!

Thank you