Python Slack Bot Guide
This guide demonstrates how to create a Slack bot using the slack-bolt framework (built on top of slack-sdk). It uses Socket Mode, which allows your bot to receive events without exposing a public HTTP endpoint (no need for ngrok or static IPs during development).
Modules Used:
slack_bolt: The official framework for building Slack apps.slack_sdk: The underlying client for the Slack API.- python-dotenv: To securely manage tokens.
Prerequisites
- Go to api.slack.com/apps and create a new app ("From scratch").
- Socket Mode: Go to "Socket Mode" in the sidebar, enable it, and generate an App-Level Token (name it
socket_token). It starts withxapp-. Copy this. - Event Subscriptions:
- Go to "Event Subscriptions", toggle "Enable Events".
- Expand "Subscribe to bot events" and add
app_mentionandmessage.channels.
- OAuth & Permissions:
- Go to "OAuth & Permissions".
- Under "Scopes" > "Bot Token Scopes", ensure
app_mentions:read,chat:write, andchannels:historyare added. - Scroll up and click "Install to Workspace".
- Copy the Bot User OAuth Token. It starts with
xoxb-.
Installation
pip install slack_bolt slack_sdk python-dotenv
Setup
Create a .env file in your project directory:
SLACK_BOT_TOKEN=xoxb-your-bot-token
SLACK_APP_TOKEN=xapp-your-app-level-token
The Code
Save this as slack_bot.py.
import os
from dotenv import load_dotenv
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
# 1. Load Environment Variables
load_dotenv()
# 2. Initialize the App
app = App(token=os.environ.get("SLACK_BOT_TOKEN"))
# --- Event Listeners ---
@app.message("hello")
def message_hello(message, say):
"""
Listens for messages containing "hello" and responds.
"""
# say() sends a message to the channel where the event was triggered
say(f"Hey there <@{message['user']}>!")
@app.event("app_mention")
def handle_app_mention_events(body, say):
"""
Listens for mentions (@BotName) and responds.
"""
say("You mentioned me?")
@app.command("/echo")
def repeat_text(ack, respond, command):
"""
Listens for a slash command /echo (must be created in Slack App settings).
"""
# Acknowledge command request
ack()
respond(f"You said: {command['text']}")
if __name__ == "__main__":
print("⚡️ Bolt app is running!")
# 3. Start Socket Mode
SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start()
Usage
- Run the script:
python slack_bot.py - In Slack, invite the bot to a channel (
/invite @YourBotName). - Type
helloor mention the bot (@YourBotName) to see it respond.