Convert Figma logo to code with AI

slackapi logobolt-js

A framework to build Slack apps using JavaScript

2,742
393
2,742
61

Top Related Projects

11,468

Botkit is an open source developer tool for building chat bots, apps and custom integrations for major messaging platforms.

Telegram Bot API for NodeJS

A powerful JavaScript library for interacting with the Discord API

Node.js helper library

Modern Telegram Bot Framework for Node.js

Quick Overview

Bolt is a framework for building Slack apps using JavaScript. It provides a simple and intuitive API for creating Slack apps with features like handling events, responding to commands, and managing interactive messages. Bolt simplifies the process of building Slack apps by abstracting away many of the complexities of the Slack API.

Pros

  • Easy to use and learn, with a clean and intuitive API
  • Supports both JavaScript and TypeScript
  • Handles common Slack app patterns and best practices out of the box
  • Extensive documentation and examples available

Cons

  • Limited to Slack app development, not a general-purpose framework
  • May have a learning curve for developers new to Slack's ecosystem
  • Some advanced features might require additional configuration or plugins

Code Examples

  1. Responding to a slash command:
app.command('/hello', async ({ command, ack, say }) => {
  await ack();
  await say(`Hello, <@${command.user_id}>!`);
});
  1. Listening for and responding to an event:
app.event('app_home_opened', async ({ event, client }) => {
  await client.views.publish({
    user_id: event.user,
    view: {
      type: 'home',
      blocks: [
        {
          type: 'section',
          text: {
            type: 'mrkdwn',
            text: 'Welcome to the app home!'
          }
        }
      ]
    }
  });
});
  1. Handling an interactive message:
app.action('button_click', async ({ body, ack, say }) => {
  await ack();
  await say(`<@${body.user.id}> clicked the button`);
});

Getting Started

To get started with Bolt for JavaScript:

  1. Install the package:

    npm install @slack/bolt
    
  2. Create a new app:

    const { App } = require('@slack/bolt');
    
    const app = new App({
      token: process.env.SLACK_BOT_TOKEN,
      signingSecret: process.env.SLACK_SIGNING_SECRET
    });
    
    app.message('hello', async ({ message, say }) => {
      await say(`Hey there <@${message.user}>!`);
    });
    
    (async () => {
      await app.start(process.env.PORT || 3000);
      console.log('⚡️ Bolt app is running!');
    })();
    
  3. Set up your Slack app in the Slack API dashboard and obtain the necessary tokens and signing secret.

  4. Run your app and start interacting with it in Slack!

Competitor Comparisons

11,468

Botkit is an open source developer tool for building chat bots, apps and custom integrations for major messaging platforms.

Pros of Botkit

  • Multi-platform support: Botkit works with various messaging platforms, not just Slack
  • Rich ecosystem: Offers a wide range of plugins and middleware
  • More mature and established: Has been around longer, with a larger community

Cons of Botkit

  • Steeper learning curve: More complex API and configuration
  • Less official support: Not directly maintained by Slack
  • Potentially slower updates: May lag behind in supporting new Slack features

Code Comparison

Bolt.js:

app.message('hello', async ({ message, say }) => {
  await say(`Hey there <@${message.user}>!`);
});

Botkit:

controller.hears('hello', ['direct_message', 'direct_mention'], (bot, message) => {
  bot.reply(message, `Hey there <@${message.user}>!`);
});

Summary

Bolt.js is Slack's official SDK, offering a simpler API and faster adoption of new Slack features. It's ideal for Slack-specific projects. Botkit provides multi-platform support and a rich ecosystem, making it suitable for cross-platform bot development. However, it may have a steeper learning curve and potentially slower updates for Slack-specific features. The choice between the two depends on project requirements, target platforms, and developer preferences.

Telegram Bot API for NodeJS

Pros of node-telegram-bot-api

  • Specifically designed for Telegram bots, offering a more tailored API for Telegram-specific features
  • Lightweight and focused, with fewer dependencies
  • Easier to get started for simple Telegram bot projects

Cons of node-telegram-bot-api

  • Less comprehensive ecosystem compared to Bolt-js
  • Limited to Telegram platform, while Bolt-js supports multiple Slack-related services
  • May require more manual handling of certain bot functionalities

Code Comparison

node-telegram-bot-api:

const TelegramBot = require('node-telegram-bot-api');
const bot = new TelegramBot(token, {polling: true});

bot.on('message', (msg) => {
  bot.sendMessage(msg.chat.id, 'Hello, ' + msg.from.first_name);
});

Bolt-js:

const { App } = require('@slack/bolt');
const app = new App({ token, signingSecret });

app.message('hello', async ({ message, say }) => {
  await say(`Hello, <@${message.user}>!`);
});

Both libraries provide straightforward ways to create bots and handle messages. node-telegram-bot-api is more specific to Telegram's API, while Bolt-js offers a higher-level abstraction for Slack interactions. Bolt-js also provides built-in support for Slack's features like interactive messages and slash commands, which would require additional implementation in node-telegram-bot-api for Telegram equivalents.

A powerful JavaScript library for interacting with the Discord API

Pros of discord.js

  • More comprehensive API coverage for Discord's features
  • Larger and more active community, resulting in better support and resources
  • Better performance for handling large-scale Discord bots

Cons of discord.js

  • Steeper learning curve due to more complex API
  • Requires more setup and configuration compared to Bolt.js
  • Less suitable for simple, quick bot implementations

Code Comparison

Bolt.js (Slack):

app.message('hello', async ({ message, say }) => {
  await say(`Hey there <@${message.user}>!`);
});

discord.js (Discord):

client.on('messageCreate', message => {
  if (message.content === 'hello') {
    message.reply(`Hey there ${message.author}!`);
  }
});

Key Differences

  • Bolt.js uses a more declarative approach with built-in middleware
  • discord.js requires manual event handling and message parsing
  • Bolt.js has simpler setup for basic functionality
  • discord.js offers more granular control over bot behavior

Use Cases

  • Bolt.js: Ideal for quick Slack integrations and simple bots
  • discord.js: Better suited for complex Discord bots with advanced features

Community and Ecosystem

  • discord.js has a larger ecosystem of plugins and extensions
  • Bolt.js benefits from Slack's official support and documentation

Learning Resources

  • Both projects have extensive documentation and examples
  • discord.js has more third-party tutorials and courses available

Node.js helper library

Pros of twilio-node

  • Broader functionality: Covers the entire Twilio API, including SMS, voice, video, and more
  • More mature and established library with a larger user base
  • Extensive documentation and examples for various use cases

Cons of twilio-node

  • Less focused on specific platform features compared to Bolt-js for Slack
  • May require more setup and configuration for basic tasks
  • Steeper learning curve due to the wide range of features

Code Comparison

Bolt-js (Slack message sending):

app.message('hello', async ({ message, say }) => {
  await say(`Hey there <@${message.user}>!`);
});

twilio-node (SMS sending):

client.messages
  .create({
     body: 'Hello from Twilio!',
     from: '+15017122661',
     to: '+15558675310'
   })
  .then(message => console.log(message.sid));

Summary

twilio-node is a comprehensive library for interacting with Twilio's services, offering a wide range of communication features. Bolt-js, on the other hand, is specifically designed for building Slack apps with a more streamlined approach. While twilio-node provides greater versatility across different communication channels, Bolt-js offers a more focused and user-friendly experience for Slack development. The choice between the two depends on the specific requirements of your project and the platforms you're targeting.

Modern Telegram Bot Framework for Node.js

Pros of Telegraf

  • More versatile, supporting multiple messaging platforms beyond just Telegram
  • Lighter weight and potentially faster due to its focused design
  • Extensive middleware ecosystem for added functionality

Cons of Telegraf

  • Less comprehensive documentation compared to Bolt
  • Smaller community and fewer resources for troubleshooting
  • May require more setup and configuration for complex use cases

Code Comparison

Bolt.js (Slack):

const { App } = require('@slack/bolt');

const app = new App({
  token: process.env.SLACK_BOT_TOKEN,
  signingSecret: process.env.SLACK_SIGNING_SECRET
});

app.message('hello', async ({ message, say }) => {
  await say(`Hey there <@${message.user}>!`);
});

Telegraf (Telegram):

const { Telegraf } = require('telegraf');

const bot = new Telegraf(process.env.BOT_TOKEN);

bot.hears('hello', (ctx) => {
  ctx.reply(`Hey there ${ctx.from.first_name}!`);
});

Both frameworks offer similar ease of use for basic bot functionality. Bolt provides more Slack-specific features out of the box, while Telegraf offers a more flexible approach for various messaging platforms. The choice between them largely depends on the specific requirements of your project and the target platform(s).

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Bolt Bolt logo for JavaScript

codecov Node.js CI

A JavaScript framework to build Slack apps in a flash with the latest platform features. Read the getting started guide to set-up and run your first Bolt app.

Read the documentation to explore the basic and advanced concepts of Bolt for JavaScript.

Setup

npm install @slack/bolt

Initialization

Create an app by calling the constructor, which is a top-level export.

const { App } = require('@slack/bolt');

const app = new App({
  signingSecret: process.env.SLACK_SIGNING_SECRET,
  token: process.env.SLACK_BOT_TOKEN,
});

/* Add functionality here */

(async () => {
  // Start the app
  await app.start(process.env.PORT || 3000);

  console.log('⚡️ Bolt app is running!');
})();

Listening for events

The Slack Request URL for a Bolt app must have the path set to /slack/events.
For example: https://my-slack-app.example.com/slack/events.
Otherwise, all incoming requests from Slack won't be handled.

Apps typically react to a collection of incoming events, which can correspond Events API events, actions, shortcuts, slash commands or options requests. For each type of request, there's a method to build a listener function.

// Listen for an action from a Block Kit element (buttons, select menus, date pickers, etc)
app.action(actionId, fn);

// Listen for dialog submissions
app.action({ callback_id: callbackId }, fn);

// Listen for slash commands
app.command(commandName, fn);

// Listen for an event from the Events API
app.event(eventType, fn);

// Listen for a custom step execution from a workflow
app.function(callbackId, fn)

// Convenience method to listen to only `message` events using a string or RegExp
app.message([pattern ,] fn);

// Listen for options requests (from select menus with an external data source)
app.options(actionId, fn);

// Listen for a global or message shortcuts
app.shortcut(callbackId, fn);

// Listen for view_submission modal events
app.view(callbackId, fn);

Making things happen

Most of the app's functionality will be inside listener functions (the fn parameters above). These functions are called with a set of arguments.

ArgumentDescription
payloadContents of the incoming event. The payload structure depends on the listener. For example, for an Events API event, payload will be the event type structure. For a block action, it will be the action from within the actions array. The payload object is also accessible via the alias corresponding to the listener (message, event, action, shortcut, view, command, or options). For example, if you were building a message() listener, you could use the payload and message arguments interchangeably. An easy way to understand what's in a payload is to log it, or use TypeScript.
sayFunction to send a message to the channel associated with the incoming event. This argument is only available when the listener is triggered for events that contain a channel_id (the most common being message events). say accepts simple strings (for plain-text messages) and objects (for messages containing blocks). say returns a promise that will resolve with a chat.postMessage response.
ackFunction that must be called to acknowledge that an incoming event was received by your app. ack exists for all actions, shortcuts, view, slash command and options requests. ack returns a promise that resolves when complete. Read more in Acknowledging events
clientWeb API client that uses the token associated with that event. For single-workspace installations, the token is provided to the constructor. For multi-workspace installations, the token is returned by the authorize function.
respondFunction that responds to an incoming event if it contains a response_url (actions, shortcuts, view submissions, and slash commands). respond returns a promise that resolves with the results of responding using the response_url.
contextEvent context. This object contains data about the event and the app, such as the botId. Middleware can add additional context before the event is passed to listeners.
bodyObject that contains the entire body of the request (superset of payload). Some accessory data is only available outside of the payload (such as trigger_id and authorizations).
completeFunction used to signal the successful completion of a custom step execution. This tells Slack to proceed with the next steps in the workflow. This argument is only available with the .function and .action listener when handling custom workflow step executions.
failFunction used to signal that a custom step failed to complete. This tells Slack to stop the workflow execution. This argument is only available with the .function and .action listener when handling custom workflow step executions.

The arguments are grouped into properties of one object, so that it's easier to pick just the ones your listener needs (using object destructuring). Here is an example where the app sends a simple response, so there's no need for most of these arguments:

// Reverse all messages the app can hear
app.message(async ({ message, say }) => {
  // Filter out message events with subtypes (see https://api.slack.com/events/message)
  if (message.subtype === undefined || message.subtype === 'bot_message') {
    const reversedText = [...message.text].reverse().join("");
    await say(reversedText);
  }
});

Calling the Web API

In addition to the client property passed to listeners, each app has a top-level client that can be used to call methods. Unlike the client passed to listeners, the top-level client must be passed a token. Read the documentation for more details.

Acknowledging events

Some types of events need to be acknowledged in order to ensure a consistent user experience inside the Slack client (web, mobile, and desktop apps). This includes all action, shortcut, view, command, and options requests. Listeners for these events need to call the ack() function, which is passed in as an argument.

In general, the Slack platform expects an acknowledgement within 3 seconds, so listeners should call this function as soon as possible.

Depending on the type of incoming event a listener is meant for, ack() should be called with a parameter:

  • Block actions, global shortcuts, and message shortcuts: Call ack() with no parameters.

  • View submissions: Call ack() with no parameters or with a response action.

  • Options requests: Call ack() with an object containing the options for the user to see.

  • Legacy message button clicks, menu selections, and slash commands: Either call ack() with no parameters, a string to to update the message with a simple message, or an object to replace it with a complex message. Replacing the message to remove the interactive elements is a best practice for any action that should only be performed once.

  • Events API events do not need an ack() function since they are automatically acknowledged by your app.

Getting Help

The documentation has more information on basic and advanced concepts for Bolt for JavaScript.

If you otherwise get stuck, we're here to help. The following are the best ways to get assistance working through your issue:

  • Issue Tracker for questions, bug reports, feature requests, and general discussion related to Bolt for JavaScript. Try searching for an existing issue before creating a new one.
  • Email our developer support team: support@slack.com

Contributing

We welcome contributions from everyone! Please check out our Contributor's Guide for how to contribute in a helpful and collaborative way.

NPM DownloadsLast 30 Days