Files
2026-matrix-csonac/bot_callbacks.py

84 lines
2.7 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.
"""Callbacks for matrix messages"""
import html
import traceback
from nio import MatrixRoom, RoomMessageText
from bot import MatrixBot
#
# PRIVATE
#
_bot: MatrixBot = None # ignore
def _generate_help_message() -> str:
"""Generates help message in HTML markup"""
result = "<b><i>Как использовать</i></b><ol>"
result += "<li>Используя <code>!auth</code>, создайте токен</li>"
result += "<li>Добавьте бота в комнату для уведомлений</li>"
result += "<li>Выполните <code>!info</code> в комнате, чтобы узнать код канала уведомений</li>"
result += "<li>Используя полученные токен и код канала, отправьте уведомление через веб-запрос</li>"
result += "</ol>"
result += "<br><br><b><i>Команды</i></b>"
for aliases in _COMMANDS:
result += f"<br><code>!{aliases[0]}</code> - <i>{html.escape(_COMMANDS[aliases][1])}</i>"
return result
#
# GENERIC EVENT HANDLERS
#
async def _on_text(room: MatrixRoom, event: RoomMessageText) -> None:
"""This callback is called when text message is received"""
if event.sender == _bot.get_client().user_id:
return
text = event.body
parts = [p for p in text.split() if p.strip()]
if len(parts) < 1:
return
cmd = parts[0].lower()
if not cmd.startswith("!"):
return
cb = None
for aliases in _COMMANDS:
for alias in aliases:
if alias == cmd.lstrip("!"):
cb = _COMMANDS[aliases][0]
break
if cb:
break
if cb is None:
await _bot.send_text_to_room(room.room_id, "<b>Используйте <code>!help</code></b>")
return
try:
await cb(room, parts[1:])
except:
traceback.print_exc()
#
# COMMAND HANDLERS
#
async def _on_cmd_help(room: MatrixRoom, args: list[str]) -> None:
"""!help"""
await _bot.send_text_to_room(room.room_id, _generate_help_message(), is_html=True)
async def _on_cmd_info(room: MatrixRoom, args: list[str]) -> None:
"""!info"""
response = "<b><i>Сведения о комнате</i></b><br>"
response += f"<b>channel: <b><code>{html.escape(room.room_id)}</code>"
await _bot.send_text_to_room(room.room_id, response, is_html=True)
_COMMANDS = {
("help", "?"): (_on_cmd_help, "Получить справку"),
("info", "room"): (_on_cmd_info, "Получить сведения о комнате"),
}
#
# PUBLIC
#
def setup(bot: MatrixBot) -> None:
"""Setup the callbacks"""
global _bot
_bot = bot
_bot.add_event_callback(_on_text, RoomMessageText)