aiogram
aiogram is a modern and fully asynchronous framework for the Telegram Bot API, built on `asyncio`. It provides a high-level, opinionated API for creating Telegram bots efficiently. The library closely follows Telegram Bot API updates, releasing new versions frequently to incorporate the latest features and changes. The current stable version is 3.27.0.
Warnings
- breaking aiogram v3 introduced significant breaking changes from v2. Key areas affected include handler registration, FSMContext usage, filters, and the main polling/webhook setup.
- gotcha aiogram is fully asynchronous. All I/O operations and handlers must be `async def` functions and use `await`. Mixing synchronous and asynchronous code incorrectly will lead to blocking, deadlocks, or unexpected behavior.
- gotcha Hardcoding your bot token directly in code is a security risk. It should be kept confidential and not exposed in version control.
- gotcha aiogram frequently updates to support new Telegram Bot API features. While this is beneficial, it means that minor API changes can sometimes introduce subtle breaking changes in types or available fields.
- breaking aiogram v3.x has specific Python version requirements. As of v3.27.0, it requires Python `>=3.10` and `<3.15`. Python 3.9 is no longer supported as of v3.23.0.
Install
-
pip install aiogram
Imports
- Bot
from aiogram import Bot
- Dispatcher
from aiogram import Dispatcher
- F
from aiogram import F
- Message
from aiogram.types import Message
- CommandStart
from aiogram.filters import CommandStart
Quickstart
import asyncio
import os
from aiogram import Bot, Dispatcher, F
from aiogram.types import Message
from aiogram.filters import CommandStart
BOT_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN', 'YOUR_BOT_TOKEN_HERE') # Replace or set env var
async def main():
bot = Bot(token=BOT_TOKEN)
dp = Dispatcher()
@dp.message(CommandStart())
async def handle_start(message: Message):
await message.answer(f"Hello, {message.from_user.full_name}!")
@dp.message(F.text == "hi")
async def handle_hi(message: Message):
await message.answer("Hi there!")
@dp.message(F.text)
async def handle_text(message: Message):
await message.answer(f"You said: {message.text}")
await dp.start_polling(bot)
if __name__ == "__main__":
if BOT_TOKEN == 'YOUR_BOT_TOKEN_HERE':
print("Please replace 'YOUR_BOT_TOKEN_HERE' with your actual bot token or set the TELEGRAM_BOT_TOKEN environment variable.")
else:
asyncio.run(main())