slack-api
Slack bot development and workspace automation using Web API, Events API, Socket Mode, and Block Kit for building interactive messaging applications
What this skill does
# Slack API Skill
Master Slack bot development and workspace automation using the Slack Platform. This skill covers the Web API, Events API, Socket Mode, Block Kit UI framework, and the Python Bolt SDK for building production-ready Slack applications.
## When to Use This Skill
### USE when:
- Building notification systems for CI/CD pipelines
- Creating interactive bots for team workflows
- Automating incident response and alerting
- Building approval workflows with interactive messages
- Integrating external services with Slack channels
- Creating slash commands for common operations
- Building internal tools with modal dialogs
- Implementing scheduled message automation
### DON'T USE when:
- Microsoft Teams is the primary platform (use teams-api)
- Simple one-way notifications only (use incoming webhooks directly)
- Need email-based workflows (different domain)
- Slack Enterprise Grid with complex org requirements
- Real-time gaming or high-frequency updates (consider WebSockets)
## Prerequisites
### Slack App Setup
```bash
# 1. Create a Slack App at https://api.slack.com/apps
# 2. Choose "From scratch" and select your workspace
# Required Bot Token Scopes (OAuth & Permissions):
# - chat:write - Post messages
# - chat:write.public - Post to channels without joining
# - channels:read - List public channels
# - channels:history - Read channel messages
# - groups:read - List private channels
# - im:read - List direct messages
# - users:read - Access user information
# - files:write - Upload files
# - reactions:write - Add reactions
# - commands - Add slash commands
# Event Subscriptions (for Events API):
# - message.channels - Messages in public channels
# - message.groups - Messages in private channels
# - message.im - Direct messages
# - app_mention - When bot is mentioned
# Interactive Components:
# - Enable in app settings
# - Set Request URL for button/select handling
```
### Python Environment Setup
```bash
# Create virtual environment
python -m venv slack-bot-env
source slack-bot-env/bin/activate # Linux/macOS
# slack-bot-env\Scripts\activate # Windows
# Install Slack Bolt SDK
pip install slack-bolt slack-sdk
# Install additional dependencies
pip install python-dotenv aiohttp requests
# Create requirements.txt
cat > requirements.txt << 'EOF'
slack-bolt>=1.18.0
slack-sdk>=3.21.0
python-dotenv>=1.0.0
aiohttp>=3.9.0
requests>=2.31.0
EOF
# Environment variables
cat > .env << 'EOF'
SLACK_BOT_TOKEN=xoxb-your-bot-token
SLACK_SIGNING_SECRET=your-signing-secret
SLACK_APP_TOKEN=xapp-your-app-token # For Socket Mode
EOF
```
### Local Development with ngrok
```bash
# Install ngrok
brew install ngrok # macOS
# Or download from https://ngrok.com/download
# Authenticate ngrok
ngrok config add-authtoken YOUR_AUTH_TOKEN
# Start tunnel for local development
ngrok http 3000
# Use the HTTPS URL for:
# - Event Subscriptions Request URL
# - Interactive Components Request URL
# - Slash Commands Request URL
```
## Core Capabilities
### 1. Basic Slack Bot with Bolt
```python
# app.py
# ABOUTME: Basic Slack bot using Bolt framework
# ABOUTME: Handles messages, mentions, and slash commands
import os
from dotenv import load_dotenv
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
load_dotenv()
# Initialize app with bot token and signing secret
app = App(
token=os.environ.get("SLACK_BOT_TOKEN"),
signing_secret=os.environ.get("SLACK_SIGNING_SECRET")
)
# Listen for messages containing "hello"
@app.message("hello")
def message_hello(message, say):
"""Respond to messages containing 'hello'"""
user = message['user']
say(f"Hey there <@{user}>!")
# Listen for app mentions
@app.event("app_mention")
def handle_app_mention(event, say, client):
"""Respond when bot is mentioned"""
user = event['user']
channel = event['channel']
text = event['text']
# Get user info
user_info = client.users_info(user=user)
user_name = user_info['user']['real_name']
say(f"Hi {user_name}! You mentioned me with: {text}")
# Handle message events
@app.event("message")
def handle_message_events(body, logger):
"""Log all message events"""
logger.info(f"Message event: {body}")
# Slash command handler
@app.command("/greet")
def handle_greet_command(ack, say, command):
"""Handle /greet slash command"""
ack() # Acknowledge command within 3 seconds
user = command['user_id']
text = command.get('text', 'everyone')
say(f"<@{user}> sends greetings to {text}!")
# Error handler
@app.error
def custom_error_handler(error, body, logger):
"""Handle errors gracefully"""
logger.exception(f"Error: {error}")
logger.info(f"Request body: {body}")
# Run with Socket Mode (no public URL needed)
if __name__ == "__main__":
handler = SocketModeHandler(
app,
os.environ.get("SLACK_APP_TOKEN")
)
print("Bot is running...")
handler.start()
```
### 2. Block Kit Messages
```python
# blocks.py
# ABOUTME: Block Kit message construction utilities
# ABOUTME: Creates rich, interactive Slack messages
from slack_bolt import App
import os
app = App(token=os.environ.get("SLACK_BOT_TOKEN"))
def create_deployment_message(
environment: str,
version: str,
status: str,
deploy_url: str,
logs_url: str
) -> list:
"""Create a deployment notification with Block Kit"""
status_emoji = {
"success": ":white_check_mark:",
"failure": ":x:",
"in_progress": ":hourglass_flowing_sand:",
"pending": ":clock3:"
}
emoji = status_emoji.get(status, ":question:")
blocks = [
{
"type": "header",
"text": {
"type": "plain_text",
"text": f"{emoji} Deployment {status.title()}",
"emoji": True
}
},
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": f"*Environment:*\n{environment}"
},
{
"type": "mrkdwn",
"text": f"*Version:*\n{version}"
},
{
"type": "mrkdwn",
"text": f"*Status:*\n{status.title()}"
},
{
"type": "mrkdwn",
"text": f"*Time:*\n<!date^{int(time.time())}^{{date_short}} at {{time}}|now>"
}
]
},
{
"type": "divider"
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {
"type": "plain_text",
"text": "View Deployment",
"emoji": True
},
"url": deploy_url,
"style": "primary"
},
{
"type": "button",
"text": {
"type": "plain_text",
"text": "View Logs",
"emoji": True
},
"url": logs_url
}
]
},
{
"type": "context",
"elements": [
{
"type": "mrkdwn",
"text": "Deployed by CI/CD Pipeline"
}
]
}
]
return blocks
def create_approval_message(
request_id: str,
requester: str,
description: str,
details: dict
) -> list:
"""Create an approval request with interactive buttons"""
blocks = [
{
"type": "header",
"text": {
"type": "plain_text",
"text": ":clipboard: Approval Request",
Related in communication
calendly-api
IncludedCalendly scheduling automation using REST API v2 for managing event types, availability, bookings, webhooks, and scheduling workflows
miro-api
IncludedMiro whiteboard automation using REST API v2 and Python SDK for creating boards, frames, shapes, connectors, and collaborative visual workflows
teams-api
IncludedMicrosoft Teams automation using Graph API, Bot Framework, Adaptive Cards, and webhooks for enterprise messaging and collaboration
Customer Support Reply
IncludedCraft empathetic, effective customer support responses that solve problems
Press Release Writer
IncludedWrite professional press releases that get media attention and coverage
Internal Memo Creator
IncludedWrite clear, professional internal memos for company communication