Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Aiogram Template

A clean and structured template project for building Telegram bots using aiogram framework (version 3.21+).

Features

  • πŸ—οΈ Clean Architecture - Well-organized project structure with separation of concerns
  • πŸ”§ Configuration Management - Easy configuration through INI files
  • 🎯 Filter System - Built-in user filtering (admin/non-admin)
  • 🎨 Keyboard Support - Ready-to-use keyboard utilities (inline and reply)
  • πŸ“Š Middleware Support - Environment middleware for dependency injection
  • πŸ“ Logging - Structured logging with admin notification utilities
  • πŸ”„ State Management - FSM (Finite State Machine) support for conversation flows

Project Structure

aiogram-template/
β”œβ”€β”€ config.ini.example          # Example configuration file
β”œβ”€β”€ requirements.txt            # Python dependencies
β”œβ”€β”€ LICENSE                     # License file
β”œβ”€β”€ README.md                   # This file
└── src/
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ main.py                 # Application entry point
    β”œβ”€β”€ config.py               # Configuration loader
    β”œβ”€β”€ filters/                # Custom filters
    β”‚   β”œβ”€β”€ __init__.py
    β”‚   └── user.py             # User filter (admin/non-admin)
    β”œβ”€β”€ handlers/               # Message and callback handlers
    β”‚   β”œβ”€β”€ __init__.py
    β”‚   └── user.py             # User-related handlers
    β”œβ”€β”€ keyboards/              # Keyboard builders
    β”‚   β”œβ”€β”€ __init__.py
    β”‚   β”œβ”€β”€ reply.py            # Reply keyboard utilities
    β”‚   └── user/               # User-specific keyboards
    β”‚       β”œβ”€β”€ __init__.py
    β”‚       β”œβ”€β”€ inline.py       # Inline keyboard builders
    β”‚       β”œβ”€β”€ reply.py        # Reply keyboard builders
    β”‚       └── util.py         # Keyboard utilities
    β”œβ”€β”€ middlewares/            # Custom middlewares
    β”‚   β”œβ”€β”€ __init__.py
    β”‚   └── environment.py      # Environment middleware for DI
    β”œβ”€β”€ misc/                   # Miscellaneous utilities
    β”‚   β”œβ”€β”€ __init__.py
    β”‚   β”œβ”€β”€ logs.py             # Logging utilities
    β”‚   β”œβ”€β”€ singleton.py        # Singleton pattern implementation
    β”‚   └── states.py           # FSM state definitions
    β”œβ”€β”€ models/                 # Data models
    β”‚   └── __init__.py
    └── services/               # External service integrations
        └── __init__.py

Installation

Prerequisites

  • Python 3.10 or higher
  • pip package manager

Setup

  1. Clone the repository:
git clone <repository-url>
cd aiogram-template
  1. Create a virtual environment (recommended):
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. Install dependencies:
pip install -r requirements.txt
  1. Configure the bot:
cp config.ini.example config.ini

Edit config.ini and add your bot token and admin IDs:

[bot]
token = your_bot_token_here
admin_ids = 123456789, 987654321

To get a bot token:

  1. Open Telegram and search for @BotFather
  2. Send /newbot and follow the instructions
  3. Copy the token provided by BotFather

To find your admin user ID:

  1. Search for @userinfobot on Telegram
  2. Start a conversation and it will show your user ID
  3. Add multiple admin IDs separated by commas

Configuration

The project uses an INI file for configuration. Create a config.ini file in the project root:

[bot]
token = your_bot_token_here
admin_ids = 123456789, 987654321

Configuration Options

  • token (required): Your Telegram bot token obtained from BotFather
  • admin_ids (optional): Comma-separated list of Telegram user IDs that should have admin privileges

Usage

Running the Bot

Start the bot with:

python -m src.main

Or:

python src/main.py

The bot will start polling for updates from Telegram.

Creating Handlers

Add new handlers in the src/handlers/ directory:

from aiogram import Router
from aiogram.filters import Command
from aiogram.types import Message

router = Router()

@router.message(Command("start"))
async def cmd_start(message: Message):
    await message.answer("Hello! Welcome to the bot.")

Then register the router in src/main.py:

from src.handlers.your_handler import router as your_router

dp.include_router(your_router)

Using Filters

The template includes a UserFilter that can be used to restrict handlers to non-admin users:

from src.filters.user import UserFilter

@router.message(Command("user_command"), UserFilter())
async def user_only_handler(message: Message):
    await message.answer("This command is available only to regular users.")

The UserFilter returns True if the user is not an admin, allowing you to filter out admin users from specific handlers.

Adding Middlewares

Use the EnvironmentMiddleware to inject dependencies into handlers:

from src.middlewares.environment import EnvironmentMiddleware

config = load_config()
dp.message.middleware(EnvironmentMiddleware(config=config))

Access injected data in handlers through the data parameter:

async def handler(message: Message, data: dict):
    config = data['config']

Development

Code Structure Guidelines

  • Handlers: Place all message and callback handlers in src/handlers/
  • Filters: Create custom filters in src/filters/
  • Keyboards: Build keyboard layouts in src/keyboards/
  • Services: Add external service integrations in src/services/
  • Models: Define data models in src/models/

Adding Dependencies

Add new Python packages to requirements.txt:

aiogram~=3.21
your-package==1.0.0

Then install:

pip install -r requirements.txt

Features Explained

User Filter

The UserFilter class checks if a user is not an admin. It accesses the configuration from the bot's data dictionary and compares the user's ID against the admin IDs list.

Environment Middleware

The EnvironmentMiddleware allows you to inject dependencies (like configuration, database connections, etc.) into all handlers without explicitly passing them.

Logging Utilities

The send_logs_to_admins function in src/misc/logs.py can be used to send log messages to all configured admin users.

Singleton Pattern

A singleton metaclass is available in src/misc/singleton.py for creating singleton classes when needed.

Troubleshooting

Bot doesn't start

  • Verify config.ini exists and contains a valid token
  • Check that all dependencies are installed: pip install -r requirements.txt
  • Ensure the bot token is correct and hasn't been revoked

Admin filter not working

  • Verify admin IDs are correctly formatted in config.ini (comma-separated integers)
  • Check that the configuration is properly loaded and injected via middleware

Import errors

  • Make sure you're running from the project root directory
  • Verify your Python path includes the project root
  • Check that all __init__.py files are present in package directories

License

See the LICENSE file for details.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Test thoroughly
  5. Submit a pull request

Resources

Support

For issues, questions, or contributions, please open an issue on the repository.

About

Production-ready aiogram 3.21+ template with organized structure, configuration management, user filtering, and middleware support. Start building Telegram bots instantly.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages