Skip to main content

Python SDK for MAX Messenger Bot API

Project description

maxapi-sdk 0.12.2

Python SDK для MAX Messenger Bot API.

Пакет публикуется в PyPI как maxapi-sdk, а в коде импортируется как maxapi.

Что есть в пакете

  • typed Bot API client для методов MAX;
  • отдельные runtime-классы PollingRunner и WebhookRunner;
  • transport-слой с retry/backoff и поддержкой Retry-After;
  • Router и Dispatcher с middleware и инъекцией зависимостей в handlers;
  • composable filters с операторами &, |, ~;
  • InlineKeyboardBuilder и media helpers для upload/send flow;
  • FSM: State, StatesGroup, FSMContext, MemoryStorage, StateFilter;
  • plugin API для модульного подключения функциональности;
  • structured callback payload parsing через CallbackPayloadSchema;
  • migration layer для старого стиля кода;
  • GitHub Actions для тестов, сборки, GitHub Releases и публикации в PyPI.

Установка

pip install maxapi-sdk
pip install "maxapi-sdk[webhook]"

Установка для разработки

pip install -e .
pip install -e .[webhook]
pip install -e .[dev]

Быстрый старт: polling

import asyncio
import os

from maxapi import Bot, Command, Dispatcher, InlineKeyboardBuilder


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


@dp.message_created(Command("start"))
async def handle_start(event):
    keyboard = (
        InlineKeyboardBuilder()
        .callback("Подтвердить", "confirm")
        .link("Документация", "https://dev.max.ru/docs-api")
        .adjust(1, 1)
    )
    await event.message.answer("Привет из maxapi 0.12.2", keyboard=keyboard)


async def main() -> None:
    await dp.start_polling(bot)


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

FSM

import asyncio
import os

from maxapi import Bot, Dispatcher, MemoryStorage, State, StateFilter, StatesGroup


class Registration(StatesGroup):
    name = State()
    confirm = State()


bot = Bot(token=os.environ["MAX_BOT_TOKEN"])
dp = Dispatcher(storage=MemoryStorage())


@dp.message_created()
async def start_form(message, state):
    if message.body.text == "/form":
        await state.set_state(Registration.name)
        await state.update_data(step="name")
        await message.answer("Введите имя")


@dp.message_created(StateFilter(Registration.name))
async def save_name(message, state, state_data):
    await state.update_data(name=message.body.text)
    data = await state.get_data()
    await state.set_state(Registration.confirm)
    await message.answer(f"Подтвердить имя: {data['name']}")


async def main() -> None:
    await dp.start_polling(bot)


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

Structured callback payload

from maxapi import CallbackPayloadSchema, Dispatcher


class AdminAction(CallbackPayloadSchema):
    prefix = "admin"
    action: str
    user_id: int


payload = AdminAction(action="ban", user_id=42).pack()


dp = Dispatcher()


@dp.message_callback(AdminAction.filter(action="ban"))
async def handle_ban(callback_event, callback_payload_text):
    parsed = callback_event.unpack(AdminAction)
    await callback_event.answer(notification=f"Ban for user {parsed.user_id}")

Plugin API

from maxapi import BasePlugin, Dispatcher


class MetricsPlugin(BasePlugin):
    name = "metrics"

    def setup(self, router) -> None:
        @router.message_created()
        async def mark_message(message, bot):
            del bot
            print(f"message_id={message.message_id}")


dp = Dispatcher()
dp.include_plugin(MetricsPlugin())

Webhook

import asyncio
import os

from maxapi import Bot, Dispatcher


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


async def main() -> None:
    await dp.handle_webhook(
        bot=bot,
        host="0.0.0.0",
        port=8080,
        path="/webhook",
        secret=os.environ["MAX_BOT_WEBHOOK_SECRET"],
    )


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

Media helpers

response = await bot.send_image(
    "/tmp/banner.png",
    chat_id=123,
    text="Готово",
    processing_wait=0.5,
    attachment_ready_retries=3,
)

Migration layer

from maxapi.compat import Keyboard, LegacyBot, LegacyDispatcher


bot = LegacyBot(token="token")
dp = LegacyDispatcher()
keyboard = Keyboard().callback("OK", "done").row()


@dp.message_handler()
async def legacy_handler(event):
    await bot.send_text(chat_id=event.chat_id, text="legacy", keyboard=keyboard)

CI/CD

В репозитории есть два workflow:

  • .github/workflows/tests.yml — тесты и проверка сборки пакета;
  • .github/workflows/publish.yml — сборка артефактов, публикация в PyPI через Trusted Publishing и создание GitHub Release по тегу v*.

Репозиторий

  • GitHub: https://github.com/Maxi-online/maxapi-sdk

Структура

  • maxapi.bot — typed Bot API client;
  • maxapi.dispatcher — Router/Dispatcher, middleware, handler injection;
  • maxapi.runners.polling — long polling runtime;
  • maxapi.runners.webhook — FastAPI/uvicorn webhook runtime;
  • maxapi.filters — composable filters;
  • maxapi.builders — keyboard/media builders;
  • maxapi.fsm — FSM, storage и state filters;
  • maxapi.plugins — plugin API;
  • maxapi.middlewares — middleware base classes;
  • maxapi.compat — migration layer;
  • maxapi.transport — HTTP transport;
  • maxapi.types — pydantic-модели.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

maxapi_sdk-0.12.2.tar.gz (35.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

maxapi_sdk-0.12.2-py3-none-any.whl (40.7 kB view details)

Uploaded Python 3

File details

Details for the file maxapi_sdk-0.12.2.tar.gz.

File metadata

  • Download URL: maxapi_sdk-0.12.2.tar.gz
  • Upload date:
  • Size: 35.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for maxapi_sdk-0.12.2.tar.gz
Algorithm Hash digest
SHA256 999cf3a9f9bf60bf4b76296c86c6a60f49087555233b1d0bea0f8d609174d754
MD5 dda94eae20a5d950a0edbd643a0fa181
BLAKE2b-256 7d1a8d791c05b6f08d7763621b6eb14909ad9645939825c75e6a9e721b86314d

See more details on using hashes here.

Provenance

The following attestation bundles were made for maxapi_sdk-0.12.2.tar.gz:

Publisher: publish.yml on Maxi-online/maxapi-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file maxapi_sdk-0.12.2-py3-none-any.whl.

File metadata

  • Download URL: maxapi_sdk-0.12.2-py3-none-any.whl
  • Upload date:
  • Size: 40.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for maxapi_sdk-0.12.2-py3-none-any.whl
Algorithm Hash digest
SHA256 60a1222e4c3a36760727bdb9b2f1182d00f315009124c6d73bcf66763e03737d
MD5 edd58fba6873e0bf01d8beddd9362565
BLAKE2b-256 6f2df2bc4d22ffa6b5cadec09c01045d68d42a6fca18fb82a8fb336b04f2dcbe

See more details on using hashes here.

Provenance

The following attestation bundles were made for maxapi_sdk-0.12.2-py3-none-any.whl:

Publisher: publish.yml on Maxi-online/maxapi-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page