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.

Diagram

Bot Architecture

💬 Platform

🔌 Gateway

🤖 Bot

🧠 Agent

📤 Response

Quick Start

  1. Create a Bot
    typescript
    import { BotConfig, BotProtocol } from 'praisonai';
    
    const config: BotConfig = {
      name: "MyBot",
      token: process.env.BOT_TOKEN,
      prefix: "!",
      channels: ["general", "support"]
    };
  2. Handle Messages
    typescript
    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
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
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
interface BotChannel {
  id: string;                // Channel ID
  name: string;              // Channel name
  type: 'text' | 'voice' | 'dm' | 'group';
  metadata?: Record<string, any>;
}

BotMessage

typescript
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
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
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
interface GatewayMessage {
  id: string;
  type: 'request' | 'response' | 'event' | 'error';
  payload: any;
  timestamp: Date;
  correlationId?: string;
  metadata?: Record<string, any>;
}

GatewayEvent

typescript
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 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
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').

GroupMembersCapabilityNotes
ConnectionCONNECT, DISCONNECT, RECONNECT—Lifecycle
SessionSESSION_START, SESSION_END, SESSION_UPDATE——
AgentAGENT_REGISTER, AGENT_UNREGISTER, AGENT_STATUS——
MessageMESSAGE, MESSAGE_ACK, MESSAGE_ABORT, TYPING—MESSAGE_ACK requires ack
StreamingTOKEN_STREAM, TOOL_CALL_STREAM, REASONING_STREAM, TOOL_PROGRESS_STREAM, STREAM_ERROR, STREAM_END, MODEL_FALLBACK_STREAM, RETRY_STREAM, TODO_STREAM, TOOL_RESULT_STREAMstreamingSee Gateway Stream Events
SystemHEALTH, ERROR, BROADCAST——
LivenessPING, PONG—Application-level heartbeat
Push channelsCHANNEL_SUBSCRIBE, CHANNEL_UNSUBSCRIBE, CHANNEL_MESSAGE, CHANNEL_CREATED, CHANNEL_DELETED——
PresencePRESENCE_JOIN, PRESENCE_LEAVE, PRESENCE_UPDATEpresence—
DeliveryMESSAGE_NACK, DELIVERY_RETRYack—
PollingPOLL_REQUEST, POLL_RESPONSE——
HandshakeHELLO, HELLO_OK, HELLO_ERROR—See Gateway Handshake Protocol

Gateway Protocol

typescript
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
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
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
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

Slack Bot

typescript
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);
      }
    };
  }
}

Gateway Client

typescript
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


Best Practices

Use failover for reliability

Configure multiple providers with FailoverManager for high availability.

Handle disconnections gracefully

Implement reconnection logic in your bot’s connect() method.

Rate limit message handling

Add rate limiting to prevent overwhelming your agent with messages.


Related