agentleFS
linuz90linuz90/claude-telegram-bot/CLAUDE.md

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
  1. Very specific:

    All config via .env (copy from .env.example).

    line 65
  2. Very specific:

    Adding a command: Create handler in commands.ts, register in index.ts with bot.command("name", handler)

    line 83
  3. Very specific:

    Adding a message handler: Create in handlers/, export from index.ts, register in index.ts with appropriate filter

    line 85
  4. Very specific:

    Streaming pattern: All handlers use createStatusCallback() from streaming.ts and session.sendMessageStreaming() for live updates.

    line 87
  5. Very specific:

    Type checking: Run bun run typecheck periodically while editing TypeScript files.

    line 89
  6. Distinctive:

    When running as a standalone binary (especially from a macOS app), the PATH may not include Homebrew.

    line 107
  7. Distinctive:

    Do not add "Generated with Claude Code" footers or "Co-Authored-By" trailers to commit messages.

    line 115

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

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 dependencies

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).

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 log

Key Modules

  • src/index.ts - Entry point, registers handlers, starts polling
  • src/config.ts - Environment parsing, MCP loading, safety prompts
  • src/session.ts - ClaudeSession class wrapping the Agent SDK query() API with streaming, session persistence (/tmp/claude-telegram-session.json), and defense-in-depth safety checks. Takes an optional sessionKey (default "default") used to scope saved history per forum topic.
  • src/security.ts - RateLimiter (token bucket), path validation, command safety checks
  • src/formatting.ts - Markdown→HTML conversion for Telegram, tool status emoji formatting
  • src/utils.ts - Audit logging, voice transcription (OpenAI), typing indicators
  • src/types.ts - Shared TypeScript types

Handlers (src/handlers/)

Each message type has a dedicated async handler:

  • commands.ts - /start, /new, /stop, /status, /resume, /restart, /retry
  • text.ts - Text messages with intent filtering
  • voice.ts - Voice→text via OpenAI, then same flow as text
  • audio.ts - Audio file transcription via OpenAI (mp3, m4a, ogg, wav, etc.), also handles audio sent as documents
  • photo.ts - Image analysis with media group buffering (1s timeout for albums)
  • document.ts - PDF extraction (pdftotext CLI), text files, archives, routes audio files to audio.ts
  • video.ts - Video messages and video notes
  • callback.ts - Inline keyboard button handling for ask_user MCP
  • streaming.ts - Shared StreamingState and status callback factory

Forum topics (src/ext/)

  • session-manager.ts - getSession(ctx) gives each forum topic (chatId:message_thread_id, only when is_topic_message is set) its own ClaudeSession and /resume history; everything outside a topic shares the "default" session.

Security Layers

  1. User allowlist (TELEGRAM_ALLOWED_USERS)
  2. Rate limiting (token bucket, configurable)
  3. Path validation (ALLOWED_PATHS)
  4. Command safety (blocked patterns)
  5. System prompt constraints
  6. 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 Claude
  • ALLOWED_PATHS - Directories Claude can access
  • OPENAI_API_KEY - For voice transcription
  • CLAUDE_MODEL - Full model ID passed to the Agent SDK (default claude-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 pdftotext

PATH 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.err

Download now (ZIP)

  • In this repositoryOne other file it gives its agents.

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.