Skip to main content

PyMax

Python-библиотека для Max API.

Python 3.10+ License: MIT Package PyPI Downloads

Что это

PyMax - асинхронная Python-библиотека для внутреннего API Max. Она умеет авторизоваться в аккаунте, слушать события, отправлять сообщения, работать с чатами, пользователями, файлами, сессиями и доменными типами Max через TCP или WebSocket.

Возможности

  • Авторизация по телефону и SMS-коду через Client.
  • QR-авторизация web-клиента через WebClient.
  • Роутеры, составные фильтры, middleware, on_start, raw-события и typed events.
  • FSM для диалогов и необязательная интеграция с Dishka.
  • Сообщения: отправка и планирование, ответы, реакции, pin, read, delete и история.
  • Комментарии к постам каналов и нажатия inline-кнопок ботов.
  • Сторис: фото и видео, лента, реакции и статистика просмотров.
  • Чаты, группы, участники, invite-ссылки и настройки групп.
  • Пользователи, контакты, профиль, папки, активные сессии и 2FA.
  • Вложения: Photo, File, Video, Voice, VideoNote.
  • Выбор версии mobile-клиента с локальным или обновляемым каталогом fingerprints.
  • SQLite-сессии, sync-state, reconnect и debug-логи.
  • Pydantic-модели и удобные domain-объекты.

Установка

Требуется Python 3.10 или новее.

pip install -U maxapi-python

Через uv:

uv add -U maxapi-python

Напрямую из репозитория:

pip install git+https://github.com/MaxApiTeam/PyMax.git

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

Client использует TCP-соединение. При первом запуске PyMax попросит SMS-код и сохранит сессию в SQLite-файл; дальше этот файл используется автоматически.

import asyncio

from pymax import Client, Message
from pymax.filters import Command

client = Client(
    phone="+79990000000",
    work_dir="cache",
    session_name="main.db",
)


@client.on_start()
async def on_start(client: Client) -> None:
    print("Клиент запущен")
    print("Ваш ID:", client.me.contact.id if client.me else "unknown")


@client.on_message(Command("start"))
async def on_message(message: Message, client: Client) -> None:
    print(message.chat_id, message.sender, message.text)

    if message.chat_id is not None and message.text:
        await message.answer("Привет от PyMax")


async def main() -> None:
    await client.start()


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

Отправьте /start, чтобы вызвать обработчик.

WebClient

WebClient использует WebSocket и QR-авторизацию:

import asyncio

from pymax import WebClient

client = WebClient(work_dir="cache", session_name="web.db")


@client.on_start()
async def on_start(client: WebClient) -> None:
    print("Web-клиент запущен")


asyncio.run(client.start())

Роутеры

Обработчики можно регистрировать на клиенте или вынести в отдельный роутер. Handler всегда принимает событие и клиента: (event, client).

from pymax import Client, ClientRouter, Message
from pymax.filters import Command

router = ClientRouter()


@router.on_message(Command("start"))
async def start(message: Message, client: Client) -> None:
    await message.answer("Готово")


client = Client(phone="+79990000000", work_dir="cache")
client.include_router(router)

Куда дальше

  • Getting Started - первый запуск и сессии.
  • Client - жизненный цикл клиента, reconnect и sync-state.
  • Router - роутеры, фильтры, middleware и raw events.
  • FSM - состояния и данные диалога.
  • DI и Dishka - зависимости обработчиков.
  • Messages - сообщения, реакции, история и вложения.
  • Stories - публикация и чтение сторис.
  • Files - отправка и скачивание файлов.
  • FAQ и Troubleshooting - частые проблемы.

Опубликованная документация:

Разработка

uv sync --all-groups
uv run pre-commit install
uv run pre-commit run --all-files
uv run pytest
uv run python -c "import pymax; print(pymax.__all__)"
uv run sphinx-build -b html docs docs/_build/html

Ссылки

Лицензия

Проект распространяется под лицензией MIT. Подробности см. в LICENSE.

Авторы

  • ink - основной разработчик, исследование API и документация.
  • noxzion - оригинальный автор проекта.

Metadata

Release files for maxapi-python 2.5.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 maxapi-python 2.5.0
File Size Uploaded Provenance Actions
maxapi_python-2.5.0.tar.gz 375.6 kB Without provenance Details for maxapi_python-2.5.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for maxapi-python 2.5.0
File Interpreter ABI Platform Actions
maxapi_python-2.5.0-py3-none-any.whl Python 3 none any Details for maxapi_python-2.5.0-py3-none-any.whl

Total release size: 570.8 kB

Release files / maxapi_python-2.5.0.tar.gz

Download URL maxapi_python-2.5.0.tar.gz
Size 375.6 kB
Tags Source
SHA-256 checksum
How to use checksums
e0e49707434e64d2befa7199b932005100b7608f82fd4457bbd638205fe41dd7
BLAKE2b-256 checksum
How to use checksums
83332cdfec83e03bbc8df65666f51ffe64cbcb8d802b9845538faddbce59c007
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / maxapi_python-2.5.0-py3-none-any.whl

Download URL maxapi_python-2.5.0-py3-none-any.whl
Size 195.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
20dcf9bfe658fd75434cc370f12c6a0114d85ee109309789c19174710cb8f479
BLAKE2b-256 checksum
How to use checksums
35ee4d2f076da9849a45804d888252008a343be33d591960a4d9423a0fb6f649
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for maxapi-python 2.5.0

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.

Release history Release notifications | RSS feed

This release

2.5.0 This release

2 release files No provenance

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