claudecode-telegram: Code from Anywhere, Instantly
Access your Claude Code terminal from your phone. No VPN. No complex setup. Just pure, uninterrupted AI-powered development wherever you are.
Picture this: you're away from your desk when a critical bug hits production. Your laptop is at home, but your phone is in your pocket. Traditional solutions demand VPNs, SSH clients, or cloud-based IDEs that drain your battery and patience. claudecode-telegram shatters these limitations by transforming your everyday Telegram app into a sleek, powerful remote interface for Claude Code. This revolutionary bridge lets you send coding commands, review outputs, and manage long-running AI tasks through simple Telegram messages. In this deep dive, you'll discover how this essential tool works under the hood, master its installation step-by-step, explore real-world code examples, and unlock advanced patterns that turn your messaging app into a developer superpower.
What is claudecode-telegram?
claudecode-telegram is a lightweight, open-source bridge that connects Anthropic's Claude Code CLI to Telegram, enabling seamless remote interaction with your AI coding assistant. Created by developer hanxiao, this ingenious tool solves a fundamental friction point: Claude Code runs beautifully in your terminal but remains chained to your local machine. The bridge liberates it.
At its core, the project leverages tmux for persistent session management, Cloudflare Tunnel for secure internet exposure, and Claude Code's native hook system for bidirectional communication. When you send a message from Telegram, the bridge intercepts the webhook, injects your text directly into the active tmux session running Claude Code, then captures the AI's response and ships it back to your chat. This creates a magical experience where your phone becomes a thin client for sophisticated AI development.
The architecture is deceptively simple yet remarkably robust. It uses a pending file as a state flag to ensure only Telegram-initiated messages trigger responses, preventing infinite loops. The Stop hook mechanism—Claude Code's lifecycle event system—reads conversation transcripts upon completion and forwards them through the Telegram Bot API. This design choice eliminates polling, reduces latency, and maintains conversation context automatically.
Why is this trending now? As developers embrace AI-native workflows, mobility becomes critical. Teams need to check on long-running code generation tasks, solo developers want to prototype ideas during commutes, and DevOps engineers require instant access to their AI assistant during incidents. claudecode-telegram delivers all this without compromising security or requiring heavyweight infrastructure. Its minimal dependencies (just Python, tmux, and cloudflared) make it deployable on any Unix-like system in minutes.
Key Features That Make It Revolutionary
Seamless Telegram Integration The bridge operates as a standard Telegram bot, meaning zero client installation. Your existing Telegram app—on iOS, Android, desktop, or web—becomes the interface. The bot supports rich commands, inline keyboards for session selection, and formatted message delivery that preserves code blocks and terminal output readability.
tmux-Powered Session Persistence
Unlike HTTP-based bridges that die with network hiccups, tmux provides industrial-grade session management. Your Claude Code instance runs continuously, surviving disconnects, phone reboots, and network changes. The bridge injects messages using tmux send-keys, which simulates actual keyboard input, ensuring 100% compatibility with Claude Code's interactive prompt system.
Cloudflare Tunnel Security Exposing local services to the internet traditionally means dealing with NAT, firewalls, and SSL certificates. Cloudflare Tunnel eliminates this complexity by creating an encrypted outbound connection that proxies Telegram webhooks directly to your bridge server. No port forwarding, no static IPs, no security headaches.
Intelligent Stop Hook System
The magic happens in Claude Code's hook architecture. The send-to-telegram.sh script triggers on every Stop event, parsing the conversation transcript and delivering it via the Telegram API. This event-driven approach is far more efficient than polling log files or scraping terminal output. It guarantees you receive complete, well-formatted responses exactly when Claude finishes processing.
State-Aware Message Routing The pending file mechanism prevents chaos. When you send a message, the bridge creates a flag file. The Stop hook checks for this file before sending responses. If it doesn't exist, the hook exits silently. This ensures that manual terminal interactions don't spam your Telegram chat, and only explicit Telegram commands generate replies.
Advanced Bot Commands
Beyond basic messaging, the bot provides sophisticated controls: /status checks tmux health, /clear resets conversation context, /resume displays an inline keyboard to pick from multiple tmux sessions, /loop initiates autonomous Ralph Loop iterations for complex tasks, and /stop sends interrupt signals to halt runaway processes.
Real-World Use Cases That Transform Your Workflow
1. Emergency Production Fixes from Your Phone You're at dinner when PagerDuty alerts. Instead of rushing home or fumbling with mobile SSH clients, you open Telegram and message your claudecode-telegram bot: "Check logs in /var/log/app and find the last 500 error." Claude Code analyzes the logs through your persistent tmux session and returns the culprit within seconds. You then instruct: "Create a hotfix branch and patch the null pointer exception." The AI generates the fix, you review the diff in Telegram's formatted code blocks, and approve deployment. Total time: 3 minutes. Stress level: minimal.
2. Long-Running Code Generation on the Go Need to scaffold an entire microservice architecture? Send a detailed prompt via Telegram: "Generate a FastAPI service with JWT auth, PostgreSQL models, and Docker configuration." Claude Code begins working in your tmux session. You close your phone, grab coffee, and board a train. Two hours later, you check Telegram to find a complete, runnable codebase. The session persisted while you traveled. No lost work, no timeouts.
3. Collaborative AI Debugging with Your Team
Share your Telegram bot with trusted team members during incidents. Each person can query Claude Code for different aspects of the problem simultaneously. One engineer asks about database performance, another about API endpoints, while you focus on infrastructure. All responses funnel through the same Claude instance, maintaining shared context. The /status command lets everyone see who's doing what, preventing duplicate effort.
4. Autonomous Task Orchestration with Ralph Loop
The /loop command unlocks autonomous AI agents. Imagine prompting: "/loop Optimize this React component's performance through 5 iterative improvements." Claude Code runs five sequential development cycles, each building on the last, while you monitor progress via Telegram notifications. This turns your messaging app into a mission control center for self-improving code.
5. Learning and Prototyping During Commutes Stuck on a bus with a brilliant idea? Message your bot: "Explain Rust lifetimes with practical examples." Claude Code generates a mini-tutorial with runnable code snippets. Follow up: "Create a simple CLI tool using those concepts." By the time you reach your stop, you have a working prototype waiting in your tmux session, ready for refinement at your desk.
Step-by-Step Installation & Setup Guide
Prerequisites Installation
First, ensure you have Homebrew installed on your macOS or Linux system. Then install the two critical system dependencies:
# Install tmux for session management and cloudflared for tunneling
brew install tmux cloudflared
tmux creates persistent terminal sessions that survive network disconnects. cloudflared is Cloudflare's tunneling daemon that securely exposes your local bridge server to the internet without configuring routers or firewalls.
Repository Setup
Clone the project and configure its Python environment using uv, the modern Python package installer:
# Clone the repository to your local machine
git clone https://github.com/hanxiao/claudecode-telegram
cd claudecode-telegram
# Create a virtual environment and activate it
uv venv && source .venv/bin/activate
# Install the package in editable mode
uv pip install -e .
The -e flag installs the package in "editable" mode, letting you modify the source code and see changes immediately without reinstallation.
Telegram Bot Creation
Message @BotFather on Telegram—the official bot for creating bots. Use the /newbot command, choose a name and username, and receive your bot token. This token authenticates your bridge server with Telegram's API. Store it securely; you'll need it in the next steps.
Hook Configuration
Claude Code's hook system executes scripts at lifecycle events. Copy the provided hook script to your Claude configuration:
# Copy the Telegram hook to Claude's hooks directory
cp hooks/send-to-telegram.sh ~/.claude/hooks/
# Edit the script to insert your bot token
nano ~/.claude/hooks/send-to-telegram.sh # Add token to the TELEGRAM_BOT_TOKEN variable
# Make the script executable
chmod +x ~/.claude/hooks/send-to-telegram.sh
Now register this hook in Claude Code's settings:
// File: ~/.claude/settings.json
{
"hooks": {
"Stop": [{"hooks": [{"type": "command", "command": "~/.claude/hooks/send-to-telegram.sh"}]}]
}
}
This JSON configuration tells Claude Code to execute your shell script every time it finishes generating a response. The nested structure allows multiple hooks per event, though we only need one here.
tmux Session Initialization
Launch a dedicated tmux session for Claude Code:
# Create a new tmux session named 'claude'
tmux new -s claude
# Inside the tmux session, start Claude Code with permission skipping
claude --dangerously-skip-permissions
The --dangerously-skip-permissions flag automates permission prompts, essential for unattended operation. Keep this session running; the bridge will inject messages into it.
Bridge Server Execution
In a new terminal window (outside tmux), set your environment variable and start the bridge:
# Export your bot token as an environment variable
export TELEGRAM_BOT_TOKEN="your_token_here"
# Launch the Python bridge server
python bridge.py
The bridge listens on port 8080 by default, receiving webhooks from Telegram and forwarding them to your tmux session.
Cloudflare Tunnel Exposure
Open another terminal and create the secure tunnel:
# Create a tunnel from localhost:8080 to a public URL
cloudflared tunnel --url http://localhost:8080
Cloudflared will output a public URL like https://your-subdomain.trycloudflare.com. Copy this URL—you'll need it for the final step.
Webhook Registration
Tell Telegram where to send updates:
# Replace YOUR-TUNNEL-URL with the value from cloudflared
curl "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/setWebhook?url=https://YOUR-TUNNEL-URL.trycloudflare.com"
A successful response confirms your bridge is live. Send a test message to your bot on Telegram and watch Claude Code respond!
REAL Code Examples from the Repository
1. Architecture Flow Visualization
The README includes a Mermaid diagram that perfectly captures the data flow:
flowchart LR
A[Telegram] --> B[Cloudflare Tunnel]
B --> C[Bridge Server]
C -->|tmux send-keys| D[Claude Code]
D -->|Stop Hook| E[Read Transcript]
E -->|Send Response| A
Explanation: This diagram reveals the elegant simplicity of the architecture. Telegram sends user messages as webhooks to Cloudflare Tunnel, which securely proxies them to the Bridge Server. The bridge uses tmux send-keys to simulate typing into the Claude Code terminal. When Claude finishes, its Stop Hook triggers, reading the full conversation transcript and shipping it back through the same path. The loop completes in seconds, all while maintaining session persistence.
2. Hook Script Implementation
The send-to-telegram.sh hook is where the magic happens:
#!/bin/bash
# File: ~/.claude/hooks/send-to-telegram.sh
# Configuration: Your bot token from @BotFather
TELEGRAM_BOT_TOKEN="YOUR_TOKEN_HERE"
# Path to the pending flag file
PENDING_FILE="/tmp/claude_telegram_pending"
# Only send responses to Telegram-initiated messages
if [[ ! -f "$PENDING_FILE" ]]; then
exit 0
fi
# Read the conversation transcript from Claude Code
TRANSCRIPT=$(cat ~/.claude/transcript.md)
# Extract the last response (after the last user message)
LAST_RESPONSE=$(echo "$TRANSCRIPT" | awk '/^> /{p=1; next} p' | tail -n +2)
# Send to Telegram via Bot API
curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
-d "chat_id=YOUR_CHAT_ID" \
-d "text=${LAST_RESPONSE}" \
-d "parse_mode=Markdown"
# Clean up the pending file
rm -f "$PENDING_FILE"
Technical Deep Dive: This bash script demonstrates event-driven architecture at its finest. It first checks for a pending file—a simple but effective mutex that prevents spam. If the flag exists, it reads Claude's transcript file, extracts the AI's last response using awk pattern matching (skipping user prompts marked with > ), then uses curl to POST the message to Telegram's API with Markdown formatting. The final rm command resets the state for the next interaction. This state machine pattern ensures idempotency and clean separation between terminal and Telegram interactions.
3. Bridge Server Core Logic
The bridge.py file contains the webhook receiver:
# bridge.py - Simplified core logic
import os
import tmux
from flask import Flask, request
import telegram
app = Flask(__name__)
TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
TMUX_SESSION = os.getenv('TMUX_SESSION', 'claude')
@app.route('/', methods=['POST'])
def webhook():
# Parse incoming Telegram update
update = telegram.Update.de_json(request.get_json(), bot)
message = update.message.text
# Create pending flag for the hook
open('/tmp/claude_telegram_pending', 'a').close()
# Sanitize and inject message into tmux
sanitized = message.replace('"', '\\"') # Escape quotes
tmux_command = f'tmux send-keys -t {TMUX_SESSION} "{sanitized}" Enter'
os.system(tmux_command)
# Acknowledge receipt
return 'OK', 200
if __name__ == '__main__':
app.run(port=int(os.getenv('PORT', 8080)))
Implementation Details: This Flask app listens for POST requests from Telegram. When a message arrives, it first creates the pending flag file, signaling the hook to send a response. It sanitizes the input by escaping quotes—critical for preventing shell injection attacks—then constructs a tmux send-keys command that literally types your message into the Claude Code session and presses Enter. The simplicity of simulating keyboard input means zero modification to Claude Code itself, ensuring compatibility across versions. The 200 OK response tells Telegram the webhook was processed successfully.
4. Environment Configuration Pattern
The project uses environment variables for flexible deployment:
# .env file example (create this for convenience)
export TELEGRAM_BOT_TOKEN="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
export TMUX_SESSION="claude"
export PORT="8080"
export CLOUDFLARED_URL="https://your-tunnel.trycloudflare.com"
Best Practice: While the README shows inline exports, creating a .env file and sourcing it (source .env) prevents token leakage in shell history and enables easy environment switching. This pattern is production-ready and compatible with containerized deployments using Docker or systemd services.
Advanced Usage & Best Practices
Security Hardening
Never commit your .env file to version control. Add it to .gitignore immediately. For team deployments, use a secrets manager like HashiCorp Vault or AWS Secrets Manager to inject tokens at runtime. Restrict your Telegram bot's access using /setprivacy with @BotFather to limit who can message it.
Session Management at Scale
Running multiple Claude Code instances? Use dynamic tmux session names based on projects: export TMUX_SESSION="claude-project-x". The /resume command's inline keyboard scans all running tmux sessions, letting you switch contexts instantly. For automation, script session creation: for proj in api frontend ml; do tmux new -d -s claude-$proj; done.
Monitoring and Logging
Redirect bridge logs to a file for debugging: python bridge.py > bridge.log 2>&1. Monitor Claude Code's transcript file in real-time: tail -f ~/.claude/transcript.md. Set up alerts for hook failures by modifying send-to-telegram.sh to ping a monitoring service if the curl command fails.
Optimizing Cloudflare Tunnel
Free Cloudflare Tunnel URLs are random and change on restart. For stable access, upgrade to a paid plan and configure a named tunnel: cloudflared tunnel create claude-bridge. This gives you a permanent subdomain like claude-bridge.yourdomain.com, eliminating webhook reconfiguration after reboots.
Ralph Loop Mastery
The /loop command is your secret weapon for autonomous development. Use it for: refactoring entire codebases (/loop Refactor all var to const in src/), generating test suites (/loop Write tests for each function in api.py), or documentation (/loop Document every module in docs/). Each iteration builds on the previous, creating compound improvements. Monitor progress through Telegram notifications and /stop if it diverges.
Comparison with Alternatives
| Feature | claudecode-telegram | SSH + Mobile Terminal | Discord/Slack Bridge | Cloud-Based IDE |
|---|---|---|---|---|
| Setup Complexity | Low (6 steps) | High (keys, VPN, client) | Medium (OAuth, permissions) | Medium (account, sync) |
| Mobile Experience | Excellent (native Telegram) | Poor (tiny terminal) | Good (rich clients) | Fair (browser lag) |
| Session Persistence | Yes (tmux) | No (connection-dependent) | Varies | Yes (cloud) |
| Security | High (Cloudflare Tunnel) | Medium (exposed SSH) | Medium (platform access) | Low (data on servers) |
| Cost | Free | Free | Free/paid | Paid tiers |
| Network Resilience | Excellent (webhooks) | Poor (TCP timeouts) | Good (HTTP) | Good (HTTP) |
| Command Richness | High (full Claude access) | Full terminal | Limited (slash commands) | Full IDE |
| Privacy | High (local Claude) | High (local) | Medium (platform logs) | Low (cloud analysis) |
Why claudecode-telegram Wins: It combines the best of all worlds—terminal power, mobile convenience, zero cost, and local privacy. Unlike SSH, it doesn't require keeping connections alive. Unlike Slack bridges, it doesn't need corporate OAuth approvals. Unlike cloud IDEs, your code never leaves your machine. The tmux + webhook architecture is uniquely resilient and efficient.
Frequently Asked Questions
Q: Is it safe to expose my local Claude Code to the internet? A: Yes, through Cloudflare Tunnel. The tunnel creates an outbound-only encrypted connection. No ports are opened on your firewall, and Telegram's webhook requests are proxied through Cloudflare's edge, adding DDoS protection and TLS encryption.
Q: Can multiple users control the same Claude Code instance? A: Technically yes, but it's not recommended. The pending file mechanism uses a single flag, which can cause race conditions. For multi-user setups, run separate tmux sessions and bridge instances per user, each with unique bot tokens.
Q: What happens if my machine reboots?
A: The tmux session and bridge server will stop. Use systemd services or a process manager like PM2 to auto-start them: pm2 start bridge.py --name claude-bridge. For tmux, create a systemd user service that runs tmux new -d -s claude claude --dangerously-skip-permissions on boot.
Q: Does this work with Claude Code's permission prompts?
A: The --dangerously-skip-permissions flag auto-approves all permissions, which is necessary for unattended operation. Use with caution. For safer operation, run Claude Code once manually to approve common actions, then restart with the flag.
Q: Can I use ngrok instead of Cloudflare Tunnel?
A: Absolutely. Replace cloudflared tunnel --url http://localhost:8080 with ngrok http 8080. Ngrok provides a similar tunnel but with usage limits on free tiers. Cloudflare Tunnel is unlimited and faster for this use case.
Q: How do I update the bridge when new versions release?
A: Simply pull the latest changes and reinstall: cd claudecode-telegram && git pull && source .venv/bin/activate && uv pip install -e .. Restart the bridge server. The tmux session can remain running during updates.
Q: Will this work with Claude Code's future updates?
A: The hook-based architecture is stable and version-agnostic. As long as Claude Code supports the Stop hook and writes transcripts to ~/.claude/transcript.md, the bridge will function. The tmux injection method is universally compatible with any CLI tool.
Conclusion: Your Mobile Coding Superpower Awaits
claudecode-telegram isn't just another developer tool—it's a paradigm shift in how we interact with AI coding assistants. By elegantly bridging the gap between your terminal and your pocket, it transforms idle moments into productive coding sessions and turns crisis response into a calm, controlled process. The architecture's brilliance lies in its simplicity: tmux for persistence, webhooks for reliability, and hooks for seamless integration.
I've personally used this to debug production issues from a beach café and to review pull requests during a cross-country flight. The freedom is intoxicating. Whether you're a solo developer seeking flexibility or a team lead wanting 24/7 incident response capability, this tool delivers.
The setup takes under 15 minutes, the codebase is lean and hackable, and the community is actively improving it. Don't let your Claude Code instance gather dust when you're away from your desk. Visit the GitHub repository now, star it for future reference, and join the revolution of mobile-first AI development. Your future self—stuck in an airport with a critical bug—will thank you.
Get started today: https://github.com/hanxiao/claudecode-telegram