Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

aiomax2

PyPI Python CI Documentation License

aiomax2 — асинхронный Python-фреймворк для разработки ботов на MAX Bot API.

Фреймворк предоставляет Bot, Dispatcher, Router, фильтры, middleware, FSM, inline-клавиатуры, Long Polling и Webhook, сохраняя модели и семантику оригинального MAX API.

Архитектура и developer experience используют знакомые подходы из aiogram 3.x, но MAX API остаётся источником истины для методов, событий, моделей и ограничений.

Документация · PyPI · Releases · MAX Bot API


Установка

Требуется Python 3.12+.

pip install aiomax2

Проверить установленную версию:

python -c "import aiomax2; print(aiomax2.__version__)"

Быстрый старт

import asyncio
import os

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

router = Router()


@router.message(Command("start"))
async def start(message: Message) -> None:
    await message.answer("Привет из aiomax2!")


async def main() -> None:
    bot = Bot(os.environ["MAX_BOT_TOKEN"])

    dp = Dispatcher()
    dp.include_router(router)

    try:
        await dp.start_polling(bot)
    finally:
        await bot.close()
        await dp.close()


if __name__ == "__main__":
    asyncio.run(main())

Запуск:

export MAX_BOT_TOKEN="..."
python bot.py

На Windows PowerShell:

$env:MAX_BOT_TOKEN="..."
python bot.py

Возможности

  • полностью асинхронная работа на asyncio и aiohttp;
  • типизированные модели MAX API на Pydantic 2;
  • Dispatcher, вложенные Router и dependency injection;
  • команды, фильтры и magic filter F;
  • middleware и FSM;
  • shortcuts для сообщений и callback;
  • InlineKeyboardBuilder и все актуальные типы inline-кнопок MAX;
  • HTML и MAX Markdown через TextFormat;
  • Long Polling и Webhook;
  • интеграция Webhook с FastAPI;
  • загрузка изображений, видео, аудио и файлов;
  • работа с подписками, чатами, сообщениями и комментариями;
  • автоматическая обработка rate limits и Retry-After;
  • безопасная по умолчанию TLS verification;
  • дополнительный CA bundle через ca_file;
  • низкоуровневый доступ к API через Bot.request().

Inline-клавиатуры

from aiomax2 import F
from aiomax2.types import CallbackQuery
from aiomax2.utils.keyboard import InlineKeyboardBuilder

builder = InlineKeyboardBuilder()
builder.button(text="Подтвердить", callback_data="confirm")
builder.button(text="Отменить", callback_data="cancel")
builder.adjust(2)

await message.answer(
    "Выберите действие",
    reply_markup=builder.as_markup(),
)


@router.callback_query(F.payload == "confirm")
async def confirm(callback: CallbackQuery) -> None:
    await callback.answer(text="Подтверждено")

Подробнее: Inline-клавиатуры и Callback.


Форматирование текста

from aiomax2 import TextFormat

await message.answer(
    "<b>Жирный</b> <i>курсив</i>",
    format=TextFormat.HTML,
)

await message.answer(
    "**Жирный** _курсив_",
    format=TextFormat.MARKDOWN,
)

Подробнее: форматирование текста.


Long Polling и Webhook

Для локальной разработки можно использовать Long Polling:

await dp.start_polling(bot)

Для production доступен Webhook с FastAPI:

app.include_router(
    dp.webhook_router(
        "/webhook",
        bot=bot,
        secret=WEBHOOK_SECRET,
    )
)

Регистрация публичного URL выполняется через:

await bot.subscribe(
    "https://bot.example.ru/webhook",
    secret=WEBHOOK_SECRET,
    update_types=dp.resolve_used_update_types(),
)

Подробнее:


TLS и сертификаты

MAX Bot API использует TLS-цепочку, для которой среда выполнения может потребовать сертификаты Национального УЦ Минцифры.

Для подключения не требуется выпускать собственный сертификат. Нужны готовые Russian Trusted Root CA и Russian Trusted Sub CA.

Сертификаты доступны на Госуслугах.

Рекомендуемый вариант — добавить их в системное trust store и использовать обычную безопасную конфигурацию:

bot = Bot(os.environ["MAX_BOT_TOKEN"])

Если изменять системное хранилище нежелательно, оба сертификата можно объединить в PEM bundle и передать только aiomax2:

bot = Bot(
    os.environ["MAX_BOT_TOKEN"],
    ca_file="/path/to/russian_trusted_ca.pem",
)

Для диагностики существует явный небезопасный режим:

bot = Bot(
    os.environ["MAX_BOT_TOKEN"],
    verify_ssl=False,
)

Подробные инструкции по установке сертификатов и созданию CA bundle: TLS и сертификаты.


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

Полная документация:

https://candycrimsie.github.io/aiomax2/

Основные разделы:

Готовые примеры находятся в каталоге examples.


Разработка

git clone https://github.com/CandyCrimsie/aiomax2.git
cd aiomax2

python -m pip install -e ".[dev]"

Перед отправкой изменений:

python -m ruff format --check .
python -m ruff check .
python -m mypy src/aiomax2
python -m pytest
python -m mkdocs build --strict

Правила участия в разработке: CONTRIBUTING.md.


Проект


Лицензия

aiomax2 распространяется по лицензии MIT.

Metadata

Release files for aiomax2 0.1.0a3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for aiomax2 0.1.0a3
File Size Uploaded
aiomax2-0.1.0a3.tar.gz 111.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for aiomax2 0.1.0a3
File Interpreter ABI Platform
aiomax2-0.1.0a3-py3-none-any.whl Python 3 none any Details

Total release size: 157.4 kB

Release files / aiomax2-0.1.0a3.tar.gz

Download URL aiomax2-0.1.0a3.tar.gz
Size 111.7 kB
Tags Source
SHA-256 checksum
How to use checksums
b1c1fbdab4fcdfd99414d423b2b43f13db91c35f697b1deda73618737f9da0cb
BLAKE2b-256 checksum
How to use checksums
5ab8950433b79435d84ea087184a0d181765de0b2d4f2c819a2685fae43bd92f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 6, 2026.

Transparency log

Release files / aiomax2-0.1.0a3-py3-none-any.whl

Download URL aiomax2-0.1.0a3-py3-none-any.whl
Size 45.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
58eb01fe86b00b4a864b35e10bcda16736e34d53997f182aa8499a5bb3989a1a
BLAKE2b-256 checksum
How to use checksums
c68eda013199f923bbcecb2a5abc95e3d0722b57a9d28a4742f7fb14e0e0cf94
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 6, 2026.

Transparency log

Release history Release notifications | RSS feed

0.1.0

2 release files

This release

0.1.0a3 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page