OpenClaw Telegram Bot Setup: Mga Utos, Routing, at Multi-Agent Sessions

Blog image

Hey mga tagabuo ng automation — kung ikinakabit mo ang OpenClaw sa Telegram at nagtataka kung paano talagang gumagana ang routing kapag nagsimula nang pumasok ang mga mensahe mula sa DMs, grupo, at paksa, manatili ka rito.

Ginugol ko ang nakaraang dalawang linggo sa pagpapatakbo ng OpenClaw sa Telegram sa tatlong magkakaibang setup: personal na DMs, mga pangkat ng koponan, at mga paksa sa forum. Hindi mga demo na eksena. Tunay na mga pagsubok sa routing kung saan sadyang sinira ko ang session isolation, binaha ito ng sabay-sabay na mga kahilingan, at pinanood kung paano hinarap ng Gateway ang mga multi-account na config.

Ang tanong na paulit-ulit kong tinatanong sa sarili: Maaari ba talagang mapanatili nito ang malinis na hangganan ng session kapag pinangangasiwaan mo ang maraming chat, o lahat ba ito ay bumagsak sa isang magulo na thread ng pag-uusap?

Narito ang aking mga natuklasan, kasama ang eksaktong mga pattern ng config na nakaligtas.

Para sa konteksto, OpenClaw (dating Moltbot at Clawdbot) ay nakakuha ng higit sa 100,000 GitHub stars noong unang bahagi ng 2026 bilang isang open-source na autonomous na AI assistant. Nilikhang ni Peter Steinberger, ito ay nag-uugnay sa mga platform ng pagmemensahe tulad ng Telegram sa mga AI agent na tumatakbo nang lokal o sa mga pribadong server.

Blog image


Gumawa ng Telegram Bot (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)

Blog image

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

Blog image

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

Blog image

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

Blog image

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.


Kung ang OpenClaw + Telegram ang nagpaparating sa'yo kung saan mo kailangan, gamitin mo na ito. Siguraduhin lang na malinis ang session keys at alam mo kung aling grupo ang may aling agent.

Sa Macaron, awtomatiko naming hinaharap ang parehong routing challenges — session isolation sa iba't ibang platform, walang manu-manong pag-patch ng config kapag nagdadagdag ka ng channels. Kung nais mong subukan ang multi-platform routing nang hindi muling binubuo ang configs tuwing nag-e-scale ka, subukan ito sa isang tunay na workflow at tingnan kung paano nito hinahawakan ang iyong setup.

FAQ

Q: Hindi tumutugon ang bot ko sa mga group messages. Saan ako unang dapat tumingin? BotFather privacy settings. Kung ito'y naka-ON, tanging mga direktang @mentions lang ang nakikita ng bot — lahat ng iba pa ay tahimik na nawawala. Pumunta sa BotFather → /mybots → Bot Settings → Group Privacy → i-turn OFF ito. Ito ang pinakakaraniwang "bakit hindi ito gumagana" para sa mga group setups.

Q: Paano ko mahahanap ang chat ID ng grupo ko? Idagdag ang bot sa grupo, magpadala ng kahit anong mensahe, pagkatapos ay patakbuhin ang openclaw logs --follow. Lalabas ang chat.id sa incoming update — ito'y magiging negatibong numero para sa mga grupo. Iyon ang ilalagay mong halaga sa iyong whitelist config.

Q: Kailangan ko ba ng hiwalay na bot token para sa bawat Telegram account na niruruta ko? Oo. Bawat entry sa channels.telegram.accounts[] ay nangangailangan ng sariling BotFather token. Isang token, isang bot identity. Kung nagrarun ka ng maraming bots at nagkakaroon ng paghalo, ang OpenClaw gateway config reference ay naglalatag kung paano gumagana ang account-level routing isolation.

Q: Mga paksa sa forum — kailangan bang i-configure ko ang bawat isa nang mano-mano? Oo, kung nais mong magkaroon ng bawat paksa ng natatanging sistema ng prompts. Awtomatikong hinahawakan ng OpenClaw ang paghihiwalay ng session key (:topic:<threadId> suffix), kaya't nananatiling hiwalay ang mga pag-uusap kahit walang config. Kinakailangan lang ang manual na setup kapag gusto mo ng iba't ibang asal ng ahente sa bawat paksa.

Q: Nawawala ang konteksto ng mga session pagkatapos mag-restart ang Gateway. Normal ba ito? Oo, sa default — hindi nagpapatuloy ang estado ng session kapag nag-restart, maliban kung nakapag-configure ka ng persistence. Kung ito ay isang malaking isyu para sa iyong paggamit, tingnan ang OpenClaw quick start guide para sa mga opsyon sa persistence na magagamit sa antas ng Gateway.

Q: Nagseset up ako nito sa isang VPS. Mayroon bang anumang Telegram-specific na dapat kong malaman? Siguraduhing hindi naka-block ang mga outbound connection ng iyong server sa api.telegram.org — ang ilang murang VPS provider ay may ganitong limitasyon. Bukod doon, ang karaniwang pag-iingat ay dapat sundin: non-root execution, mga patakaran ng firewall, token sa env vars hindi hardcoded. Ang OpenClaw VPS deployment guide ay nagpapaliwanag ng buong setup kung magsisimula ka mula sa wala.

Q: Dati akong gumagamit ng Moltbot para sa Telegram. Madali bang mag-migrate? Karamihan oo, pero nagbago ang istruktura ng config. Kung makaranas ka ng mga problema o hindi inaasahang pag-uugali pagkatapos magpalit, ang Moltbot Telegram setup comparison ay kapaki-pakinabang na tingnan — inilalarawan nito ang mga pagbabagong naganap sa pagitan ng dalawa.

Hey, I’m Hanks — a workflow tinkerer and AI tool obsessive with over a decade of hands-on experience in automation, SaaS, and content creation. I spend my days testing tools so you don’t have to, breaking down complex processes into simple, actionable steps, and digging into the numbers behind “what actually works.”

Apply to become Macaron's first friends