claude-telegram-bot
CLAUDE.md448 starsChanged 10 months agoMITView on GitHub
Managed worktrees run ./workspace-setup.sh init; after a plain git worktree add, run it yourself. Every checkout shares the .env bot token, so stop any other running instance before bun run dev (Telegram rejects concurrent polling with a 409). This is a Telegram bot (~3,300 lines TypeScript) that lets you control Claude Code from your phone via text, voice, photos, and documents. Built with Bun and grammY. Each message type has a dedicated async handler: - commands.ts - /start, /new, /stop,…
- Reads credentials
- Installs packages
We split this CLAUDE.md into the rules it gives an agent
7 rules. About 0 are common, 2 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 65
All config via .env (copy from .env.example).
- Very specific: line 83
Adding a command: Create handler in commands.ts, register in index.ts with bot.command("name", handler)
- Very specific: line 85
Adding a message handler: Create in handlers/, export from index.ts, register in index.ts with appropriate filter
- Very specific: line 87
Streaming pattern: All handlers use createStatusCallback() from streaming.ts and session.sendMessageStreaming() for live updates.
- Very specific: line 89
Type checking: Run bun run typecheck periodically while editing TypeScript files.
- Distinctive: line 107
When running as a standalone binary (especially from a macOS app), the PATH may not include Homebrew.
- Distinctive: line 115
Do not add "Generated with Claude Code" footers or "Co-Authored-By" trailers to commit messages.
≈ “Common” is an estimate: at least 1 in 5 of the 25,680 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Commands
bun run start # Run the bot
bun run dev # Run with auto-reload (--watch)
bun run typecheck # Run TypeScript type checking
bun test # Run unit tests (colocated *.test.ts)
bun install # Install dependenciesManaged worktrees run ./workspace-setup.sh init; after a plain git worktree add, run it yourself. Every checkout shares the .env bot token, so stop any other running instance before bun run dev (Telegram rejects concurrent polling with a 409).
Architecture
This is a Telegram bot (~3,300 lines TypeScript) that lets you control Claude Code from your phone via text, voice, photos, and documents. Built with Bun and grammY.
Message Flow
Telegram message → Handler → Auth check → Rate limit → Claude session → Streaming response → Audit logKey Modules
src/index.ts- Entry point, registers handlers, starts pollingsrc/config.ts- Environment parsing, MCP loading, safety promptssrc/session.ts-ClaudeSessionclass wrapping the Agent SDKquery()API with streaming, session persistence (/tmp/claude-telegram-session.json), and defense-in-depth safety checks. Takes an optionalsessionKey(default"default") used to scope saved history per forum topic.src/security.ts-RateLimiter(token bucket), path validation, command safety checkssrc/formatting.ts- Markdown→HTML conversion for Telegram, tool status emoji formattingsrc/utils.ts- Audit logging, voice transcription (OpenAI), typing indicatorssrc/types.ts- Shared TypeScript types
Handlers (src/handlers/)
Each message type has a dedicated async handler:
commands.ts-/start,/new,/stop,/status,/resume,/restart,/retrytext.ts- Text messages with intent filteringvoice.ts- Voice→text via OpenAI, then same flow as textaudio.ts- Audio file transcription via OpenAI (mp3, m4a, ogg, wav, etc.), also handles audio sent as documentsphoto.ts- Image analysis with media group buffering (1s timeout for albums)document.ts- PDF extraction (pdftotext CLI), text files, archives, routes audio files toaudio.tsvideo.ts- Video messages and video notescallback.ts- Inline keyboard button handling for ask_user MCPstreaming.ts- SharedStreamingStateand status callback factory
Forum topics (src/ext/)
session-manager.ts-getSession(ctx)gives each forum topic (chatId:message_thread_id, only whenis_topic_messageis set) its ownClaudeSessionand/resumehistory; everything outside a topic shares the"default"session.
Security Layers
- User allowlist (
TELEGRAM_ALLOWED_USERS) - Rate limiting (token bucket, configurable)
- Path validation (
ALLOWED_PATHS) - Command safety (blocked patterns)
- System prompt constraints
- Audit logging
Configuration
All config via .env (copy from .env.example). Key variables:
TELEGRAM_BOT_TOKEN,TELEGRAM_ALLOWED_USERS(required)CLAUDE_WORKING_DIR- Working directory for ClaudeALLOWED_PATHS- Directories Claude can accessOPENAI_API_KEY- For voice transcriptionCLAUDE_MODEL- Full model ID passed to the Agent SDK (defaultclaude-sonnet-5-5)CLAUDE_CLI_PATH- Claude Code executable; unset uses the CLI bundled with the Agent SDK. New models need an SDK bump (or a newer CLI here) for correct context window and pricing
MCP servers defined in mcp-config.ts.
Runtime Files
/tmp/claude-telegram-session.json- Session persistence for/resume/tmp/telegram-bot/- Downloaded photos/documents/tmp/claude-telegram-audit.log- Audit log
Patterns
Adding a command: Create handler in commands.ts, register in index.ts with bot.command("name", handler)
Adding a message handler: Create in handlers/, export from index.ts, register in index.ts with appropriate filter
Streaming pattern: All handlers use createStatusCallback() from streaming.ts and session.sendMessageStreaming() for live updates.
Type checking: Run bun run typecheck periodically while editing TypeScript files. Fix any type errors before committing.
After code changes: Restart the bot so changes can be tested. Use launchctl kickstart -k gui/$(id -u)/com.claude-telegram-ts if running as a service, or bun run start for manual runs.
Standalone Build
The bot can be compiled to a standalone binary with bun build --compile. This is used by the ClaudeBot macOS app wrapper. A compiled binary can't resolve the SDK's bundled CLI, so the launcher must set CLAUDE_CLI_PATH (the older CLAUDE_CODE_PATH still works).
External Dependencies
PDF extraction uses pdftotext CLI instead of an npm package (to avoid bundling issues):
brew install poppler # Provides pdftotextPATH Requirements
When running as a standalone binary (especially from a macOS app), the PATH may not include Homebrew. The launcher must ensure PATH includes:
/opt/homebrew/bin(Apple Silicon Homebrew)/usr/local/bin(Intel Homebrew)
Without this, pdftotext won't be found and PDF parsing will fail silently with an error message.
Commit Style
Do not add "Generated with Claude Code" footers or "Co-Authored-By" trailers to commit messages.
Running as Service (macOS)
cp launchagent/com.claude-telegram-ts.plist.template ~/Library/LaunchAgents/com.claude-telegram-ts.plist
# Edit plist with your paths
launchctl load ~/Library/LaunchAgents/com.claude-telegram-ts.plist
# Logs
tail -f /tmp/claude-telegram-bot-ts.log
tail -f /tmp/claude-telegram-bot-ts.errIn this repositoryOne other file it gives its agents.
- AGENTS.mdAGENTS.md
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

