Slack Plugin

Team notifications and collaboration with Slack messaging, threads, and file sharing. Built on `slack-sdk`.

#Installation

bash
pip install slack-sdk

#Quick Start

python
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

python
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-...) - required
  • bot_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

python
# 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:

python
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")

Slack plugin exposes messaging operations as tools that agents can use autonomously:

python
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:

ToolDescriptionParameters
send_slack_messageSend message to channelchannel (required), text (required)
send_slack_summarySend formatted agent summarychannel (required), summary (required), results (object)
list_slack_channelsList available channelsNone

Tool Categories: communication Tool Source: plugin Bot Token: Configured at plugin initialization

#Tool Usage Example

python
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

python
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:

python
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:

python
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

  1. Go to https://api.slack.com/apps
  2. Create a new app or select existing app
  3. Navigate to "OAuth & Permissions"
  4. Add required bot token scopes:
    • chat:write - Send messages
    • files:write - Upload files
    • channels:history - Read channel history
    • channels:read - List channels
  5. Install app to workspace
  6. Copy the "Bot User OAuth Token" (starts with xoxb-)

#Troubleshooting

IssueSolution
slack-sdk not installedpip install slack-sdk
Invalid Slack tokenVerify bot token starts with xoxb-
invalid_authCheck token is correct and app is installed
channel_not_foundVerify channel name/ID, ensure bot is invited
not_in_channelInvite bot to channel: /invite @your-bot
rate_limitedReduce message frequency, implement backoff
file_too_largeCompress file or split into multiple files

#Common Patterns

Daily digest:

python
async with slack(token=os.getenv("SLACK_BOT_TOKEN")) as slack:
    summary = generate_daily_summary()
    await slack.send_message("#daily-digest", summary)

Error notifications:

python
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)}")
        raise

Workflow progress:

python
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