Modern and fully asynchronous framework for Telegram Bot API
npx @tessl/cli install tessl/pypi-aiogram@3.22.0A modern and fully asynchronous framework for Telegram Bot API. aiogram provides a comprehensive Python toolkit for building Telegram bots with async/await support, type safety, powerful filtering system, finite state machines, middleware support, and complete coverage of the Telegram Bot API v9.2.
pip install aiogramimport aiogramCommon imports for bot development:
from aiogram import Bot, Dispatcher, Router, F, html, md, flags
from aiogram.types import Message, CallbackQuery, Update
from aiogram.filters import Command, StateFilter
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import State, StatesGroupimport asyncio
from aiogram import Bot, Dispatcher, Router, F
from aiogram.types import Message
from aiogram.filters import Command
# Initialize bot and dispatcher
bot = Bot(token="YOUR_BOT_TOKEN")
dp = Dispatcher()
router = Router()
# Register handlers using decorators
@router.message(Command("start"))
async def cmd_start(message: Message):
await message.answer("Hello! This is a bot built with aiogram.")
@router.message(F.text == "hello")
async def hello_handler(message: Message):
await message.answer("Hello there!")
# Include router in dispatcher
dp.include_router(router)
# Start polling
async def main():
await dp.start_polling(bot)
if __name__ == "__main__":
asyncio.run(main())aiogram follows a modular, event-driven architecture built on asyncio:
This design enables scalable bot development with clean separation of concerns, type safety, and powerful abstraction layers.
Core classes for bot instantiation, update processing, and event routing. The Bot class handles API communication while Dispatcher manages update distribution and middleware execution.
class Bot:
def __init__(self, token: str, **kwargs): ...
async def get_me(self) -> User: ...
async def send_message(self, chat_id: int | str, text: str, **kwargs) -> Message: ...
class Dispatcher(Router):
def __init__(self, **kwargs): ...
async def start_polling(self, bot: Bot, **kwargs): ...
def include_router(self, router: Router): ...Complete type system covering all Telegram objects including messages, users, chats, keyboards, media, payments, and inline queries. Over 319 classes with full type safety.
class Message(TelegramObject):
message_id: int
from_user: User | None
sender_chat: Chat | None
date: datetime.datetime
chat: Chat
text: str | None
entities: list[MessageEntity] | None
class User(TelegramObject):
id: int
is_bot: bool
first_name: str
last_name: str | None
username: str | NoneComplete coverage of all 162+ Telegram Bot API methods for sending messages, managing chats, handling payments, games, stickers, and webhooks. Type-safe method calls with automatic serialization.
async def send_message(
chat_id: int | str,
text: str,
parse_mode: str | None = None,
reply_markup: InlineKeyboardMarkup | ReplyKeyboardMarkup | None = None
) -> Message: ...
async def edit_message_text(
text: str,
chat_id: int | str | None = None,
message_id: int | None = None,
parse_mode: str | None = None
) -> Message | bool: ...Powerful filtering system with magic filters, command matching, state filtering, and custom filters. Handler registration with decorators and functional approaches.
class Filter:
async def __call__(self, obj: TelegramObject) -> bool | dict[str, Any]: ...
class Command(Filter):
def __init__(self, *commands: str): ...
F: MagicFilter # Magic filter instance for complex conditions
@router.message(Command("start"))
async def start_handler(message: Message): ...
@router.message(F.text.contains("hello"))
async def text_filter_handler(message: Message): ...Built-in FSM support for complex conversational flows with multiple storage backends, state groups, and context management.
class State:
def __init__(self, state: str, group_name: str | None = None): ...
class StatesGroup:
pass
class FSMContext:
async def set_state(self, state: State | str | None) -> None: ...
async def get_state(self) -> str | None: ...
async def set_data(self, data: dict[str, Any]) -> None: ...
async def get_data(self) -> dict[str, Any]: ...Comprehensive utility functions for deep linking, keyboard building, text formatting, and validation. Complete enumeration system for API constants.
def create_start_link(bot_username: str, payload: str | None = None) -> str: ...
class InlineKeyboardBuilder:
def button(self, text: str, **kwargs) -> InlineKeyboardBuilder: ...
def adjust(self, *sizes: int) -> InlineKeyboardBuilder: ...
def as_markup(self) -> InlineKeyboardMarkup: ...
# Enums
class ChatType(str, Enum):
PRIVATE = "private"
GROUP = "group"
SUPERGROUP = "supergroup"
CHANNEL = "channel"class TelegramObject:
"""Base class for all Telegram objects"""
pass
class Update(TelegramObject):
"""Represents an incoming update"""
update_id: int
message: Message | None
edited_message: Message | None
channel_post: Message | None
edited_channel_post: Message | None
business_connection: BusinessConnection | None
business_message: Message | None
edited_business_message: Message | None
deleted_business_messages: BusinessMessagesDeleted | None
message_reaction: MessageReactionUpdated | None
message_reaction_count: MessageReactionCountUpdated | None
inline_query: InlineQuery | None
chosen_inline_result: ChosenInlineResult | None
callback_query: CallbackQuery | None
shipping_query: ShippingQuery | None
pre_checkout_query: PreCheckoutQuery | None
purchased_paid_media: PaidMediaPurchased | None
poll: Poll | None
poll_answer: PollAnswer | None
my_chat_member: ChatMemberUpdated | None
chat_member: ChatMemberUpdated | None
chat_join_request: ChatJoinRequest | None
chat_boost: ChatBoostUpdated | None
removed_chat_boost: ChatBoostRemoved | None
class Bot:
"""Main bot class for API interactions"""
def __init__(
self,
token: str,
parse_mode: str | None = None,
disable_web_page_preview: bool | None = None,
protect_content: bool | None = None,
session: BaseSession | None = None,
**kwargs
): ...