Files
2026-matrix-csonac/bot_callbacks.py

71 lines
1.7 KiB
Python

"""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><br>"
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)
_COMMANDS = {
("help", "?"): (_on_cmd_help, "Получить справку")
}
#
# PUBLIC
#
def setup(bot: MatrixBot) -> None:
"""Setup the callbacks"""
global _bot
_bot = bot
_bot.add_event_callback(_on_text, RoomMessageText)