Responding to app mentions

Beginner

In this tutorial, you'll see how you can use Socket Mode to receive events anytime your app is mentioned. We'll show you how apps can respond to these events with a helpful message.

Create a pre-configured app

Quickly create an app with the correct configuration of scopes and features for this tutorial by clicking below.

Step 1Setup Bolt to build your app

Bolt is the swiftest way to start building on the Slack Platform. Before you proceed with this tutorial, follow our Getting Started with Bolt for JavaScript, Python, and Java guides to get setup and ready to build.

    Step complete!

    Step 2Enable Socket Mode in Bolt

    • Overview of Socket Mode

      Socket Mode allows your app to use the Events API and interactive featureswithout exposing a public HTTP Request URL.

      Instead of sending payloads to a public endpoint, Slack will use a WebSocket URL to communicate with your app. WebSockets use a bidirectional stateful protocol with low latency to communicate between two parties—in this case, Slack and your app.

      Unlike a public HTTP endpoint, the WebSocket URL you listen to is not static. The URL is created at runtime by calling the apps.connections.open method, and it refreshes regularly.

      Socket Mode helps developers working behind a corporate firewall, or who have other security concerns that don't allow exposing a static HTTP endpoint.

      You can still switch between a direct HTTP endpoint and Socket Mode at any time in the app config.

      We recommend using our Bolt frameworks or SDKs for Java, Javascript, or Python to handle the details of Socket Mode. The process is streamlined, and you get access to all the other pleasant features of our SDKs.

    • Using Socket Mode in Bolt

      You can use Socket Mode with the Bolt framework.

      First, grab your app-level token from the Basic Information section of your app's config and set it as an environmental variable:

      export SLACK_APP_TOKEN='xapp-***'
      

      Next make a change to your basic Bolt initialization code:

      Capturing events using Socket Mode
      Java
      JavaScript
      Python
      Java
      package hello; import com.slack.api.bolt.App; import com.slack.api.bolt.AppConfig; import com.slack.api.bolt.socket_mode.SocketModeApp; import com.slack.api.model.event.AppMentionEvent; // Required dependencies: // implementation("com.slack.api:bolt-socket-mode:(latest version)") // implementation("org.glassfish.tyrus.bundles:tyrus-standalone-client:1.17") public class MyApp { public static void main(String[] args) throws Exception { String botToken = System.getenv("SLACK_BOT_TOKEN"); App app = new App(AppConfig.builder().singleTeamBotToken(botToken).build()); String appToken = System.getenv("SLACK_APP_TOKEN"); SocketModeApp socketModeApp = new SocketModeApp(appToken, app); socketModeApp.start(); } }
      JavaScript
      Code to initialize Bolt app
      // Require the Node Slack SDK package (github.com/slackapi/node-slack-sdk) const { WebClient, LogLevel } = require("@slack/web-api"); // WebClient instantiates a client that can call API methods // When using Bolt, you can use either `app.client` or the `client` passed to listeners. const client = new WebClient("xoxb-your-token", { // LogLevel can be imported and used to make debugging simpler logLevel: LogLevel.DEBUG });
      const { App } = require('@slack/bolt'); const app = new App({ token: process.env.BOT_TOKEN, appToken: process.env.SLACK_APP_TOKEN, socketMode: true, }); (async () => { await app.start(); console.log('⚡️ Bolt app started'); })();
      Python
      import os from slack_bolt import App from slack_bolt.adapter.socket_mode import SocketModeHandler # Install the Slack app and get xoxb- token in advance app = App(token=os.environ["SLACK_BOT_TOKEN"]) if __name__ == "__main__": SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start()
    Step complete!

    Step 3Capture and respond to app_mention events

    • Capture app_mention events using Bolt

      Using Bolt, you can quickly build an event listener for the Events API.

      Here we'll listen for the app_mention event type, which is sent whenever your app is @mentioned in a Slack channel. After we receive it, we'll send a brief message in response, to the same channel the mention was posted in:

      Capturing events using Socket Mode
      Java
      JavaScript
      Python
      Java
      package hello; import com.slack.api.bolt.App; import com.slack.api.bolt.AppConfig; import com.slack.api.bolt.socket_mode.SocketModeApp; import com.slack.api.model.event.AppMentionEvent; // Required dependencies: // implementation("com.slack.api:bolt-socket-mode:(latest version)") // implementation("org.glassfish.tyrus.bundles:tyrus-standalone-client:1.17") public class MyApp { public static void main(String[] args) throws Exception { String botToken = System.getenv("SLACK_BOT_TOKEN"); App app = new App(AppConfig.builder().singleTeamBotToken(botToken).build()); app.event(AppMentionEvent.class, (req, ctx) -> { ctx.say("Hi there!"); return ctx.ack(); }); String appToken = System.getenv("SLACK_APP_TOKEN"); SocketModeApp socketModeApp = new SocketModeApp(appToken, app); socketModeApp.start(); } }
      JavaScript
      Code to initialize Bolt app
      // Require the Node Slack SDK package (github.com/slackapi/node-slack-sdk) const { WebClient, LogLevel } = require("@slack/web-api"); // WebClient instantiates a client that can call API methods // When using Bolt, you can use either `app.client` or the `client` passed to listeners. const client = new WebClient("xoxb-your-token", { // LogLevel can be imported and used to make debugging simpler logLevel: LogLevel.DEBUG });
      const { App } = require('@slack/bolt'); const app = new App({ token: process.env.BOT_TOKEN, appToken: process.env.SLACK_APP_TOKEN, socketMode: true, }); (async () => { await app.start(); console.log('⚡️ Bolt app started'); })(); // subscribe to 'app_mention' event in your App config // need app_mentions:read and chat:write scopes app.event('app_mention', async ({ event, context, client, say }) => { try { await say({"blocks": [ { "type": "section", "text": { "type": "mrkdwn", "text": `Thanks for the mention <@${event.user}>! Here's a button` }, "accessory": { "type": "button", "text": { "type": "plain_text", "text": "Button", "emoji": true }, "value": "click_me_123", "action_id": "first_button" } } ]}); } catch (error) { console.error(error); } });
      Python
      import os from slack_bolt import App from slack_bolt.adapter.socket_mode import SocketModeHandler # Install the Slack app and get xoxb- token in advance app = App(token=os.environ["SLACK_BOT_TOKEN"]) @app.command("/hello-socket-mode") def hello_command(ack, body): user_id = body["user_id"] ack(f"Hi, <@{user_id}>!") @app.event("app_mention") def event_test(say): say("Hi there!") if __name__ == "__main__": SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start()
    Step complete!

    Step 4Going further

    Now that you've built an event handling app, you can take things a step further by adding other platform features. For example, your response message could be interactive, allowing the app_mention to trigger a longer-running work flow.

    Check out our tutorial on Publishing Interactive Notifications to see how you could proceed.

      Step complete!

      Was this page helpful?