Slack Plugin
Team notifications and collaboration with Slack messaging, threads, and file sharing. Built on `slack-sdk`.
#Installation
pip install slack-sdk#Quick Start
from daita import Agent
from daita.plugins import slack
# Create plugin
slack_client = slack(token="xoxb-your-bot-token")
# Agent uses Slack tools autonomously
agent = Agent(
name="Notification Agent",
prompt="You are a notification specialist. Help users send messages to Slack.",
tools=[slack_client]
)
await agent.start()
result = await agent.run("Send a message to #alerts that the deployment is complete")#Direct Usage
The plugin can be used directly without agents for programmatic access. For comprehensive Slack API documentation, see the official Slack API docs. The main value of this plugin is agent integration - enabling LLMs to autonomously send notifications and interact with Slack channels.
#Connection Parameters
slack(
token: str,
bot_user_oauth_token: Optional[str] = None,
app_token: Optional[str] = None,
default_channel: Optional[str] = None,
**kwargs
)#Parameters
token(str): Slack bot token (xoxb-...) - requiredbot_user_oauth_token(str): Bot user OAuth token for extended permissions (optional)app_token(str): App-level token for Socket Mode (optional)default_channel(str): Default channel for messages (optional)- **
**kwargs**: Additional Slack client parameters
#Connection Methods
# Basic bot token
async with slack(token="xoxb-your-bot-token") as slack:
await slack.send_message("#general", "Hello!")
# With default channel
async with slack(
token="xoxb-your-bot-token",
default_channel="#alerts"
) as slack:
await slack.send_message(None, "Using default channel")
# From environment variable (recommended)
import os
async with slack(token=os.getenv("SLACK_BOT_TOKEN")) as slack:
await slack.send_message("#team", "Secure notification")#Using with Agents
#Direct Messaging Operations (Scripts)
For scripts that don't need agent capabilities:
from daita.plugins import slack
import os
async with slack(token=os.getenv("SLACK_BOT_TOKEN")) as slack_client:
# Notify start
result = await slack_client.send_message("#processing", "Starting data processing")
thread_ts = result['ts']
# Process data
processed_count = 100 # Your processing logic here
# Notify completion in thread
await slack_client.send_message(
channel="#processing",
text=f"Processed {processed_count} records",
thread_ts=thread_ts
)
print(f"Notifications sent: {processed_count} records processed")#Tool-Based Integration (Recommended)
Slack plugin exposes messaging operations as tools that agents can use autonomously:
from daita import Agent
from daita.plugins import slack
import os
# Create Slack plugin
slack_client = slack(token=os.getenv("SLACK_BOT_TOKEN"))
# Pass plugin to agent - agent can now use Slack tools autonomously
agent = Agent(
name="Notification Agent",
prompt="You are a notification specialist. Help users send messages and updates to Slack.",
llm_provider="openai",
model="gpt-4",
tools=[slack_client]
)
await agent.start()
# Agent autonomously uses Slack tools to answer questions
result = await agent.run("Send a summary of today's metrics to #analytics")
# The agent will autonomously:
# 1. Use send_slack_message or send_slack_summary tool
# 2. Format the message appropriately
# 3. Send to the correct channel
await agent.stop()#Available Tools
The Slack plugin exposes these tools to LLM agents:
| Tool | Description | Parameters |
|---|---|---|
| send_slack_message | Send message to channel | channel (required), text (required) |
| send_slack_summary | Send formatted agent summary | channel (required), summary (required), results (object) |
| list_slack_channels | List available channels | None |
Tool Categories: communication
Tool Source: plugin
Bot Token: Configured at plugin initialization
#Tool Usage Example
from daita import Agent
from daita.plugins import slack
import os
# Setup Slack with tool integration
slack_client = slack(token=os.getenv("SLACK_BOT_TOKEN"))
agent = Agent(
name="Alert System",
prompt="You are an alert system. Help users send notifications to Slack channels.",
llm_provider="openai",
model="gpt-4",
tools=[slack_client]
)
await agent.start()
# Natural language command - agent uses tools autonomously
result = await agent.run("""
Monitor system status and notify team:
1. Check all available channels
2. Send deployment status to #ops
3. Post error summary to #alerts if errors found
""")
# Agent orchestrates Slack tool calls to send notifications
print(result)
await agent.stop()#Error Handling
from daita.agents import Agent
agent = Agent(name="Agent")
try:
async with slack(token="xoxb-token") as slack:
await slack.send_message("#alerts", "Test message")
except RuntimeError as e:
if "slack-sdk not installed" in str(e):
print("Install slack-sdk: pip install slack-sdk")
elif "Invalid Slack token" in str(e):
print("Check your bot token")
elif "invalid_auth" in str(e):
print("Authentication failed - verify token")#Best Practices
Security:
- Store bot tokens in environment variables, never hardcode
- Use bot tokens (xoxb-) instead of user tokens for automation
- Rotate tokens regularly
- Restrict bot permissions to minimum required scopes
Performance:
- Use threads to organize related messages
- Batch notifications when possible to avoid rate limits
- Cache channel IDs to reduce API calls
- Use Block Kit for rich formatting instead of attachments
Message Design:
- Keep messages concise and actionable
- Use threads for detailed information
- Include context (agent name, timestamp, etc.)
- Use emojis and formatting for better visibility
Error Handling:
- Always handle connection failures gracefully
- Validate channel names before sending
- Check file sizes before uploading (max 1GB)
- Implement retry logic for transient failures
#Block Kit Examples
Status notification:
blocks = [
{"type": "header", "text": {"type": "plain_text", "text": "🚀 Deployment Status"}},
{
"type": "section",
"fields": [
{"type": "mrkdwn", "text": "*Environment:* Production"},
{"type": "mrkdwn", "text": "*Status:* ✅ Success"},
{"type": "mrkdwn", "text": "*Duration:* 2m 34s"},
{"type": "mrkdwn", "text": "*Deployed by:* CI/CD"}
]
}
]
await slack.send_message("#deploys", "Deployment", blocks=blocks)Alert with actions:
blocks = [
{
"type": "section",
"text": {"type": "mrkdwn", "text": "⚠️ *High CPU Usage Detected*\nServer: web-01\nCPU: 95%"}
},
{
"type": "actions",
"elements": [
{"type": "button", "text": {"type": "plain_text", "text": "View Logs"}, "value": "view_logs"},
{"type": "button", "text": {"type": "plain_text", "text": "Restart"}, "value": "restart"}
]
}
]
await slack.send_message("#ops", "Alert", blocks=blocks)#Getting Your Bot Token
- Go to https://api.slack.com/apps
- Create a new app or select existing app
- Navigate to "OAuth & Permissions"
- Add required bot token scopes:
chat:write- Send messagesfiles:write- Upload fileschannels:history- Read channel historychannels:read- List channels
- Install app to workspace
- Copy the "Bot User OAuth Token" (starts with
xoxb-)
#Troubleshooting
| Issue | Solution |
|---|---|
slack-sdk not installed | pip install slack-sdk |
Invalid Slack token | Verify bot token starts with xoxb- |
invalid_auth | Check token is correct and app is installed |
channel_not_found | Verify channel name/ID, ensure bot is invited |
not_in_channel | Invite bot to channel: /invite @your-bot |
rate_limited | Reduce message frequency, implement backoff |
file_too_large | Compress file or split into multiple files |
#Common Patterns
Daily digest:
async with slack(token=os.getenv("SLACK_BOT_TOKEN")) as slack:
summary = generate_daily_summary()
await slack.send_message("#daily-digest", summary)Error notifications:
async with slack(token=os.getenv("SLACK_BOT_TOKEN")) as slack:
try:
process_data()
except Exception as e:
await slack.send_message("#errors", f"⚠️ Error: {str(e)}")
raiseWorkflow progress:
async with slack(token=os.getenv("SLACK_BOT_TOKEN")) as slack:
msg = await slack.send_message("#workflows", "Starting workflow")
thread_ts = msg['ts']
for step in workflow_steps:
await slack.send_message(
"#workflows",
f"✓ Completed: {step}",
thread_ts=thread_ts
)#Next Steps
- Plugin Overview - All available plugins
- Redis Plugin - Distributed messaging
- REST Plugin - API integrations