Async Python framework for Max Bot API, inspired by aiogram
Project description
maxogram
Асинхронный 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.update import MessageCreatedUpdate
router = Router()
@router.message_created()
async def echo(
event: MessageCreatedUpdate,
bot: Bot,
**kwargs: object,
) -> None:
"""Повторяет любое текстовое сообщение."""
text = event.message.body.text
chat_id = event.message.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
Лицензия
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file maxogram-1.0.0.tar.gz.
File metadata
- Download URL: maxogram-1.0.0.tar.gz
- Upload date:
- Size: 100.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c7e36ec9a63d5d8155b71a43ba76219d82f9e533f1a9c603c181f22eb3b94774
|
|
| MD5 |
fbb27aa252883a9e4a717176a4de076b
|
|
| BLAKE2b-256 |
d3c941493b33ee1af071b141176635d9c3c2ff899a978b78cbb407df6ad1ec16
|
Provenance
The following attestation bundles were made for maxogram-1.0.0.tar.gz:
Publisher:
publish.yml on mccalpink/maxogram
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
maxogram-1.0.0.tar.gz -
Subject digest:
c7e36ec9a63d5d8155b71a43ba76219d82f9e533f1a9c603c181f22eb3b94774 - Sigstore transparency entry: 1180078598
- Sigstore integration time:
-
Permalink:
mccalpink/maxogram@75f880fdda4b0af57036687bcb7a8c8dbfe6120c -
Branch / Tag:
refs/tags/v1.0.0 - Owner: https://github.com/mccalpink
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@75f880fdda4b0af57036687bcb7a8c8dbfe6120c -
Trigger Event:
release
-
Statement type:
File details
Details for the file maxogram-1.0.0-py3-none-any.whl.
File metadata
- Download URL: maxogram-1.0.0-py3-none-any.whl
- Upload date:
- Size: 160.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ee23e6c0fd58424e959fdf05c51ba710a86d502b13261d4772ddcb6d57d816df
|
|
| MD5 |
25e1248f12e2b7d143896a9ce712b33a
|
|
| BLAKE2b-256 |
9ff4ce0a995b84a008780ffc3b8bf580a31352263eeab18260a6f16c199249f2
|
Provenance
The following attestation bundles were made for maxogram-1.0.0-py3-none-any.whl:
Publisher:
publish.yml on mccalpink/maxogram
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
maxogram-1.0.0-py3-none-any.whl -
Subject digest:
ee23e6c0fd58424e959fdf05c51ba710a86d502b13261d4772ddcb6d57d816df - Sigstore transparency entry: 1180078611
- Sigstore integration time:
-
Permalink:
mccalpink/maxogram@75f880fdda4b0af57036687bcb7a8c8dbfe6120c -
Branch / Tag:
refs/tags/v1.0.0 - Owner: https://github.com/mccalpink
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@75f880fdda4b0af57036687bcb7a8c8dbfe6120c -
Trigger Event:
release
-
Statement type: