{"id":18243798,"url":"https://github.com/say8hi/tgbottemplate","last_synced_at":"2026-01-28T13:02:09.835Z","repository":{"id":261092778,"uuid":"883233528","full_name":"say8hi/TgBotTemplate","owner":"say8hi","description":"A production-ready Telegram bot template built with aiogram 3.x, featuring PostgreSQL for data storage, Redis for state management, and webhook support with a local Telegram API server.","archived":false,"fork":false,"pushed_at":"2024-11-04T16:21:47.000Z","size":123,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-25T11:52:26.854Z","etag":null,"topics":["aiogram","aiogram3","docker","nginx","python","redis"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/say8hi.png","metadata":{"files":{"readme":".github/README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-11-04T15:53:11.000Z","updated_at":"2025-03-07T15:14:17.000Z","dependencies_parsed_at":"2024-11-04T17:38:50.406Z","dependency_job_id":null,"html_url":"https://github.com/say8hi/TgBotTemplate","commit_stats":null,"previous_names":["say8hi/tgbottemplate"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/say8hi%2FTgBotTemplate","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/say8hi%2FTgBotTemplate/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/say8hi%2FTgBotTemplate/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/say8hi%2FTgBotTemplate/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/say8hi","download_url":"https://codeload.github.com/say8hi/TgBotTemplate/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248434481,"owners_count":21102845,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aiogram","aiogram3","docker","nginx","python","redis"],"created_at":"2024-11-05T09:03:17.060Z","updated_at":"2026-01-28T13:02:09.798Z","avatar_url":"https://github.com/say8hi.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Advanced Telegram Bot Template\n\n![Logo](./logo.webp)\n\nA production-ready Telegram bot template built with aiogram 3.x, featuring PostgreSQL for data storage, Redis for state management, and webhook support with a local Telegram API server.\n\n## Features\n\n- 🚀 Built with aiogram 3.x\n- 🔄 Webhook mode with local Telegram API server\n- 📦 Docker containerization\n- 💾 PostgreSQL with SQLAlchemy ORM\n- 🔄 Redis for FSM and caching\n- 🔐 Middleware system\n- 📝 Alembic migrations with auto-apply\n- 🎨 Modular architecture\n- ⚙️ Environment-based configuration\n- 🔒 Nginx reverse proxy\n- 👥 Admin panel with broadcast feature\n- 🔍 Comprehensive logging\n\n## Tech Stack\n\n- Python 3.11+\n- aiogram 3.x\n- PostgreSQL + asyncpg\n- Redis\n- SQLAlchemy + Alembic\n- Docker \u0026 Docker Compose\n- Nginx\n- Local Telegram API server\n\n## Project Structure\n\n```\n├── alembic.ini          # Alembic configuration\n├── bot.py               # Main bot file\n├── docker-compose.yml   # Docker services configuration\n├── Dockerfile           # Bot image configuration\n├── migrations/          # Database migrations\n├── nginx/               # Nginx configuration\n└── tgbot/               # Main bot package\n    ├── config.py        # Configuration management\n    ├── database/        # Database models and ORM\n    ├── filters/         # Custom aiogram filters\n    ├── handlers/        # Message handlers\n    ├── keyboards/       # Keyboard layouts\n    ├── middlewares/     # Middleware components\n    ├── misc/            # Additional utilities\n    └── services/        # Business logic services\n```\n\n## Installation\n\n### Prerequisites\n\n- Docker and Docker Compose\n\n### Setup\n\n1. Clone the repository:\n```bash\ngit clone https://github.com/say8hi/TgBotTemplate.git\ncd TgBotTemplate\n```\n\n2. Create .env file:\n```bash\ncp .env.example .env\n```\n\n3. Configure environment variables in .env:\n```env\n# Telegram Bot\nBOT_TOKEN=           # Your bot token from @BotFather\nADMINS=              # Comma-separated admin user IDs\n\n# PostgreSQL\nPOSTGRES_DB=         # Database name\nPOSTGRES_USER=       # Database user\nPOSTGRES_PASSWORD=   # Database password\nPOSTGRES_HOST=       # Host (postgres_db)\n\n# Redis\nREDIS_HOST=          # Redis host (redis)\nREDIS_PORT=          # Redis port (6379)\nREDIS_PASSWORD=      # Redis password\n\n# Telegram API Server\nTELEGRAM_API_ID=     # API ID for local server\nTELEGRAM_API_HASH=   # API Hash for local server\nTELEGRAM_LOCAL=1     # Use local API server\n\n# Development\nIN_DEVELOPMENT=     # Development mode (true/false)\n```\n\n### Running\n\n1. Build and start containers:\n```bash\ndocker-compose up -d --build\n```\n\nThe bot will automatically:\n- Check database connection\n- Create initial migrations if not exist\n- Apply pending migrations\n- Detect and create migrations for model changes\n\n## Configuration System\n\nThe bot uses a typed configuration system with dataclasses:\n\n```python\n@dataclass\nclass Config:\n    tg_bot: TgBot         # Bot token and admin IDs\n    postgres: Postgres    # Database configuration\n    redis: Redis          # Redis configuration\n    misc: Misc            # Additional settings\n```\n\nConfiguration is loaded from environment variables with strong typing and validation.\n\n## Features\n\n### User Commands\n- `/start` - Start the bot\n- `👤Profile` - View user profile\n- `❗️Info` - Get support information\n\n### Admin Panel\n- `/admin` - Access admin panel\n- Broadcast feature with text and photo support\n- User management\n- Statistics\n\n### Keyboard System\n\n#### Inline Keyboards\n```python\nadmin_menu = InlineKeyboardMarkup(\n    inline_keyboard=[\n        [\n            InlineKeyboardButton(text=\"📬Broadcast\", callback_data=\"broadcast\"),\n        ],\n        [InlineKeyboardButton(text=\"✖️Close\", callback_data=\"close\")],\n    ]\n)\n```\n\n#### Reply Keyboards\n```python\nmain_menu = ReplyKeyboardMarkup(\n    resize_keyboard=True,\n    keyboard=[\n        [KeyboardButton(text=\"👤Profile\"), KeyboardButton(text=\"❗️Info\")],\n    ],\n)\n```\n\n## Database System\n\n### Automatic Migrations\n\nThe bot includes an advanced migration system that automatically:\n\n1. Checks database connectivity on startup\n2. Creates initial migrations if database is empty\n3. Detects model changes and creates new migrations\n4. Applies pending migrations\n5. Handles migration dependencies\n\nAll this happens automatically when you start the bot - no manual migration commands needed!\n\n### Models\n```python\nclass User(Base):\n    __tablename__ = \"users\"\n    \n    id: Mapped[int]                      # Telegram user ID\n    username: Mapped[str]                # Username\n    registered_at: Mapped[datetime]      # Registration date\n```\n\n### ORM Usage\n```python\n# Create user\nuser = await AsyncORM.users.create(id=user_id, username=\"example\")\n\n# Get user\nuser = await AsyncORM.users.get(user_id)\n\n# Update user\nawait AsyncORM.users.update(user_id, username=\"new_username\")\n\n# Get all users\nusers = await AsyncORM.users.get_all()\n```\n\n## Middleware System\n\n### ConfigMiddleware\nInjects configuration and Redis client into handler context.\n\n### DatabaseMiddleware\nAutomatically:\n- Creates new user records\n- Updates usernames\n- Adds user object to context\n\n## Nginx Configuration\n\nThe project includes a pre-configured Nginx setup for the local Telegram API server:\n\n- Token hiding in logs\n- File serving optimization\n- Gzip compression\n- Extended timeouts\n- Large file support\n- Health checks\n\n```nginx\nupstream telegram-bot-api {\n    server telegram-api-server:8081;\n}\n\nserver {\n    listen 80;\n    server_name _;\n    \n    # Security and optimization settings\n    chunked_transfer_encoding on;\n    client_max_body_size 2G;\n    client_body_buffer_size 30M;\n    \n    # Token hiding in logs\n    set $sanitized_request $request;\n    if ( $sanitized_request ~ (\\w+)\\s(\\/bot\\d+):[-\\w]+\\/(\\S+)\\s(.*) ) {\n        set $sanitized_request \"$1 $2:/$3 $4\";\n    }\n}\n```\n\n## Development\n\n### Adding New Handlers\n\n1. Create a new file in `tgbot/handlers/`\n2. Create and configure a router:\n```python\nfrom aiogram import Router\n\nmy_router = Router()\n\n@my_router.message()\nasync def my_handler(message: Message):\n    await message.answer(\"Hello!\")\n```\n\n3. Add the router to `routers_list` in `tgbot/handlers/__init__.py`\n\n### Creating New Models\n\n1. Add model to `tgbot/database/models.py`\n2. Create repository in `tgbot/database/orm.py`\n3. The bot will automatically detect and apply changes on next restart\n\n## Testing\n\nFor local testing:\n\n1. Start:\n```bash\ndocker-compose up -d --build\n```\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch\n3. Make your changes\n4. Create a Pull Request\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsay8hi%2Ftgbottemplate","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsay8hi%2Ftgbottemplate","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsay8hi%2Ftgbottemplate/lists"}