Listening to Events and Slash Commands
app_mention, slash commands, and action handlers in Slack Bolt.
Slack Event Subscriptions Overview
Slack sends your app events when things happen — a message posted, someone mentioning your bot, a user joining a channel. You subscribe to specific event types in the Slack App dashboard, then register handlers in Bolt using the @app.event() decorator.
from slack_bolt import App
import os
app = App(
token=os.environ['SLACK_BOT_TOKEN'],
signing_secret=os.environ['SLACK_SIGNING_SECRET']
)
# Register event handlers with @app.event()
# The string argument must match the Slack event type exactly
@app.event('app_mention')
def handle_mention(event, say, logger):
logger.info(f'Mention event: {event}')
say(f'Hello <@{event["user"]}>!')
@app.event('message')
def handle_message(event, say):
# Fires for every message in subscribed channels
if event.get('subtype') is None: # ignore bot messages
print(f'Message: {event["text"]}')Handling app_mention Events
The app_mention event fires when someone types @YourBot in a channel. The event['text'] contains the full message including the mention. Strip the mention prefix to get the user's actual query.
import re
@app.event('app_mention')
def handle_mention(event, say, client):
# event['text'] example: '<@U0123BOT> summarize this'
text = event.get('text', '')
user_id = event['user']
channel = event['channel']
# Remove the @mention to get the clean query
clean_text = re.sub(r'<@[A-Z0-9]+>', '', text).strip()
print(f'User {user_id} asked: {clean_text}')
if not clean_text:
say(f'Hi <@{user_id}>! How can I help you today?')
return
# Process the query
response = process_user_query(clean_text, user_id)
say(response)All lessons in this course
- Slack Bolt SDK Basics
- Listening to Events and Slash Commands
- Sending Messages and Rich Blocks
- Building a Team Notification Bot