Skip to main content

Лого Pyromax

Современный асинхронный Python-фреймворк для создания юзерботов в MAX Messenger.

Python PyPI License Status

Pyromax — современный фреймворк, вдохновлённый aiogram 3.x, который переносит привычную архитектуру Telegram-ботов в экосистему MAX Messenger.

Библиотека предоставляет всё необходимое для разработки масштабируемых проектов: Router, Dispatcher, Middlewares, FSM, Magic Filters, строгую типизацию и полностью асинхронное ядро.


✨ Основные возможности

📦 Router

Разделяйте проект на независимые модули.

⚡ Async First

Полностью асинхронное ядро на asyncio, aiohttp и websockets.

🛡 Middlewares

Перехватывайте события до и после обработки.

Подходит для:

  • логирования;
  • антифлуда;
  • проверки прав;
  • работы с БД;
  • Dependency Injection;
  • аналитики.

🎭 FSM (Finite State Machine)

Создавайте сложные сценарии общения:

  • анкеты;
  • формы;
  • мастера настройки;
  • регистрации;
  • диалоги;
  • опросы.

✨ Magic Filters

Фильтрация сообщений похожа на aiogram.

@router.message(F.text.startswith("!"))

🧩 Масштабируемая архитектура

Pyromax подходит как для небольших скриптов, так и для крупных проектов.

Используйте:

  • Routers
  • Nested Routers
  • Middlewares
  • FSM
  • Custom Filters
  • Dependency Injection

без необходимости переписывать архитектуру.


📦 Установка

pip install pyromax

или

uv add pyromax

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

import asyncio


from pyromax import MaxApi, Dispatcher
from pyromax.models import Message

# Инициализация диспетчера
dp = Dispatcher()


# Регистрация хендлера (обрабатываем все сообщения, включая свои)
@dp.message(from_me=True)
async def echo(message: Message):
    await message.reply(message.text)


async def main():
    # Создаем экземпляр API
    max_api = await MaxApi()
    # Запускаем бота с диспетчером
    await dp.start_polling(max_api=max_api)



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

📱 Версии мобильного клиента

VersionApi связывает версию Android-клиента с её build number и APK fingerprint. Встроенный каталог работает без сети, а адрес удалённого каталога при необходимости задаётся явно через remote_url.

import os

from pyromax import MaxApi, VersionApi
from pyromax.config import ExtraConfig
from pyromax.models import DeviceType

max_api = await MaxApi(
    device_type=DeviceType.Android,
    extra_config=ExtraConfig(
        app_version="26.28.0",
        version_api=VersionApi(
            remote_url=os.environ["PYROMAX_VERSION_CATALOG_URL"],
        ),
    ),
)

app_version применяется к любому совместимому user-agent. app_fingerprint относится только к Android: если он не задан, клиент ищет fingerprint итоговой версии в каталоге и применяет его только при наличии. Неизвестная Android-версия не мешает подключению — fingerprint просто не отправляется. Приоритет значений: user-agent из сессии → app_version из ExtraConfig → Android fingerprint из каталога → явный app_fingerprint. Для совместимости доступно также имя VersionCatalog, а catalog= является алиасом version_api= внутри ExtraConfig. Строгую проверку наличия версии можно выполнить явно через strict_fingerprint_pair = True.


🧩 Router

Разделяйте проект по файлам.

router = Router()


@router.message(Command("ping"))
async def ping(message: Message):
    await message.reply("🏓 Pong")
dp.include_router(router)

🛡 Middlewares

Используйте middleware для обработки каждого события.

Здесь ключами в data выступают объекты, которыми вы аннотируете хэндлер(по ним библиотека и понимает что нужно передать в соответствующий хэндлер). В самом простом случае ключ это класс, а значение ключа это объект этого класса

from pyromax import Dispatcher
from pyromax.dispatcher.middlewares.base import BaseMiddleware
from pyromax.dispatcher.event import MaxObject


dp = Dispatcher()

class MyDB:
    """Your DB, now its just dummy for demonstrate"""

class MyUpdateOuterMiddleware(BaseMiddleware):
    async def __call__(
            self,
            handler: Callable[[MaxObject, dict[Any, Any]], Awaitable[Any]],
            event: MaxObject,
            data: dict[type[Any] | str, Any],
    ) -> Any:
        data[MyDB] = MyDB()
        return await handler(event, data)
    
    
dp.update.outer_middleware(
    MyUpdateOuterMiddleware()
)

@dp.message()
async def need_to_get_db_instance(my_db: MyDB):
    pass

Также в data ключами могут быть не только классы, которыми вы аннотируете параметры в хэндлерах, но и также forward ref, и обращаться в хэндлерах надо через них соответственно

class MyUpdateOuterMiddleware(BaseMiddleware):
    async def __call__(
            self,
            handler: Callable[[MaxObject, dict[Any, Any]], Awaitable[Any]],
            event: MaxObject,
            data: dict[type[Any] | str, Any],
    ) -> Any:
        data['DataBase'] = MyDB()
        return await handler(event, data)

@dp.message()
async def need_to_get_db_instance(my_db: 'DataBase'):
    pass

🎭 FSM

from pyromax.fsm.state import State, StatesGroup
from pyromax.fsm.context import FSMContext
from pyromax import Dispatcher, MaxApi
from pyromax.filters.command import Command
from pyromax.models import Message

class SimpleSurvey(StatesGroup):
    name = State()
    weather = State()
    whats_up = State()

dp = Dispatcher()


@dp.message(Command('survey'))
async def start_survey(msg: Message, state: FSMContext):
    await msg.reply(
        text='Привет, как тебя зовут?'
    )
    
    await state.set_state(
        SimpleSurvey.name
    )

@dp.message(SimpleSurvey.name)
async def handle_name(msg: Message, state: FSMContext):
    if not msg.text:
        await msg.reply(
            text='Напиши свое имя текстом!'
        )
        return
    await state.update_data(
        user_name=msg.text
    )
    await state.set_state(
        SimpleSurvey.weather
    )
    await msg.answer(
        text='Какая у тебя погода?'
    )

@dp.message(SimpleSurvey.weather)
async def handle_weather(msg: Message, st: FSMContext):
    if not msg.text:
        await msg.reply(
            text='Напиши свою погоду текстом!'
        )
        return
    await st.update_data(
        weather=msg.text
    )
    await st.set_state(
        SimpleSurvey.whats_up
    )
    
    await msg.reply(
        text="Как дела?"
    )

@dp.message(SimpleSurvey.whats_up)
async def handle_whats_up(msg: Message, state: FSMContext):
    if not msg.text:
        await msg.reply(
            text='Напиши свои дела текстом!'
        )
        return 
    await state.update_data(
        whats_up=msg.text
    )
    data = await state.get_data()

    await state.clear()

    await msg.answer(
        text=f"Тебя зовут {data.get('user_name')}, погода у тебя {data.get('weather')}, а дела у тебя {data.get('whats_up')}"
    )

✨ Magic Filters

@router.message(
    F.text.startswith("/"),
    from_me=True
)
async def handler(message: Message):
    ...

💬 Форматирование сообщений

Поддерживается разметка MAX.

@dp.message(Command('lyric'), from_me=True)
async def lyric(msg: Message):
    await msg.answer(text='<STRONG>They tell me, "keep it simple"</STRONG>'
                             '<QUOTE>I tell them, "take it slow"</QUOTE>'
                             '<STRIKETHROUGH>I feed a water an idea so I let it grow </STRIKETHROUGH> \n'
                             '<UNDERLINE>I tell them, "take it easy"</UNDERLINE> \n'
                             '<EMPHASIZED>They laugh and tell me, "No"</EMPHASIZED> \n'
                             '<LINK url="https://www.youtube.com/watch?v=9Zj0JOHJR-s">its cool...</LINK>'
                     )

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

📚 Roadmap

Уже реализовано

  • ✅ Async Core
  • ✅ Dispatcher
  • ✅ Router
  • ✅ Nested Routers
  • ✅ Observer Pattern
  • ✅ Magic Filters
  • ✅ Middlewares
  • ✅ FSM
  • ✅ telemetry
  • ✅ Типизация
  • ✅ Formatting API
  • ✅ Redis Storage
  • ✅ Memory Storage
  • ✅ Memory Storage
  • ✅ покрытие MAX API
  • ✅ Документация

🤝 Contributing

Pull Requests приветствуются.

Если хотите предложить новую возможность — создайте Issue или откройте Pull Request.


📞 Контакты

Telegram разработчика: ТЫК

Ссылки

📄 License

MIT License.

Metadata

Release files for pyromax 0.9

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

Source distribution (sdist)

Source distribution for pyromax 0.9
File Size Uploaded Provenance Actions
pyromax-0.9.tar.gz 198.8 kB Without provenance Details for pyromax-0.9.tar.gz

Built distribution (wheel)

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

Total release size: 485.3 kB

Release files / pyromax-0.9.tar.gz

Download URL pyromax-0.9.tar.gz
Size 198.8 kB
Tags Source
SHA-256 checksum
How to use checksums
90f8326477417fa25f601d95a05f8f68dbb6b9e72d7fa4f6060c871660410e02
BLAKE2b-256 checksum
How to use checksums
c88543d555dd220018e596f04fdddf79b9496ff83a19dc51f5b1423d67279b95
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.8.3

Release files / pyromax-0.9-py3-none-any.whl

Download URL pyromax-0.9-py3-none-any.whl
Size 286.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
53c396d8570a6a195399987e5f22234ee9d6da11ddacd56b15d6a6021945a7b7
BLAKE2b-256 checksum
How to use checksums
a62b4fc4c68984ac4be9b549e5f3d050f8b9e76e3ce1fe85f10a894c73482aa5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.8.3

Security for pyromax 0.9

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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