DispelEvilBot/bot/commands_menu.py

61 lines
2.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Меню команд бота: латинские имена + русские описания.
Telegram разрешает в меню только ``a-z``, ``0-9`` и ``_``, поэтому русские
команды остаются доступны при вводе вручную, а в меню показываются алиасы.
"""
from __future__ import annotations
import logging
from aiogram import Bot
from aiogram.types import BotCommand
logger = logging.getLogger(__name__)
#: Ожидаемый набор команд в меню (порядок = порядок в Telegram).
BOT_COMMANDS: tuple[BotCommand, ...] = (
BotCommand(command="start", description="Начать"),
BotCommand(command="help", description="Помощь"),
BotCommand(command="info", description="Инфо"),
BotCommand(command="nick", description="Сменить ник"),
BotCommand(command="list", description="Список игроков"),
BotCommand(command="who", description="Кто это"),
BotCommand(command="purify", description="Очищение"),
BotCommand(command="eggs", description="Яички"),
BotCommand(command="shop", description="Магазин"),
BotCommand(command="top", description="Рейтинг"),
BotCommand(command="sub", description="Подписка"),
BotCommand(command="unsub", description="Отписка"),
)
def _key(commands: list[BotCommand]) -> list[tuple[str, str]]:
return [(command.command, command.description) for command in commands]
async def ensure_commands(bot: Bot) -> bool:
"""Сверить меню команд с ожидаемым и обновить при расхождении.
Возвращает ``True``, если набор пришлось обновить. Ошибки Telegram не
прерывают запуск бота — только пишутся в лог.
"""
try:
current = await bot.get_my_commands()
except Exception:
logger.warning("Не удалось прочитать меню команд Telegram", exc_info=True)
return False
if _key(current) == _key(list(BOT_COMMANDS)):
logger.info("Меню команд актуально (%s команд)", len(BOT_COMMANDS))
return False
try:
await bot.set_my_commands(list(BOT_COMMANDS))
except Exception:
logger.warning("Не удалось обновить меню команд Telegram", exc_info=True)
return False
logger.info("Меню команд обновлено (%s команд)", len(BOT_COMMANDS))
return True