DEV Community

Cover image for Create a Slack Bot with TypeScript in 3 Steps
Upsilon
Upsilon

Posted on • Updated on • Originally published at upsilonit.com

Create a Slack Bot with TypeScript in 3 Steps

Today Slack has become a tool that more and more companies use for communication within their teams. Though Slack App Directory offers a great number of applications, sometimes it is necessary to create a custom bot. In this guide you will be able to learn how to create a simple Slack bot of your own.


Today more and more companies use Slack to ensure communication within their teams. Slack includes different features, including direct messages, private and public channels, voice and video calls, file searching, and bot integrations.

This article is a tutorial on how to make a Slack bot. A Slack bot is a program that can perform different tasks, like sending messages, files, pictures, opening modals, sending emoji reactions, alerting on various events, etc.

Why create a Slack bot?

Though Slack offers a lot of applications for any purpose in the Slack App Directory, there can still be a need for custom Slack Bots, as every business has its own needs and requirements. Sometimes it is extremely hard to find a suitable option from the existing ones. In this case, it can be a great idea to create a Slack bot of your own.

There are many ways Slack bots can be used to simplify work processes or to increase revenue, so let’s recall some of them.

  1. Automating business processes;
  2. Integrating with the tools used for marketing, sales or project management;
  3. Giving the users an option to perform actions without leaving Slack;
  4. Providing support services;
  5. Assistance in sales, allowing to place orders using a Slack bot;
  6. Creating a fun tool that can be a part of your company's culture.

If you want to create your own bot, let’s take a look at an example of how to make a simple Slack bot.

Step 1: Initial Slack Bot Setup

For study purposes we’ll create a simple Slack bot that adds a new command to your workspace that mentions all admins in your workspace.

All code listed below can be found in our repository:

It’s assumed that you have Node.js installed on your computer. Open your favorite editor and start a new project. Create a package.json file in there and paste:

{
  "name": "slack-bot-example",
  "version": "0.1.0",
  "description": "",
  "private": true,
  "scripts": {
    "start": "ts-node index.ts"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@slack/bolt": "^3.10.0",
    "ts-node": "^10.7.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

We need ts-node as we use TypeScript (hope you do it as well), and @slack/bolt — official Slack package to create bots.

Now we need you to write actual code. Create index.ts file and paste:

import { App } from "@slack/bolt";

const SLACK_APP_TOKEN = "<PASTE ME>";
const SLACK_BOT_TOKEN = "<PASTE ME>";

const app = new App({
  appToken: SLACK_APP_TOKEN,
  token: SLACK_BOT_TOKEN,
  socketMode: true,
});

app.command("/admins", async ({ ack, client }) => {
  const { members } = await client.users.list();
  const admins = members!.filter((member) => member.is_admin);

  await ack({
    blocks: [
      {
        "type": "section",
        "text": {
          "type": "mrkdwn",
          "text": `${admins.map((admin) => `@${admin.name}`).join(", ")}`
        }
      },
    ],
    response_type: "ephemeral", // change to "in_channel" to make it visible to others
  });
});

app.start().catch((error) => {
  console.error(error);
  process.exit(1);
});
Enter fullscreen mode Exit fullscreen mode

In general, Slack bot is simply an HTTP server that provides webhook endpoints and handles events sent by Slack. How Slack might reach your local machine HTTP server? Well, in this exact case it doesn’t as we use so called Socket Mode. It makes our application connect to Slack servers and listen to events from there instead of Slack connecting to our server. If there were no Socket Mode, we would have to use something like ngrok to expose our local port to the Internet. Read more about Socket Mode on official documentation.

As you can see, there are SLACK_APP_TOKEN and SLACK_BOT_TOKEN variables missing in index.ts, these are used to authenticate our application. In order to get them, we should register a new Slack application.

Step 2: Creating a Slack Bot

Go to https://api.slack.com/apps?new_app=1. You should see a modal window there:

Create a Slack App

Choose “From an app manifest”, select your workspace in the dropdown and then paste the following YAML to the text area, and then press “Create”:

display_information:
 name: Article Test App
features:
 bot_user:
   display_name: Article Test App
   always_online: false
 slash_commands:
   - command: /admins
     description: Mention all admins in your workspace.
     should_escape: false
oauth_config:
 scopes:
   bot:
     - commands
     - users:read
settings:
 interactivity:
   is_enabled: true
 socket_mode_enabled: true
Enter fullscreen mode Exit fullscreen mode

You will be redirected to the app page. Press the “Install to Workspace” button, and then allow access to your workspace. When you click “Allow”, Slack grants the permissions you asked in the manifest. If you should add a new permission, you should reinstall the application as well.

Next we need an app-level token to use Socket Mode. When you’re redirected back to the app page, scroll down to “App-Level Tokens” sections and click “Generate Token and Scopes” there. Enter a name and add connection:write scope as on the picture below:

Generate an app-level token

Copy the token you got here to the SLACK_APP_TOKEN variable.

Next we need an OAuth token. In production you will ask the user to install your application to the user’s workspace and then store an OAuth token you got from Slack in the database. But for the development purposes Slack also provides a special OAuth token that can be found right in the admin panel. Remember that it grants access only to the workspace you chose when you created the application. You can find the OAuth token in the “Install App” section in the sidebar. There you’ll find a bot token, copy it to the SLACK_BOT_TOKEN variable.

Installed App Settings

Step 3: Running and Testing the Application

Run npm install and then npm start in your terminal, no error should appear there.

Go to any channel and start typing “/admins”. You should see a suggestion with your app command.

App Command Suggestion

Choose it and then send the message. An ephemeral message will be sent to the channel (hence only you can see the message).

Message Sent by the App

In order to make messages visible to others, change response_type to in_channel in your index.ts file. But try not to annoy others too much:)

Conclusion

Slack applications can be a powerful tool to automate your business' workflows and make them more effective. When you think about how to create a Slack bot, it is very important to consider its infrastructure, the events it receives and the user experience.

Hope that this guide helped you better understand how to make a Slack bot that can perform some useful tasks. It is also possible to add some extra features to your bot, or modify it so that it will suit your requirements.

Top comments (0)