> ## Documentation Index
> Fetch the complete documentation index at: https://docs.praison.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Channels Gateway

> Connect agents to chat platforms like Telegram, Discord, Slack, and WhatsApp

Connect PraisonAI agents to popular chat platforms through the channels gateway integration.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Chat Platforms"
        A[📱 Telegram] --> B[🤖 BotOS]
        C[💬 Discord] --> B
        D[💼 Slack] --> B
        E[📞 WhatsApp] --> B
    end
    subgraph "PraisonAI"
        B --> F[⚙️ Gateway]
        F --> G[🧠 Agents]
    end
    
    classDef platform fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef gateway fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef agent fill:#10B981,stroke:#7C90A0,color:#fff
    
    class A,C,D,E platform
    class B,F gateway
    class G agent
```

## Quick Start

<Steps>
  <Step title="Install Bot Dependencies">
    Install the bot integration package:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    pip install "praisonai[bot]"
    ```

    This adds support for Telegram, Discord, Slack, and WhatsApp platforms.
  </Step>

  <Step title="Configure Platform Tokens">
    Set environment variables for your chosen platforms:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Telegram
    export TELEGRAM_BOT_TOKEN="your_telegram_token"

    # Discord  
    export DISCORD_BOT_TOKEN="your_discord_token"

    # Slack
    export SLACK_BOT_TOKEN="xoxb-your-slack-token"
    export SLACK_APP_TOKEN="xapp-your-slack-app-token"

    # WhatsApp
    export WHATSAPP_ACCESS_TOKEN="your_whatsapp_token"
    export WHATSAPP_PHONE_NUMBER_ID="your_phone_number_id"
    ```
  </Step>

  <Step title="Launch Gateway with Channels">
    Start the integrated gateway with channel bot support:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    praisonai dashboard --aiui
    ```

    This starts Pattern B host integration with channels feature enabled.

    <Note>
      All configured channels now start reliably from a single gateway, resolving the previous `cannot pickle '_thread.RLock' object` error through automatic [Agent Cloning](/features/agent-cloning).
    </Note>
  </Step>
</Steps>

***

## Platform Configuration

### Telegram Setup

1. Create bot with [@BotFather](https://t.me/botfather)
2. Get your bot token
3. Set environment variable:

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
export TELEGRAM_BOT_TOKEN="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
```

### Discord Setup

1. Create application in [Discord Developer Portal](https://discord.com/developers/applications)
2. Create bot and get token
3. Set environment variable:

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
export DISCORD_BOT_TOKEN="your_discord_bot_token"
```

### Slack Setup

1. Create Slack app in [Slack API](https://api.slack.com/apps)
2. Get Bot User OAuth Token and App-Level Token
3. Set environment variables:

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
export SLACK_BOT_TOKEN="xoxb-your-bot-token"
export SLACK_APP_TOKEN="xapp-your-app-token"
```

### WhatsApp Setup

1. Set up WhatsApp Business API
2. Get access token and phone number ID
3. Set environment variables:

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
export WHATSAPP_ACCESS_TOKEN="your_access_token"
export WHATSAPP_PHONE_NUMBER_ID="your_phone_number_id"
```

***

## Gateway Patterns

### Pattern B: In-Process Host

Run channels within your application process:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai.integration import configure_host, create_host_app

configure_host(
    title="Bot Gateway",
    pages=["chat", "agents", "sessions"],
    agents=[{
        "name": "Support Agent",
        "instructions": "Help users with their questions",
        "llm": "gpt-4o"
    }]
)

app = create_host_app()
# Channels auto-start if environment variables are set
```

### Pattern C: Integrated Gateway

Single process with WebSocket support:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import asyncio
from praisonai.integration import run_integrated_gateway

async def main():
    await run_integrated_gateway(
        port=8080,
        title="Multi-Platform Bot",
        agents=[{
            "name": "Assistant", 
            "llm": "gpt-4o"
        }]
    )

asyncio.run(main())
```

The gateway serves:

* Chat UI at `http://localhost:8080`
* REST API at `http://localhost:8080/api`
* WebSocket at `ws://localhost:8080/ws`
* Bot integrations auto-start based on environment variables

### Legacy Mode

For callback-only integration without provider wiring:

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
export PRAISONAI_HOST_LEGACY=1
praisonai ui
```

This uses only `@aiui.reply` callbacks without automatic agent integration.

***

## BotOS Multi-Platform Orchestration

Use `BotOS` for advanced multi-platform management:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai.bots import BotOS

# Initialize BotOS with all available platforms
bot_os = BotOS()

# Platforms auto-detected from environment variables
available_platforms = bot_os.get_available_platforms()
# ['telegram', 'discord'] # Based on set environment variables

# Start specific platforms
await bot_os.start_platform('telegram')
await bot_os.start_platform('discord')

# Or start all available
await bot_os.start_all()
```

***

## Channel Features Integration

The `praisonaiui.features.channels` module provides:

| Feature                 | Description                                                      |
| ----------------------- | ---------------------------------------------------------------- |
| **Auto-detection**      | Platforms start automatically when environment variables are set |
| **Session Management**  | Each user gets persistent sessions across bot restarts           |
| **Gateway Integration** | Works seamlessly with Pattern B/C host integration               |
| **WebSocket Support**   | Real-time updates via `/ws` endpoint in Pattern C                |

Example with custom configuration:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiui.features.channels import enable_channels

# Manual channel configuration
enable_channels({
    'telegram': {
        'token': os.getenv('TELEGRAM_BOT_TOKEN'),
        'agent_config': {
            'name': 'Telegram Assistant',
            'instructions': 'You are helpful on Telegram'
        }
    },
    'discord': {
        'token': os.getenv('DISCORD_BOT_TOKEN'), 
        'agent_config': {
            'name': 'Discord Bot',
            'instructions': 'You are helpful on Discord'
        }
    }
})
```

***

## Channel Security

All channels enforce the same access-control pipeline regardless of whether you run them via `praisonai bot start` or `praisonai gateway start`.

| Feature                                | Standalone Bot | Gateway Mode |
| -------------------------------------- | -------------- | ------------ |
| User allowlist (`allowed_users`)       | ✅              | ✅            |
| Channel allowlist (`allowed_channels`) | ✅              | ✅            |
| Unknown user pairing                   | ✅              | ✅            |
| Group policy enforcement               | ✅              | ✅            |

<Card title="Gateway YAML Reference" icon="shield" href="/docs/features/bot-gateway#channel-security">
  Complete YAML field documentation and pipeline diagram
</Card>

<Card title="BotConfig Reference" icon="code" href="/docs/features/messaging-bots#configuration-options">
  Standalone bot configuration options
</Card>

***

## Platform-Specific Features

### Telegram

* Supports markdown formatting
* File uploads and downloads
* Inline keyboards
* Command handling (`/start`, `/help`)

### Discord

* Rich embeds and attachments
* Slash commands
* Thread support
* Role-based permissions

### Slack

* Block kit UI components
* App Home tab
* Workflow integration
* Enterprise security features

### WhatsApp

* Media message support
* Template messages
* Business API features
* Webhook verification

***

## Development vs Production

<Tabs>
  <Tab title="Development">
    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Single platform for testing
    export TELEGRAM_BOT_TOKEN="your_token"
    praisonai dashboard --aiui

    # Check logs
    tail -f ~/.praisonai/unified/logs/ui.log
    ```
  </Tab>

  <Tab title="Production">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    import os
    import asyncio
    from praisonai.integration import run_integrated_gateway

    async def main():
        await run_integrated_gateway(
            port=int(os.getenv("PORT", "8080")),
            host="0.0.0.0",
            title="Production Bot Gateway",
            agents=[{
                "name": "Support Bot",
                "llm": os.getenv("PRAISONAI_MODEL", "gpt-4o"),
                "instructions": "Professional customer support assistant"
            }],
            ui_config={
                "analytics": os.getenv("ANALYTICS_ID"),
                "error_reporting": True
            }
        )

    if __name__ == "__main__":
        asyncio.run(main())
    ```
  </Tab>
</Tabs>

***

## Troubleshooting

### Common Issues

<AccordionGroup>
  <Accordion title="Bot not starting">
    Check environment variables are set correctly:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Verify tokens are set
    echo $TELEGRAM_BOT_TOKEN
    echo $DISCORD_BOT_TOKEN

    # Check bot permissions
    # Telegram: Bot must be added to chat
    # Discord: Bot needs appropriate server permissions
    # Slack: App must be installed to workspace
    ```
  </Accordion>

  <Accordion title="Messages not reaching agents">
    Ensure gateway is running with proper agent configuration:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Verify agent is configured
    from praisonai.integration import configure_host

    configure_host(
        agents=[{
            "name": "Bot Agent",  # Required
            "instructions": "You are helpful",  # Required
            "llm": "gpt-4o"  # Model must be valid
        }]
    )
    ```
  </Accordion>

  <Accordion title="WebSocket connection issues">
    For Pattern C, ensure WebSocket endpoint is accessible:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Test WebSocket connectivity
    curl -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" \
      http://localhost:8080/ws
    ```
  </Accordion>
</AccordionGroup>

***

## Best Practices

<AccordionGroup>
  <Accordion title="Use environment variables for tokens">
    Never hardcode tokens in source code:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Good
    token = os.getenv('TELEGRAM_BOT_TOKEN')
    if not token:
        raise ValueError("TELEGRAM_BOT_TOKEN not set")

    # Bad
    token = "123456:hardcoded_token"  # Security risk
    ```
  </Accordion>

  <Accordion title="Handle rate limits gracefully">
    Different platforms have different rate limits:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Built-in rate limiting
    from praisonai.bots import BotOS

    bot_os = BotOS(rate_limit_config={
        'telegram': {'requests_per_second': 30},
        'discord': {'requests_per_minute': 50},
        'slack': {'requests_per_minute': 100}
    })
    ```
  </Accordion>

  <Accordion title="Monitor bot health">
    Set up monitoring for production deployments:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Health check endpoint
    @app.get("/health")
    async def health_check():
        bot_status = await bot_os.get_platform_status()
        return {"status": "healthy", "bots": bot_status}
    ```
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card title="Host Integration" icon="plug" href="/docs/features/host-integration">
    Pattern B/C integration
  </Card>

  <Card title="Integration Patterns" icon="diagram-project" href="/docs/features/integration-patterns">
    Pattern comparison
  </Card>
</CardGroup>
