> 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/ch20-core-channel-implementations/20.2-telegram-channel.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 20.2 Telegram Channel (grammY)

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

***

Telegram is one of the best-supported channels in OpenClaw—its Bot API is well-designed, well-documented, and supports rich message formats. OpenClaw uses the **grammY** framework to interface with the Telegram Bot API.

***

## 20.2.1 grammY Framework and Bot API Integration

> **Sidebar: grammY**
>
> grammY is a modern Telegram Bot framework written in TypeScript, providing type-safe API wrappers, middleware systems, and a plugin ecosystem. Compared to older frameworks like Telegraf, grammY has better type inference and a more active ecosystem.

OpenClaw's Telegram module is located in the `src/telegram/` directory, with the core file being `bot.ts`. Bot creation involves coordination of multiple components:

```typescript
// src/telegram/bot.ts (simplified)
import { Bot, webhookCallback } from "grammy";
import { sequentialize } from "@grammyjs/runner";
import { apiThrottler } from "@grammyjs/transformer-throttler";

export function createTelegramBot(options: TelegramBotOptions) {
  const bot = new Bot(options.token);

  // Install API throttler
  bot.api.config.use(apiThrottler());

  // Install sequentialization middleware—ensures updates from the same chat are processed serially
  bot.use(sequentialize(getTelegramSequentialKey));

  // Register native commands
  registerTelegramNativeCommands(bot, ...);

  // Register message handlers
  registerTelegramHandlers(bot, ...);

  return bot;
}
```

### Sequentialization

The `sequentialize` middleware ensures updates from the **same chat** are processed serially, avoiding race conditions. The sequential key generation logic considers multiple contexts:

```typescript
// src/telegram/bot.ts (simplified)
export function getTelegramSequentialKey(ctx): string {
  // Prefer chat.id
  const chatId = ctx.chat?.id
    ?? ctx.update?.message?.chat?.id
    ?? ctx.update?.callback_query?.message?.chat?.id;

  if (chatId) return String(chatId);
  return ctx.me?.id ? `bot-${ctx.me.id}` : "global";
}
```

### API Throttling

The `apiThrottler()` plugin automatically throttles Telegram API calls to avoid triggering Telegram's rate limits (429 Too Many Requests). This is critical for high-concurrency scenarios with multiple groups and users.

## 20.2.2 Telegram Bot Configuration and Webhook Mode

Telegram Bot supports two modes for receiving updates:

| Mode             | Mechanism                                        | Use Case                                |
| ---------------- | ------------------------------------------------ | --------------------------------------- |
| **Long Polling** | Bot actively pulls updates from Telegram servers | Development, servers behind NAT         |
| **Webhook**      | Telegram servers push updates to Bot             | Production, publicly accessible servers |

OpenClaw supports both. Webhook mode is registered via `webhookCallback`:

```typescript
// src/telegram/webhook.ts (conceptual)
import { webhookCallback } from "grammy";

// Register Webhook endpoint
const handleUpdate = webhookCallback(bot, "express");
app.post(`/webhook/${token}`, handleUpdate);

// Set Webhook URL
await bot.api.setWebhook(webhookUrl);
```

The advantage of Webhook mode is **low latency**—Telegram servers push immediately upon receiving a message, whereas long polling must wait for the next polling cycle.

Configuration also includes proxy support (`src/telegram/proxy.ts`) and network error handling (`src/telegram/network-errors.ts`), enabling the Bot to run stably in network-restricted environments.

## 20.2.3 Draft Stream Implementation

Telegram's draft stream (Draft Stream) was discussed in detail in Section 18.4. Here we supplement how it integrates at the Bot message dispatch layer.

In `bot-message-dispatch.ts`, the conditions for enabling draft stream are:

```typescript
const canStreamDraft =
  streamMode !== "off" &&
  isPrivateChat &&                    // Private chat only
  typeof draftThreadId === "number" && // Has thread ID
  (await resolveBotTopicsEnabled(primaryCtx)); // Topics feature enabled
```

Stream mode (`streamMode`) is parsed from configuration via `resolveTelegramStreamMode`, supporting three values: `"off"`, `"partial"`, and `"block"`.

Telegram also has dedicated draft chunking configuration (`src/telegram/draft-chunking.ts`) for parsing BlockChunker parameters in block mode.

## 20.2.4 Custom Commands

Telegram Bot supports native slash commands (`/start`, `/help`, etc.). OpenClaw allows users to define custom commands in configuration:

```typescript
// src/config/telegram-custom-commands.ts
export const TELEGRAM_COMMAND_NAME_PATTERN = /^[a-z0-9_]{1,32}$/;

export function resolveTelegramCustomCommands(params) {
  const entries = params.commands ?? [];
  const resolved = [];
  const issues = [];

  for (const entry of entries) {
    const normalized = normalizeTelegramCommandName(entry.command);

    // Validation: only lowercase letters, digits, underscores, max 32 characters
    if (!TELEGRAM_COMMAND_NAME_PATTERN.test(normalized)) {
      issues.push({ message: `"/${normalized}" is invalid` });
      continue;
    }

    // Check: cannot conflict with native commands
    if (reserved.has(normalized)) {
      issues.push({ message: `"/${normalized}" conflicts with native command` });
      continue;
    }

    // Check: cannot be duplicated
    if (seen.has(normalized)) {
      issues.push({ message: `"/${normalized}" is duplicated` });
      continue;
    }

    resolved.push({ command: normalized, description });
  }

  return { commands: resolved, issues };
}
```

Custom command processing goes through four layers of validation: format legality → reserved word conflicts → duplication detection → description completeness. This ensures the command list submitted to the Telegram Bot API is always valid.

Native commands are registered in `bot-native-commands.ts`, with built-in commands including `/start` (start conversation), `/help` (help), `/model` (switch model), etc. Command authorization checks can be configured to allow only bot owner execution.

***

## Section Summary

1. **grammY framework** provides type-safe Telegram Bot API wrappers; OpenClaw uses its sequentialization middleware and API throttler.
2. Supports both **long polling and Webhook** modes; Webhook is recommended for production for low latency.
3. **Draft stream** is enabled only in private chats, supporting both partial and block stream modes.
4. **Custom commands** are registered to the Telegram Bot API after passing four layers of validation: format, conflicts, duplication, and description.
