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.
pip install aiogramconda install -c conda-forge aiogramAiogram 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.
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.
await bot.send_message(chat_id=123456789, text='Hello from Aiogram!')Sends a message to a specific chat using the bot instance.
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.
@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.
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.
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.
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.
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.