A modern, high-performance Telegram e-commerce bot built with FastAPI + aiogram. This bot provides a complete digital product sales platform with multi-gateway payments, automated delivery, and comprehensive admin management.
- Digital Product Catalog - Software, games, subscriptions, digital content
- Multi-Payment Support - Telegram Stars (built-in) + Cryptomus (crypto)
- Automated Delivery - Instant product delivery with customizable templates
- Inventory Management - Stock tracking with unlimited/limited quantities
- Order Processing - Complete order lifecycle with status tracking
- Trial System - Free trial access for new users
- Referral Program - Multi-level referral rewards
- User Profiles - Activity tracking and purchase history
- Admin Panel - Comprehensive user and system management
- FastAPI Backend - High-performance async API with automatic docs
- aiogram 3.x - Modern Telegram bot framework
- SQLAlchemy 2.x - Async ORM with type safety
- Pydantic - Data validation and serialization
- Background Tasks - Automated cleanup and maintenance
- Docker Ready - Production deployment with Docker Compose
- Python 3.11+
- Docker & Docker Compose (recommended)
- Telegram Bot Token from @BotFather
-
Clone and setup:
git clone <repository-url> cd digital-store cp .env.example .env
-
Configure environment: Edit
.envfile with your settings:BOT_TOKEN=your_bot_token_here BOT_DOMAIN=yourdomain.com # For webhooks ADMIN_IDS=123456789 DEVELOPER_ID=123456789 -
Start services:
docker compose up -d
-
Check status:
docker compose logs -f bot curl http://localhost:8000/api/webhooks/health
-
Setup Python environment:
pip install poetry poetry install
-
Initialize database:
alembic upgrade head
-
Run in development mode:
python -m app.main
| Variable | Required | Default | Description |
|---|---|---|---|
BOT_TOKEN |
β | - | Telegram bot token |
BOT_DOMAIN |
- | Domain for webhooks (production) | |
ADMIN_IDS |
β | - | Comma-separated admin IDs |
DEVELOPER_ID |
β | - | Developer Telegram ID |
DATABASE_URL |
β | sqlite+aiosqlite:///./data/store.db | Database connection |
REDIS_URL |
β | redis://redis:6379/0 | Redis connection |
TELEGRAM_STARS_ENABLED |
β | true | Enable Telegram Stars |
CRYPTOMUS_ENABLED |
β | false | Enable Cryptomus payments |
TRIAL_ENABLED |
β | true | Enable trial system |
REFERRAL_ENABLED |
β | true | Enable referral program |
Products are defined in data/products.json:
{
"categories": ["software", "gaming", "subscription", "digital", "education"],
"products": [
{
"name": "Premium Software License",
"description": "Professional software with full features",
"category": "software",
"price": 999.99,
"currency": "RUB",
"delivery_type": "license_key",
"duration_days": 365,
"delivery_config": {
"template": "π Your license: {license_key}",
"key_format": "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX"
},
"is_active": true,
"is_featured": true
}
]
}digital-store/
βββ app/
β βββ main.py # FastAPI application entry
β βββ config.py # Pydantic settings management
β βββ database.py # SQLAlchemy async setup
β βββ models/ # Database models
β βββ schemas/ # Pydantic request/response models
β βββ services/ # Business logic layer
β βββ bot/ # Telegram bot handlers
β β βββ handlers/ # Message and callback handlers
β β βββ keyboards.py # Inline keyboard layouts
β β βββ middleware.py # User management middleware
β βββ api/ # FastAPI routes
β β βββ webhooks.py # Payment gateway webhooks
β β βββ admin.py # Admin API endpoints
β βββ tasks/ # Background job scheduler
β βββ utils/ # Helper utilities
βββ alembic/ # Database migrations
βββ data/ # Runtime data (SQLite, JSON)
βββ docker-compose.yml # Production deployment
- Pragmatic over Perfect - Simple, maintainable solutions
- Service-Oriented - Clear separation of business logic
- Type-Safe - Comprehensive type hints with Pydantic
- Async-First - Full async/await support throughout
- Production-Ready - Docker, health checks, graceful shutdown
TELEGRAM_STARS_ENABLED=true
# No additional configuration neededCRYPTOMUS_ENABLED=true
CRYPTOMUS_API_KEY=your_api_key
CRYPTOMUS_MERCHANT_ID=your_merchant_idSet webhook URL in Cryptomus dashboard:
https://yourdomain.com/api/webhooks/cryptomus
# Database migrations
alembic revision --autogenerate -m "description"
alembic upgrade head
# Code formatting
black app/
isort app/
# Type checking
mypy app/
# Testing
pytest
pytest --cov=app
# Run specific handler tests
pytest tests/test_bot_handlers.py -v- Models (
app/models/) - SQLAlchemy database models - Schemas (
app/schemas/) - Pydantic validation models - Services (
app/services/) - Business logic with dependency injection - Handlers (
app/bot/handlers/) - Telegram bot interaction logic - API (
app/api/) - FastAPI routes for webhooks and admin - Tasks (
app/tasks/) - Background job processing
- Database Model - Create in
app/models/ - Pydantic Schema - Define in
app/schemas/ - Service Logic - Implement in
app/services/ - Bot Handler - Add to
app/bot/handlers/ - Migration - Generate with alembic
- Tests - Add comprehensive test coverage
/admin- Access admin panel/find_user [id]- Find user by Telegram ID/ban_user [id]- Ban user/unban_user [id]- Unban user
- π Statistics - Users, products, orders, revenue
- π₯ User Management - View, ban, manage users
- π¦ Product Management - Import/export, stock management
- π Order Management - View orders, process refunds
- π’ Broadcasting - Send messages to all users
- βοΈ Settings - System configuration
GET /api/admin/stats/users- User statisticsGET /api/admin/stats/products- Product statisticsGET /api/admin/stats/orders- Order statisticsPOST /api/admin/users/{id}/ban- Ban userPOST /api/admin/orders/cleanup- Cleanup expired orders
Automated maintenance tasks:
- Order Cleanup - Expire pending orders (every 15 minutes)
- System Stats - Log daily statistics (daily at midnight)
- Referral Processing - Process pending rewards (hourly)
- Database Backup - Automatic backups (daily at 2 AM)
# Production stack
docker compose up -d
# With nginx reverse proxy
docker compose --profile nginx up -d
# Database backup
docker compose --profile backup run backup# Install dependencies
poetry install --only=main
# Set environment
export ENVIRONMENT=production
export BOT_TOKEN=your_token
# Run migrations
alembic upgrade head
# Start application
python -m app.main- Health Check:
GET /api/webhooks/health - Metrics: Available via admin API
- Logs: Structured logging to files and stdout
- Graceful Shutdown: Proper cleanup of resources
- Input Validation - Pydantic schema validation
- SQL Injection Protection - SQLAlchemy ORM
- Rate Limiting - Built-in middleware support
- Webhook Verification - Cryptographic signature validation
- User Authentication - Admin permission system
- Data Sanitization - HTML escaping and input cleaning
- Async Operations - Non-blocking I/O throughout
- Connection Pooling - SQLAlchemy and Redis pooling
- Database Indexing - Optimized queries with proper indexes
- Caching - Redis-based caching for frequently accessed data
- Background Processing - Non-blocking task execution
Bot not responding:
# Check logs
docker compose logs bot --tail 50
# Verify webhook
curl -X GET "https://api.telegram.org/bot{BOT_TOKEN}/getWebhookInfo"
# Test health endpoint
curl http://localhost:8000/api/webhooks/healthDatabase issues:
# Check migration status
alembic current
# Apply migrations
alembic upgrade head
# Reset database (β οΈ DATA LOSS)
rm data/store.db && alembic upgrade headPayment webhook failures:
- Verify webhook URLs in payment provider dashboard
- Check SSL certificate validity
- Review webhook signature verification logs
This project is licensed under the MIT License - see the LICENSE file for details.
- Fork the repository
- Create feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open Pull Request
- Issues: Create GitHub issue for bugs/features
- Documentation: Check inline code documentation
- Community: Join our discussion forums
Built with β€οΈ using FastAPI + aiogram for modern, scalable Telegram bot development.