aiogram Documentation

repository·dev-3.x·Indexed 26 days ago

https://github.com/aiogram/aiogram

A modern, fully asynchronous Python framework for building Telegram bots using the Telegram Bot API. It provides core components like Bot, Dispatcher, and Router, along with expressive filtering via MagicFilter (F), text decoration utilities for HTML and Markdown, and comprehensive error handling for Telegram API and framework-level exceptions.

Tokens
71.5K
Snippets
322
Records
701
Agent score
81%

What's inside aiogram

  1. Overview of aiogram features

    dev-3.x

    aiogram is a modern, fully asynchronous framework for the Telegram Bot API, built on Python 3.10+, asyncio, and aiohttp.

    Key features include:

    • Asynchronous core: Built using asyncio.
    • Type Safety: Full support for type hints and mypy.
    • High Performance: Supports PyPy and provides fast updates to the latest Telegram Bot API versions.
    • Routing: Uses an updated router system (Blueprints).
    • State Management: Includes a Finite State Machine (FSM).
    • Filtering: Features powerful magic filters.
    • Extensibility: Supports Middlewares for both incoming updates and API calls.
    • Webhooks: Provides 'Replies into Webhook' capabilities.
    • Localization: Integrated I18n/L10n support using GNU Gettext or Fluent.
  2. Understand the aiogram Bot API support

    dev-3.x
    aiogram provides full support for the Telegram Bot API. All methods and types used in the library are automatically generated from the official Telegram Bot API documentation via a code-generator, ensuring high fidelity with the official Telegram specification.
  3. Understand how filters route updates

    dev-3.x

    Filters are used to route incoming updates to specific handlers. When an update arrives, aiogram searches for a matching handler by checking the filters associated with each handler.

    Key behaviors:

    • First Match Wins: The search stops at the first handler whose filters all pass.
    • Default Behavior: Handlers with an empty set of filters will match all updates. They should generally be placed last in your routing logic to avoid intercepting updates intended for more specific handlers.
  4. Understand the Dispatcher and Router mechanism

    dev-3.x

    In aiogram, the Dispatcher is the core mechanism used to handle incoming updates from Telegram. It allows you to:

    • Handle incoming updates.
    • Filter incoming events before they reach specific handlers.
    • Modify events and related data using middlewares.
    • Separate bot functionality across different handlers, modules, and packages.

    The architecture distinguishes between two entities:

    1. Router: Used to organize handlers and logic.
    2. Dispatcher: A subclass of Router that must always serve as the root router of your application.
  5. Implement Webhooks with aiohttp

    dev-3.x

    aiogram provides built-in integration with aiohttp to handle Telegram webhooks. You can choose from three webhook controller implementations depending on your needs:

    • SimpleRequestHandler: A simple controller that uses a single Bot instance.
    • TokenBasedRequestHandler: A controller that supports multiple Bot instances and tokens.
    • BaseRequestHandler: An abstract base class if you need to implement a custom aiohttp webhook controller.

    Note: If you use webhooks, you cannot use long polling simultaneously.

  6. Use lazy gettext for filters

    dev-3.x

    When the current language is not known at the moment of code execution (e.g., inside keyword or magic filters), use lazy_gettext (conventionally __).

    Warning:

    • Lazy gettext calls cannot be used as values for API methods or Telegram objects (like InlineKeyboardButton).
    from aiogram import F
    from aiogram.utils.i18n import lazy_gettext as __
    
    @router.message(F.text == __("My menu entry"))
    async def my_handler(message: Message):
        ...
  7. Use class-based handlers to structure Telegram event handlers

    dev-3.x
    In aiogram, handlers can be implemented as classes instead of just asynchronous functions. This approach allows you to structure your event logic more effectively and reuse code through inheritance and mixins. To implement a class-based handler, you must inherit from one of the provided base handler classes (such as Message, CallbackQuery, Error, etc.) depending on the type of Telegram event you are handling.
  8. Use Magic Filters (F) for event filtering

    dev-3.x

    Magic filters allow you to create expressive, chainable filters for Telegram events using the F object. While F is an alias for MagicFilter from the magic-filter package, you should import F from aiogram to access aiogram-specific extensions like .as_().

    F works by chaining attribute getters (e.g., F.user.id) and applying actions or comparisons. The resulting object is a callable that can be used directly in router decorators.

  9. Set up aiogram development environment using uv

    dev-3.x

    For a faster and more modern workflow, use uv to manage dependencies and virtual environments automatically. uv handles environment creation, dependency resolution, and lockfile generation.

    1. Install uv:
      • Linux / macOS: curl -LsSf https://astral.sh/uv/install.sh | sh
      • Windows: powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
      • via pip: pip install uv
    2. Sync project: Run uv sync to create the .venv and install all dependencies, including extras and development groups.
    3. Install hooks: Run uv run pre-commit install to set up git hooks.

    When using uv, prefix all commands with uv run to execute them within the managed environment.

    # Install uv (Linux/macOS example)
    curl -LsSf https://astral.sh/uv/install.sh | sh
    
    # Setup project
    git clone https://github.com/aiogram/aiogram.git
    cd aiogram
    uv sync --all-extras --group dev --group test
    uv run pre-commit install
  10. Configure proxy authorization in AiohttpSession

    dev-3.x

    You can provide proxy credentials in two ways:

    1. Using aiohttp.BasicAuth: Pass a tuple containing the proxy URL and an instance of aiohttp.BasicAuth to the proxy argument. This is the preferred method.
    2. In the URL: Include credentials directly in the proxy URL (e.g., protocol://user:password@host:port).

    Note: If both a BasicAuth object and credentials in the URL are provided, aiogram will prioritize the credentials from the BasicAuth instance.

    from aiohttp import BasicAuth
    from aiogram.client.session.aiohttp import AiohttpSession
    
    # Method 1: Using BasicAuth (Preferred)
    auth = BasicAuth(login="user", password="password")
    session = AiohttpSession(proxy=("protocol://host:port", auth))
    
    # Method 2: Using URL credentials
    session = AiohttpSession(proxy="protocol://user:password@host:port")
  11. Enter a Scene using different methods

    dev-3.x

    There are four primary ways to transition a user into a Scene:

    1. As a regular handler: Convert the scene's entry point to a handler and register it with a router.

      router.message.register(SettingsScene.as_handler(), Command("settings"))
    2. Using ScenesManager: From any regular handler, use the ScenesManager dependency. You must explicitly pass any additional arguments required by the scene's entry point.

      @router.message(Command("settings"))
      async def settings_handler(message: Message, scenes: ScenesManager):
          await scenes.enter(SettingsScene, some_data="data")
    3. Using After.goto marker: Transition to another scene automatically after a handler finishes execution.

      @on.message(F.text.startswith("🚀"), after=After.goto(AnotherScene))
      async def on_message(self, message: Message):
          # Logic runs, then transition occurs
          pass
    4. Using SceneWizard.goto: For direct control within a scene handler. Dependencies are injected normally, then extended with arguments from goto.

      @on.message(F.text.startswith("🚀"))
      async def on_message(self, message: Message):
          await self.wizard.goto(AnotherScene, value=message.text)
    # 1. Register as handler
    router.message.register(SettingsScene.as_handler(), Command("settings"))
    
    # 2. Use ScenesManager
    @router.message(Command("settings"))
    async def settings_handler(message: Message, scenes: ScenesManager):
        await scenes.enter(SettingsScene, some_data="data")
    
    # 3. Use After.goto marker
    @on.message(F.text.startswith("🚀"), after=After.goto(AnotherScene))
    async def on_message(self, message: Message):
        pass
    
    # 4. Use wizard.goto
    @on.message(F.text.startswith("🚀"))
    async def on_message(self, message: Message):
        await self.wizard.goto(AnotherScene, value=message.text)