OpenClaw Telegram 机器人设置:命令、路由和多代理会话

嘿,自动化构建者们——如果你正在将 OpenClaw 连接到 Telegram,并且想知道当消息从私信、群组和话题中飞来时,路由是如何工作的,请继续阅读。

过去两周,我在三种不同的设置下通过 Telegram 运行了 OpenClaw:个人私信、团队群组和论坛话题。这不是演示场景,而是真实的路由测试,我故意打破会话隔离,用并发请求淹没它,并观察网关如何处理多账户配置。

我不断思考的问题是:当你处理多个聊天时,它能否真正保持干净的会话边界,还是会全部崩溃成一个混乱的对话线程?

这是我发现的结果,以及那些成功的配置模式。

背景介绍,OpenClaw(以前称为 Moltbot 和 Clawdbot)在 2026 年初作为一个开源的自主 AI 助手,获得了超过 10 万个 GitHub 星标。由 Peter Steinberger 创建,它将像 Telegram 这样的消息平台连接到本地或私有服务器上运行的 AI 代理。


创建一个 Telegram 机器人(BotFather)

Every OpenClaw Telegram setup starts with @BotFather, Telegram's official bot creation interface. This hasn't changed since Telegram launched bots — it's still the only way to generate API tokens.

What you'll need:

  • Active Telegram account (phone verification required)
  • 3 minutes for initial setup
  • Bot token stored somewhere secure (I use a password manager)

Step-by-step bot creation

  1. Open Telegram and search for @BotFather
    1. Verified account has a blue checkmark
    2. Send /start to see available commands
  2. Create new bot with /newbot
    1. Bot name: What users see in conversations (can include spaces)
    2. Username: Must end with bot (e.g., YourProjectBot)
    3. Username must be globally unique across Telegram
  3. Save your API token immediately
    1. Format: 123456789:ABCdefGHIjklMNOpqrsTUVwxyz
    2. Treat this like a password — anyone with this token controls your bot
    3. If compromised, use /revoke in BotFather to generate a new one

Critical BotFather settings (optional but recommended):

/setjoingroups  → Allow/deny adding bot to groups
/setprivacy     → OFF = bot sees all group messages
                  ON = bot only sees mentions and commands

I learned this the hard way: if you set privacy to ON and wonder why your bot ignores group messages, that's why. OpenClaw's routing expects full message access by default.


Connect Token + Verify Updates

Getting the token into OpenClaw is where most setup guides stop — but that's where real testing should start.

Basic connection config

OpenClaw supports two token input methods:

Environment variable (quick testing):

export TELEGRAM_BOT_TOKEN="your_token_here"
openclaw gateway

Config file (production approach):

{
  "channels": {
    "telegram": {
      "enabled": true,
      "botToken": "123456789:ABCdefGHIjklMNOpqrsTUVwxyz",
      "dmPolicy": "pairing"
    }
  }
}

Verification test sequence

Here's the sequence I run every time to confirm the Gateway actually sees Telegram updates:

  1. Start Gateway with logging:
openclaw gateway --log-level debug
  1. Send /start to your bot in Telegram
    1. Should trigger pairing flow if dmPolicy: "pairing"
    2. Check terminal for incoming update logs
  2. Monitor update stream:
openclaw logs --follow

Common failure point: Bot token typo. If you see 401 Unauthorized in logs, regenerate the token in BotFather and update your config. Don't waste an hour troubleshooting like I did.

Security note: For production deployments, consider using DigitalOcean's hardened OpenClaw image which includes firewall rules, container isolation, and non-root execution by default.


Command Design That Scales

OpenClaw's command system is where routing logic starts to matter. The Gateway recognizes slash commands across all channels, but Telegram adds its own command autocomplete layer.

The official OpenClaw repository documents the full command set, but after real-world testing, only a handful prove essential.

Core command patterns

These are the commands I actually use in production setups (not the full list — just what survives real usage):

Command
Purpose
Session Scope
/new
Force new session (clears context)
Per-chat
/status
Show session + model + token usage
Current session
/activation
Toggle mention-only vs always-respond
Session-only*
/help
List available commands
N/A

Important: /activation always only affects the current session. To persist it, add it to your config's requireMention settings.

Setting up custom commands in BotFather

This is what makes your bot feel native in Telegram:

  1. In BotFather: /mybots → Select your bot → Edit Commands
  2. Send command list (one per line):
new - Start fresh sessionstatus - Check session statehelp - Show all commands
  1. These appear in Telegram's / autocomplete menu

Reality check: I initially set up 15 commands. After two weeks, I only use 4. Start minimal.

For deeper understanding of Telegram's bot architecture, see the official Telegram Bot tutorial which covers the Bot API fundamentals.


Routing by Chat/User/Topic

This is where OpenClaw's session architecture either makes sense or falls apart. Session keys determine whether conversations stay isolated or bleed together.

Session key structure

OpenClaw generates session keys using this pattern:

agent:<agentId>:telegram:<chatType>:<chatId>[:topic:<topicId>]

Breakdown:

  • DMs: All messages from one user → shared main session
  • Groups: Each group → isolated session (telegram:group:<chatId>)
  • Forum topics: Each topic → separate session (:topic:<threadId> suffix)

Multi-account routing config

Here's a real config I ran for testing three separate Telegram bots routing to different agents:

{
  "channels": {
    "telegram": {
      "accounts": [
        {
          "name": "personal",
          "botToken": "token1...",
          "routing": { "agent": "main" }
        },
        {
          "name": "work",
          "botToken": "token2...",
          "routing": { "agent": "work-agent" }
        },
        {
          "name": "testing",
          "botToken": "token3...",
          "routing": { "agent": "sandbox" }
        }
      ]
    }
  }
}

Each account routes to a separate agent workspace with independent memory and tools. No cross-contamination.

Group routing with mention controls

Default behavior: groups require @mention to trigger responses. Override per-group:

{
  "channels": {
    "telegram": {
      "groups": {
        "*": { "requireMention": true },
        "-1001234567890": { 
          "requireMention": false 
        }
      }
    }
  }
}

Group ID discovery: Add bot to group, send a message, check openclaw logs --follow for the chat.id value (always negative for groups).

Forum topic isolation

Telegram forums add message_thread_id to messages. OpenClaw appends :topic:<threadId> to session keys automatically.

Critical edge case I hit: Topic ID 1 (general topic) requires special handling. OpenClaw omits message_thread_id when sending to topic 1 because Telegram rejects it.

Config example for per-topic system prompts:

{
  "telegram": {
    "groups": {
      "-1003595003457": {
        "requireMention": false,
        "topics": {
          "14": {
            "requireMention": false,
            "systemPrompt": "You are a coding assistant."
          },
          "27": {
            "systemPrompt": "You focus on deployment issues."
          }
        }
      }
    }
  }
}

Each topic maintains isolated conversation history.


Debugging Missed Messages

When messages disappear into the void, it's usually one of these three culprits.

Diagnostic checklist

  1. Check BotFather privacy settings
/mybots → Your Bot → Bot Settings → Group Privacy → OFF
  1. If ON, bot only sees mentions — not regular messages.
  2. Verify group whitelist
openclaw logs --follow | grep "skipping group message"
  1. If channels.telegram.groups is defined, unlisted groups are ignored.
  2. Confirm bot membership
    1. Bot must be added as a member (not just admin with no read access)
    2. Test: send a message, check if bot's "last seen" timestamp updates
  3. Review Gateway logs
openclaw logs --level debug --filter telegram

Common routing failures

Symptom
Likely Cause
Fix
Bot responds in DMs, silent in groups
Privacy mode ON
BotFather → Group Privacy → OFF
Some groups work, others don't
Groups whitelist active
Add "*": or specific IDs
Forum topics get mixed responses
Session key collision
Check :topic:<id> suffix in logs
No response at all
Wrong token or Gateway not running
openclaw status, verify token

Session hygiene checks

I run this sequence weekly to catch routing drift:

# List active sessions
openclaw sessions list
# Check specific session state
openclaw sessions show <sessionKey>
# Force session cleanup (last resort)
openclaw sessions prune --older-than 7d

When sessions leak: If you see context bleeding between chats, it's usually a config error where multiple chats map to the same session key. Review channels.telegram.accounts[].routing.agent settings.


What Actually Worked Long-Term

After two weeks of daily use across three different Telegram setups, here's what survived:

Stable config pattern

{
  "channels": {
    "telegram": {
      "enabled": true,
      "botToken": "env:TELEGRAM_BOT_TOKEN",
      "dmPolicy": "pairing",
      "groups": {
        "*": { "requireMention": true }
      }
    }
  }
}

Why this works:

  • DM pairing prevents unauthorized access
  • Wildcard group policy with mention requirement = safe defaults
  • Token from env var = easier rotation without touching config

What didn't scale

  • Custom commands beyond /new, /status, /help — Users forget them
  • Per-topic system prompts — Maintenance burden grows fast
  • Multiple accounts without clear routing rules — Session chaos

Boundary conditions

OpenClaw Telegram routing is solid for:

  • Personal DM automation (single user)
  • Small team groups (< 20 active members)
  • Forum topics with distinct purposes

It gets messy when:

  • You're managing 10+ groups without config discipline
  • Users expect instant responses (add queue monitoring)
  • Session state matters across Gateway restarts (implement persistence checks)

Security reminder: As noted in security analysis, OpenClaw stores session transcripts and credentials locally. Treat your ~/.openclaw directory as sensitive — use encrypted drives and restrict file permissions.


如果 OpenClaw + Telegram 能带你到达目的地,那就继续使用吧。只要保持会话密钥干净,并了解哪个组使用哪个代理。

在 Macaron,我们自动处理相同的路由挑战——跨平台会话隔离,添加频道时无需手动配置补丁。如果你想在不重建配置的情况下测试多平台路由,用真实的工作流试试,看看它如何处理你的设置。

常见问题

问:我的机器人完全不响应群组消息。我应该先检查哪里? BotFather 的隐私设置。如果设置为开启,机器人只能看到直接 @提到的消息,其他消息会被静默丢弃。前往 BotFather → /mybots → 机器人设置 → 群组隐私 → 关闭它。这是群组设置中最常见的“为什么不工作”的原因。

问:我如何找到我群组的聊天 ID? 将机器人添加到群组,发送任何消息,然后运行 openclaw logs --follow。在传入更新中会显示 chat.id——对于群组来说,它将是一个负数。这就是你在白名单配置中需要填写的值。

问:每个我正在路由的 Telegram 账号都需要单独的机器人令牌吗? 是的。channels.telegram.accounts[] 中的每个条目都需要自己的 BotFather 令牌。一个令牌,一个机器人身份。如果你运行多个机器人并且出现混淆,OpenClaw 网关配置参考 会详细说明账户级路由隔离的实际工作方式。

问:论坛主题——我需要手动配置每个主题吗? 只有当您想为每个主题设置系统提示时才需要。OpenClaw 会自动处理会话键隔离(:topic:<threadId> 后缀),因此无需任何配置就能保持对话独立。只有当您想为每个主题设置不同的代理行为时才需要手动设置。

问:网关重启后会话总是丢失上下文。这是正常的吗? 默认情况下是这样的——会话状态在重启后不会持久化,除非您已配置持久化。如果这对您的使用场景是个障碍,请查看 OpenClaw 快速入门指南,了解网关级别可用的持久化选项。

问:我正在 VPS 上设置这个。有任何 Telegram 相关的注意事项吗? 确保您的服务器对 api.telegram.org 的出站连接没有被阻止——一些廉价的 VPS 提供商会限制这一点。除此之外,通常的安全措施仍然适用:非 root 执行、防火墙规则、环境变量中设置令牌而非硬编码。如果您从头开始,OpenClaw VPS 部署指南 涵盖了完整的设置。

问:我以前在 Telegram 上运行 Moltbot。迁移是否简单? 大多数情况下是的,但配置结构已更改。如果切换后遇到冲突或意外行为,请查看 Moltbot Telegram 设置比较,了解两者之间的变化。

嗨,我是 Hanks — 一个工作流程爱好者和 AI 工具狂热者,拥有超过十年的自动化、SaaS 和内容创作的实践经验。我每天都在测试工具,这样你就不必费心,将复杂的流程简化为简单、可执行的步骤,并深入挖掘“什么真正有效”的数据。

申请成为 Macaron 的首批朋友