Skip to main content

Python SDK and Chatbot Framework for MAX API

Project description

maxbot-chatbot-python

maxbot-chatbot-python — это асинхронный фреймворк для создания масштабируемых ботов для MAX BOT API на языке Python.

Построенная на основе maxbot_api_client_python, эта библиотека предоставляет чистый маршрутизатор, автоматическое получение обновлений (Long Polling) и надежный менеджер состояний (FSM) для построения многошаговых диалоговых сценариев.

Для использования библиотеки требуется получить токен бота в консоли разработчика MAX API.
Ознакомиться с инструкцией можно по ссылке.

API

Документацию по REST API MAX можно найти по ссылке dev.max.ru/docs-api. Библиотека является оберткой для REST API, поэтому документация по указанной выше ссылке также применима к используемым здесь моделям.

Документацию по MAX BOT API можно найти по ссылке green-api.com/max-bot-api/docs.

Поддержка

Support Support Support

Руководства и новости

Guides News News

Установка

Убедитесь, что у вас установлен Python версии 3.12 или выше.

python --version

Установите библиотеку:

pip install maxbot-chatbot-python

Использование и примеры

Параметры конфигурации:

  • base_url - Базовый URL-адрес серверов платформы MaxBot. Все методы API будут маршрутизироваться по этому корневому адресу. Актуальный адрес указан в официальной документации.
  • token - Уникальный секретный ключ авторизации (API-ключ) вашего бота. Получить его можно в личном кабинете после регистрации или создании бота на платформе business.max.ru.
  • ratelimiter - Встроенный ограничитель частоты запросов. Он контролирует количество исходящих запросов в секунду (RPS), защищая бота от блокировки со стороны сервера за превышение лимитов. Рекомендуемое значение — не менее 25.
  • timeout - Максимальное время ожидания ответа от сервера (в секундах). Если сервер не ответит в течение этого времени, запрос будет завершен с ошибкой. Оптимальное значение — 30 секунд.

Инициализация бота

Использование асинхронного контекстного менеджера (async with API(...)) гарантирует безопасное закрытие сетевых соединений при остановке бота.

import asyncio

from maxbot_api_client_python import API, Config
from maxbot_chatbot_python import Bot, MapStateManager

async def main():
    cfg = Config(
        base_url="https://platform-api.max.ru/", 
        token="YOUR_BOT_TOKEN", 
        ratelimiter=25,
        timeout=35
    )

    async with API(cfg) as api_client:
        bot = Bot(api_client)
        bot.state_manager = MapStateManager(init_data={})

        polling_task = asyncio.create_task(bot.start_polling())

        try:
            await polling_task
        except asyncio.CancelledError:
            pass

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("Bot stopped by user")

Маршрутизация команд, сообщений и коллбэков

Встроенный маршрутизатор (Router) позволяет легко обрабатывать конкретные команды (начинающиеся со слэша /) и нажатия на inline-кнопки (коллбэки).

@bot.router.command("/start")
async def start_command(notification):
    await notification.reply("Hello! Welcome to the MAX Bot.")

@bot.router.register("message_created")
async def ping_handler(notification):
    try:
        if notification.text() == "ping":
            await notification.reply("pong")
    except ValueError:
        pass

@bot.router.callback("accept_rules")
async def rules_callback(notification):
    await notification.reply("*Thank you for accepting the rules!*", format_type="markdown")
    await notification.answer_callback("Success!")

Управление состояниями и Сцены (FSM)

Для сложных многошаговых диалогов (например, регистрация или анкетирование) используйте Менеджер состояний (StateManager) и Сцены (Scene).

from maxbot_chatbot_python import Scene

class RegistrationScene(Scene):
    async def start(self, notification):
        try:
            text = notification.text()
        except ValueError:
            return

        if text == "/start":
            await notification.reply("Let's register! What is your *login*?", "markdown")
            return 
        
        if len(text) >= 4:
            if notification.state_manager:
                notification.state_manager.update_state_data(notification.state_id, {"login": text})
            
            await notification.reply(f"**Login** `{text}` accepted. Now enter your **password**:", "markdown")
            notification.activate_next_scene(PasswordScene())
        else:
            await notification.reply("Login must be **at least 4 characters long**.", "markdown")

class PasswordScene(Scene):
    async def start(self, notification):
        try:
            password = notification.text()
        except ValueError:
            return

        state_data = notification.state_manager.get_state_data(notification.state_id)
        login = state_data.get("login", "Unknown")

        await notification.reply(f"Success! Profile created.\nLogin: `{login}`\nPass: `{password}`", "markdown")

        notification.activate_next_scene(RegistrationScene())

@bot.router.register("message_created")
async def fsm_handler(notification):
    current_scene = notification.get_current_scene()
    if current_scene:
        await current_scene.start(notification)

Ответ с медиафайлами

Обертка Notification содержит готовые асинхронные методы для отправки файлов, геолокаций, стикеров и статусов набора текста.

@bot.router.command("/photo")
async def send_photo(notification):
    await notification.show_action("sending_photo")

    await notification.reply_with_media(
        text="Check out this image!", 
        format_type="markdown", 
        file_source="https://storage.yandexcloud.net/sw-prod-03-test/ChatBot/corgi.jpg"
    )

Эхо-бот

import asyncio

from maxbot_api_client_python import API, Config
from maxbot_chatbot_python import Bot, MapStateManager

async def main():
    cfg = Config(
        base_url="https://platform-api.max.ru/", 
        token="YOUR_BOT_TOKEN",
        ratelimiter=25
    )

    async with API(cfg) as api_client:
        bot = Bot(api_client)
        bot.state_manager = MapStateManager(init_data={})

        @bot.router.register("message_created")
        async def echo_handler(notification):
            try:
                text = notification.text()
                await notification.reply(f"**Echo:** {text}", "markdown")
            except Exception as e:
                print(f"Error handling message: {e}")

        polling_task = asyncio.create_task(bot.start_polling())

        try:
            await polling_task
        except asyncio.CancelledError:
            pass

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("Bot stopped by user (KeyboardInterrupt)")

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

maxbot_chatbot_python-1.1.0.tar.gz (12.5 kB view details)

Uploaded Source

Built Distribution

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

maxbot_chatbot_python-1.1.0-py3-none-any.whl (10.5 kB view details)

Uploaded Python 3

File details

Details for the file maxbot_chatbot_python-1.1.0.tar.gz.

File metadata

  • Download URL: maxbot_chatbot_python-1.1.0.tar.gz
  • Upload date:
  • Size: 12.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for maxbot_chatbot_python-1.1.0.tar.gz
Algorithm Hash digest
SHA256 326e280276b7a916767656c51c0181559b9419b822e634e6c79a83cb27ee513b
MD5 121a49a859e5b2b69becb407fea3b6fd
BLAKE2b-256 2716e68e9746642fe7c39b04c22b01ff40ac063f4c6de30083f92d35ed1bdc96

See more details on using hashes here.

File details

Details for the file maxbot_chatbot_python-1.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for maxbot_chatbot_python-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 fa4c9ef857f11568d036d931caa980851b62c4afd75b60bc61f839f98c907fdd
MD5 aac552d8802a63a4cbc6c6ea5b5d7023
BLAKE2b-256 a8927378ad35aa38911787a6dd99eaf39c4e6de2adb41a4b9141c730e0cbe930

See more details on using hashes here.

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