aiogram 3.x Guide

repository·master·Indexed 22 days ago

https://github.com/mastergroosha/aiogram-3-guide

A comprehensive guide and collection of examples for developing Telegram bots using the aiogram 3.x framework in Python. The documentation covers basics like quickstart and message handling, as well as advanced topics including Routers, Filters, Middlewares, Finite State Machines (FSM), Inline Mode, and payment integrations. It also includes a project demonstrating an AI bot with topic support using aiogram 3.25.0, local LLM integration via llama.cpp, and Telegram's Threads in Private Chats.

Tokens
52.2K
Snippets
128
Records
165
Agent score
77%

What's inside aiogram-3-guide

  1. Overview of Filters and Middlewares in aiogram 3.x

    master

    This directory contains source code examples for implementing Filters and Middlewares in aiogram 3.x.

    • Filters are used to determine whether an incoming update should be handled by a specific handler. They allow you to narrow down the scope of handlers based on content, state, or other criteria.
    • Middlewares are used to intercept updates before they reach handlers (or responses before they reach the Telegram server). They are useful for cross-cutting concerns like logging, authentication, database session management, or rate limiting.
  2. Overview of Filters and Middlewares in aiogram 3.x

    master
    This guide covers the implementation and usage of filters and middlewares in aiogram version 3.14.0. It explores how to use standard filters, how to implement filters as classes, and introduces 'Magic Filters', a specialized feature in the framework designed to replace complex lambda expressions for more readable and powerful condition checking.
  3. Introduction to Finite State Machines (FSM) in aiogram 3.x

    master

    This directory contains source code and examples for implementing Finite State Machines (FSM) using aiogram 3.x. FSM is used to manage user states within a bot, allowing the bot to remember where a user is in a multi-step conversation flow (e.g., waiting for a name, then waiting for an age).

    For detailed narrative explanations and the full tutorial, refer to the official guide: https://mastergroosha.github.io/aiogram-3-guide/fsm/

  4. Explore advanced Telegram bot development topics

    master

    For developers looking to move beyond basic aiogram usage, the advanced curriculum covers several professional-grade technologies and patterns:

    • aiogram-dialog: Building complex, beautiful, and user-friendly interfaces within the Telegram messenger window.
    • Testing: Implementing automated testing to verify code logic and prevent bugs in production without manual testing.
    • Docker: Containerizing bots for easy deployment and sharing, using Docker Compose, and automating builds via GitHub or GitLab.
    • Localization: Enabling multi-language support for bots using tools like Babel and Project Fluent.
    • Message Queues: Using brokers like RabbitMQ or NATS to offload tasks to microservices, improving reliability and delivery guarantees.
    • Database Management: Working with modern DBMS and tools to efficiently store user data and content.
  5. Project Overview: AI Bot with Topic Support

    master

    This project demonstrates how to build a Telegram bot using aiogram 3.25.0 that integrates with a Large Language Model (LLM) and utilizes the Telegram Bot API 9.4+ feature of Threads in Private Chats.

    Key Technical Details:

    • Framework: aiogram 3.25.0
    • LLM: Uses a local Qwen2.5-7B-Instruct model (GGUF format) for privacy and cost-efficiency.
    • Streaming: AI responses are sent via streaming to mimic modern AI interfaces.
    • State Management: Chat history is stored in RAM for simplicity, but is designed to be adaptable to PostgreSQL or Redis.
    • Thread Strategy: The implementation follows Variant 2 (Bot-managed threads), where the bot controls thread creation to separate AI conversations from system/settings messages in the General thread.
  6. Configure Bot Settings via TOML and Environment Variables

    master

    Configuration is managed in config.py using TOML files. To support environments without files, the implementation should include a fallback to environment variables.

    Environment Variable Convention: Use double underscores (__) as a separator for nested keys. For example, a token inside a [bot] section in settings.toml is mapped to BOT__TOKEN in environment variables.

    ```toml
    [bot]
    token = "1234567890:AaBbCcDdEeFfGrOoShAHhIiJjKkLlMmNnOo"

    Equivalent Environment Variable:

    BOT__TOKEN=1234567890:AaBbCcDdEeFfGrOoShAHhIiJjKkLlMmNnOo

  7. Detect when a bot is added to a group or supergroup

    master

    To detect when a bot is added to a group, listen for my_chat_member updates where the status transitions from a non-member state to a member state.

    In aiogram 3.x, you can use several levels of abstraction for these transitions:

    1. Manual Transition: Define specific sets of states using bitwise operators. Use >> to indicate the direction of the transition (from old to new). Use + or - to modify the is_member flag for the RESTRICTED status.
      • Example: (KICKED | LEFT | -RESTRICTED) >> (+RESTRICTED | MEMBER | ADMINISTRATOR)
    2. Predefined Sets: Use IS_NOT_MEMBER >> IS_MEMBER to catch any transition from a non-member state to a member state.
    3. Convenience Constant: Use JOIN_TRANSITION for the most common 'added to chat' scenario.

    Important Note on Group Conversion: When a standard group is converted into a supergroup, it may trigger a my_chat_member update as if the bot were being added to a new chat. To avoid duplicate logic, check if the incoming message contains a non-empty migrate_to_chat_id field.

    # Option 1: Manual (Detailed)
    from aiogram.filters.chat_member_updated import ChatMemberUpdatedFilter, KICKED, LEFT, MEMBER, RESTRICTED, ADMINISTRATOR, CREATOR
    
    @router.my_chat_member(ChatMemberUpdatedFilter(
        member_status_changed=(KICKED | LEFT | -RESTRICTED) >> (+RESTRICTED | MEMBER | ADMINISTRATOR | CREATOR)
    ))
    
    # Option 2: Using IS_NOT_MEMBER / IS_MEMBER
    from aiogram.filters.chat_member_updated import ChatMemberUpdatedFilter, IS_NOT_MEMBER, IS_MEMBER
    
    @router.my_chat_member(ChatMemberUpdatedFilter(IS_NOT_MEMBER >> IS_MEMBER))
    
    # Option 3: Using JOIN_TRANSITION (Recommended)
    from aiogram.filters.chat_member_updated import ChatMemberUpdatedFilter, JOIN_TRANSITION
    
    @router.my_chat_member(ChatMemberUpdatedFilter(JOIN_TRANSITION))
  8. How outer and inner middlewares work

    master

    aiogram 3.x distinguishes between two types of middlewares based on when they execute relative to filter checking:

    1. Outer Middlewares: Execute before filters are checked. An outer middleware can decide to drop an update before it even reaches the filtering stage.
    2. Inner Middlewares: Execute after filters have matched a handler. If an update reaches an inner middleware, it is guaranteed to be handled by some handler.

    Important Note on Update-type Middlewares:

    • An inner middleware for the Update type is always called (there is no distinction between outer and inner for the base Update type).
    • Middlewares for the Update type can only be attached to the Dispatcher (the root router).
  9. How Guest Mode works in aiogram

    master

    Guest Mode allows bots to send messages in chats where they are not members. It is architecturally similar to Inline Mode but functions as a "fire and forget" mechanism.

    Workflow:

    • A user invokes the bot using a message like @bot TEXT_QUERY.
    • The bot receives a specific update containing the trigger message. If the user's message was a reply to another message, the bot also receives that original message via .reply_to_message.
    • The bot can respond exactly once within a short period.

    Key Differences from Inline Mode:

    • Scope: Guest mode provides information about the chat (ID, title, etc.) where the bot was invoked, even if the bot isn't a member.
    • Access: The bot only has access to the trigger message and the message it replied to.
    • Message Deletion: You cannot use deleteMessage() on guest mode responses because they return an inline_message_id instead of a standard message_id. To "clear" a message, you must use a button to edit the message to an empty string (e.g., a space or dot).