👉 Setup: see SETUP.md for installation, configuration, and multi-bot deployment.
A Telegram bot that bridges Claude Code CLI with Telegram, enabling you to run Claude Code commands, manage multi-session workflows, send voice commands, attach files, and deploy — all from your phone.
Built for DevOps engineers and developers who want to interact with Claude Code on the go.
If you've used Claude Code or OpenAI Codex, you know the frustration: SSH sessions drop, VPN connections timeout mid-task, and you lose hours of AI-generated work. This is especially painful for developers in regions with unreliable connectivity to AI services (Iran, etc.).
The solution: Deploy this bot on a VPS where the connection to Anthropic is stable, then control everything through Telegram — which works everywhere, even on the slowest connections.
You (anywhere) → Telegram → VPS (stable connection) → Claude Code CLI → Results back to Telegram
Fire a task, close your phone, come back to a full report. No more babysitting SSH sessions. No more re-running commands after a disconnect. Your VPS maintains the stable connection while you interact through Telegram's lightweight protocol.
This is async DevOps — send your coding task, go about your day, get the results as Telegram messages with shareable report links.
- Multi-Session Management — Hold up to 9 logical Claude Code sessions per chat, each with its own project context; a bounded number (default 2) execute at once while the rest queue
- Voice Commands — Speak in Farsi or English; Gemini transcribes and refines your voice into structured prompts
- File Attachments — Send documents/photos with instructions; they're passed to Claude Code automatically
- Smart Fallback Chain — When Claude is rate-limited, falls back to Gemini → GPT-4o → OpenRouter (configurable)
- Runtime Model Selection — Switch fallback models on the fly via
/model, including OpenRouter search - Deploy Controls — One-tap deploy with branch selection and confirmation
- Health & Logs — Quick-access buttons for server health checks and log collection
- Usage Tracking — Token usage estimates with hourly/daily/weekly bars and alerts
- Session Auto-Cleanup — Idle sessions auto-close after configurable timeout
- Graceful Shutdown — On SIGTERM, notifies active chats and cleanly terminates Claude processes
- OOM Protection — Systemd memory limits prevent the OS from killing the bot
- Pause Window — 5-second countdown before execution lets you cancel or edit
- Report Generation — Save full outputs as browsable reports (verified Summary + ZIP, clickable links) retained for 15 days via a single canonical cleanup timer
The bot can act as a delivery channel for an external monitoring service. A
small HMAC-authenticated HTTP endpoint listens on 127.0.0.1:9091 and accepts
pre-formatted digest messages from any tool you trust — typical use case is a
nightly Sentry summary that you want delivered to the bot's admin chat
without coupling the summarizer to the Telegram API.
- What it is: an opt-in localhost-only HTTP server (
POST /inject,GET /healthz) that turns the bot into a Telegram-delivery layer for any external job that produces a daily report. - Why use it: keep Telegram credentials in one place (this bot), and let any monitoring/digest pipeline POST messages here. The job stays decoupled from Telegram's rate limits, retry policy, and chat allowlist.
- How to enable: set
BOT_NIGHTWATCH_HMAC_SECRETin.env(32+ random hex chars). The IPC server starts at bot startup. Leave the variable unset and the IPC stays off — the bot logs a warning at startup and otherwise runs normally. - New commands (registered when the IPC is enabled):
/nightwatch_ping(health probe),/nightwatch_run(manual trigger of the external service if installed),/nightwatch_last(re-send the previous digest). - Protocol reference: see
docs/NIGHTWATCH_IPC.mdfor the full request/response schema, signing rules, and security notes.
- Python 3.10+
- Claude Code CLI installed and authenticated
- A Telegram bot token from @BotFather
- (Optional) Gemini API key for voice commands
# Clone the repo
git clone https://github.com/saeidsm/ClaudeCodeTelegramBot.git
cd ClaudeCodeTelegramBot
# Install dependencies
pip install -r requirements.txt
# Configure
cp .env.example .env
# Edit .env with your tokens and settings
# Run
python bot.pyTELEGRAM_BOT_TOKEN=your-bot-token-from-botfather
TELEGRAM_CHAT_ID=123456789
GEMINI_API_KEY=your-gemini-api-key # Optional, for voiceSee SETUP.md for the full setup guide (single-bot, multi-bot, configuration reference).
- Start the bot:
/start - Create a session:
/new my-task - Select a project from the list
- Send text messages — they go to Claude Code
- Reply to session messages to route to specific sessions
Send a voice message in Farsi or English:
- Short commands auto-execute: "deploy", "health", "test", "logs"
- Long commands are transcribed → refined into structured prompts → confirmed before execution
- Send a file to a session (reply or auto-routes if one session active)
- Files are queued until you send a text instruction
- Or send a file with a caption — executes immediately
/new frontend-fix → creates session, pick project
/new api-refactor → creates another session
/sessions → list all active sessions
/kill frontend-fix → end a session
Reply to any session message to route your next command there. If only one session is active, messages auto-route.
| Command | Description |
|---|---|
/start |
Home screen with keyboard |
/new <name> |
Create a new session |
/sessions |
List active sessions |
/kill <name> |
End a session |
/project <name> |
Change project for current session |
/model |
Select fallback AI model |
/usage |
View token usage stats |
/help |
Show help |
See docs/COMMANDS.md for the full command reference.
Telegram Message
├─ Voice → Gemini STT → Refine → Confirm → Claude Code CLI
├─ Text → Session Router → Claude Code CLI
└─ File → Queue in Session → Next text triggers execution
│
Claude Code CLI (async subprocess)
│
┌─────┴─────┐
│ Success │ Rate Limited
▼ ▼
Telegram Fallback Chain
Response Gemini → GPT → OpenRouter
See docs/ARCHITECTURE.md for details.
All configuration is via environment variables. See .env.example for the full list.
| Variable | Required | Description |
|---|---|---|
TELEGRAM_BOT_TOKEN |
Yes | Bot token from @BotFather |
TELEGRAM_CHAT_ID |
Yes | Comma-separated authorized chat IDs |
GEMINI_API_KEY |
No | Enables voice transcription + Gemini fallback |
OPENAI_API_KEY |
No | Enables GPT fallback |
OPENROUTER_API_KEY |
No | Enables OpenRouter model selection |
BOT_MAX_SESSIONS |
No | Max concurrent sessions (default: 4) |
BOT_SESSION_TIMEOUT_HOURS |
No | Auto-close idle sessions after N hours (default: 72) |
The bot calls shell scripts for health, logs, and deploy. Create your own in scripts/:
scripts/health-check.sh— Called by 📊 Health buttonscripts/collect-logs.sh— Called by 📋 Logs buttonscripts/deploy-to-prod.sh— Called by 🚀 Deploy (receives$1=project $2=branch)
Example scripts are included in scripts/. Copy and customize them for your infrastructure.
# Copy the systemd unit file
sudo cp systemd/claude-telegram-bot.service /etc/systemd/system/
# Edit paths in the service file to match your installation
sudo systemctl edit claude-telegram-bot
# Enable and start
sudo systemctl daemon-reload
sudo systemctl enable claude-telegram-bot
sudo systemctl start claude-telegram-bot
# Check status
sudo systemctl status claude-telegram-botThe service file includes:
- MemoryHigh/MemoryMax — Prevents OOM killer from targeting the bot process
- KillSignal=SIGTERM — Triggers graceful shutdown (notifies chats, kills Claude processes)
- TimeoutStopSec=30 — Gives the bot 30 seconds to clean up before force kill
ClaudeCodeTelegramBot/
├── bot.py # Main bot (single file, ~1700 lines)
├── .env.example # Environment variable template
├── requirements.txt # Python dependencies
├── configs/
│ ├── gemini-prompts.json # Customizable Gemini prompts
│ └── projects.json # Project registry (auto-generated)
├── scripts/
│ ├── health-check.sh.example # Example health check script
│ ├── collect-logs.sh.example # Example log collection script
│ └── deploy-to-prod.sh.example # Example deploy script
├── systemd/
│ └── claude-telegram-bot.service # Systemd unit file
└── docs/
├── SETUP.md # Detailed setup guide
├── COMMANDS.md # Full command reference
└── ARCHITECTURE.md # Architecture overview
Voice transcription and prompt refinement use Gemini. Customize the prompts in configs/gemini-prompts.json:
{
"transcribe": {
"model": "gemini-2.5-flash",
"prompt": "Transcribe this voice message exactly..."
},
"refine": {
"model": "gemini-2.5-flash",
"prompt": "Convert this casual command into a structured prompt..."
},
"voice_commands": {
"deploy": ["deploy", "ship it"],
"health": ["health", "status"],
"test": ["test", "run tests"]
}
}See docs/CHANGELOG.md for notable changes. Most recent
entry: 2026-04-20 — fix silent drop of long reports caused by HTML
<pre> tag splitting.
Contributions are welcome! Please open an issue or submit a pull request.
MIT — Copyright (c) 2025 Saeid Saeidimehr