Building your first Slack Bot using Node.js
A bot is a type of Slack App designed to interact with users via conversation. It is the same as a regular app: it can access the same range of APIs and do all of the magical things that a Slack App can do. But when you build a bot for your Slack App, you’re giving that app a face, a name, and a personality, and encouraging users to talk to it. Your bot can send DMs, it can be mentioned by users, it can post messages or upload files, and it can be invited to channels.
Creating a new project in Node.js
Let’s create one of our own. Open up a terminal window and create a new folder by typing in the following and hitting Enter:
mkdir SlackBot && cd SlackBot
This creates a new directory and navigates to said directory. Next, enter the
following:
npm init
Follow the onscreen prompts and you will end up with something like this:
Once completed, you’ll find that a package.json file has been created in your
directory
Now that we’ve created a template for our app, let’s now install some dependencies:
touch index.js
npm install @slack/client –-save
These commands create an empty JavaScript file named index and install the Slack Real Time Messaging (RTM) client.
Your package.json file should now look something like this:
{
"name": "slackbot",
"version": "1.0.0",
"description": "My Slack bot",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Mitusha",
"license": "ISC",
"dependencies": {
"@slack/client": "^5.0.2"
}
}
Creating a Slack API token
Open up a browser and navigate to- https://my.slack.com/apps/build/custom-integration
Follow these steps:
1. Select Bots from the list of available custom integrations.
2. Select a name and click on Add Bot Integration. The name of your bot
can be changed later.
3. Copy the newly generated API token. As an optional step, you can
choose to customize the bot further on this screen.
4. Click on Save Integration at the bottom of the page.
Now let’s write some code
Open your index.js file and paste the following code-
Bots are restricted in the actions they can perform themselves. As such, bots need to be invited to channels via the invite command within the Slack client:
/invite [BOT_NAME]
After this, you’ll get confirmation of the bot entering the channel like this:
Finally, we have successfully created a bot