Skip to main content

Библиотека для разработки чат-ботов с помощью API мессенджера MAX

Project description

MaxAPI

MAX ЧатTG Чат

PyPI version Python Version Coverage License

● Документация и примеры использования

Можно посмотреть здесь: https://love-apples.github.io/maxapi/

● Установка из PyPi

Стабильная версия

pip install maxapi

● Установка из GitHub

Свежая версия, возможны баги. Рекомендуется только для ознакомления с новыми коммитами.

pip install git+https://github.com/love-apples/maxapi.git

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

Если вы тестируете бота в чате - не забудьте дать ему права администратора!

● Запуск Polling

Если у бота установлены подписки на Webhook - события не будут приходить при методе start_polling. При таком случае удалите подписки на Webhook через await bot.delete_webhook() перед start_polling.

import asyncio
import logging

from maxapi import Bot, Dispatcher
from maxapi.types import BotStarted, Command, MessageCreated

logging.basicConfig(level=logging.INFO)

# Внесите токен бота в переменную окружения MAX_BOT_TOKEN
# Не забудьте загрузить переменные из .env в os.environ
# или задайте его аргументом в Bot(token='...')
bot = Bot()
dp = Dispatcher()

# Ответ бота при нажатии на кнопку "Начать"
@dp.bot_started()
async def bot_started(event: BotStarted):
    await event.bot.send_message(
        chat_id=event.chat_id,
        text='Привет! Отправь мне /start'
    )

# Ответ бота на команду /start
@dp.message_created(Command('start'))
async def hello(event: MessageCreated):
    await event.message.answer("Пример чат-бота для MAX 💙")


async def main():
    await dp.start_polling(bot)


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

● Запуск Webhook

Webhook работает «из коробки» — aiohttp уже включён в базовый пакет:

pip install maxapi

Указан пример простого запуска, для более низкого уровня можете рассмотреть этот пример.

import asyncio
import logging

from maxapi import Bot, Dispatcher
from maxapi.types import BotStarted, Command, MessageCreated

logging.basicConfig(level=logging.INFO)

bot = Bot()
dp = Dispatcher()


# Команда /start боту
@dp.message_created(Command('start'))
async def hello(event: MessageCreated):
    await event.message.answer("Привет из вебхука!")


async def main():
    await dp.handle_webhook(
        bot=bot,
        host='0.0.0.0',
        port=8080,
    )


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

Хотите использовать FastAPI или Litestar вместо aiohttp? Установите нужную опциональную зависимость:

pip install maxapi[fastapi]   # FastAPI + uvicorn
pip install maxapi[litestar]  # Litestar + uvicorn

Пример запуска через FastAPI:

import asyncio
import uvicorn
from fastapi import FastAPI
from maxapi.webhook.fastapi import FastAPIMaxWebhook

async def main():
    webhook = FastAPIMaxWebhook(dp=dp, bot=bot)
    app = FastAPI(lifespan=webhook.lifespan)
    webhook.setup(app, path='/webhook')
    await uvicorn.Server(uvicorn.Config(app, host='0.0.0.0', port=8080)).serve()

asyncio.run(main())

Пример запуска через Litestar:

import asyncio
import uvicorn
from maxapi.webhook.litestar import LitestarMaxWebhook

async def main():
    webhook = LitestarMaxWebhook(dp=dp, bot=bot)
    app = webhook.create_app(path='/webhook')
    await uvicorn.Server(uvicorn.Config(app, host='0.0.0.0', port=8080)).serve()

asyncio.run(main())

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-1.1.0.tar.gz (191.6 kB view details)

Uploaded Source

Built Distribution

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

maxapi-1.1.0-py3-none-any.whl (199.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: maxapi-1.1.0.tar.gz
  • Upload date:
  • Size: 191.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for maxapi-1.1.0.tar.gz
Algorithm Hash digest
SHA256 93f0327d131a2128d46f1364a1e39c26eef0ff52d736ab4cec0a58d421a5d309
MD5 8f76a8cb72e8593e1253f4aed0c95cb7
BLAKE2b-256 02e4b7f10d7d456e853e8ae0ad7e3d07ab7a57bbbc187286d18347394530b744

See more details on using hashes here.

Provenance

The following attestation bundles were made for maxapi-1.1.0.tar.gz:

Publisher: publish.yml on love-apples/maxapi

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-1.1.0-py3-none-any.whl.

File metadata

  • Download URL: maxapi-1.1.0-py3-none-any.whl
  • Upload date:
  • Size: 199.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for maxapi-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d651f125afe219497d9db767000e5f897a7160071fd2e5bcdc91935b1e7f2115
MD5 11600f94d0c1e40760dec2f0175d1c6a
BLAKE2b-256 beab6339b095f4d5a0b75cf53fd8407527e77f1889df10a6613ae2e7ab1d216d

See more details on using hashes here.

Provenance

The following attestation bundles were made for maxapi-1.1.0-py3-none-any.whl:

Publisher: publish.yml on love-apples/maxapi

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