Aiogram

Language: Python

Web

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.

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.

Installation

pip: pip install aiogram
conda: conda install -c conda-forge aiogram

Usage

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.

Simple bot responding to /start

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)

Creates a bot that responds with a greeting when a user sends the /start command.

Sending a message

await bot.send_message(chat_id=123456789, text='Hello from Aiogram!')

Sends a message to a specific chat using the bot instance.

Using inline keyboards

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)

Adds an inline keyboard to a message and handles user interactions via callback data.

Handling callback queries

@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!')

Processes user clicks on inline buttons and sends a response message.

Finite State Machine example

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()

Defines states for managing multi-step conversations in a Telegram bot using FSM.

Middleware usage

from aiogram.dispatcher.middlewares import BaseMiddleware

class LoggingMiddleware(BaseMiddleware):
    async def on_pre_process_message(self, message, data):
        print(f'Received message: {message.text}')

Demonstrates how to create a middleware to log messages before processing.

Error handling

from aiogram.utils.exceptions import BotBlocked
try:
    await bot.send_message(user_id, 'Hello!')
except BotBlocked:
    print('Bot was blocked by the user')

Handles exceptions like when the bot is blocked by a user.

Error Handling

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.