> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch42-hands-on-project/42.3-channel-integration.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 42.3 Channel Integration

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~360k tokens, Output \~5k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

The previous section implemented MiniClaw's core skeleton. This section will integrate two message channels: Telegram Bot and WebChat, allowing users to interact with the AI assistant through different platforms.

## 42.3.1 Implementing Telegram Bot Channel Adapter

### Prerequisites

1. Find `@BotFather` in Telegram and send `/newbot` to create a bot
2. Record the returned Bot Token (format like `123456789:ABCdefGHIjklMNOpqrsTUVwxyz`)
3. Set the Token to the environment variable `TELEGRAM_BOT_TOKEN`

### Using the grammY Framework

grammY is a lightweight yet feature-complete Telegram Bot framework (referencing OpenClaw's Telegram channel implementation, Chapter 19):

```typescript
// src/channels/telegram.ts

import { Bot } from "grammy";
import { WebSocket } from "ws";

export class TelegramChannel {
  private bot: Bot;
  private gatewayWs: WebSocket;

  constructor(params: {
    botToken: string;
    gatewayUrl: string;
  }) {
    this.bot = new Bot(params.botToken);
    this.gatewayWs = new WebSocket(params.gatewayUrl);
  }

  start() {
    // Wait for Gateway connection to be ready
    this.gatewayWs.on("open", () => {
      console.log("Telegram channel connected to Gateway");
    });

    // Handle events returned from Gateway
    this.gatewayWs.on("message", (raw) => {
      const frame = JSON.parse(raw.toString());
      if (frame.type === "event" && frame.event === "chat") {
        this.handleChatEvent(frame.payload);
      }
    });

    // Listen for Telegram messages
    this.bot.on("message:text", async (ctx) => {
      const chatId = ctx.chat.id;
      const senderId = ctx.from?.id;
      const text = ctx.message.text;

      // Construct session key (one session per Telegram user)
      const sessionKey = `telegram:${senderId}`;

      // Send to Gateway
      this.sendToGateway("chat.send", {
        sessionKey,
        message: text,
        channel: "telegram",
        accountId: String(senderId),
        to: String(chatId),
      });
    });

    this.bot.start();
    console.log("Telegram Bot started");
  }

  private handleChatEvent(payload: {
    sessionKey: string;
    state: string;
    message?: { content: string };
  }) {
    if (payload.state !== "final") return;
    if (!payload.sessionKey.startsWith("telegram:")) return;

    // Reverse lookup chatId from sessionKey
    // (In a real project, maintain a sessionKey → chatId mapping)
    const content = payload.message?.content;
    if (content) {
      // Route reply back to the correct chat via Gateway
      this.bot.api.sendMessage(/* chatId */, content);
    }
  }

  private sendToGateway(method: string, params: unknown) {
    const frame = {
      type: "req",
      id: crypto.randomUUID(),
      method,
      params,
    };
    this.gatewayWs.send(JSON.stringify(frame));
  }
}
```

### Channel-Session Mapping

OpenClaw uses a carefully designed session key system (Chapter 14) to map channel users to sessions. MiniClaw's simplified version:

```typescript
// Each Telegram user → one independent session
const sessionKey = `telegram:${telegramUserId}`;

// Maintain reverse mapping (for reply delivery)
const channelMeta = new Map<string, {
  channel: "telegram";
  chatId: number;
  userId: number;
}>();
```

## 42.3.2 Implementing Discord Bot Channel Adapter

The Discord channel implementation pattern is similar to Telegram (referencing Chapter 20), but with a different API style:

```typescript
// src/channels/discord.ts

import { Client, GatewayIntentBits } from "discord.js";

export class DiscordChannel {
  private client: Client;

  constructor(params: { botToken: string; gatewayUrl: string }) {
    this.client = new Client({
      intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.DirectMessages,
        GatewayIntentBits.MessageContent,
      ],
    });
  }

  start() {
    this.client.on("messageCreate", async (message) => {
      if (message.author.bot) return;  // Ignore bot messages

      const sessionKey = `discord:${message.author.id}`;
      // Send to Gateway...

      // Discord supports message segmentation (2000 character limit)
    });

    this.client.on("ready", () => {
      console.log(`Discord Bot logged in as ${this.client.user?.tag}`);
    });
  }
}
```

Key differences for Discord:

| Feature              | Telegram                      | Discord                            |
| -------------------- | ----------------------------- | ---------------------------------- |
| Message length limit | 4096 characters               | 2000 characters                    |
| Rich text            | Markdown subset               | Markdown subset                    |
| Permissions          | Bot Token only                | Requires Intent + Permissions      |
| Group chat trigger   | Respond to all DMs by default | Requires @mention or configuration |

## 42.3.3 Implementing WebChat Channel

WebChat is the most flexible channel—users interact directly with the Gateway's WebSocket through a browser.

### Frontend (HTML + JavaScript)

```html
<!-- ui/index.html -->
<!DOCTYPE html>
<html>
<head>
  <title>MiniClaw Chat</title>
  <style>
    body { font-family: system-ui; max-width: 800px; margin: 0 auto; }
    #messages { height: 500px; overflow-y: auto; border: 1px solid #ccc;
                padding: 16px; margin: 16px 0; }
    .user { color: #0066cc; }
    .assistant { color: #333; }
    #input { width: 80%; padding: 8px; }
    button { padding: 8px 16px; }
  </style>
</head>
<body>
  <h1>MiniClaw</h1>
  <div id="messages"></div>
  <input id="input" placeholder="Enter message..." />
  <button onclick="sendMessage()">Send</button>

  <script>
    const ws = new WebSocket("ws://localhost:3000");
    const messages = document.getElementById("messages");
    const input = document.getElementById("input");
    const SESSION_KEY = "webchat:default";
    let reqId = 0;

    ws.onmessage = (event) => {
      const frame = JSON.parse(event.data);
      if (frame.type === "event" && frame.event === "chat") {
        if (frame.payload.state === "final") {
          appendMessage("assistant", frame.payload.message.content);
        }
      }
    };

    function sendMessage() {
      const text = input.value.trim();
      if (!text) return;
      appendMessage("user", text);
      ws.send(JSON.stringify({
        type: "req",
        id: String(++reqId),
        method: "chat.send",
        params: { sessionKey: SESSION_KEY, message: text },
      }));
      input.value = "";
    }

    function appendMessage(role, content) {
      const div = document.createElement("div");
      div.className = role;
      div.innerHTML = `<strong>${role}:</strong> ${escapeHtml(content)}`;
      messages.appendChild(div);
      messages.scrollTop = messages.scrollHeight;
    }

    function escapeHtml(text) {
      const div = document.createElement("div");
      div.textContent = text;
      return div.innerHTML;
    }

    input.addEventListener("keydown", (e) => {
      if (e.key === "Enter") sendMessage();
    });
  </script>
</body>
</html>
```

### Static File Serving

Use Express to serve the WebChat frontend:

```typescript
// src/channels/webchat.ts

import express from "express";
import path from "node:path";

export function serveWebChat(port: number) {
  const app = express();
  app.use(express.static(path.join(import.meta.dirname, "../../ui")));
  app.listen(port, () => {
    console.log(`WebChat UI available at http://localhost:${port}`);
  });
}
```

### Streaming Output Enhancement

The WebChat example above only receives the final reply. Referencing OpenClaw's streaming design (Chapter 11), you can add incremental update support:

```typescript
// Gateway side: send delta events during Agent execution
gateway.broadcast("chat", {
  sessionKey,
  state: "delta",
  message: { content: partialText },
});

// Frontend: append incrementally
if (frame.payload.state === "delta") {
  updateStreamingMessage(frame.payload.message.content);
}
```

### Unified Channel Entry Point

Centralize the startup logic for all channels:

```typescript
// src/index.ts (updated)

// Start Gateway
const gateway = new Gateway(3000);
registerRoutes(gateway, sessions, agent);

// Start channels
if (process.env.TELEGRAM_BOT_TOKEN) {
  const telegram = new TelegramChannel({
    botToken: process.env.TELEGRAM_BOT_TOKEN,
    gatewayUrl: "ws://localhost:3000",
  });
  telegram.start();
}

// Start WebChat UI
serveWebChat(8080);

console.log("MiniClaw is running!");
console.log("  Gateway: ws://localhost:3000");
console.log("  WebChat: http://localhost:8080");
```

***

## Summary of This Section

1. **Telegram channel** uses the grammY framework, receives messages via Bot Token, forwards them to the Gateway, and delivers Agent replies back to users.
2. **Discord channel** uses discord.js, requires configuring Intents and permissions, and must account for the 2000 character message length limit.
3. **WebChat channel** is the simplest implementation—the frontend communicates directly with the Gateway via WebSocket without needing an intermediate adapter layer.
4. **Channel-session mapping** implements per-user independent sessions using session keys in the format `{channel}:{userId}`.
5. **Streaming output** is implemented through the Gateway's `delta` event for incremental text updates.
