Skip to main content

maxogram

Python PyPI Downloads CI License: MIT mypy

Асинхронный Python-фреймворк для Max Bot API, вдохновленный aiogram. Предоставляет типизированный, расширяемый интерфейс для создания ботов в мессенджере Max.

Возможности

Ядро фреймворка

  • Полное покрытие Max Bot API — 30 методов, 96 типов, все 13 типов событий
  • Router + Dispatcher — дерево роутеров с propagation событий, вложенность, lifecycle hooks
  • Фильтры — Command, ChatType, ContentType, CallbackData, MagicFilter (DSL), ExceptionType
  • Middleware — onion pattern, inner/outer и request-level middleware (RetryMiddleware, LoggingMiddleware)
  • FSM — конечные автоматы с MemoryStorage, RedisStorage и MongoStorage
  • Scene — высокоуровневый FSM для сложных диалогов (Scene, WizardScene, SceneRegistry)
  • Multi-bot — несколько ботов в одном Dispatcher
  • Webhook — aiohttp handler, WebhookManager с auto-resubscribe, IP whitelist security
  • Polling — long polling с exponential backoff и graceful shutdown
  • Keyboard builder — InlineKeyboardBuilder с adjust() для раскладки кнопок
  • Class-based handlers — BaseHandler, MessageHandler, CallbackHandler
  • Flags — декораторы метаданных на хендлерах для use-case-specific middleware
  • Dependency Injection — автоматическое внедрение bot, state, event в хендлеры
  • Типизация — py.typed, mypy strict, Pydantic v2 модели

Уникальные фичи Max

  • Message Constructor — интерактивное конструирование сообщений (нативная фича Max API)
  • Resumable Upload — загрузка файлов до 4 GB чанками с возобновлением после сбоя

Утилиты

  • I18n — интернационализация через gettext (I18nMiddleware, LazyProxy)
  • Text Formatting — Bold, Italic, Code, Link, UserMention builders
  • ChatActionSender — автоматическая отправка typing/recording actions
  • MediaGroupBuilder — групповая отправка медиа
  • Deep Linking — create_start_link, encode_payload, decode_payload
  • WebApp Validation — HMAC-SHA256 валидация initData
  • CallbackAnswerMiddleware — автоответ на callback если хендлер не ответил

Установка

pip install maxogram

Дополнительные зависимости:

pip install maxogram[redis]   # RedisStorage для FSM
pip install maxogram[mongodb]  # MongoStorage для FSM
pip install maxogram[fast]    # uvloop + aiodns
pip install maxogram[proxy]   # SOCKS-прокси
pip install maxogram[i18n]    # интернационализация (gettext)

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

import os

from maxogram.client.bot import Bot
from maxogram.dispatcher.dispatcher import Dispatcher
from maxogram.dispatcher.router import Router
from maxogram.types.message import Message

router = Router()


@router.message_created()
async def echo(
    event: Message,
    bot: Bot,
    **kwargs: object,
) -> None:
    """Повторяет любое текстовое сообщение."""
    text = event.body.text
    chat_id = event.recipient.chat_id
    if text and chat_id:
        await bot.send_message(chat_id=chat_id, text=text)


bot = Bot(token=os.environ["MAX_BOT_TOKEN"])
dp = Dispatcher()
dp.include_router(router)
dp.run_polling(bot)

Больше примеров: examples/

Основные концепции

Router

Маршрутизатор событий. Содержит observer для каждого из 13 типов событий Max API. Роутеры вкладываются друг в друга, образуя дерево — событие проходит по дереву до первого обработчика.

main_router = Router(name="main")
admin_router = Router(name="admin")
main_router.include_router(admin_router)

Filters

Фильтры определяют, какой хендлер обработает событие. Встроенные фильтры: Command, ChatTypeFilter, ContentTypeFilter, CallbackData, MagicData, ExceptionTypeFilter.

from maxogram.filters import Command

@router.message_created(Command("start"))
async def cmd_start(event, bot, command, **kwargs):
    ...

Middleware

Onion-pattern middleware для pre/post обработки. Два уровня: outer_middleware (до фильтров) и inner_middleware (после фильтров, перед хендлером).

from maxogram.dispatcher.middlewares.base import BaseMiddleware

class LogMiddleware(BaseMiddleware):
    async def __call__(self, handler, event, data):
        print(f"Event: {event}")
        return await handler(event, data)

router.message_created.outer_middleware.register(LogMiddleware())

FSM

Конечные автоматы для диалоговых сценариев. State + StatesGroup описывают состояния, FSMContext управляет переходами и данными.

from maxogram.fsm.state import State, StatesGroup
from maxogram.fsm.context import FSMContext

class Form(StatesGroup):
    name = State()
    age = State()

@router.message_created()
async def ask_name(event, bot, state: FSMContext, **kwargs):
    await state.set_state(Form.name)
    ...

Webhook

Production-ready webhook с aiohttp. WebhookManager управляет lifecycle, auto-resubscribe и graceful shutdown. IPWhitelistMiddleware защищает endpoint от поддельных запросов.

Инструменты разработчика

Schema Diff Tool

CLI-инструмент для сравнения OpenAPI-схемы Max Bot API с кодом библиотеки. Помогает отслеживать расхождения при обновлении API.

poetry run schema-diff                        # сравнить с актуальной схемой
poetry run schema-diff --schema path/to/openapi.json  # указать путь к схеме

Выводит: новые методы в API, удалённые методы, изменённые параметры.

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

Требования

  • Python 3.11+
  • aiohttp >= 3.9
  • pydantic >= 2.4
  • magic-filter >= 1.0.12
  • aiofiles >= 23.2
  • certifi >= 2023.7

Лицензия

MIT

Metadata

Release files for maxogram 1.1.0

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

Source distribution (sdist)

Source distribution for maxogram 1.1.0
File Size Uploaded
maxogram-1.1.0.tar.gz 101.0 kB Details

Built distribution (wheel)

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

Total release size: 261.5 kB

Release files / maxogram-1.1.0.tar.gz

Download URL maxogram-1.1.0.tar.gz
Size 101.0 kB
Tags Source
SHA-256 checksum
How to use checksums
9df2ebaeee167f5cf0929974e4a4b11fc9ec2be89c364fbda16f5d14730ab612
BLAKE2b-256 checksum
How to use checksums
ce8ba59d780c0eb8bc87dae77175defddf91c721e7562c65ffbaaeb76071a217
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

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 Mar 25, 2026.

Transparency log

Release files / maxogram-1.1.0-py3-none-any.whl

Download URL maxogram-1.1.0-py3-none-any.whl
Size 160.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b227c6962a6adc014389f090b2f68644f613dcf6cf90d56244d0c832f65c212e
BLAKE2b-256 checksum
How to use checksums
3f051ee9275e92a72e0d308b598bd890f54fd87b28191ddba5996aee11b0811d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

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 Mar 25, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

1.1.0 This release

2 release files

1.0.0

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