
Olá, construtores de automação — se você está conectando o OpenClaw ao Telegram e se perguntando como o roteamento realmente funciona quando as mensagens começam a chegar de DMs, grupos e tópicos, continue por aqui.
Passei as últimas duas semanas executando o OpenClaw através do Telegram em três configurações diferentes: DMs pessoais, grupos de equipe e tópicos de fórum. Não são cenários de demonstração. Testes reais de roteamento onde eu quebrei deliberadamente o isolamento de sessão, sobrecarreguei com solicitações simultâneas e observei como o Gateway lidava com configurações de várias contas.
A pergunta que continuei fazendo: Isso realmente pode manter limites de sessão limpos quando você está lidando com vários chats, ou tudo se transforma em um único fio de conversa confuso?
Aqui está o que descobri, além dos padrões de configuração exatos que sobreviveram.
Para contexto, OpenClaw (anteriormente Moltbot e Clawdbot) ganhou mais de 100.000 estrelas no GitHub no início de 2026 como um assistente de IA autônomo de código aberto. Criado por Peter Steinberger, ele conecta plataformas de mensagens como o Telegram a agentes de IA que rodam localmente ou em servidores privados.

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:

/start to see available commands/newbot
bot (e.g., YourProjectBot)123456789:ABCdefGHIjklMNOpqrsTUVwxyz/revoke in BotFather to generate a new oneCritical 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.
Getting the token into OpenClaw is where most setup guides stop — but that's where real testing should start.
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"
}
}
}
Here's the sequence I run every time to confirm the Gateway actually sees Telegram updates:
openclaw gateway --log-level debug
/start to your bot in Telegram
dmPolicy: "pairing"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.
Nota de segurança: Para implantações em produção, considere usar a imagem OpenClaw reforçada da DigitalOcean que inclui regras de firewall, isolamento de contêineres e execução sem privilégios de root por padrão.

O sistema de comandos do OpenClaw é onde a lógica de roteamento começa a fazer diferença. O Gateway reconhece comandos de barra em todos os canais, mas o Telegram adiciona sua própria camada de autocompletar comandos.
O repositório oficial do OpenClaw documenta todo o conjunto de comandos, mas após testes no mundo real, apenas alguns se mostram essenciais.
Estes são os comandos que realmente uso em configurações de produção (não a lista completa — apenas o que sobrevive ao uso real):
Important: /activation always only affects the current session. To persist it, add it to your config's requireMention settings.
This is what makes your bot feel native in Telegram:
/mybots → Select your bot → Edit Commandsnew - Start fresh sessionstatus - Check session statehelp - Show all commands
/ autocomplete menuReality 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.

This is where OpenClaw's session architecture either makes sense or falls apart. Session keys determine whether conversations stay isolated or bleed together.
OpenClaw generates session keys using this pattern:
agent:<agentId>:telegram:<chatType>:<chatId>[:topic:<topicId>]
Breakdown:
main sessiontelegram:group:<chatId>):topic:<threadId> suffix)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.
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).

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.
When messages disappear into the void, it's usually one of these three culprits.
/mybots → Your Bot → Bot Settings → Group Privacy → OFF
openclaw logs --follow | grep "skipping group message"
channels.telegram.groups is defined, unlisted groups are ignored.openclaw logs --level debug --filter telegram
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.
After two weeks of daily use across three different Telegram setups, here's what survived:
{
"channels": {
"telegram": {
"enabled": true,
"botToken": "env:TELEGRAM_BOT_TOKEN",
"dmPolicy": "pairing",
"groups": {
"*": { "requireMention": true }
}
}
}
}
Why this works:
/new, /status, /help — Users forget themOpenClaw Telegram routing is solid for:
It gets messy when:
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.
Se OpenClaw + Telegram levar você onde precisa, continue com isso. Apenas mantenha as chaves de sessão limpas e saiba quais grupos recebem qual agente.
Na Macaron, lidamos com os mesmos desafios de roteamento automaticamente — isolamento de sessão entre plataformas, sem necessidade de ajustes manuais ao adicionar canais. Se você deseja testar o roteamento multiplataforma sem reconstruir configurações sempre que escalar, experimente com um fluxo de trabalho real e veja como ele lida com sua configuração.
Perguntas Frequentes
P: Meu bot não está respondendo a mensagens de grupo. Onde devo verificar primeiro? Configurações de privacidade do BotFather. Se estiver ativado, o bot só vê menções diretas @ — tudo o mais é silenciosamente descartado. Vá para BotFather → /mybots → Configurações do Bot → Privacidade do Grupo → desative-o. Este é o motivo mais comum de "por que não está funcionando" para configurações de grupo.
P: Como encontro o ID de chat do meu grupo? Adicione o bot ao grupo, envie qualquer mensagem e, em seguida, execute openclaw logs --follow. O chat.id aparecerá na atualização recebida — será um número negativo para grupos. Esse é o valor que você coloca na configuração de lista branca.
P: Preciso de um token de bot separado para cada conta do Telegram que estou roteando? Sim. Cada entrada em channels.telegram.accounts[] precisa do seu próprio token do BotFather. Um token, uma identidade de bot. Se você estiver executando múltiplos bots e as coisas estiverem se misturando, a referência de configuração do gateway OpenClaw explica como o isolamento de roteamento em nível de conta realmente funciona.
Q: Forum topics — do I need to configure each one manually? Only if you want per-topic system prompts. OpenClaw handles the session key isolation automatically (:topic:<threadId> suffix), so conversations stay separate without any config. Manual setup is only needed when you want different agent behavior per topic.
Q: Sessions keep losing context after Gateway restarts. Is that expected? By default, yes — session state doesn't persist across restarts unless you've configured persistence. If that's a dealbreaker for your use case, check the OpenClaw quick start guide for the persistence options available at the Gateway level.
Q: I'm setting this up on a VPS. Anything Telegram-specific I should know? Make sure your server's outbound connections to api.telegram.org aren't blocked — some cheap VPS providers restrict this. Beyond that, the usual hardening applies: non-root execution, firewall rules, token in env vars not hardcoded. The OpenClaw VPS deployment guide covers the full setup if you're starting from scratch.
Q: I used to run Moltbot for Telegram. Is migration straightforward? Mostly yes, but the config structure changed. If you hit conflicts or unexpected behavior after switching, the Moltbot Telegram setup comparison is worth checking — it maps out what changed between the two.