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

# Gateway & Bot Module

> Build chat bots and gateway integrations for messaging platforms

Build powerful chat bots and gateway integrations for Slack, Discord, and other messaging platforms.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Bot Architecture"
        A[💬 Platform] --> B[🔌 Gateway]
        B --> C[🤖 Bot]
        C --> D[🧠 Agent]
        D --> E[📤 Response]
    end
    
    classDef platform fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef gateway fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef bot fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef agent fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef response fill:#10B981,stroke:#7C90A0,color:#fff
    
    class A platform
    class B gateway
    class C bot
    class D agent
    class E response
    classDef agent fill:#8B0000,color:#fff
    classDef tool fill:#189AB4,color:#fff
```

## Quick Start

**1. Create a Bot**

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { BotConfig, BotProtocol } from 'praisonai';

const config: BotConfig = {
  name: "MyBot",
  token: process.env.BOT_TOKEN,
  prefix: "!",
  channels: ["general", "support"]
};
```

**2. Handle Messages**

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
class MyBot implements BotProtocol {
  name = "MyBot";
  config: BotConfig;
  
  constructor(config: BotConfig) {
    this.config = config;
  }
  
  async connect() {
    console.log("Bot connected!");
  }
  
  async disconnect() {
    console.log("Bot disconnected!");
  }
  
  async sendMessage(channel: string, content: string) {
    // Send message to channel
    return { id: "msg-1", content, ... };
  }
  
  onMessage(handler: (msg: BotMessage) => void) {
    // Register message handler
  }
}
```

***

## Bot Types

### BotConfig

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
interface BotConfig {
  name: string;              // Bot name
  token?: string;            // Authentication token
  prefix?: string;           // Command prefix (e.g., "!")
  channels?: string[];       // Allowed channels
  allowedUsers?: string[];   // Allowed user IDs
  metadata?: Record<string, any>;
}
```

### BotUser

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
interface BotUser {
  id: string;                // User ID
  name: string;              // Username
  displayName?: string;      // Display name
  isBot?: boolean;           // Is this a bot?
  metadata?: Record<string, any>;
}
```

### BotChannel

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
interface BotChannel {
  id: string;                // Channel ID
  name: string;              // Channel name
  type: 'text' | 'voice' | 'dm' | 'group';
  metadata?: Record<string, any>;
}
```

### BotMessage

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
interface BotMessage {
  id: string;                // Message ID
  content: string;           // Message content
  author: BotUser;           // Message author
  channel: BotChannel;       // Channel
  timestamp: Date;           // When sent
  attachments?: Array<{
    url: string;
    type: string;
    name?: string;
  }>;
  metadata?: Record<string, any>;
}
```

***

## Bot Protocol

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
interface BotProtocol {
  name: string;
  config: BotConfig;
  
  connect(): Promise<void>;
  disconnect(): Promise<void>;
  
  sendMessage(channel: string, content: string): Promise<BotMessage>;
  onMessage(handler: (message: BotMessage) => void | Promise<void>): void;
  
  getUser(userId: string): Promise<BotUser | null>;
  getChannel(channelId: string): Promise<BotChannel | null>;
}
```

***

## Gateway Types

### GatewayConfig

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
interface GatewayConfig {
  url: string;               // Gateway URL
  apiKey?: string;           // API key
  timeout?: number;          // Request timeout (ms)
  retryAttempts?: number;    // Retry count
  retryDelay?: number;       // Delay between retries (ms)
  metadata?: Record<string, any>;
}
```

### GatewayMessage

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
interface GatewayMessage {
  id: string;
  type: 'request' | 'response' | 'event' | 'error';
  payload: any;
  timestamp: Date;
  correlationId?: string;
  metadata?: Record<string, any>;
}
```

### GatewayEvent

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
interface GatewayEvent {
  type: string;              // Wire value of a GatewayEventType member
  data: any;                 // Event data
  timestamp: Date;
  source?: string;           // Event source
  metadata?: Record<string, any>;
}
```

`type` carries the wire value of a [`GatewayEventType`](#gateway-event-types) member.

***

## Gateway Event Types

`GatewayEventType` is the typed enum of every wire event the gateway can send over the WebSocket. Branch on it instead of raw strings.

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { GatewayEventType, GatewayEvent } from 'praisonai';

// gateway: any GatewayClientProtocol implementation
gateway.onEvent((event: GatewayEvent) => {
  switch (event.type) {
    case GatewayEventType.MESSAGE:
      renderMessage(event.data);
      break;
    case GatewayEventType.TOKEN_STREAM:
      appendToken(event.data);
      break;
    case GatewayEventType.STREAM_END:
      finalizeAnswer();
      break;
    case GatewayEventType.HELLO_ERROR:
      handleHandshakeError(event.data);
      break;
  }
});
```

Wire values are the lowercase member names (`GatewayEventType.MESSAGE_ABORT === 'message_abort'`).

| Group | Members | Capability | Notes |
| - | - | - | - |
| Connection | `CONNECT`, `DISCONNECT`, `RECONNECT` | — | Lifecycle |
| Session | `SESSION_START`, `SESSION_END`, `SESSION_UPDATE` | — | — |
| Agent | `AGENT_REGISTER`, `AGENT_UNREGISTER`, `AGENT_STATUS` | — | — |
| Message | `MESSAGE`, `MESSAGE_ACK`, `MESSAGE_ABORT`, `TYPING` | — | `MESSAGE_ACK` requires `ack` |
| Streaming | `TOKEN_STREAM`, `TOOL_CALL_STREAM`, `REASONING_STREAM`, `TOOL_PROGRESS_STREAM`, `STREAM_ERROR`, `STREAM_END`, `MODEL_FALLBACK_STREAM`, `RETRY_STREAM`, `TODO_STREAM`, `TOOL_RESULT_STREAM` | `streaming` | See [Gateway Stream Events](https://praison.ai/docs/features/gateway-stream-events.md) |
| System | `HEALTH`, `ERROR`, `BROADCAST` | — | — |
| Liveness | `PING`, `PONG` | — | Application-level heartbeat |
| Push channels | `CHANNEL_SUBSCRIBE`, `CHANNEL_UNSUBSCRIBE`, `CHANNEL_MESSAGE`, `CHANNEL_CREATED`, `CHANNEL_DELETED` | — | — |
| Presence | `PRESENCE_JOIN`, `PRESENCE_LEAVE`, `PRESENCE_UPDATE` | `presence` | — |
| Delivery | `MESSAGE_NACK`, `DELIVERY_RETRY` | `ack` | — |
| Polling | `POLL_REQUEST`, `POLL_RESPONSE` | — | — |
| Handshake | `HELLO`, `HELLO_OK`, `HELLO_ERROR` | — | See [Gateway Handshake Protocol](https://praison.ai/docs/features/gateway-handshake-protocol.md) |

> [!NOTE]
>
> `GatewayEventType` mirrors Python's `praisonaiagents.gateway.protocols.EventType` member-for-member — same names, same wire values. The two are kept in lockstep by [`test_gateway_ts_event_type_lockstep.py`](https://github.com/MervinPraison/PraisonAI/blob/main/src/praisonai-agents/tests/unit/test_gateway_ts_event_type_lockstep.py), which fails CI on any drift. Branch on `GatewayEventType` members with the same confidence as the Python server.

***

## Gateway Protocol

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
interface GatewayProtocol {
  config: GatewayConfig;
  
  connect(): Promise<void>;
  disconnect(): Promise<void>;
  isConnected(): boolean;
  
  send(message: GatewayMessage): Promise<void>;
  receive(): Promise<GatewayMessage | null>;
  
  onEvent(handler: (event: GatewayEvent) => void | Promise<void>): void;
  onError(handler: (error: Error) => void): void;
}
```

***

## Failover Manager

Handle provider failover for high availability:

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { FailoverManager, FailoverConfig, ProviderStatus } from 'praisonai';

const config: FailoverConfig = {
  providers: ["openai", "anthropic", "google"],
  maxRetries: 3,
  retryDelay: 1000,
  healthCheckInterval: 30000
};

const manager = new FailoverManager(config);

// Get next available provider
const provider = manager.getNextProvider();

// Mark provider as failed
manager.markFailed("openai");

// Check provider status
const status = manager.getStatus("openai");
// Returns: ProviderStatus.HEALTHY | DEGRADED | FAILED
```

***

## Autonomy Levels

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { AutonomyLevel } from 'praisonai';

AutonomyLevel.NONE        // No autonomous actions
AutonomyLevel.LOW         // Minimal autonomy
AutonomyLevel.MEDIUM      // Moderate autonomy
AutonomyLevel.HIGH        // High autonomy
AutonomyLevel.FULL        // Full autonomy
```

***

## Sandbox Types

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { SandboxStatus, SandboxResult, SandboxProtocol } from 'praisonai';

// Sandbox status
SandboxStatus.IDLE
SandboxStatus.RUNNING
SandboxStatus.COMPLETED
SandboxStatus.FAILED
SandboxStatus.TIMEOUT

// Sandbox result
interface SandboxResult {
  status: SandboxStatus;
  output?: string;
  error?: string;
  executionTime?: number;
  metadata?: Record<string, any>;
}
```

***

## Common Patterns

> [tab] Slack Bot
>
> ```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> import { BotProtocol, BotConfig, BotMessage, Agent } from 'praisonai';
>
> class SlackBot implements BotProtocol {
>   name = "SlackBot";
>   config: BotConfig;
>   private agent: Agent;
>
>   constructor(config: BotConfig) {
>     this.config = config;
>     this.agent = new Agent({
>       name: "SlackAssistant",
>       instructions: "Help users in Slack"
>     });
>   }
>
>   onMessage(handler: (msg: BotMessage) => void) {
>     // When message received
>     this.handleMessage = async (msg) => {
>       if (msg.content.startsWith(this.config.prefix!)) {
>         const query = msg.content.slice(1);
>         const response = await this.agent.start(query);
>         await this.sendMessage(msg.channel.id, response);
>       }
>     };
>   }
> }
> ```

> [tab] Gateway Client
>
> ```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> import { GatewayProtocol, GatewayConfig, GatewayMessage } from 'praisonai';
>
> class WebSocketGateway implements GatewayProtocol {
>   config: GatewayConfig;
>   private ws: WebSocket | null = null;
>
>   constructor(config: GatewayConfig) {
>     this.config = config;
>   }
>
>   async connect() {
>     this.ws = new WebSocket(this.config.url);
>     await new Promise((resolve) => {
>       this.ws!.onopen = resolve;
>     });
>   }
>
>   async send(message: GatewayMessage) {
>     this.ws?.send(JSON.stringify(message));
>   }
>
>   isConnected() {
>     return this.ws?.readyState === WebSocket.OPEN;
>   }
> }
> ```

***

## API Reference

> [card] [BotProtocol](https://praison.ai/docs/sdk/reference/typescript/classes/BotProtocol.md)
>
> Bot protocol interface

> [card] [GatewayProtocol](https://praison.ai/docs/sdk/reference/typescript/classes/GatewayProtocol.md)
>
> Gateway protocol interface

***

## Best Practices

> [accordion] Use failover for reliability
>
> Configure multiple providers with `FailoverManager` for high availability.

> [accordion] Handle disconnections gracefully
>
> Implement reconnection logic in your bot's `connect()` method.

> [accordion] Rate limit message handling
>
> Add rate limiting to prevent overwhelming your agent with messages.

***

## Related

> [card] [Slack Bot](https://praison.ai/docs/js/slackbot-agent.md)
>
> Build Slack integrations

> [card] [Voice](https://praison.ai/docs/js/voice.md)
>
> Voice-enabled agents


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.