What it is
Aiogram is a modern and fully asynchronous Python framework for building Telegram bots. It leverages Python’s asyncio capabilities to provide high-performance, scalable, and efficient bot development.
Aiogram allows you to create Telegram bots that handle messages, commands, inline queries, callback queries, and more. It supports middlewares, FSM (Finite State Machines) for complex conversations, and robust error handling.
Installation
pip install aiogramGetting started
The smallest useful thing you can do with it, and what each part means.
from aiogram import Bot, Dispatcher, types
from aiogram.utils import executor
TOKEN = 'YOUR_BOT_TOKEN'
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)
@dp.message_handler(commands=['start'])
async def start_handler(message: types.Message):
await message.reply('Hello! I am your Aiogram bot.')
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)await bot.send_message(chat_id=123456789, text='Hello from Aiogram!')Advanced usage
Where the library earns its place over a simpler alternative.
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
keyboard = InlineKeyboardMarkup()
keyboard.add(InlineKeyboardButton('Click me', callback_data='button_click'))
await message.reply('Choose an option:', reply_markup=keyboard)@dp.callback_query_handler(lambda c: c.data == 'button_click')
async def process_callback(callback_query: types.CallbackQuery):
await bot.answer_callback_query(callback_query.id)
await bot.send_message(callback_query.from_user.id, 'Button clicked!')from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.contrib.fsm_storage.memory import MemoryStorage
storage = MemoryStorage()
class Form(StatesGroup):
name = State()
age = State()from aiogram.dispatcher.middlewares import BaseMiddleware
class LoggingMiddleware(BaseMiddleware):
async def on_pre_process_message(self, message, data):
print(f'Received message: {message.text}')from aiogram.utils.exceptions import BotBlocked
try:
await bot.send_message(user_id, 'Hello!')
except BotBlocked:
print('Bot was blocked by the user')Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- BotBlocked
- Occurs when a user blocks the bot. Handle gracefully and log the incident.
- RetryAfter
- Occurs when hitting Telegram’s rate limits. Implement retry mechanisms or delays.
- NetworkError
- Retry the request and handle transient network issues appropriately.
Best practices
- Use FSM for multi-step conversations to maintain state cleanly.
- Leverage middlewares for logging, validation, and preprocessing messages.
- Handle exceptions for blocked users or network errors.
- Keep the bot fully asynchronous to maximize performance.
- Use proper token and environment variable management for security.
Background
Why it exists, and what it was reacting to.
Aiogram was created to provide developers with a fast, asynchronous, and type-annotated framework for building Telegram bots. It focuses on simplicity, performance, and the latest Python features, making it ideal for both small and large-scale bot projects.
