0Pricing
AI Agents · Lesson

Listening to Events and Slash Commands

app_mention, slash commands, and action handlers in Slack Bolt.

Listening to Events and Slash Commands is a free AI Agents lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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)

Accessing the event Payload

Every event handler receives the event dict, which contains the raw Slack event payload. Key fields: event['user'] (user ID), event['channel'] (channel ID), event['text'] (message content), event['ts'] (timestamp/message ID).

@app.event('app_mention')
def handle_mention(event, say, client):
    print('Event type:', event.get('type'))
    print('User ID:', event.get('user'))     # e.g. 'U0123ABC'
    print('Channel:', event.get('channel'))   # e.g. 'C0456DEF'
    print('Text:', event.get('text'))          # full message text
    print('Timestamp:', event.get('ts'))       # '1234567890.123456'
    print('Thread TS:', event.get('thread_ts')) # if in a thread

    # Get full user info from the user ID
    user_info = client.users_info(user=event['user'])
    real_name = user_info['user']['real_name']
    email = user_info['user']['profile'].get('email', '')
    say(f'Hello {real_name}!')

Slash Commands — Registering and Responding

Slash commands let users trigger agent actions from any Slack channel. Register the command URL in the Slack App dashboard (under Slash Commands), then handle it with @app.command('/command-name'). Always call ack() immediately — Slack times out in 3 seconds if you don't.

@app.command('/summarize')
def handle_summarize(ack, body, say, respond):
    # CRITICAL: ack() must be called within 3 seconds
    ack()  # acknowledge the command immediately

    # body contains the command payload
    user_id = body['user_id']
    channel_id = body['channel_id']
    text = body.get('text', '').strip()  # text after the command

    print(f'User {user_id} ran /summarize with: "{text}"')

    if not text:
        respond('Usage: /summarize <text or URL to summarize>')
        return

    # Process and respond
    summary = generate_summary(text)
    say(f'Summary by <@{user_id}>:\n{summary}')

ack() — The 3-Second Rule

Slack requires your app to ack() (acknowledge) every incoming slash command and interactive payload within 3 seconds. If you don't, Slack shows the user an error. For long-running operations, ack immediately, start processing in a background thread, then respond using respond() with the result.

import threading

@app.command('/analyze')
def handle_analyze(ack, body, respond):
    ack()  # Must be within 3 seconds!

    text = body.get('text', '').strip()
    if not text:
        respond('Please provide text to analyze.')
        return

    # For slow operations: run in background thread
    def process_in_background():
        result = slow_ai_analysis(text)  # may take 10+ seconds
        respond(f'Analysis complete:\n{result}')

    thread = threading.Thread(target=process_in_background)
    thread.daemon = True
    thread.start()

    # respond() is safe to call from a different thread
    # ack() already sent, Slack won't time out

say() vs respond() — When to Use Each

Two functions post messages back to Slack:

  • say() — posts to the channel where the event occurred; visible to everyone
  • respond() — available only in slash command handlers; can post ephemeral messages visible only to the command user

Use respond(response_type='in_channel') for public responses and respond(response_type='ephemeral') for private ones.

@app.command('/status')
def handle_status(ack, respond, body):
    ack()

    # Ephemeral: only visible to the user who ran the command
    respond(
        text='Agent status: Running | Queue: 3 tasks | Uptime: 4h 22m',
        response_type='ephemeral'  # private to command user
    )

@app.command('/broadcast')
def handle_broadcast(ack, say, respond, body):
    ack()
    text = body.get('text', '')

    # Public: visible to everyone in the channel
    say(
        text=f'<@{body["user_id"]}> broadcast: {text}',
        channel=body['channel_id']
    )

    # Confirm privately to the sender
    respond('Broadcast sent!', response_type='ephemeral')

Message Events and Subtypes

The generic message event fires for all messages, including bot messages, edits, and deletes. Use the subtype field to filter. Common subtypes: bot_message, message_changed, message_deleted. If subtype is absent, it's a regular user message.

@app.event('message')
def handle_message(event, say, client):
    subtype = event.get('subtype')

    # Ignore bot messages to prevent loops
    if subtype == 'bot_message':
        return

    # Ignore message edits and deletes
    if subtype in ('message_changed', 'message_deleted'):
        return

    # Only process direct messages (DMs) to the bot
    channel_type = event.get('channel_type', '')
    if channel_type == 'im':
        text = event.get('text', '').strip()
        user = event['user']
        print(f'DM from {user}: {text}')
        say(f'You said: {text}')

Listening to Reactions

The reaction_added event fires when someone adds an emoji reaction to a message. You can use this to trigger agent actions — for example, adding a 📌 reaction to save a message, or a ✅ to mark a task complete.

@app.event('reaction_added')
def handle_reaction(event, client, say):
    reaction = event['reaction']  # e.g. 'thumbsup', 'white_check_mark'
    user_id = event['user']  # who reacted
    item = event['item']  # what was reacted to

    print(f'User {user_id} reacted :{reaction}: to {item["type"]}')

    if reaction == 'white_check_mark' and item['type'] == 'message':
        # Fetch the original message
        result = client.conversations_history(
            channel=item['channel'],
            oldest=item['ts'],
            latest=item['ts'],
            inclusive=True,
            limit=1
        )
        messages = result.get('messages', [])
        if messages:
            text = messages[0].get('text', '')
            print(f'Task completed: {text[:100]}')

Action Payloads from Interactive Components

When a user clicks a button or selects a menu item, Slack sends an action payload. Handle it with @app.action('action_id'). The action ID is the string you set when creating the Block Kit component. Always ack() immediately.

@app.action('approve_task')
def handle_approve(ack, body, respond, client):
    ack()  # acknowledge within 3 seconds

    action = body['actions'][0]  # the button that was clicked
    action_id = action['action_id']  # 'approve_task'
    value = action.get('value', '')  # data attached to the button
    user_id = body['user']['id']

    print(f'User {user_id} clicked {action_id} with value: {value}')

    # Update the original message to show it was approved
    client.chat_update(
        channel=body['container']['channel_id'],
        ts=body['container']['message_ts'],
        text=f'Task approved by <@{user_id}>',
        blocks=[]  # remove buttons after action
    )
    respond('Task approved!', response_type='ephemeral')

Filtering Events by Channel or User

In large workspaces, your bot may receive events from many channels. Filter early in your handler to process only relevant events. Check event['channel'] against an allowed list or event['user'] to ignore certain users (like other bots).

import os

# Only respond in designated channels
ALLOWED_CHANNELS = set(
    os.environ.get('ALLOWED_CHANNELS', '').split(',')
)

BOT_USER_IDS = set()  # will be populated at startup

@app.event('app_mention')
def handle_mention(event, say, client):
    channel = event.get('channel', '')
    user = event.get('user', '')

    # Skip if channel not in allowed list (if list is configured)
    if ALLOWED_CHANNELS and channel not in ALLOWED_CHANNELS:
        return

    # Skip if the 'user' is actually a bot
    if user in BOT_USER_IDS:
        return

    text = event.get('text', '').strip()
    say(f'Processing: {text[:50]}')

Thread Reply Support

To reply in a thread (instead of the main channel), pass thread_ts to say(). Use event.get('thread_ts', event['ts']) to get the thread timestamp — thread_ts exists only if the message is already in a thread; if not, use the message's own ts to start a new thread.

@app.event('app_mention')
def handle_mention_in_thread(event, say):
    user = event['user']
    text = event.get('text', '').strip()

    # Reply in the same thread (or start a new one)
    thread_ts = event.get('thread_ts') or event.get('ts')

    response_text = f'<@{user}>, processing your request...'

    say(
        text=response_text,
        thread_ts=thread_ts  # keeps the reply in the thread
    )

    # Do the actual work
    result = do_agent_work(text)

    say(
        text=f'Done! Result:\n{result}',
        thread_ts=thread_ts
    )

Quick Check: ack() Timing

Test your understanding of Slack event handling.

Events and Slash Commands Recap

Your Slack agent can now respond to any user interaction:

  • @app.event('app_mention') — handle @bot mentions; strip mention prefix with regex
  • @app.command('/cmd') — handle slash commands; always ack() within 3 seconds
  • say() — post publicly to the channel; respond() — reply to slash command (can be ephemeral)
  • @app.action('id') — handle button clicks and interactive component interactions
  • @app.event('reaction_added') — trigger on emoji reactions
  • Use thread_ts in say() to keep replies in threads
  • Filter by channel/user early to avoid processing irrelevant events

Frequently asked questions

Is the “Listening to Events and Slash Commands” lesson free?

Yes — the full text of “Listening to Events and Slash Commands” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.

What will I learn in “Listening to Events and Slash Commands”?

app_mention, slash commands, and action handlers in Slack Bolt. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start AI Agents?

No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Listening to Events and Slash Commands” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this AI Agents lesson?

Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Slack Bolt SDK Basics
  2. Listening to Events and Slash Commands
  3. Sending Messages and Rich Blocks
  4. Building a Team Notification Bot
← Back to AI Agents