A professional Telegram bot that helps users optimize their prompts using different AI-powered methodologies (CRAFT, LYRA, GGL). Built with a clean, modular architecture and comprehensive testing.
- Multi-Method Prompt Optimization: CRAFT, LYRA (Basic & Detailed), and GGL methodologies
- Dual LLM Support: OpenAI and OpenRouter API integration with factory pattern
- Conversation Management: Full conversation context and token usage tracking
- Google Sheets Integration: Optional structured logging with batched, non-blocking writes
- Robust Error Handling: Comprehensive error handling with automatic fallbacks
- Production Ready: Docker support, comprehensive testing, and monitoring
- Clean Architecture: Modular design with dependency injection and factory patterns
The bot follows clean architecture principles with clear separation of concerns:
telegram_bot/
├── core/ # Core business logic
│ ├── bot_handler.py # Bot conversation orchestration
│ ├── conversation_manager.py # Conversation state and token tracking
│ └── state_manager.py # User state management
├── services/ # External service integrations
│ ├── llm/ # LLM client implementations
│ │ ├── base.py # Abstract base for LLM clients
│ │ ├── factory.py # Factory for creating LLM clients
│ │ ├── openai_client.py # OpenAI API client
│ │ └── openrouter_client.py # OpenRouter API client
│ ├── email_service.py # Email delivery service
│ ├── gsheets_logging.py # Google Sheets integration
│ └── redis_client.py # Redis caching service
├── auth/ # Authentication and user management
│ ├── auth_service.py # Email-based authentication
│ └── user_profile_utils.py # User profile management
├── data/ # Data layer
│ └── database.py # Database models and operations
├── utils/ # Utility modules
│ ├── config.py # Configuration management
│ ├── messages.py # Message formatting and parsing
│ ├── prompt_loader.py # Prompt file management
│ ├── email_templates.py # Email template rendering
│ ├── logging_utils.py # Structured logging with PII protection
│ ├── metrics.py # Metrics collection
│ ├── health_checks.py # Service health monitoring
│ ├── audit_service.py # Audit logging
│ └── graceful_degradation.py # Service degradation handling
├── flows/ # Complex workflows
│ ├── email_flow.py # Email authentication flow
│ └── background_tasks.py # Background task management
├── prompts/ # Optimization method prompts
│ ├── CRAFT_prompt.txt
│ ├── CRAFT_email_prompt.txt
│ ├── LYRA_prompt.txt
│ ├── LYRA_email_prompt.txt
│ ├── GGL_prompt.txt
│ ├── GGL_email_prompt.txt
│ └── Follow_up_questions_prompt.txt
├── main.py # Application entry point
└── dependencies.py # Dependency injection container
scripts/
└── tools/ # Utility scripts
├── diagnose_gsheets.py # Google Sheets diagnostic tool
├── repair_gsheets.py # Google Sheets repair tool
└── README.md # Tools documentation
docs/ # Documentation
├── INDEX.md # Documentation index
├── architecture/ # Architecture documentation
├── deployment/ # Deployment guides
├── guides/ # User guides
├── guidelines/ # Development guidelines
└── development/ # Development notes
For detailed documentation, see docs/INDEX.md.
-
Install dependencies:
pip install -r requirements.txt
-
Create a
.envfile with your credentials:# Required TELEGRAM_TOKEN=your_telegram_token LLM_BACKEND=OPENROUTER # or OPENAI # OpenAI Configuration (if using OPENAI backend) OPENAI_API_KEY=your_openai_api_key OPENAI_MAX_RETRIES=5 OPENAI_REQUEST_TIMEOUT=60.0 OPENAI_MAX_WAIT_TIME=300.0 # OpenRouter Configuration (if using OPENROUTER backend) OPENROUTER_API_KEY=your_openrouter_api_key OPENROUTER_TIMEOUT=60.0 # Model Configuration MODEL_NAME=openai/gpt-4 # For OpenRouter, or gpt-4o for OpenAI INITIAL_PROMPT=your_system_prompt # Optional BOT_ID=your_bot_id # Optional # Google Sheets Logging (Optional) GSHEETS_LOGGING_ENABLED=true GOOGLE_SERVICE_ACCOUNT_JSON={"type":"service_account",...} # OR GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json GSHEETS_SPREADSHEET_ID=your_spreadsheet_id # OR GSHEETS_SPREADSHEET_NAME=Your Spreadsheet Name GSHEETS_WORKSHEET=Logs GSHEETS_BATCH_SIZE=20 GSHEETS_FLUSH_INTERVAL_SECONDS=5.0 # Redis (recommended in production) REDIS_URL=redis://redis:6379 # Fail fast if Redis is read-only REDIS_WRITE_CHECK_STRICT=false
-
Run the bot:
# Using the entry point script (recommended) python run_bot.py # Or using module execution python -m telegram_bot.main
-
Build the Docker image:
docker build -t prompt-improver-bot . -
Run the container (using your .env file):
docker run --env-file .env prompt-improver-bot
-
Make sure your
.envfile is present in the project root. -
Start the bot with Docker Compose:
docker compose up --build
-
Run database migrations against Postgres (recommended):
# Build image to ensure alembic config is inside the container docker compose -f docker-compose.yml build --no-cache prompt-improver-bot # Run migrations using Postgres service defined in compose docker compose -f docker-compose.yml run --rm \ -e DATABASE_URL=postgresql://botuser:botpass@postgres:5432/botdb \ prompt-improver-bot alembic upgrade head
- Avoid bind-mounting the repo during migrations; it can hide
alembic/in the image. - If you use a dev override that sets SQLite, override
DATABASE_URLas shown above.
- Avoid bind-mounting the repo during migrations; it can hide
The project includes VS Code launch configurations for easy debugging:
- "Run Telegram Bot": Uses the entry point script
- "Run Telegram Bot (Module)": Runs as Python module (recommended for debugging)
- "Run Tests": Execute the test suite
- "Debug Test": Debug specific test functions
-
Build the Docker image:
docker build -t prompt-improver-bot . -
Run the container:
docker run --env-file .env prompt-improver-bot
- Ensure your
.envfile is in the project root - Start with Docker Compose:
docker compose up --build
The project includes comprehensive test coverage (84% overall):
# Run all tests
python -m pytest tests/ -v
# Run with coverage report
python -m pytest tests/ --cov=telegram_bot --cov-report=html
# Run specific test categories
python -m pytest tests/unit/ -v # Unit tests
python -m pytest tests/integration/ -v # Integration tests
python -m pytest tests/e2e/ -v # End-to-end tests
# Run specific test files
python -m pytest tests/unit/test_config.py -v
python -m pytest tests/integration/test_bot_handler.py -v
# Test imports and architecture
python scripts/test_imports.py- BotHandler: 95% - Core bot logic and conversation flows
- Config: 100% - Configuration management and validation
- ConversationManager: 100% - State and token tracking
- StateManager: 100% - User state management
- PromptLoader: 100% - Prompt file management
- LLMFactory: 100% - Client creation and backend switching
- Messages: 100% - Response parsing and formatting
| Variable | Required | Default | Description |
|---|---|---|---|
TELEGRAM_TOKEN |
✅ | - | Your Telegram bot token |
LLM_BACKEND |
✅ | OPENROUTER |
OPENAI or OPENROUTER |
MODEL_NAME |
❌ | Backend-specific | Model to use |
OPENAI_API_KEY |
✅* | - | Required if using OpenAI backend |
OPENROUTER_API_KEY |
✅* | - | Required if using OpenRouter backend |
GSHEETS_LOGGING_ENABLED |
❌ | false |
Enable Google Sheets logging |
*Required based on selected backend
To enable Google Sheets logging:
- Create a Google Cloud project and Service Account
- Enable the Google Sheets API
- Share your spreadsheet with the service account email (Editor access)
- Configure credentials using either:
GOOGLE_SERVICE_ACCOUNT_JSON: Raw JSON credentialsGOOGLE_APPLICATION_CREDENTIALS: Path to credentials file
- Set spreadsheet target using either:
GSHEETS_SPREADSHEET_ID: Spreadsheet ID (recommended)GSHEETS_SPREADSHEET_NAME: Spreadsheet name
If you see empty cells at the beginning of your Google Sheets rows:
-
Diagnose the issue:
python tools/diagnose_gsheets.py
-
Common causes:
- Extra empty columns in your Google Sheet
- Header mismatch between sheet and expected fields
- Custom
GSHEETS_FIELDSconfiguration
-
Quick fix:
python tools/repair_gsheets.py
-
Manual fix:
- Open your Google Sheet
- Ensure the first row headers exactly match:
DateTime, BotID, TelegramID, LLM, OptimizationModel, UserRequest, Answer, prompt_tokens, completion_tokens, total_tokens - Delete any extra empty columns at the beginning
The bot now automatically validates Google Sheets headers and logs warnings if mismatches are detected. Check your logs for detailed mismatch information.
If you see "Country, region, or territory not supported" errors:
- Switch to OpenRouter: Set
LLM_BACKEND=OPENROUTER - Or use a VPN/proxy if appropriate for your use case
- The bot includes automatic retry logic with exponential backoff
- For high-volume usage, consider upgrading your API plan
Add to your .env:
LOG_LEVEL=DEBUGWhen running in Docker/Compose, logs are written to stdout/stderr by default:
docker compose logs -f prompt-improver-botIf you explicitly enable file logging, set environment variables and ensure write permissions:
LOG_TO_FILE=true
LOG_FILE_PATH=/app/bot.logAnd then you can tail the file in the container:
docker exec -it prompt-improver-bot sh -lc 'tail -f /app/bot.log'This project uses automated security scanning to catch vulnerabilities before they reach production. Pre-commit hooks run on every commit to check for:
- Secrets Detection: Prevents hardcoded API keys, tokens, and passwords
- Python Security Issues: Identifies SQL injection, command injection, and other vulnerabilities
- Dependency Vulnerabilities: Scans for known CVEs in third-party packages
- Code Quality: Enforces security best practices and coding standards
Install the security tools:
pip install pre-commit
pre-commit installThe hooks will run automatically on every commit. For more information, see:
- Pre-commit Setup Guide - Installation and configuration
- Security Tools Reference - Detailed tool documentation
- Troubleshooting Guide - Common issues and solutions
- CI Integration Guide - Running security checks in CI/CD
Comprehensive documentation is available in the docs/ directory:
- Documentation Index - Complete documentation overview
- Migration Guide - Guide for migrating to the new project structure
- Architecture - System architecture and design
- Deployment - Deployment guides and best practices
- User Guides - End-to-end user documentation
- Guidelines - Development and contribution guidelines
- Security - Security configuration and best practices
- Factory Pattern:
LLMClientFactoryfor creating LLM clients - Strategy Pattern: Different prompt optimization methods
- Dependency Injection: Clean separation of concerns
- Abstract Base Classes: Consistent LLM client interface
- BotHandler: Orchestrates conversation flow and user interactions
- ConversationManager: Manages conversation state and token tracking
- StateManager: Handles user state (waiting for prompt, method selection)
- PromptLoader: Loads and manages optimization method prompts
- LLMClientBase: Abstract interface for all LLM clients
The User model stores authentication data and Telegram profile information:
Authentication Fields:
telegram_id: Unique Telegram user identifieremail: User's verified email addressis_authenticated: Email verification statusemail_verified_at: Timestamp of email verificationlast_authenticated_at: Last successful authentication
Profile Fields (Auto-captured from Telegram):
first_name: User's first name from Telegram profilelast_name: User's last name from Telegram profileis_bot: Boolean indicating if user is a bot accountis_premium: Telegram Premium subscription statuslanguage_code: User's language preference (ISO 639-1 code)
Profile Update Strategy:
- New users: All available profile data captured during first interaction
- Existing users: Selective updates only when meaningful changes detected (name changes, premium status changes)
- Performance optimization: Profile updates only occur when necessary to minimize database writes
- Error handling: Graceful handling of missing or null Telegram profile data
Database Indexes:
- Language-based queries:
ix_users_language_code - Premium user filtering:
ix_users_is_premium - User type analytics:
ix_users_bot_premium(composite)
For detailed information about the user profile system, see User Profile System Documentation.
- Automatic fallbacks for Markdown parsing errors
- Retry logic with exponential backoff for API calls
- Graceful degradation when external services fail
- Comprehensive logging for debugging and monitoring
- Use environment variables for all configuration
- Enable Google Sheets logging for monitoring
- Set appropriate timeout values for your use case
- Monitor token usage and costs
- Use Docker for consistent deployments
- The bot uses in-memory state management (suitable for single-instance deployment)
- For multi-instance deployment, consider adding Redis for shared state
- Google Sheets logging is batched and non-blocking for performance
- Follow the existing modular architecture
- Add comprehensive tests for new features
- Use type hints and proper documentation
- Follow the established error handling patterns
- Update configuration management for new settings