Skip to content

Telegram bot for interacting with Claude Code CLI - execute commands, analyze files, maintain conversation context

License

Notifications You must be signed in to change notification settings

gmen1057/claude-cli-telegrambot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

10 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Claude Code Telegram Bot

License: MIT Python 3.9+ Code style: black

English | Русский

Control Claude Code CLI through Telegram. Execute commands, analyze files, and manage your server directly from your phone.

✨ Features

  • Full Claude Code Access β€” Execute any Claude Code command via Telegram
  • Session Persistence β€” Context preserved between messages (stored in PostgreSQL)
  • File Support β€” Upload and analyze files and images
  • Safe by Default β€” Read-only mode unless you explicitly request changes
  • Command Cancellation β€” Cancel long-running operations with /cancel
  • Timeout Protection β€” 5-minute timeout prevents hanging processes
  • Access Control β€” Restrict bot access to specific Telegram user IDs
  • Graceful Shutdown β€” Clean termination of all processes

πŸ“‹ Prerequisites

  • Python 3.9+
  • PostgreSQL 12+
  • Claude Code CLI installed (npm install -g @anthropic-ai/claude-code)
  • Telegram Bot Token (from @BotFather)

πŸš€ Quick Start

1. Clone the repository

git clone https://github.com/gmen1057/claude-cli-telegrambot.git
cd claude-cli-telegrambot

2. Create virtual environment

python -m venv venv
source venv/bin/activate  # Linux/Mac
# or: venv\Scripts\activate  # Windows

3. Install dependencies

pip install -r requirements.txt

4. Configure environment

cp .env.example .env
# Edit .env with your settings

5. Create database

sudo -u postgres psql -c "CREATE DATABASE claude_code_bot;"
sudo -u postgres psql -c "CREATE USER your_user WITH PASSWORD 'your_password';"
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE claude_code_bot TO your_user;"

6. Run the bot

python -m bot.main

🐳 Docker Installation

# Configure environment
cp .env.example .env
# Edit .env with your settings

# Run with Docker Compose
docker-compose up -d

# View logs
docker-compose logs -f bot

βš™οΈ Configuration

Variable Description Default
TELEGRAM_TOKEN Bot token from @BotFather Required
ALLOWED_USER_ID Comma-separated Telegram user IDs None (all users)
DB_NAME PostgreSQL database name claude_code_bot
DB_USER Database username postgres
DB_PASSWORD Database password postgres
DB_HOST Database host localhost
DB_PORT Database port 5432
CLAUDE_CLI_PATH Path to Claude CLI binary /root/.bun/bin/claude
CLAUDE_TIMEOUT Command timeout in seconds 300
DEFAULT_WORKING_DIR Default working directory /root

Getting Your Telegram User ID

Send /start to @userinfobot to get your user ID.

πŸ“– Usage

Bot Commands

Command Description
/start Start the bot and create session
/reset Start new session (clear context)
/status Show current session status
/context Show recent conversation context
/history Show command history
/cancel Cancel running command
/cd <path> Change working directory
/help Show help message

Execution Keywords

Commands are executed only when you use trigger keywords:

Russian: Π²Ρ‹ΠΏΠΎΠ»Π½ΠΈ, сдСлай, запусти, ΠΈΡΠΏΡ€Π°Π²ΡŒ, создай, ΡƒΠ΄Π°Π»ΠΈ, пСрСзапусти

English: execute, run, do, fix, create, delete, restart

Examples

Information only (no execution):

Show me the list of files
What does this script do?
Check nginx status

With execution:

Restart nginx service
Create a new Python script
Fix the error in bot.py

File Uploads

Upload any file to the chat and Claude will analyze it:

  • Images β€” Visual analysis and description
  • Code files β€” Code review and suggestions
  • Logs β€” Error analysis and troubleshooting
  • Documents β€” Content extraction and summary

πŸ—οΈ Architecture

claude-code-bot/
β”œβ”€β”€ bot/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ main.py              # Entry point, application setup
β”‚   β”œβ”€β”€ config.py            # Configuration from environment
β”‚   β”œβ”€β”€ handlers/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ commands.py      # Bot command handlers
β”‚   β”‚   β”œβ”€β”€ messages.py      # Text message handler
β”‚   β”‚   └── files.py         # File upload handler
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ claude.py        # Claude CLI executor
β”‚   β”‚   β”œβ”€β”€ session.py       # Session management
β”‚   β”‚   └── formatter.py     # Telegram HTML formatter
β”‚   └── database/
β”‚       β”œβ”€β”€ __init__.py
β”‚       └── pool.py          # PostgreSQL connection pool
β”œβ”€β”€ user_files/              # Uploaded files storage
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ docker-compose.yml
β”œβ”€β”€ .env.example
β”œβ”€β”€ LICENSE
└── README.md

πŸ” Security

Access Control

  • Set ALLOWED_USER_ID to restrict access to specific Telegram user IDs
  • Multiple IDs can be comma-separated: 123456789,987654321
  • Warning: Without this setting, anyone can use your bot!

Safe Execution

  • Commands run in read-only mode by default
  • Explicit trigger keywords required for modifications
  • Safety instructions embedded in every prompt

Timeout Protection

  • 5-minute timeout on all Claude operations
  • Cancel any time with /cancel

πŸ–₯️ Systemd Service

Create /etc/systemd/system/claude-code-bot.service:

[Unit]
Description=Claude Code Telegram Bot
After=network.target postgresql.service

[Service]
Type=simple
User=root
WorkingDirectory=/path/to/claude-code-bot
Environment=PATH=/root/.bun/bin:/usr/local/bin:/usr/bin:/bin
ExecStart=/path/to/claude-code-bot/venv/bin/python -m bot.main
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Enable and start:

systemctl daemon-reload
systemctl enable claude-code-bot
systemctl start claude-code-bot

View logs:

journalctl -u claude-code-bot -f

πŸ”§ Troubleshooting

Bot not responding

  1. Check logs: journalctl -u claude-code-bot -f
  2. Verify Claude CLI works: claude --version
  3. Check database connection: psql -h localhost -U your_user -d claude_code_bot

Timeout errors

  1. Increase CLAUDE_TIMEOUT in .env
  2. Simplify your request
  3. Check if Claude CLI is responding: claude "Hello"

Permission errors

  1. Ensure bot runs as user with Claude CLI access
  2. Check working directory permissions
  3. Verify file upload directory is writable

Database errors

  1. Check PostgreSQL is running: systemctl status postgresql
  2. Verify credentials in .env
  3. Check database exists: psql -l | grep claude_code_bot

πŸ“ Database Schema

The bot uses two tables:

sessions β€” User session data

CREATE TABLE sessions (
    user_id BIGINT PRIMARY KEY,
    context TEXT,
    working_dir TEXT,
    message_count INTEGER DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

command_logs β€” Command history

CREATE TABLE command_logs (
    id SERIAL PRIMARY KEY,
    user_id BIGINT NOT NULL,
    command TEXT NOT NULL,
    response TEXT,
    execution_time_ms INTEGER DEFAULT 0,
    error TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

🀝 Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m 'Add amazing feature'
  4. Push to the branch: git push origin feature/amazing-feature
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License β€” see the LICENSE file for details.

πŸ™ Acknowledgments

πŸ“ž Support

About

Telegram bot for interacting with Claude Code CLI - execute commands, analyze files, maintain conversation context

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •