Skip to main content

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

Metadata

Release files for AstrixLibrary 1.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for AstrixLibrary 1.1.1
File Size Uploaded
astrixlibrary-1.1.1.tar.gz 6.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for AstrixLibrary 1.1.1
File Interpreter ABI Platform
astrixlibrary-1.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 12.0 kB

Release files / astrixlibrary-1.1.1.tar.gz

Download URL astrixlibrary-1.1.1.tar.gz
Size 6.2 kB
Tags Source
SHA-256 checksum
How to use checksums
cdf98ee0412c3f2975d79ca1bb93d5491df278af62d75c3d16f4e6ed2c33d998
BLAKE2b-256 checksum
How to use checksums
79b0f2e6d6bc2b7f5a2e6917728fd1fe665df87f4e3fb027cecda340cdf72922
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.2

Release files / astrixlibrary-1.1.1-py3-none-any.whl

Download URL astrixlibrary-1.1.1-py3-none-any.whl
Size 5.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1015adb732f3c88e7448c41f4419e272cd900c675f0056f403947b4a7d6c4334
BLAKE2b-256 checksum
How to use checksums
9a503f1eb12fbdaff4eb1e35cf29249495fee9de9d05cd6c16cab3f138fda66a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.2

Release history Release notifications | RSS feed

This release

1.1.1 This release

2 release files

1.1

2 release files

1.0.3

2 release files

1.0.2

2 release files

1.0.1

2 release files

1.0.0

2 release files

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