aiogram Beta badge#

Небезпека

Ще в розробці!

MIT License PyPi status PyPi Package Version Завантаження Підтримувані версії Python Telegram Bot API Тести Codecov

aiogram це сучасний та повністю асинхронний фреймворк для розробки чат-ботів Telegram Bot API на Python 3.8 з використанням asyncio та aiohttp.

Зробіть своїх ботів швидшими та потужнішими!

Документація

Небезпека

Важливі новини

aiogram 3.0 має зміни, що ламають зворотну сумісність.

Порушує зворотну сумісність, вводячи нові критичні зміни!

Особливості#

  • Асинхронність (asyncio docs, PEP 492)

  • Має анотації типів (PEP 484) та може використовуватись з mypy

  • Працює з PyPy

  • Supports Telegram Bot API 6.6 and gets fast updates to the latest versions of the Bot API

  • Код інтеграції з Bot API є автогенерованим що надає змогу дуже легко оновлювати фреймворк до останніх версій АПІ

  • Має роутери подій (Blueprints)

  • Має вбудований кінцевий автомат

  • Uses powerful magic filters <https://docs.aiogram.dev/en/dev-3.x/dispatcher/filters/magic_filters.html#magic-filters>

  • Підтримує мідлвари (для вхідних подій від АПІ та для вихідних запитів до АПІ)

  • Підтримує можливість відповіді у вебхук

  • Має вбудовану інтеграцію для використання інтернаціоналізації та локалізації GNU Gettext (або Fluent)

Попередження

Наполегливо рекомендується навчитись працювати з asyncio перед тим, як починати використовувати цей фреймворк. asyncio

Якщо є якість додаткові запитання, ласкаво просимо до онлайн-спільнот:

Приклад використання#

import asyncio
import logging

from aiogram import Bot, Dispatcher, Router, types
from aiogram.filters import Command
from aiogram.types import Message

# Bot token can be obtained via https://t.me/BotFahter
TOKEN = "42:TOKEN"

# All handlers should be attached to the Router (or Dispatcher)
router = Router()


@router.message(Command(commands=["start"]))
async def command_start_handler(message: Message) -> None:
    """
    This handler receive messages with `/start` command
    """
    # Most event objects have aliases for API methods that can be called in events' context
    # For example if you want to answer to incoming message you can use `message.answer(...)` alias
    # and the target chat will be passed to :ref:`aiogram.methods.send_message.SendMessage`
    # method automatically or call API method directly via
    # Bot instance: `bot.send_message(chat_id=message.chat.id, ...)`
    await message.answer(f"Hello, <b>{message.from_user.full_name}!</b>")


@router.message()
async def echo_handler(message: types.Message) -> None:
    """
    Handler will forward received message back to the sender

    By default, message handler will handle all message types (like text, photo, sticker and etc.)
    """
    try:
        # Send copy of the received message
        await message.send_copy(chat_id=message.chat.id)
    except TypeError:
        # But not all the types is supported to be copied so need to handle it
        await message.answer("Nice try!")


async def main() -> None:
    # Dispatcher is a root router
    dp = Dispatcher()
    # ... and all other routers should be attached to Dispatcher
    dp.include_router(router)

    # Initialize Bot instance with a default parse mode which will be passed to all API calls
    bot = Bot(TOKEN, parse_mode="HTML")
    # And the run events dispatching
    await dp.start_polling(bot)


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    asyncio.run(main())

Зміст#