OpenClaw 텔레그램 봇 설정: 명령어, 라우팅 및 다중 에이전트 세션

안녕하세요, 자동화 빌더 여러분 — OpenClaw를 텔레그램에 연결하고 DM, 그룹, 주제에서 메시지가 날아들 때 라우팅이 실제로 어떻게 작동하는지 궁금하시다면 계속 읽어보세요.

저는 지난 2주 동안 OpenClaw를 텔레그램에서 세 가지 다른 방식으로 실행했습니다: 개인 DM, 팀 그룹, 포럼 주제. 데모 시나리오가 아닙니다. 저는 고의로 세션 격리를 깨고, 동시 요청으로 넘쳐나게 하며 게이트웨이가 다중 계정 구성을 어떻게 처리하는지 관찰했습니다.

제가 계속해서 되돌아보게 된 질문은: 여러 채팅을 처리할 때 실제로 깨끗한 세션 경계를 유지할 수 있는지, 아니면 모두 하나의 혼란스러운 대화 스레드로 무너지는지?

제가 발견한 것과 살아남은 정확한 구성 패턴을 공유합니다.

참고로, OpenClaw (이전의 Moltbot 및 Clawdbot)은 2026년 초에 오픈 소스 자율 AI 어시스턴트로서 GitHub에서 100,000개 이상의 스타를 얻었습니다. 피터 스타인버거가 만든 이 도구는 텔레그램과 같은 메시징 플랫폼을 로컬 또는 개인 서버에서 실행되는 AI 에이전트에 연결합니다.


텔레그램 봇 만들기 (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.

보안 참고: 프로덕션 배포 시 DigitalOcean의 강화된 OpenClaw 이미지를 사용하는 것을 고려하세요. 이 이미지에는 기본적으로 방화벽 규칙, 컨테이너 격리, 비루트 실행이 포함되어 있습니다.


확장 가능한 명령어 설계

OpenClaw의 명령어 시스템은 라우팅 로직이 중요한 부분입니다. 게이트웨이는 모든 채널에서 슬래시 명령어를 인식하지만, Telegram은 자체 명령어 자동완성 레이어를 추가합니다.

공식 OpenClaw 저장소에는 전체 명령어 세트가 문서화되어 있지만, 실제 테스트 후에는 소수의 명령어만이 필수적임을 증명합니다.

핵심 명령어 패턴

프로덕션 설정에서 실제로 사용하는 명령어입니다 (전체 목록이 아닌 실제로 사용되는 것들만):

명령어
목적
세션 범위
/new
새 세션 강제 시작 (컨텍스트 초기화)
채팅별
/status
세션 + 모델 + 토큰 사용량 표시
현재 세션
/activation
멘션 전용 vs 항상 응답 전환
세션 전용*
/help
사용 가능한 명령어 목록 표시
해당 없음

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에서는 같은 라우팅 문제를 자동으로 처리해요 — 플랫폼 간 세션 분리, 채널을 추가할 때 수동 구성 패치를 할 필요가 없어요. 매번 구성을 새로 만들지 않고 여러 플랫폼 라우팅을 테스트하려면 실제 워크플로우로 시도해보세요 그리고 설정이 어떻게 처리되는지 확인해보세요.

FAQ

Q: 제 봇이 그룹 메시지에 전혀 응답하지 않아요. 어디를 먼저 확인해야 하나요? BotFather의 프라이버시 설정을 확인하세요. 설정이 ON으로 되어 있으면 봇은 직접 @멘션만 볼 수 있고 나머지는 조용히 무시됩니다. BotFather → /mybots → Bot Settings → Group Privacy → OFF로 설정하세요. 그룹 설정에서 가장 흔한 "작동하지 않는 이유"입니다.

Q: 내 그룹의 채팅 ID를 어떻게 찾나요? 봇을 그룹에 추가하고 아무 메시지나 보낸 후 openclaw logs --follow를 실행하세요. 들어오는 업데이트에서 chat.id가 나타납니다 — 그룹의 경우 음수로 표시됩니다. 이 값을 화이트리스트 구성에 넣으세요.

Q: 라우팅하는 각 Telegram 계정마다 별도의 봇 토큰이 필요하나요? 네. channels.telegram.accounts[]의 각 항목에는 별도의 BotFather 토큰이 필요합니다. 하나의 토큰, 하나의 봇 아이덴티티. 여러 봇을 운영하고 있고 문제가 발생한다면, OpenClaw 게이트웨이 구성 참조를 통해 계정 수준의 라우팅 분리가 실제로 어떻게 작동하는지 확인할 수 있습니다.

Q: 포럼 주제를 각각 수동으로 설정해야 하나요? 주제별 시스템 프롬프트를 원할 경우에만 필요해요. OpenClaw는 세션 키 분리를 자동으로 처리해 줍니다 (:topic:<threadId> 접미사 사용). 따라서 별도 설정 없이도 대화가 개별적으로 유지됩니다. 주제별로 에이전트 행동을 다르게 설정하고 싶을 때만 수동 설정이 필요해요.

Q: 게이트웨이 재시작 후 세션이 계속 컨텍스트를 잃어요. 이게 정상인가요? 기본적으로는 그렇습니다 — 세션 상태는 재시작 시 유지되지 않아요, 지속성을 설정하지 않는 한. 만약 이게 사용 사례에서 문제가 된다면, 게이트웨이 수준에서 가능한 지속성 옵션을 보려면 OpenClaw 빠른 시작 가이드를 참조하세요.

Q: VPS에 이 설정을 하고 있어요. 텔레그램 관련해서 알아야 할 게 있나요? 서버의 api.telegram.org에 대한 아웃바운드 연결이 차단되지 않았는지 확인하세요 — 일부 저렴한 VPS 제공업체는 이를 제한할 수 있습니다. 그 외에는 일반적인 강화 조치를 따르세요: 비루트 사용자로 실행, 방화벽 규칙 설정, 환경 변수에 토큰 저장 등. 처음부터 설정 중이라면 OpenClaw VPS 배포 가이드를 참고하세요.

Q: 텔레그램용 Moltbot을 운영했었어요. 마이그레이션이 간단한가요? 대부분은 그렇지만, 설정 구조가 변경되었습니다. 전환 후 충돌이나 예상치 못한 동작이 발생하면, Moltbot 텔레그램 설정 비교를 확인해 보세요 — 두 가지 간의 변경 사항이 정리되어 있습니다.

안녕하세요, 저는 Hanks입니다 — 워크플로우 조작자이자 AI 도구 애호가로, 자동화, SaaS 및 콘텐츠 제작 분야에서 10년 이상의 실무 경험을 가지고 있습니다. 제가 도구를 테스트하니 여러분은 그럴 필요 없습니다. 복잡한 과정을 간단하고 실행 가능한 단계로 나누고, '실제로 효과가 있는 것'의 숫자를 파헤칩니다.

지원하기 Macaron 의 첫 친구들