A clean, maintainable Telegram bot template with essential features and modern architecture.
- π Locale Management - Multi-language support with easy translation management
- β¨οΈ Keyboard Management - Dynamic inline keyboards with language-aware buttons
- π€ OpenRouter AI Integration - Modern AI provider with multiple model support
- π Optional Support Bot - Built-in support system for user assistance
- πΎ Database with Migrations - PostgreSQL with Alembic migration management
- π Auto-Migration - Automatic schema updates on bot startup
- ποΈ Click CLI - Command-line interface with migration commands
- π Clean Architecture - Well-organized, extensible codebase
telegram_bot_template/
βββ __init__.py # Package initialization
βββ main.py # Entry point with click options
βββ cli.py # CLI commands for migrations
βββ config/
β βββ __init__.py
β βββ settings.py # Configuration management
βββ core/
β βββ __init__.py
β βββ bot.py # Main bot class
β βββ database.py # Database operations with migrations
β βββ migration_manager.py # Alembic migration management
β βββ locale_manager.py # Localization support
β βββ keyboard_manager.py # Keyboard management
β βββ ai_provider.py # OpenRouter integration
βββ models/
β βββ __init__.py # SQLAlchemy metadata
β βββ base.py # Base table definitions
β βββ users.py # Users table schema
βββ handlers/
β βββ __init__.py
β βββ basic.py # Basic commands (/start, /help, /about)
β βββ message.py # Message handling with AI
βββ support/
β βββ __init__.py
β βββ bot.py # Optional support bot
βββ utils/
βββ __init__.py
βββ helpers.py # Utility functions
alembic/ # Database migration files
βββ env.py # Alembic environment configuration
βββ script.py.mako # Migration template
βββ versions/ # Migration version files
βββ 001_initial_users_table.py
alembic.ini # Alembic configuration
-
Clone the repository
git clone <repository-url> cd telegram-bot-template
-
Install dependencies
pip install -r requirements.txt # or with uv uv pip install -r requirements.txt -
Setup environment
cp .env.example .env # Edit .env with your configuration -
Setup database
# Create PostgreSQL database createdb botdb
# Required
TELEGRAM_BOT_TOKEN=your_bot_token_here
DATABASE_URL=postgresql://user:password@localhost:5432/botdb# OpenRouter AI (optional)
OPENROUTER_API_KEY=your_openrouter_api_key_here
OPENROUTER_MODEL=openai/gpt-3.5-turbo
# Support Bot (optional)
SUPPORT_BOT_TOKEN=your_support_bot_token_here
SUPPORT_CHAT_ID=your_support_chat_id_here
# Bot Metadata (optional)
BOT_NAME=My Telegram Bot
BOT_DESCRIPTION=A simple Telegram bot
BOT_VERSION=1.0.0
# Localization (optional)
DEFAULT_LANGUAGE=en
SUPPORTED_LANGUAGES=en,ru,es
# Logging (optional)
LOG_LEVEL=INFO# Start the bot
python -m telegram_bot_template.main
# Start with specific language
python -m telegram_bot_template.main --locale ru
# Start in debug mode
python -m telegram_bot_template.main --debug
# Validate configuration without starting
python -m telegram_bot_template.main --dry-run# Initialize configuration file
python -m telegram_bot_template.main init-config
# Validate configuration
python -m telegram_bot_template.main validate
# Test AI connection
python -m telegram_bot_template.main test-ai
# Test database connection
python -m telegram_bot_template.main test-db
# Show bot statistics
python -m telegram_bot_template.main --statsThe template uses Alembic for professional database schema management with automatic migration support.
By default, the bot automatically applies pending migrations on startup:
# Bot will check and apply migrations automatically
python -m telegram_bot_template.main# Check migration status
telegram-bot-template db status
# Apply all pending migrations
telegram-bot-template migrate
# Create a new migration
telegram-bot-template db revision -m "Add new table"
# Apply migrations manually
telegram-bot-template db upgrade
# Rollback to previous migration
telegram-bot-template db downgrade
# Show migration history
telegram-bot-template db history
# Show current revision
telegram-bot-template db currentControl migration behavior with environment variables:
# Enable/disable automatic migrations (default: true)
AUTO_MIGRATE=true
# Migration timeout in seconds (default: 300)
MIGRATION_TIMEOUT=300- Modify your models in
telegram_bot_template/models/ - Generate migration:
telegram-bot-template db revision --autogenerate -m "Description of changes" - Review the generated migration in
alembic/versions/ - Apply the migration:
telegram-bot-template db upgrade
- Always review auto-generated migrations before applying
- Test migrations in a staging environment first
- Backup your database before applying migrations in production
- Use descriptive messages when creating migrations
- Keep migrations small and focused on single changes
from telegram_bot_template import TelegramBot, BotConfig
# Load configuration from environment
config = BotConfig.from_env()
# Create and run bot
bot = TelegramBot(config)
await bot.run()The template uses OpenRouter for AI functionality, which provides access to multiple AI models through a unified API.
- OpenAI GPT models (gpt-3.5-turbo, gpt-4, etc.)
- Anthropic Claude models
- Google PaLM models
- And many more through OpenRouter
- Visit OpenRouter.ai
- Sign up for an account
- Generate an API key
- Add it to your
.envfile
The optional support bot allows users to send messages directly to administrators.
- Create a second bot with @BotFather
- Get the bot token
- Get your Telegram user ID (chat with @userinfobot)
- Add both to your
.envfile:SUPPORT_BOT_TOKEN=your_support_bot_token SUPPORT_CHAT_ID=your_telegram_user_id
- Users send messages to the support bot
- Messages are forwarded to the admin
- Admin replies to forwarded messages
- Replies are sent back to users
-
Create a new JSON file in
locales/directory:cp locales/en.json locales/de.json
-
Translate the strings in the new file
-
Add the language to supported languages:
SUPPORTED_LANGUAGES=en,ru,es,de
The template includes these translation keys:
welcome_message- Bot welcome messagehelp_message- Help textabout_message- About textlanguage_changed- Language change confirmationprocessing- Processing messageerror_occurred- Generic error message- And more...
The template uses a simple database schema with just a users table:
CREATE TABLE users (
user_id BIGINT PRIMARY KEY,
username VARCHAR(255),
language VARCHAR(10) DEFAULT 'en',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);# Run all tests
pytest
# Run with coverage
pytest --cov=telegram_bot_template# Format code
black telegram_bot_template/
isort telegram_bot_template/
# Type checking
mypy telegram_bot_template/- New Handlers: Add to
handlers/directory - New Commands: Register in
core/bot.py - New Keyboards: Add to
keyboard_manager.py - New Translations: Add to locale files
# Build image
docker build -t telegram-bot .
# Run with docker-compose
docker-compose up -dfrom telegram_bot_template import TelegramBot, BotConfig
config = BotConfig.from_env()
config.openrouter_api_key = None # Disable AI
bot = TelegramBot(config)
await bot.run()from telegram_bot_template import TelegramBot, BotConfig
config = BotConfig.from_env()
# AI will be enabled if OPENROUTER_API_KEY is set
bot = TelegramBot(config)
await bot.run()from telegram_bot_template import TelegramBot, BotConfig
config = BotConfig(
bot_token="your_token",
database_url="postgresql://...",
bot_name="Custom Bot",
default_language="ru"
)
bot = TelegramBot(config)
await bot.run()- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
- Create an issue for bug reports
- Join our Telegram group for discussions
- Check the documentation for detailed guides
If you're migrating from the complex template:
- Database: Only the users table is needed
- Configuration: Update environment variables
- AI Provider: Replace OpenAI with OpenRouter
- Features: Remove payment/subscription code
- Handlers: Simplify message handling
- Plugin system for extensions
- Webhook support
- Admin dashboard
- Message scheduling
- User analytics
- Rate limiting
- Message templates
Made with β€οΈ for the Telegram bot community