Skip to main content

Python библиотека для создания ботов AstrixRU

Project description

AstrixLibrary

Библиотека для создания ботов для платформы AstrixRU с использованием WebSocket.

pip install websockets aiohttp

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

from AstrixLibrary import AstrixBot, Context, Message

bot = AstrixBot(token="YOUR_BOT_TOKEN")

@bot.on_message()
async def on_message(ctx: Context, message: Message):
    print(f"Сообщение: {message.text}")

@bot.command("start", "Запуск бота")
async def cmd_start(ctx: Context):
    await ctx.send("Привет! Я бот!")

bot.run()

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

1. Обработчики событий

# Все сообщения
@bot.on_message()
async def on_message(ctx: Context, message: Message):
    await ctx.send("Получил сообщение!")

# Реакции
@bot.on_reaction()
async def on_reaction(data):
    print(f"Реакция: {data}")

2. Команды

# Простая команда
@bot.command("ping", "Проверка бота") # Второй аргумент "Проверка бота" нужен для того, чтобы в будущем был выпадающий список, и была команда а внизу ее описание, значит второй аргумент - описание команды.
async def cmd_ping(ctx: Context):
    await ctx.send("Понг!")

# Команда с аргументами
@bot.command("echo", "Повторить текст")
async def cmd_echo(ctx: Context, args):
    await ctx.send(f"🔊 {' '.join(args)}")

3. Context методы

@bot.on_message()
async def on_message(ctx: Context, message: Message):
    # Отправить сообщение
    await ctx.send("Привет!")
    
    # Ответить на сообщение
    await ctx.reply("Ответ на ваше сообщение")
    
    # Удалить сообщение
    await ctx.delete()
    
    # Поставить реакцию
    await ctx.react("👍")
    
    # Редактировать сообщение
    await ctx.edit("Новый текст")

4. API методы бота

# Отправка сообщения
await bot.send_message(chat_id, "Текст")

# Удаление сообщения
await bot.delete_message(chat_id, message_id)

# Редактирование
await bot.edit_message(message_id, "Новый текст")

# Реакции
await bot.add_reaction(message_id, "👍")
await bot.remove_reaction(message_id, "👍")

# Печать
await bot.start_typing(chat_id) # Внимание! Данный метод еще пока что не работает.

# Получить пользователя
user = await bot.find_user("nickname") # Внимание! Данный метод еще пока что не реализован. Скоро он появится в библиотеке.

# История чата
history = await bot.get_chat_history(chat_id, limit=50)

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

Эхо-бот

from AstrixLibrary import AstrixBot, Context, Message

bot = AstrixBot(token="YOUR_TOKEN")

@bot.on_message()
async def on_message(ctx: Context, message: Message):
    if message.text.startswith("!"):
        await ctx.send(message.text[1:])

bot.run()

Бот с командами

from AstrixLibrary import AstrixBot, Context

bot = AstrixBot(token="YOUR_TOKEN")

@bot.command("start", "Запуск")
async def cmd_start(ctx: Context):
    await ctx.send("Привет! Используй /help для списка команд.")

@bot.command("help", "Помощь")
async def cmd_help(ctx: Context):
    await ctx.send(
        "📚 Команды:\n"
        "/start - Запуск\n"
        "/help - Помощь\n"
        "/ping - Проверка"
    )

@bot.command("ping", "Проверка")
async def cmd_ping(ctx: Context):
    msg = await ctx.send("Понг!")
    await asyncio.sleep(2)
    await msg.edit("Бот работает!")

bot.run()

Получение токена

  1. Зарегистрируйтесь в AstrixRU, а затем зайдите на страницу https://astrixru.online/developers/bots.
  2. Нажмите "Создать бота"
  3. Заполните всю информацию о боте, нажмите создать.
  4. Скопируйте токен

Поддержка

Лицензия

MIT License

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

astrixlibrary-1.1.1.tar.gz (6.2 kB view details)

Uploaded Source

Built Distribution

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

astrixlibrary-1.1.1-py3-none-any.whl (5.8 kB view details)

Uploaded Python 3

File details

Details for the file astrixlibrary-1.1.1.tar.gz.

File metadata

  • Download URL: astrixlibrary-1.1.1.tar.gz
  • Upload date:
  • Size: 6.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.2

File hashes

Hashes for astrixlibrary-1.1.1.tar.gz
Algorithm Hash digest
SHA256 cdf98ee0412c3f2975d79ca1bb93d5491df278af62d75c3d16f4e6ed2c33d998
MD5 f69c8e9f937913e0b85c4e31b5d31415
BLAKE2b-256 79b0f2e6d6bc2b7f5a2e6917728fd1fe665df87f4e3fb027cecda340cdf72922

See more details on using hashes here.

File details

Details for the file astrixlibrary-1.1.1-py3-none-any.whl.

File metadata

  • Download URL: astrixlibrary-1.1.1-py3-none-any.whl
  • Upload date:
  • Size: 5.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.2

File hashes

Hashes for astrixlibrary-1.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 1015adb732f3c88e7448c41f4419e272cd900c675f0056f403947b4a7d6c4334
MD5 89cbc155e3eed5c8b267bc88664b1cae
BLAKE2b-256 9a503f1eb12fbdaff4eb1e35cf29249495fee9de9d05cd6c16cab3f138fda66a

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