### Install Bot using uv Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Install the bot using uv, the recommended package and environment manager, which installs packages in an isolated environment. ```bash uv tool install git+https://github.com/RichardAtCT/claude-code-telegram@v1.3.0 ``` -------------------------------- ### Enable and Start Systemd User Service Source: https://github.com/richardatct/claude-code-telegram/blob/main/SYSTEMD_SETUP.md Reload systemd to recognize the new service, enable it to start automatically on login, and start the service immediately. ```bash # Reload systemd to recognize the new service systemctl --user daemon-reload # Enable auto-start on login systemctl --user enable claude-telegram-bot.service # Start the service now systemctl --user start claude-telegram-bot.service ``` -------------------------------- ### Install Dependencies with Make Source: https://github.com/richardatct/claude-code-telegram/blob/main/CONTRIBUTING.md Install project dependencies and pre-commit hooks using the provided Makefile. This command ensures all necessary packages are installed and code formatting is set up. ```bash make dev ``` -------------------------------- ### Install Bot using pip Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Install the bot using pip. This command installs directly from the Git repository at a specific tag or the latest release. ```bash pip install git+https://github.com/RichardAtCT/claude-code-telegram@v1.3.0 ``` ```bash pip install git+https://github.com/RichardAtCT/claude-code-telegram@latest ``` -------------------------------- ### Install Poetry Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md Install Poetry, a dependency management tool for Python, if it is not already installed. ```bash pip install poetry ``` -------------------------------- ### Install Production Dependencies Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md Install only the dependencies required for the production environment. ```bash make install ``` -------------------------------- ### Install ffmpeg on Ubuntu/Debian Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/local-whisper-cpp.md Installs the ffmpeg package on Ubuntu or Debian-based systems using apt. ```bash sudo apt update && sudo apt install -y ffmpeg ``` -------------------------------- ### Set Up Environment Configuration Source: https://github.com/richardatct/claude-code-telegram/blob/main/CONTRIBUTING.md Copy the example environment file and edit it with your specific development settings. This step is crucial for configuring the application's behavior. ```bash cp .env.example .env # Edit .env with your development settings ``` -------------------------------- ### Verify Development Setup Source: https://github.com/richardatct/claude-code-telegram/blob/main/CONTRIBUTING.md Run tests and linting to verify that the development environment is set up correctly. These commands ensure code quality and functionality. ```bash make test make lint ``` -------------------------------- ### Install whisper.cpp system-wide Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/local-whisper-cpp.md Copies the compiled whisper-cpp binary to a system-wide accessible location. ```bash sudo cp build/bin/whisper-cli /usr/local/bin/whisper-cpp ``` -------------------------------- ### Classic Mode Navigation Example Source: https://github.com/richardatct/claude-code-telegram/blob/main/README.md Shows basic directory navigation and action execution in Classic Mode. Commands like `/cd`, `/ls`, and `/actions` are used. ```text You: /cd my-web-app Bot: Directory changed to my-web-app/ You: /ls Bot: src/ tests/ package.json README.md You: /actions Bot: [Run Tests] [Install Deps] [Format Code] [Run Linter] ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Clone the bot's repository from GitHub and install development dependencies using the provided Makefile. This is for development purposes. ```bash git clone https://github.com/RichardAtCT/claude-code-telegram.git cd claude-code-telegram make dev ``` -------------------------------- ### Install Voice Extras for Cloud Providers Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Install the 'voice' extras for the package if using cloud-based transcription providers like Mistral or OpenAI. ```bash pip install "claude-code-telegram[voice]" ``` -------------------------------- ### Copy and Edit Environment File Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Copy the example environment file and then edit it to configure the bot's settings, including tokens and user IDs. ```bash cp .env.example .env nano .env ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md Set up pre-commit hooks for automated code quality checks before committing. This is optional but recommended. ```bash poetry run pre-commit install ``` -------------------------------- ### Install ffmpeg on Alpine Linux Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/local-whisper-cpp.md Installs the ffmpeg package on Alpine Linux using the apk package manager. ```bash apk add ffmpeg ``` -------------------------------- ### Manually Install aiolimiter and Re-run Tests Source: https://github.com/richardatct/claude-code-telegram/blob/main/CONTRIBUTING.md Manually install the 'aiolimiter' package and re-run tests if initial setup failed due to test failures. This is a recovery step for specific Linux environments. ```bash poetry run pip install aiolimiter make test ``` -------------------------------- ### Development and Production Commands Source: https://github.com/richardatct/claude-code-telegram/blob/main/CLAUDE.md Common commands for managing dependencies, running the bot, and testing. Use 'make dev' for full development setup. ```bash make dev # Install all deps (including dev) make install # Production deps only make run # Run the bot make run-debug # Run with debug logging make test # Run tests with coverage make lint # Black + isort + flake8 + mypy make format # Auto-format with black + isort ``` -------------------------------- ### Verify ffmpeg installation Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/local-whisper-cpp.md Checks if ffmpeg is installed and accessible on the system. ```bash ffmpeg -version ``` -------------------------------- ### Run Development Commands Source: https://github.com/richardatct/claude-code-telegram/blob/main/README.md Execute common development tasks such as installing dependencies, running tests, linting, formatting, and debugging. ```bash make dev # Install all dependencies make test # Run tests with coverage make lint # Black + isort + flake8 + mypy make format # Auto-format code make run-debug # Run with debug logging make run-watch # Run with auto-restart on code changes ``` -------------------------------- ### Install ffmpeg on macOS with Homebrew Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/local-whisper-cpp.md Installs the ffmpeg package on macOS using the Homebrew package manager. ```bash brew install ffmpeg ``` -------------------------------- ### Troubleshoot Systemd Service Startup Issues Source: https://github.com/richardatct/claude-code-telegram/blob/main/SYSTEMD_SETUP.md Commands to help diagnose why a systemd user service might not be starting, including checking logs, verifying service file configuration, and testing the bot manually. ```bash # Check logs for errors journalctl --user -u claude-telegram-bot -n 100 # Verify paths in service file are correct systemctl --user cat claude-telegram-bot # Check that Poetry is installed poetry --version # Test the bot manually first cd /home/ubuntu/Code/oss/claude-code-telegram poetry run claude-telegram-bot ``` -------------------------------- ### Authenticate with Claude CLI Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Use this command to log in to the Claude CLI, which the SDK will use for authentication. Ensure you have the Claude CLI installed first. ```bash claude auth login ``` ```bash claude auth status ``` -------------------------------- ### Python Type Hinting Example Source: https://github.com/richardatct/claude-code-telegram/blob/main/CONTRIBUTING.md Demonstrates comprehensive type hinting for function arguments and return values. Ensure all code includes type hints. ```python from typing import Optional, List, Dict, Any from pathlib import Path async def process_data( items: List[Dict[str, Any]], config: Optional[Path] = None ) -> bool: """Process data with optional config.""" # Implementation return True ``` -------------------------------- ### Custom `can_use_tool` Callback Example Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/SDK_DUPLICATION_REVIEW.md Provides an example of a custom `can_use_tool` callback function that can deny or modify tool calls based on specific criteria like file paths or bash commands. ```python async def permission_handler(tool_name, input_data, context): if tool_name == "Write" and "/system/" in input_data.get("file_path", ""): return PermissionResultDeny(message="System dir write blocked", interrupt=True) if tool_name == "Bash": cmd = input_data.get("command", "") ok, err = check_boundary(cmd, working_dir, approved_dir) if not ok: return PermissionResultDeny(message=err) return PermissionResultAllow(updated_input=input_data) ``` ```python options = ClaudeAgentOptions( can_use_tool=permission_handler, allowed_tools=["Read", "Write", "Bash"], disallowed_tools=["WebFetch"], ) ``` -------------------------------- ### Pytest Example for Feature Testing Source: https://github.com/richardatct/claude-code-telegram/blob/main/CONTRIBUTING.md Provides an example of writing asynchronous tests using pytest. Use the pytest.mark.asyncio decorator and create test configurations. ```python import pytest from src.config import create_test_config @pytest.mark.asyncio async def test_feature(): """Test feature functionality.""" config = create_test_config(debug=True) # Test implementation assert config.debug is True ``` -------------------------------- ### Install Claude Code Telegram Bot using uv Source: https://github.com/richardatct/claude-code-telegram/blob/main/README.md Installs the bot from a release tag using uv, which is the recommended method for isolated environments. ```bash # Using uv (recommended — installs in an isolated environment) uv tool install git+https://github.com/RichardAtCT/claude-code-telegram@v1.3.0 ``` -------------------------------- ### Configure Environment Variables for Claude Code Telegram Bot Source: https://github.com/richardatct/claude-code-telegram/blob/main/README.md Copies the example environment file and lists the minimum required variables to configure the bot. ```bash cp .env.example .env # Edit .env with your settings: **Minimum required:** TELEGRAM_BOT_TOKEN=1234567890:ABC-DEF1234ghIkl-zyx57W2v1u123ew11 TELEGRAM_BOT_USERNAME=my_claude_bot APPROVED_DIRECTORY=/Users/yourname/projects ALLOWED_USERS=123456789 # Your Telegram user ID ``` -------------------------------- ### Install Claude Code Telegram Bot using pip Source: https://github.com/richardatct/claude-code-telegram/blob/main/README.md Installs the bot from a release tag using pip. ```bash # Or using pip pip install git+https://github.com/RichardAtCT/claude-code-telegram@v1.3.0 ``` -------------------------------- ### Install Claude Code Telegram Bot from Source for Development Source: https://github.com/richardatct/claude-code-telegram/blob/main/README.md Installs the bot from source for development purposes, requiring Poetry. ```bash git clone https://github.com/RichardAtCT/claude-code-telegram.git cd claude-code-telegram make dev # requires Poetry ``` -------------------------------- ### Run Bot in Debug Mode Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Execute this command to run the bot with debug logging enabled. This is recommended for initial setup and troubleshooting. ```bash make run-debug ``` -------------------------------- ### Conventional Commit Message Examples Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md Examples of commit messages following the conventional commits specification. This format helps in automating changelog generation and understanding commit history. ```text feat: add rate limiting functionality fix: resolve configuration validation issue docs: update development guide test: add tests for authentication system ``` -------------------------------- ### Example of Verbose Tool Output Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/tools.md When verbose output is enabled, Claude displays each tool call with its icon as it processes the request. ```text You: Add type hints to utils.py Bot: Working... (5s) 📖 Read: utils.py 💬 I'll add type annotations to all functions ✏️ Edit: utils.py 💻 Bash: poetry run mypy src/utils.py Bot: [Claude shows the changes and type-check results] ``` -------------------------------- ### Load Configuration and Access Feature Flags Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/configuration.md Load configuration settings and instantiate FeatureFlags to check if specific features are enabled. This is typically done at the start of the application. ```python from src.config import load_config, FeatureFlags config = load_config() features = FeatureFlags(config) if features.agentic_mode_enabled: # Use agentic mode handlers pass if features.api_server_enabled: # Start webhook API server pass ``` -------------------------------- ### Download GGML models for whisper.cpp Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/local-whisper-cpp.md Downloads GGML model weights from Hugging Face to the default cache directory (~/.cache/whisper-cpp). Examples include 'base' and 'small' models. ```bash # Create the model cache directory mkdir -p ~/.cache/whisper-cpp # Download the base model (recommended starting point) curl -L -o ~/.cache/whisper-cpp/ggml-base.bin \ https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-base.bin # Or download small for better accuracy curl -L -o ~/.cache/whisper-cpp/ggml-small.bin \ https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-small.bin ``` -------------------------------- ### Check Claude API Key Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Verify your Anthropic API key starts with the expected prefix. Ensure the environment variable is set. ```bash # Verify key starts with: sk-ant-api03- echo $ANTHROPIC_API_KEY ``` -------------------------------- ### Accessing Bot Dependencies in Python Source: https://github.com/richardatct/claude-code-telegram/blob/main/CLAUDE.md Example of how to access bot dependencies like authentication managers and Claude integration within Python handlers. ```python context.bot_data["auth_manager"] context.bot_data["claude_integration"] context.bot_data["storage"] context.bot_data["security_validator"] ``` -------------------------------- ### Use Existing Claude CLI Authentication Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/configuration.md Recommended for authentication. Ensure the Claude CLI is installed and authenticated using 'claude auth login'. No ANTHROPIC_API_KEY is needed as the SDK will use CLI credentials. ```bash # No ANTHROPIC_API_KEY needed - SDK will use CLI credentials # Ensure Claude CLI is installed and authenticated: claude auth login ``` -------------------------------- ### Agentic Mode Conversation Example Source: https://github.com/richardatct/claude-code-telegram/blob/main/README.md Demonstrates a typical conversation in Agentic Mode where the user asks about project files and requests code modifications. Shows the bot's internal steps and final output. ```text You: What files are in this project? Bot: Working... (3s) 📖 Read 📂 LS 💬 Let me describe the project structure Bot: [Claude describes the project structure] You: Add a retry decorator to the HTTP client Bot: Working... (8s) 📖 Read: http_client.py 💬 I'll add a retry decorator with exponential backoff ✏️ Edit: http_client.py 💻 Bash: poetry run pytest tests/ -v Bot: [Claude shows the changes and test results] You: /verbose 0 Bot: Verbosity set to 0 (quiet) ``` -------------------------------- ### Pytest Unit Test with Configuration Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md Example of a unit test using pytest that involves creating a test configuration and asserting its properties. Ensure tests are organized and cover specific functionalities. ```python import pytest from src.config import create_test_config def test_feature_with_config(): """Test feature with specific configuration.""" config = create_test_config( debug=True, claude_max_turns=5 ) # Test implementation assert config.debug is True assert config.claude_max_turns == 5 ``` -------------------------------- ### Add New Setting to Settings Class Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md Example of adding a new boolean configuration setting to the Settings class. This involves defining the field with a default value and a description. ```python new_setting: bool = Field(False, description="Description of new setting") ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/richardatct/claude-code-telegram/blob/main/CONTRIBUTING.md Clone the project repository and change into the project directory. This is the first step to setting up your development environment. ```bash git clone https://github.com/your-username/claude-code-telegram.git cd claude-code-telegram ``` -------------------------------- ### Show All Make Commands Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md Display a help message listing all available `make` commands and their descriptions. ```bash make help ``` -------------------------------- ### Project Structure Overview Source: https://github.com/richardatct/claude-code-telegram/blob/main/CONTRIBUTING.md Understand the directory structure for the project, including configuration, security, bot, Claude integration, and storage modules. ```bash src/ ├── config/ # Configuration (✅ Complete) ├── security/ # Authentication & Security (✅ Complete) ├── bot/ # Telegram bot (✅ Complete - TODO-4) ├── claude/ # Claude integration (✅ Complete - TODO-5) └── storage/ # Database (✅ Complete - TODO-6) ``` -------------------------------- ### Install Latest Stable Release of Claude Code Telegram Bot Source: https://github.com/richardatct/claude-code-telegram/blob/main/README.md Installs the latest stable release of the bot using pip. ```bash # Track the latest stable release pip install git+https://github.com/RichardAtCT/claude-code-telegram@latest ``` -------------------------------- ### Show Current Version Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md Display the current version of the project. ```bash make version ``` -------------------------------- ### Run Claude Code on Remote Mac with Keychain Unlock Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Execute `make run-remote` to start the bot on a remote Mac. This command unlocks the keychain and starts the bot in a detached tmux session. ```bash make run-remote ``` -------------------------------- ### Storage and Database Settings Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/configuration.md Configure the database connection URL, session timeouts, maximum sessions per user, and data retention periods. ```bash # Database URL (SQLite by default) DATABASE_URL=sqlite:///data/bot.db # Session management SESSION_TIMEOUT_HOURS=24 MAX_SESSIONS_PER_USER=5 # Data retention DATA_RETENTION_DAYS=90 AUDIT_LOG_RETENTION_DAYS=365 ``` -------------------------------- ### Configure Development and Logging Settings Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Enable debugging and set logging levels for development environments. `DEVELOPMENT_MODE` and `ENVIRONMENT` can be set for specific configurations. ```bash DEBUG=true DEVELOPMENT_MODE=true LOG_LEVEL=DEBUG ENVIRONMENT=development RATE_LIMIT_REQUESTS=100 CLAUDE_TIMEOUT_SECONDS=600 ``` -------------------------------- ### Recommended Security Settings Source: https://github.com/richardatct/claude-code-telegram/blob/main/SECURITY.md Implement strict rate limiting, cost controls, and enable telemetry for production environments. Set LOG_LEVEL to INFO to capture security events. Ensure ENVIRONMENT is set to 'production' for strict defaults. ```bash # Strict rate limiting for production RATE_LIMIT_REQUESTS=5 RATE_LIMIT_WINDOW=60 RATE_LIMIT_BURST=10 # Cost controls CLAUDE_MAX_COST_PER_USER=5.0 # Security features ENABLE_TELEMETRY=true # For security monitoring LOG_LEVEL=INFO # Capture security events # Environment ENVIRONMENT=production # Enables strict security defaults ``` -------------------------------- ### Required Security Settings Source: https://github.com/richardatct/claude-code-telegram/blob/main/SECURITY.md Configure base directory, user access, and optional token authentication. Ensure APPROVED_DIRECTORY is set to a secure, isolated path. Generate AUTH_TOKEN_SECRET using a strong random method. ```bash # Base directory for all operations (CRITICAL) APPROVED_DIRECTORY=/path/to/approved/projects # User access control ALLOWED_USERS=123456789,987654321 # Telegram user IDs # Optional: Token-based authentication ENABLE_TOKEN_AUTH=true AUTH_TOKEN_SECRET=your-secret-here # Generate with: openssl rand -hex 32 ``` -------------------------------- ### Bumping Project Version using Make Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md Automate version bumping, committing, tagging, and pushing using these make commands. Choose the appropriate command based on the type of version increment needed. ```bash # Bump the version (choose one) — commits, tags, and pushes automatically make bump-patch # 1.2.0 -> 1.2.1 make bump-minor # 1.2.0 -> 1.3.0 make bump-major # 1.2.0 -> 2.0.0 ``` -------------------------------- ### Run Tests and Code Quality Checks Source: https://github.com/richardatct/claude-code-telegram/blob/main/CONTRIBUTING.md Execute tests and code quality checks using make commands. Ensure code is formatted and linted before committing. ```bash # Add tests in tests/unit/ or tests/integration/ make test ``` ```bash make format # Auto-format code ``` ```bash make lint # Check code quality ``` -------------------------------- ### SDK Permission Evaluation Pipeline Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/SDK_DUPLICATION_REVIEW.md Illustrates the SDK's native permission evaluation flow, emphasizing the role of the `can_use_tool` callback before tool execution. ```text Hooks → Deny Rules → Allow Rules → Ask Rules → Permission Mode → can_use_tool callback ``` -------------------------------- ### Test Configuration Loading Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md Programmatically load the application configuration and print its model dump. This is useful for verifying that the configuration is loaded correctly. ```python from src.config import load_config config = load_config() print(config.model_dump()) ``` -------------------------------- ### Structured Logging in Python Source: https://github.com/richardatct/claude-code-telegram/blob/main/CONTRIBUTING.md Shows how to implement structured logging using structlog. Log events with contextual information like operation names and user IDs. ```python import structlog logger = structlog.get_logger() def some_function(): logger.info("Operation started", operation="example", user_id=123) # Implementation ``` -------------------------------- ### Build whisper.cpp from source Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/local-whisper-cpp.md Clones the whisper.cpp repository and builds the project using CMake for a release configuration. The binary is typically found at build/bin/whisper-cli. ```bash # Clone the repository git clone https://github.com/ggerganov/whisper.cpp.git cd whisper.cpp # Build with CMake (recommended) cmake -B build cmake --build build --config Release # The binary is at build/bin/whisper-cli (or build/bin/main on older versions) ls build/bin/whisper-cli ``` -------------------------------- ### Set Minimal Directory Permissions Source: https://github.com/richardatct/claude-code-telegram/blob/main/SECURITY.md Ensure that directories used for approved projects have minimal necessary permissions to prevent unauthorized access. Avoid using sensitive system directories. ```bash # Use minimal necessary permissions chmod 755 /path/to/approved/projects # Avoid sensitive directories # Don't use: /, /home, /etc, /var # Use: /home/user/projects, /opt/bot-projects ``` -------------------------------- ### Download base model if not found Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/local-whisper-cpp.md Provides the command to download the 'base' GGML model to the default cache directory if it's missing, addressing a common troubleshooting step. ```bash mkdir -p ~/.cache/whisper-cpp curl -L -o ~/.cache/whisper-cpp/ggml-base.bin \ https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-base.bin ``` -------------------------------- ### Running the Application in Development Mode Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md Use these commands to run the application with debug output enabled. You can export variables directly or rely on a `.env` file. ```bash # Basic run with environment variables export TELEGRAM_BOT_TOKEN=test_token export TELEGRAM_BOT_USERNAME=test_bot export APPROVED_DIRECTORY=/tmp/test_projects make run-debug # Or with .env file make run-debug ``` -------------------------------- ### Add New Feature Flag Property Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md Example of adding a new property to the FeatureFlags class to enable a new feature. This property checks the settings for the feature's enablement. ```python @property def new_feature_enabled(self) -> bool: return self.settings.enable_new_feature ``` -------------------------------- ### Check Project Directory Permissions Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Ensure the approved directory for your projects exists and is accessible by listing its contents. ```bash # Check approved directory exists and is accessible ls -la /path/to/your/projects ``` -------------------------------- ### Create Systemd User Service File Source: https://github.com/richardatct/claude-code-telegram/blob/main/SYSTEMD_SETUP.md Create the directory for user services and the service definition file for the Claude Code Telegram Bot. Ensure to update the WorkingDirectory to your project's path. ```bash mkdir -p ~/.config/systemd/user nano ~/.config/systemd/user/claude-telegram-bot.service ``` ```ini [Unit] Description=Claude Code Telegram Bot After=network.target [Service] Type=simple WorkingDirectory=/home/ubuntu/Code/oss/claude-code-telegram ExecStart=/home/ubuntu/.local/bin/poetry run claude-telegram-bot Restart=always RestartSec=10 StandardOutput=journal StandardError=journal # Environment Environment="PATH=/home/ubuntu/.local/bin:/usr/local/bin:/usr/bin:/bin" [Install] WantedBy=default.target ``` -------------------------------- ### Conventional Commit Message Examples Source: https://github.com/richardatct/claude-code-telegram/blob/main/CONTRIBUTING.md Follow the conventional commits specification for clear and consistent commit messages. Use prefixes like 'feat', 'fix', 'docs', 'test', 'refactor' to indicate the type of change. ```git feat: add rate limiting functionality ``` ```git fix: resolve configuration validation issue ``` ```git docs: update development guide ``` ```git test: add tests for authentication system ``` ```git refactor: reorganize bot handlers ``` -------------------------------- ### Common Systemd User Service Commands Source: https://github.com/richardatct/claude-code-telegram/blob/main/SYSTEMD_SETUP.md A collection of essential commands for managing the Claude Code Telegram Bot systemd user service, including starting, stopping, restarting, viewing status, logs, and enabling/disabling auto-start. ```bash # Start service systemctl --user start claude-telegram-bot # Stop service systemctl --user stop claude-telegram-bot # Restart service systemctl --user restart claude-telegram-bot # View status systemctl --user status claude-telegram-bot # View live logs journalctl --user -u claude-telegram-bot -f # View recent logs (last 50 lines) journalctl --user -u claude-telegram-bot -n 50 # Disable auto-start systemctl --user disable claude-telegram-bot # Enable auto-start systemctl --user enable claude-telegram-bot ``` -------------------------------- ### Python Function with Type Hints Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md Demonstrates comprehensive type hinting for function arguments and return values. Ensure all functions include type hints for clarity and static analysis. ```python from typing import Optional, List, Dict, Any from pathlib import Path def process_config( settings: Settings, overrides: Optional[Dict[str, Any]] = None ) -> Path: """Process configuration with optional overrides.""" # Implementation return Path("/example") ``` -------------------------------- ### Development Environment Configuration Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/configuration.md Enable or disable development-specific features. Set DEBUG and DEVELOPMENT_MODE to true for enhanced debugging and features during development. Use ENVIRONMENT to specify the current deployment stage. ```bash # Enable debug mode DEBUG=false # Enable development features DEVELOPMENT_MODE=false # Environment override (development, testing, production) ENVIRONMENT=development ``` -------------------------------- ### Source Code Package Structure Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md Illustrates the organization of the main application source code, including configuration, bot logic, Claude integration, storage, security, and utilities. ```tree src/ ├── config/ # Configuration management (✅ Complete) │ ├── __init__.py │ ├── settings.py # Pydantic Settings class │ ├── loader.py # Environment detection and loading │ ├── environments.py # Environment-specific overrides │ └── features.py # Feature flag management ├── bot/ # Telegram bot implementation (✅ Complete) │ ├── __init__.py │ ├── core.py # Main bot class │ ├── handlers/ # Command and message handlers │ ├── middleware/ # Authentication and rate limiting │ └── utils/ # Response formatting utilities ├── claude/ # Claude Code integration (✅ Complete) │ ├── __init__.py │ ├── integration.py # Subprocess management │ ├── parser.py # Output parsing and formatting │ ├── session.py # Session management │ ├── monitor.py # Tool usage monitoring │ ├── facade.py # High-level integration API │ └── exceptions.py # Claude-specific exceptions ├── storage/ # Database and persistence (✅ Complete) │ ├── __init__.py │ ├── database.py # Database connection and migrations │ ├── models.py # Data models with type safety │ ├── repositories.py # Repository pattern data access │ ├── facade.py # Storage facade interface │ └── session_storage.py # Persistent session storage ├── security/ # Authentication and security (✅ Complete) │ ├── __init__.py │ ├── auth.py # Authentication logic │ ├── validators.py # Input validation │ └── rate_limiter.py # Rate limiting ├── utils/ # Utilities and constants (✅ Complete) │ ├── __init__.py │ └── constants.py # Application constants ├── exceptions.py # Custom exception hierarchy (✅ Complete) └── main.py # Application entry point (✅ Complete) ``` -------------------------------- ### Required Environment Variables for Development Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md These variables must be set in your `.env` file for basic functionality, Claude authentication, and development-specific settings. Choose one method for Claude authentication. ```bash # Required for basic functionality TELEGRAM_BOT_TOKEN=test_token_for_development TELEGRAM_BOT_USERNAME=test_bot APPROVED_DIRECTORY=/path/to/your/test/projects # Claude Authentication (choose one method) # Option 1: Use existing Claude CLI auth (no API key needed) # Option 2: Direct API key # ANTHROPIC_API_KEY=sk-ant-api03-your-development-key # Development settings DEBUG=true DEVELOPMENT_MODE=true LOG_LEVEL=DEBUG ENVIRONMENT=development # Optional for testing specific features ENABLE_GIT_INTEGRATION=true ENABLE_FILE_UPLOADS=true ENABLE_QUICK_ACTIONS=true ``` -------------------------------- ### Configure Logging and Monitoring Source: https://github.com/richardatct/claude-code-telegram/blob/main/SECURITY.md Enable logging and telemetry for the bot. Monitor logs for security-related events by filtering for keywords like 'security', 'auth', or 'violation'. ```bash # Enable logging and monitoring export LOG_LEVEL=INFO export ENABLE_TELEMETRY=true # Monitor logs for security events tail -f bot.log | grep -i "security\|auth\|violation" ``` -------------------------------- ### Format Code Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md Automatically format the codebase to maintain consistent style before committing. ```bash make format ``` -------------------------------- ### Activate Poetry Environment Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md Activate the virtual environment managed by Poetry to ensure correct dependencies are used. ```bash poetry shell ``` -------------------------------- ### Set Approved Directory for Security Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Configure the `APPROVED_DIRECTORY` environment variable to specify a project directory for isolation. This is not your home directory. ```bash # Set to a specific project directory, not your home directory APPROVED_DIRECTORY=/Users/yourname/projects ``` -------------------------------- ### Run Bot in Production Mode Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Execute this command to run the bot in its standard production mode. This is suitable for deployment after successful testing. ```bash make run ``` -------------------------------- ### Agentic Platform: Webhook API Server Settings Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/configuration.md Enable and configure the FastAPI webhook API server, including the port and authentication secrets for GitHub and generic providers. ```bash # Webhook API Server ENABLE_API_SERVER=false API_SERVER_PORT=8080 # Webhook Authentication GITHUB_WEBHOOK_SECRET=your-secret WEBHOOK_API_SECRET=your-secret ``` -------------------------------- ### Rate Limiting Settings Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/configuration.md Configure request limits, window size, and burst capacity to manage API usage and prevent abuse. ```bash # Number of requests allowed per window RATE_LIMIT_REQUESTS=10 # Rate limit window in seconds RATE_LIMIT_WINDOW=60 # Burst capacity for rate limiting RATE_LIMIT_BURST=20 ``` -------------------------------- ### Using ClaudeSDKClient for Stateful Conversations Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/SDK_DUPLICATION_REVIEW.md Demonstrates the recommended approach for multi-turn conversations using ClaudeSDKClient. This client natively handles session management, allowing for context to be maintained across multiple exchanges. ```python async with ClaudeSDKClient(options) as client: await client.query("first message") async for msg in client.receive_response(): process(msg) # Follow-up -- Claude remembers everything above await client.query("follow up question") async for msg in client.receive_response(): process(msg) ``` -------------------------------- ### Authenticate Claude with SDK and CLI Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Check the authentication status for the Claude SDK and CLI. Log in if not authenticated. ```bash claude auth status # If not authenticated: claude auth login ``` -------------------------------- ### Add whisper.cpp build directory to PATH Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/local-whisper-cpp.md Appends the whisper.cpp build/bin directory to the system's PATH environment variable for easier access to the binary. ```bash export PATH="$PWD/build/bin:$PATH" ``` -------------------------------- ### Required Bot Configuration Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md These are the essential environment variables that must be set in the .env file for the bot to function correctly. Ensure you replace placeholder values with your actual credentials and paths. ```bash TELEGRAM_BOT_TOKEN=1234567890:ABC-DEF1234ghIkl-zyx57W2v1u123ew11 TELEGRAM_BOT_USERNAME=your_bot_username APPROVED_DIRECTORY=/path/to/your/projects ALLOWED_USERS=123456789 ``` -------------------------------- ### Required Telegram Bot Configuration Source: https://github.com/richardatct/claude-code-telegram/blob/main/README.md Set these environment variables to configure your Telegram bot. Obtain your bot token from @BotFather and your username from the bot's settings. APPROVED_DIRECTORY specifies the base directory for project access, and ALLOWED_USERS should be a comma-separated list of Telegram user IDs permitted to use the bot. ```bash TELEGRAM_BOT_TOKEN=... TELEGRAM_BOT_USERNAME=... APPROVED_DIRECTORY=... ALLOWED_USERS=123456789 ``` -------------------------------- ### Configure Local whisper.cpp Voice Provider Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Set the voice provider to local and specify the path to the whisper.cpp binary and model. This option does not require an API key. ```bash VOICE_PROVIDER=local # Optional — auto-detected from PATH if unset WHISPER_CPP_BINARY_PATH=/usr/local/bin/whisper-cpp # Model name ("base", "small", "medium") or full path to .bin file WHISPER_CPP_MODEL_PATH=base ``` -------------------------------- ### Set Production Environment Variables Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Configure environment variables for production deployment, including debug mode, logging level, rate limiting, cost limits, session timeout, and telemetry. ```bash ENVIRONMENT=production DEBUG=false LOG_LEVEL=INFO RATE_LIMIT_REQUESTS=5 CLAUDE_MAX_COST_PER_USER=5.0 SESSION_TIMEOUT_HOURS=12 ENABLE_TELEMETRY=true ``` -------------------------------- ### Mode Selection Setting Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/configuration.md Choose between agentic conversational mode with limited commands or classic terminal mode with extensive commands and inline keyboards. ```bash # Agentic mode (default: true) # true = conversational mode with 3 commands (/start, /new, /status) # false = classic terminal mode with 13 commands and inline keyboards AGENTIC_MODE=true ``` -------------------------------- ### Claude Configuration Settings Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/configuration.md Configure Claude API key, conversation limits, timeouts, cost controls, and allowed tools for enhanced AI interactions. ```bash # Authentication ANTHROPIC_API_KEY=sk-ant-api03-... # Maximum conversation turns before requiring new session CLAUDE_MAX_TURNS=10 # Timeout for Claude operations in seconds CLAUDE_TIMEOUT_SECONDS=300 # Maximum cost per user in USD (lifetime budget for rate limiter) CLAUDE_MAX_COST_PER_USER=10.0 # Maximum cost per individual request in USD (SDK-level hard cap) CLAUDE_MAX_COST_PER_REQUEST=5.0 # Allowed Claude tools (comma-separated list; see docs/tools.md for descriptions) CLAUDE_ALLOWED_TOOLS=Read,Write,Edit,Bash,Glob,Grep,LS,Task,TaskOutput,MultiEdit,NotebookRead,NotebookEdit,WebFetch,TodoRead,TodoWrite,WebSearch ``` -------------------------------- ### Feature Flags for MCP, Git, File Uploads, and Quick Actions Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/configuration.md Enable or disable features like Model Context Protocol, Git integration, file uploads, and quick action buttons. ```bash # Enable Model Context Protocol ENABLE_MCP=false MCP_CONFIG_PATH=/path/to/mcp/config.json # Enable Git integration (classic mode) ENABLE_GIT_INTEGRATION=true # Enable file upload handling ENABLE_FILE_UPLOADS=true # Enable quick action buttons (classic mode) ENABLE_QUICK_ACTIONS=true ``` -------------------------------- ### Project Configuration Schema Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/configuration.md Defines the structure for the YAML registry file used to configure projects. Each project entry requires a slug, name, path, and an enabled status. ```yaml projects: - slug: my-app name: My App path: my-app enabled: true ``` -------------------------------- ### GitHub Workflow in Agentic Mode Source: https://github.com/richardatct/claude-code-telegram/blob/main/README.md Illustrates how to interact with GitHub repositories using Agentic Mode. Commands like `/repo` are used to list, clone, and manage repositories conversationally. ```text You: List my repos related to monitoring Bot: [Claude runs gh repo list, shows results] You: Clone the uptime one Bot: [Claude runs gh repo clone, clones into workspace] You: /repo Bot: 📦 uptime-monitor/ ◀ 📁 other-project/ You: Show me the open issues Bot: [Claude runs gh issue list] You: Create a fix branch and push it Bot: [Claude creates branch, commits, pushes] ``` -------------------------------- ### Configure OpenAI Whisper Voice Provider Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Set the voice provider to OpenAI and provide your OpenAI API key. ```bash VOICE_PROVIDER=openai OPENAI_API_KEY=your-openai-api-key ``` -------------------------------- ### Configure Allowed Tools with Environment Variables Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/tools.md Set the CLAUDE_ALLOWED_TOOLS environment variable to a comma-separated list of tools to permit. This configuration takes precedence over disallowed tools unless CLAUDE_DISALLOWED_TOOLS is also set. ```bash # Allow only specific tools (comma-separated) CLAUDE_ALLOWED_TOOLS=Read,Write,Edit,Bash,Glob,Grep,LS,Task,TaskOutput,MultiEdit,NotebookRead,NotebookEdit,WebFetch,TodoRead,TodoWrite,WebSearch ``` -------------------------------- ### Project Thread Mode Configuration Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/configuration.md Configure project routing and Telegram project topics. Set ENABLE_PROJECT_THREADS to true to enable topic-based routing. Define the mode (private/group), path to the projects configuration file, and optional chat ID for group mode. Adjust the sync interval to control API call pacing. ```bash # Strict project routing via Telegram project topics ENABLE_PROJECT_THREADS=false # Mode: private (default) or group PROJECT_THREADS_MODE=private # YAML registry file with project slugs/names/paths PROJECTS_CONFIG_PATH=config/projects.yaml # Required only for PROJECT_THREADS_MODE=group PROJECT_THREADS_CHAT_ID=-1001234567890 # Minimum delay (seconds) between Telegram API calls during topic sync # Set 0 to disable pacing PROJECT_THREADS_SYNC_ACTION_INTERVAL_SECONDS=1.1 ``` -------------------------------- ### Monitoring and Logging Configuration Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/configuration.md Configure logging levels and telemetry. Set LOG_LEVEL to control verbosity and ENABLE_TELEMETRY to disable anonymous data collection. Provide a SENTRY_DSN for error tracking integration. ```bash # Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL) LOG_LEVEL=INFO # Enable anonymous telemetry ENABLE_TELEMETRY=false # Sentry DSN for error tracking SENTRY_DSN=https://your-sentry-dsn@sentry.io/project ``` -------------------------------- ### Enable Webhook API Server Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Enable the webhook API server to receive external webhooks. Specify the port for the server. ```bash ENABLE_API_SERVER=true API_SERVER_PORT=8080 ``` -------------------------------- ### Pytest Async Unit Test Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/development.md Demonstrates how to write an asynchronous unit test using pytest with the pytest-asyncio marker. Ensure async functionalities are tested appropriately. ```python @pytest.mark.asyncio async def test_async_feature(): """Test async functionality.""" # Test async code result = await some_async_function() assert result is not None ``` -------------------------------- ### Test ffmpeg audio conversion Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/local-whisper-cpp.md Generates a 2-second sine wave audio file at 16kHz mono WAV format using ffmpeg for testing purposes. ```bash ffmpeg -f lavfi -i "sine=frequency=440:duration=2" -ar 16000 -ac 1 /tmp/test.wav -y ``` -------------------------------- ### Configure Rate Limiting and Cost Control Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/setup.md Adjust rate limiting parameters with `RATE_LIMIT_REQUESTS`, `RATE_LIMIT_WINDOW`, and `RATE_LIMIT_BURST`. Set `CLAUDE_MAX_COST_PER_USER` to limit costs. ```bash RATE_LIMIT_REQUESTS=10 RATE_LIMIT_WINDOW=60 RATE_LIMIT_BURST=20 CLAUDE_MAX_COST_PER_USER=10.0 ``` -------------------------------- ### Local Whisper.cpp Settings Source: https://github.com/richardatct/claude-code-telegram/blob/main/docs/configuration.md Configure local whisper.cpp settings for voice transcription, including binary path and model path. ```bash # Local whisper.cpp settings (only used when VOICE_PROVIDER=local) WHISPER_CPP_BINARY_PATH= WHISPER_CPP_MODEL_PATH=base ```