A professional Telegram bot for AI-powered image generation with integrated payment system, referral program, and admin panel.
Bananapics Bot is a production-ready Telegram bot that provides AI image generation services powered by Wavespeed API. Built with a clean architecture approach, it features a scalable multi-instance deployment, comprehensive payment system with Telegram Stars, and full internationalization support.
- 🎨 AI Image Generation - Text-to-image and image-to-image generation with multiple models
- 📱 Telegram Mini App - Modern React-based webapp with native mobile experience
- 💰 Payment System - Integrated Telegram Stars payments with dynamic exchange rates
- 👥 Referral Program - Automatic bonus system for referred users
- 🌍 Multi-language Support - Uzbek, Russian, and English localization
- 📊 Admin Panel - Comprehensive admin dashboard with statistics and user management
- 📢 Broadcast System - Targeted message broadcasting with progress tracking
- 🔒 Security - Rate limiting, input validation, and secure payment handling
- 📈 Scalability - Multi-instance bot support with Redis FSM storage
- 🛠️ Professional Architecture - Clean architecture with DDD principles
- Code of Conduct: CODE_OF_CONDUCT.md
- Security Policy: SECURITY.md
- Legal: legal/README.md
The project is built with a microservices architecture:
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Telegram Bot │────▶│ FastAPI API │◀────│ Mini App │
│ (aiogram) │◀────│ (Clean Arch.) │ │ (React + Vite) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
┌─────────────────────┼─────────────────────┐
│ │ │
┌────▼────┐ ┌──────▼──────┐ ┌──────▼──────┐
│ Redis │ │ PostgreSQL │ │ Celery │
│ (Cache) │ │ (Data) │ │ (Workers) │
└─────────┘ └─────────────┘ └─────────────┘
- bot - Telegram bot interface (aiogram 3.x)
- api - FastAPI backend with Clean Architecture
- webapp - Telegram Mini App (React 18 + TypeScript + Vite)
- celery-worker - Background task processor for generations and broadcasts
- celery-beat - Scheduled tasks (cleanup, monitoring)
- redis - Caching, FSM storage, rate limiting, Celery broker
- db - PostgreSQL database with Alembic migrations
bananapicsbot/
├── bot/ # Telegram bot application
│ ├── core/ # DI container, config, logging
│ ├── handlers/ # Request handlers (commands, callbacks, messages)
│ ├── keyboards/ # Inline keyboard builders
│ ├── middlewares/ # Error handling, i18n, throttling
│ ├── services/ # Business logic layer
│ ├── states/ # FSM states
│ ├── locales/ # i18n translations (uz, ru, en)
│ └── infrastructure/ # API client, Redis, storage
│
├── api/ # FastAPI application
│ ├── app/
│ │ ├── domain/ # Entities and interfaces
│ │ ├── application/ # Use cases
│ │ ├── infrastructure/# Repositories, cache, logging
│ │ ├── api/v1/ # FastAPI endpoints
│ │ ├── worker/ # Celery tasks
│ │ ├── core/ # Configuration
│ │ ├── deps/ # FastAPI dependencies
│ │ ├── db/ # SQLAlchemy models
│ │ └── schemas/ # Pydantic models
│ └── alembic/ # Database migrations
│
├── webapp/ # Telegram Mini App
│ ├── src/
│ │ ├── components/ # React UI components
│ │ ├── hooks/ # Custom React hooks (useTelegram)
│ │ ├── services/ # API client
│ │ ├── store/ # Zustand state management
│ │ └── types/ # TypeScript definitions
│ ├── Dockerfile # Production build
│ └── vite.config.ts # Vite configuration
│
├── docs/ # Project documentation
│ ├── api.md # API architecture details
│ ├── bot.md # Bot architecture details
│ ├── webapp.md # Mini App documentation
│ ├── functionality.md # Feature documentation
│ └── env.md # Environment variables guide
│
├── docker-compose.yml # Service orchestration
├── .env.example # Environment template
└── README.md # This file
- Docker & Docker Compose
- Telegram Bot Token (from @BotFather)
- Wavespeed API Key (from Wavespeed)
- Clone the repository
git clone https://github.com/blogchik/bananapicsbot.git
cd bananapicsbot- Configure environment
cp .env.example .envEdit .env and set required variables:
# Required
BOT_TOKEN=your_telegram_bot_token_here
WAVESPEED_API_KEY=your_wavespeed_api_key_here
# Admin (comma-separated Telegram user IDs)
ADMIN_IDS=123456789
# Optional but recommended
SENTRY_DSN=your_sentry_dsn- Start services
docker compose up -d --buildThis repository also includes a local compose file (docker-compose.local.yml) that uses a separate env file.
cp .env.example .env.local
docker compose -f docker-compose.local.yml up -d --buildMake sure .env.local matches what the compose file expects (at minimum set POSTGRES_* and REDIS_PASSWORD, and update REDIS_URL if you use a Redis password).
- Check status
docker compose ps
docker compose logs -f bot- Access the bot
Open Telegram and send /start to your bot.
- Bot: Your Telegram bot
- API: http://localhost:9000/api/v1/health
- API docs: http://localhost:9000/docs
- Redis: localhost:6479
- PostgreSQL: localhost:5433
| Variable | Description | Default | Required |
|---|---|---|---|
BOT_TOKEN |
Telegram bot token | - | ✅ |
WAVESPEED_API_KEY |
Wavespeed API key | - | ✅ |
ADMIN_IDS |
Admin user IDs (comma-separated) | - | ✅ |
DEFAULT_LANGUAGE |
Default language (uz/ru/en) | uz |
❌ |
| Variable | Description | Default |
|---|---|---|
BOT_MODE |
Bot mode (polling/webhook) | polling |
REDIS_URL |
Redis connection URL | redis://redis:6379/0 |
API_BASE_URL |
API base URL | http://api:9000 |
RATE_LIMIT_MESSAGES |
Messages per minute limit | 30 |
RATE_LIMIT_CALLBACKS |
Callbacks per minute limit | 60 |
If you set a Redis password (REDIS_PASSWORD), make sure REDIS_URL includes it (example: redis://:yourpass@redis:6379/0).
| Variable | Description | Default |
|---|---|---|
API_PREFIX |
API prefix path | /api/v1 |
ENVIRONMENT |
Environment (local/staging/prod) | local |
RATE_LIMIT_RPS |
Requests per second | 5 |
MAX_PARALLEL_GENERATIONS_PER_USER |
Max parallel generations | 2 |
| Variable | Description | Default |
|---|---|---|
STARS_ENABLED |
Enable Stars payments | true |
STARS_MIN_AMOUNT |
Minimum Stars amount | 70 |
STARS_PRESETS |
Payment presets (comma-separated) | 70,140,210,350,700,1400 |
STARS_EXCHANGE_NUMERATOR |
Exchange rate numerator | 1000 |
STARS_EXCHANGE_DENOMINATOR |
Exchange rate denominator | 70 |
REFERRAL_BONUS_PERCENT |
Referral bonus percentage | 10 |
REFERRAL_JOIN_BONUS |
Bonus credits when referral joins | 20 |
GENERATION_PRICE_MARKUP |
Admin markup added to base prices | 40 |
See docs/env.md for complete configuration reference.
Supported Models:
- seedream-v4 - 27 credits (size parameter)
- nano-banana - 38 credits (aspect ratio)
- nano-banana-pro - 140-240 credits (aspect ratio, resolution)
- gpt-image-1.5 - Dynamic pricing (quality, input fidelity)
- qwen - 20 credits (size parameter, bilingual text rendering)
Generation Types:
- 📝 Text-to-Image - Generate images from text prompts
- 🖼️ Image-to-Image - Generate variations of existing images
- 🎨 Watermark Removal - Remove watermarks (12 credits)
Features:
- Multiple image inputs (1-10 images)
- Model-specific parameters (size, aspect ratio, resolution, quality)
- Real-time generation status tracking
- Automatic retry on failure with credit refund
- 5-minute timeout protection
- Results delivered as files (preserves original format)
- 💳 Telegram Stars Integration - Native in-app payments
- 📊 Dynamic Exchange Rates - Configurable Stars to credits conversion
- 🎁 Preset Amounts - Quick payment options
- 💰 Custom Amounts - Flexible payment amounts
- 📜 Payment History - Complete ledger tracking
- 💸 Refund System - Admin-controlled refunds for both Stars and credits
- 🔗 Unique Referral Links - Each user gets a personal link
- 🎁 Join Bonus - 20 credits awarded immediately when someone joins via referral
- 💰 Payment Commission - 10% bonus on all referral payments (rounded up)
- 📊 Statistics - Track referral count and total bonuses
- 🔔 Notifications - Real-time alerts for new referrals
- 🛡️ Fraud Prevention - One-time referral binding, self-referral protection
Access via /admin command (admin users only):
📊 Statistics
- Overview: Users, generations, revenue
- User analytics: Active users (7d/30d), growth trends
- Generation analytics: Success rate, model usage
- Revenue tracking: Total revenue, average per user
👥 User Management
- Search users by ID or username
- View detailed user profiles
- Ban/unban users
- Adjust user credits
- View user history
💰 Credit Management
- Add/remove credits from user balance
- View credit transaction history
- Bulk credit operations
📢 Broadcast System
- Create targeted broadcasts
- Filter recipients: All users, Active (7d/30d), With balance, Paid users, New users
- Support for text, photo, video, audio, stickers
- Add custom inline buttons
- Real-time progress tracking
- Cancel running broadcasts
- View broadcast history and statistics
💸 Refund System
- Credit Refunds - Refund credits for failed generations
- Stars Refunds - Refund Telegram Stars payments via API
- View user's unrefunded payments
- Select payment to refund
- Automatic credit deduction
- Handles Telegram API errors gracefully
Supported Languages:
- 🇺🇿 Uzbek (uz)
- 🇷🇺 Russian (ru)
- 🇬🇧 English (en)
Features:
- Auto-detection from Telegram language settings
- User-configurable language in settings
- Consistent UI across all languages
- Translation system for all user-facing text
The API is available at http://localhost:9000/api/v1
Health & Info:
GET /health- Health checkGET /info- API information
Users:
POST /users/sync- Sync user from TelegramGET /users/{telegram_id}/balance- Get user balanceGET /users/{telegram_id}/trial- Get trial status
Generations:
POST /generations/submit- Start generationGET /generations/active- Get active generationGET /generations/{id}- Get generation statusGET /generations/{id}/results- Get generation results
Payments:
GET /payments/stars/options- Get payment optionsPOST /payments/stars/confirm- Confirm payment
Admin:
GET /admin/stats- Get statisticsGET /admin/users- List usersPOST /admin/credits- Adjust creditsPOST /admin/broadcasts- Create broadcastPOST /admin/broadcasts/{id}/start- Start broadcastPOST /admin/broadcasts/{id}/cancel- Cancel broadcast
See docs/api.md for detailed API documentation.
# Start all services
docker compose up -d --build
# View logs
docker compose logs -f bot
docker compose logs -f api
docker compose logs -f celery-worker
# Stop services
docker compose down
# Restart a service
docker compose restart bot# Create a new migration
docker compose exec api alembic -c /app/alembic.ini revision --autogenerate -m "description"
# Apply migrations
docker compose exec api alembic -c /app/alembic.ini upgrade head
# Rollback
docker compose exec api alembic -c /app/alembic.ini downgrade -1Bot Logs:
docker compose logs -f botAPI Logs:
docker compose logs -f apiCelery Logs:
docker compose logs -f celery-worker
docker compose logs -f celery-beatDatabase Access:
docker compose exec db psql -U bananapics -d bananapicsRedis CLI:
docker compose exec redis redis-cli- ✅ Rate limiting on bot and API levels
- ✅ Input validation and sanitization
- ✅ Secure payment handling
- ✅ Environment-based secrets management
- ✅ No hardcoded credentials
- ✅ Docker network isolation
- ✅ Request ID tracking for audit
- ✅ Structured logging with Sentry integration
Best Practices:
- Never commit
.envfile - Rotate tokens regularly
- Use strong database passwords
- Enable Sentry for production
- Monitor rate limit violations
- Review admin actions regularly
# Bot health (check logs)
docker compose logs --tail=50 bot
# API health
curl http://localhost:9000/api/v1/health
# Database health
docker compose exec db pg_isready -U bananapics
# Redis health
docker compose exec redis redis-cli pingThe system tracks:
- User activity (registrations, active users)
- Generation statistics (success rate, model usage)
- Payment metrics (revenue, average transaction)
- Error rates and types
- API response times
Configure Sentry for:
- Uncaught exceptions
- Payment failures
- API errors
- Generation failures
- Timeout errors
This repo uses a GitHub Actions workflow (.github/workflows/ci.yml) that:
- Runs
rufflint + format checks - Runs API tests with Postgres + Redis services
- Runs a Trivy security scan
- Builds and pushes
apiandbotimages to GHCR - Deploys to production from
mainvia SSH +docker compose
Notes:
- The Trivy SARIF upload requires GitHub Code Scanning to be enabled in the repo settings.
- Images are tagged using
docker/metadata-action(includingsha-<shortsha>tags). The production deploy usesIMAGE_TAG=sha-<shortsha>.
The workflow deploy step connects to your server via SSH, writes the production .env from a secret, pulls the tagged images from GHCR, and runs docker compose up -d.
Required repository secrets (names used by the workflow):
SSH_KEY(private key)SSH_HOST(server host/IP)SSH_USERNAME(SSH user)PROD_ENV_FILE(full.envfile contents for production)
Server prerequisites:
- Docker + Docker Compose plugin installed
- Repo directory exists on server:
~/bananapicsbot/ - GHCR pull access (the workflow logs in on the server before pulling)
- Set strong database password in
.env - Configure Sentry DSN
- Set appropriate rate limits
- Configure webhook mode (recommended for production)
- Set up domain and SSL certificate
- Configure CORS origins
- Set up backup strategy for PostgreSQL
- Enable Redis persistence
- Set up log aggregation
- Configure monitoring and alerting
- Test payment flow thoroughly
- Test admin panel functionality
- Test broadcast system with small audience first
For production, webhook mode is recommended:
BOT_MODE=webhook
WEBHOOK_URL=https://yourdomain.com/webhook
WEBHOOK_SECRET=your_random_secretHorizontal Scaling:
- Run multiple bot instances (Redis FSM allows this)
- Scale Celery workers based on load
- Use Redis Cluster for high availability
- Use PostgreSQL replication
Vertical Scaling:
- Increase Celery worker concurrency
- Adjust rate limits
- Optimize database queries
- Add caching layers
Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Make your changes following the code style
- Ensure all tests pass (when available)
- Update documentation if needed
- Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- Follow PEP 8 for Python code
- Use type hints
- Write clear commit messages
- Add docstrings to functions/classes
- Keep functions small and focused
- Use dependency injection
- Follow Clean Architecture principles
- Update relevant documentation in
docs/ - Keep README.md in sync with changes
- Document all environment variables
- Provide examples for new features
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
Copyright 2026 Jabborov Abduroziq
- aiogram - Modern Telegram Bot framework
- FastAPI - Modern web framework
- Wavespeed - Image generation API
- Celery - Distributed task queue
- SQLAlchemy - SQL toolkit and ORM
For questions or issues:
- Create an issue in this repository
- Check documentation in
docs/folder - Review existing issues and discussions
Current Version: 0.1.4
Status: Production Ready ✅
Roadmap:
- Additional payment methods
- More image generation models
- Generation history and favorites
- Batch generation support
- Advanced admin analytics
- API rate limiting by user
- Automated testing suite
- Performance optimization
- Telegram Mini App (webapp)
Made with ❤️ for the AI art community