0Pricing
AI Agents · Lesson

Slack Bolt SDK Basics

App initialization, bot tokens, socket mode vs HTTP, and event subscriptions.

Slack Bolt SDK Basics is a free AI Agents lesson on CoddyKit — lesson 1 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.

Why Slack Bolt for Agent Development?

Slack Bolt is the official Python SDK for building Slack apps. It handles OAuth, event routing, middleware, and the request/response lifecycle — so your agent focuses on business logic, not HTTP plumbing. Bolt supports both Socket Mode (WebSocket) and HTTP mode.

# Install Slack Bolt
# pip install slack-bolt

# Slack Bolt handles:
# - Event subscriptions (messages, mentions, reactions)
# - Slash commands (/summarize, /ask)
# - Interactive components (buttons, modals, select menus)
# - Shortcuts (global and message shortcuts)
# - OAuth 2.0 for multi-workspace apps
# - Request signature verification (security)

print('Slack Bolt is the official Python SDK for Slack apps')

Bot Token and Signing Secret

A Slack app needs two credentials: a Bot Token (starts with xoxb-) for making API calls and posting messages, and a Signing Secret for verifying that incoming events genuinely come from Slack. Both are found in the Slack app settings dashboard.

import os
from slack_bolt import App

# Load credentials from environment variables
# Never hardcode tokens!
BOT_TOKEN = os.environ['SLACK_BOT_TOKEN']        # xoxb-...
SIGNING_SECRET = os.environ['SLACK_SIGNING_SECRET']  # hex string

# Initialize the Bolt app
app = App(
    token=BOT_TOKEN,
    signing_secret=SIGNING_SECRET
)

print('Slack Bolt app initialized')
print(f'Bot token prefix: {BOT_TOKEN[:10]}...')

Required Bot Token Scopes

Slack apps use OAuth scopes to define what the bot can do. Add scopes in the Slack App dashboard under OAuth & Permissions → Scopes → Bot Token Scopes. Common scopes for an AI agent bot:

  • chat:write — post messages
  • app_mentions:read — receive @mentions
  • channels:history — read channel messages
  • commands — receive slash commands
  • im:write — send direct messages
# Required scopes for a typical AI agent bot:
# - chat:write          → post messages to channels
# - app_mentions:read   → receive @bot mentions
# - channels:history    → read message history
# - channels:read       → list channels
# - commands            → handle slash commands
# - im:write            → send DMs
# - im:read             → receive DMs
# - users:read          → get user info (name, email)

# Add these in Slack App settings:
# https://api.slack.com/apps -> Your App -> OAuth & Permissions

print('Configure scopes in Slack App dashboard before installing')

Socket Mode vs HTTP Mode

Socket Mode connects to Slack via a persistent WebSocket — no public URL needed, perfect for development and internal tools. HTTP Mode requires a public HTTPS endpoint that Slack POSTs events to — necessary for production apps and multi-workspace installations.

# SOCKET MODE (development / internal tools):
# - No public URL needed
# - Uses an App-Level Token (xapp-...)
# - Great for local development
from slack_bolt.adapter.socket_mode import SocketModeHandler

APP_TOKEN = os.environ['SLACK_APP_TOKEN']  # xapp-...
handler = SocketModeHandler(app, APP_TOKEN)

# handler.start()  # blocks and handles events

# HTTP MODE (production):
# - Requires public HTTPS URL configured in Slack app settings
# - Works with Flask, FastAPI, etc.
from slack_bolt.adapter.flask import SlackRequestHandler
from flask import Flask, request

flask_app = Flask(__name__)
slack_handler = SlackRequestHandler(app)

print('Socket Mode: dev/internal; HTTP Mode: production')

Initializing the App and Starting Socket Mode

The minimal Slack Bolt app in Socket Mode: create the App, register at least one handler, then start the SocketModeHandler. The handler connects to Slack's event infrastructure and stays connected until you stop the process.

import os
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler

app = App(
    token=os.environ['SLACK_BOT_TOKEN'],
    signing_secret=os.environ['SLACK_SIGNING_SECRET']
)

@app.event('app_mention')
def handle_mention(event, say):
    user = event['user']
    text = event['text']
    say(f'Hi <@{user}>! You said: {text}')

# Start the app
if __name__ == '__main__':
    handler = SocketModeHandler(
        app,
        os.environ['SLACK_APP_TOKEN']
    )
    handler.start()  # blocks until process is killed

Testing with ngrok (HTTP Mode)

During development with HTTP Mode, use ngrok to expose your local server to the internet. Run ngrok http 3000 to get a public HTTPS URL, then update your Slack app's Event Subscriptions and Slash Command URLs to point to it.

# HTTP mode setup with Flask:
from flask import Flask, request
from slack_bolt import App
from slack_bolt.adapter.flask import SlackRequestHandler
import os

app = App(
    token=os.environ['SLACK_BOT_TOKEN'],
    signing_secret=os.environ['SLACK_SIGNING_SECRET']
)

@app.event('app_mention')
def handle_mention(event, say):
    say('Hello from HTTP mode!')

flask_app = Flask(__name__)
handler = SlackRequestHandler(app)

@flask_app.route('/slack/events', methods=['POST'])
def slack_events():
    return handler.handle(request)

# Run: python app.py
# In another terminal: ngrok http 3000
# Set https://abc123.ngrok.io/slack/events as your Request URL in Slack

App-Level Token for Socket Mode

Socket Mode requires an additional App-Level Token (starts with xapp-) with the connections:write scope. This is separate from the Bot Token. Generate it in the Slack App settings under Basic Information → App-Level Tokens.

# App-Level Token setup:
# 1. Go to https://api.slack.com/apps -> Your App
# 2. Click 'Basic Information'
# 3. Scroll to 'App-Level Tokens'
# 4. Click 'Generate Token and Scopes'
# 5. Name it 'socket-mode-token'
# 6. Add scope: connections:write
# 7. Click 'Generate'
# 8. Copy the xapp-... token

# In your .env file:
# SLACK_BOT_TOKEN=xoxb-...
# SLACK_SIGNING_SECRET=abc123...
# SLACK_APP_TOKEN=xapp-...

from slack_bolt.adapter.socket_mode import SocketModeHandler
import os

handler = SocketModeHandler(
    app=app,
    app_token=os.environ['SLACK_APP_TOKEN']  # xapp-...
)
print('App-Level Token required for Socket Mode')

Bolt Middleware

Bolt supports middleware — functions that run before every event handler. Use middleware for logging, authentication, rate limiting, or enriching events with user data. Call next() to pass control to the next middleware or handler.

from slack_bolt import App
import time
import logging

app = App(
    token=os.environ['SLACK_BOT_TOKEN'],
    signing_secret=os.environ['SLACK_SIGNING_SECRET']
)

logger = logging.getLogger(__name__)

# Request logging middleware
@app.middleware
def log_request(logger, body, next):
    event_type = body.get('event', {}).get('type', 'unknown')
    start = time.time()
    logger.info(f'Incoming event: {event_type}')
    next()  # must call next() to continue
    elapsed = time.time() - start
    logger.info(f'Handled {event_type} in {elapsed:.2f}s')

print('Middleware runs before every event handler')

Error Handling in Bolt

Register a global error handler with @app.error to catch unhandled exceptions from your event handlers. This prevents the app from crashing and allows you to log errors, notify a monitoring channel, or send an error message back to the user.

from slack_bolt import App
import traceback

app = App(
    token=os.environ['SLACK_BOT_TOKEN'],
    signing_secret=os.environ['SLACK_SIGNING_SECRET']
)

@app.error
def custom_error_handler(error, body, logger):
    logger.error(f'Error handling event: {error}')
    logger.error(traceback.format_exc())

    # Try to notify the user who triggered the error
    event = body.get('event', {})
    channel = event.get('channel')
    if channel:
        app.client.chat_postMessage(
            channel=channel,
            text='Sorry, I encountered an error. The team has been notified.'
        )

print('Global error handler prevents unhandled crashes')

Using the Slack Web API Client

The app.client property gives direct access to the Slack Web API for any operation not covered by event handlers. Use it to post messages, upload files, invite users to channels, or retrieve channel history programmatically.

from slack_bolt import App

app = App(
    token=os.environ['SLACK_BOT_TOKEN'],
    signing_secret=os.environ['SLACK_SIGNING_SECRET']
)

# Use app.client for direct API calls
def post_to_channel(channel_id, text):
    result = app.client.chat_postMessage(
        channel=channel_id,
        text=text
    )
    print(f'Message posted: ts={result["ts"]}')
    return result

# Get channel list
def list_channels():
    result = app.client.conversations_list(
        types='public_channel',
        limit=100
    )
    channels = result['channels']
    print(f'Found {len(channels)} public channels')
    return channels

# Look up user info
def get_user(user_id):
    result = app.client.users_info(user=user_id)
    return result['user']

Environment Setup Checklist

Before your Slack bot goes live, run through this setup checklist to ensure it's correctly configured:

  • Bot Token and Signing Secret in environment variables
  • Required scopes added in Slack App dashboard
  • Event subscriptions enabled (app_mention, message.im, etc.)
  • Socket Mode enabled (or public URL set for HTTP mode)
  • App installed to your workspace (OAuth flow completed)
import os
from slack_bolt import App

def verify_slack_setup():
    required_env = [
        'SLACK_BOT_TOKEN',
        'SLACK_SIGNING_SECRET',
        'SLACK_APP_TOKEN'
    ]
    missing = [var for var in required_env if not os.environ.get(var)]
    if missing:
        raise EnvironmentError(f'Missing env vars: {missing}')

    token = os.environ['SLACK_BOT_TOKEN']
    if not token.startswith('xoxb-'):
        raise ValueError('SLACK_BOT_TOKEN must start with xoxb-')

    app_token = os.environ['SLACK_APP_TOKEN']
    if not app_token.startswith('xapp-'):
        raise ValueError('SLACK_APP_TOKEN must start with xapp-')

    print('Slack environment setup looks correct!')

verify_slack_setup()

Quick Check: Socket Mode vs HTTP Mode

Test your understanding of Slack Bolt deployment modes.

Slack Bolt Basics Recap

You have the foundation for building Slack bots with Bolt:

  • App(token, signing_secret) — initializes the Bolt app with credentials from env vars
  • Bot Token (xoxb-) for API calls; App-Level Token (xapp-) for Socket Mode
  • Socket Mode — WebSocket, no public URL, great for development and internal tools
  • HTTP Mode — public HTTPS endpoint, required for production/multi-workspace apps
  • Scopes — configure in Slack App dashboard; add only what you need
  • Middleware and @app.error — for logging, validation, and error handling

Frequently asked questions

Is the “Slack Bolt SDK Basics” lesson free?

Yes — the full text of “Slack Bolt SDK Basics” 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 “Slack Bolt SDK Basics”?

App initialization, bot tokens, socket mode vs HTTP, and event subscriptions. 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 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Slack Bolt SDK Basics” 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