Create slackbot using slack bolt API and Node.js
Slack
Slack is a popular team communication tool that offers a variety of integrations and extensions to simplify your team’s workflow. One such extension is the Slack Bot, which helps automate tasks and make communication more efficient.
In this tutorial, I’ll show you how to create a Slack bot using Bolt, Slack’s library for building Slack apps with node.js which can interact with your message.
Prerequisites:
Before we get started, make sure you have the following:
· Node.js v12 or higher installed on your machine
· npm installed on your machine
· A basic understanding of JavaScript, Node.js
Steps To install the bot in a workspace
Create a new Slack workspace
To create a Slack workspace follow below steps —
1. Visit the Slack website and
2. Click on Create a new workspace
3. Enter your email address
4. Follow the on-screen instructions to complete the setup process
5. Click the verification link in the email to verify your email address and start using your new Slack workspace.
6. Create channels, invite team members, and send messages instantly in your newly created workspace.
Create a new Slack app
To create a new Slack app follow below steps —
1. Go to the Slack API website
2. Click on Create an app
3. Click on Create new app
4. Give your app a name and select the workspace you want to add it to.
5. Once you’ve done that, you should be redirected to the Basic Information page of your app.
oAuth and Permissions
Set app permissions before your app can communicate with Slack. You need to set app permissions. To do this, go to the OAuth & Permissions page and scroll down to scopes. Add the following scopes to your app:
Installing the app in your workspace
With all the above configurations, the app can now be installed into the workspace. In the left sidebar, go to Settings → Install apps → Install to workspace.
Note: The installation part can be tricky due to privacy concerns. Each organization defines its process internally. Please take this into consideration when installing the app in your organization’s workplace. You can also check with your Slack admin for prerequisites to the installation process.
Slackbot Server Setup
Now let’s write some code. You need to configure a server for Slackbot that can handle requests sent for slackbot. Coding time!!
Create a directory with name test-bot
and initiate the npm:
mkdir test-bot && cd test-bot
npm init -y
Install the following package inside our directory:
- slack/bolt: As per it’s description, it is swiftest way to start programming with the Slack Platform
- dotenv: It is a zero-dependency module that loads environment variables from a .env file into process.env
To do this, open your terminal and navigate to your test-bot
directory. Then run the following command:
yarn add @slack/bolt
yarn add -D dotenv
Authentication the bot with tokens and secrets
Before communicating with bot, Slack first needs to verify your bot with SIGNING_SECRET
and a BOT_TOKEN
. Both should be stored in the .env file so that they are not exposed while using Git.
- SIGNING_SECRET: Navigate to Basic Information → App Credentials → Signing Secret.
- BOT_TOKEN: Navigate to Settings → Install App → Bot User oAuth Token.
Create a .env
in the root directory of your project and assign the SECRET
and TOKEN
you obtained from the step above:
SLACK_SIGNING_SECRET="YOUR SIGNING SECRET"
SLACK_BOT_TOKEN="YOUR BOT TOKEN"
Server setup
Create a file called index.js
, keep it at root level of your bot directory, and add following code:
const { App } = require("@slack/bolt");
require("dotenv").config();
// Initializes your app with credentials
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET,
});
(async () => {
const port = 3000
await app.start(process.env.PORT || port);
console.log('Bolt app started!!');
})();
Now, run node index.js
. If everything was done correctly, you should see the message Bolt app started!!
is displayed in your terminal like below:
How slackbot and our server communicates
Your Slack app / bot needs a way to reach the server you created on your localhost
. Slack has a feature called socket mode that allows Slack to use the WebSockets to connect to your application server.
Go to Settings → Basic Info → App Level Tokens. Click the Generate Tokens and Scopes button. Give your token a name and give your app two available scopes:
- connections:write
- authorizations:read
Click the Generate button. Then from the next screen copy the token to your .env
file with name APP_TOKEN
.
Then go to Settings → Socket Mode. Toggle the Enable Socket Mode switch. Finally, go to your index.js
file and update the code that initializes your app
with socketMode:true
and your appToken
:
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET,
socketMode:true, // enable to use socket mode
appToken: process.env.APP_TOKEN
});
Once this is done, all requests to the development server will be made over WebSockets, and when you run node index.js
you should see something like this in your terminal:
Messages in Slack
You can mention your bot or include @ and additional text that will be sent to your bot as a message.
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/app to listen to events, you need to set up an event subscription.
Since we enabled socket mode, we don’t need to specify an explicit URL.
Now, we need to give the app some event permissions. Click the subscribe to bot events dropdown menu and add the following event:
There are four events associated with messages.
message.channels
: listens for messages in public channelsmessage.groups
: listens for messages in private channelsmessage.im
: listens for messages in your app’s DMs with usersmessage.mpim
: listens for messages in multi-person DMs
Now you can test your app to make sure it can receive and respond to messages. Add the following code to index.js
:
app.message("hey", async ({ command, say }) => {
try {
say("Hello Human!");
} catch (error) {
console.log("err")
console.error(error);
}
});
This is the last step before testing your bot. You may not be able to send messages to your newly created Slackbot. If you click on the bot in the Apps tab of Slack, you may see the message “Messaging for this app has been disabled.” Turn it on!
Go back to the App settings page. Under Features, click the App Home menu option. Scroll down and check the box with allow users to send slash commands and messages from the Messages tab.
Reload Slack using CMD + R
If you’re on a Mac and CTRL + R
if you’re on a PC . Now, you should be able to send messages to your bot.
Go back to the test-bot
app and send a message like @test-bot hey
. You should get a reply from bot.
Everytime we can’t really match exact words. We need a way to check if the message a user is sending to our bot contains a keyword / only some part of it. For that, Slack allows us to use regex expressions. For example, let’s update the code block that we used above to look like this:
// matches any string with RegEx
app.message(/hi/, async ({ command, say }) => {
try {
say("Hello Human!");
} catch (error) {
console.log("err")
console.error(error);
}
});
Send a message that containing the string hi
in the format hi bot
. Our bot will still responds becasue the message contains the string hi
.
I hope you have enjoyed creating the bot which can listen to your message and reply back to your message.
There are multiple activities that the bot can perform. All of these can be found here: https://slack.dev/bolt-js/concepts
#slackbot #Javascript #nodejs