diff --git a/bot_callbacks.py b/bot_callbacks.py new file mode 100644 index 0000000..c637b9f --- /dev/null +++ b/bot_callbacks.py @@ -0,0 +1,71 @@ +"""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 = "Команды
" + for aliases in _COMMANDS: + result += f"
!{aliases[0]} - {html.escape(_COMMANDS[aliases][1])}" + 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, "Используйте !help") + 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) \ No newline at end of file diff --git a/main.py b/main.py index a5c3151..4b86cb7 100644 --- a/main.py +++ b/main.py @@ -8,24 +8,16 @@ import signal import html from pathlib import Path -import config -import util - from bot import MatrixBot from bot_types import MatrixBotConfig -import nio.events -from nio import MatrixRoom, RoomMessageText - from datatypes import AppConfig +import config +import util +import bot_callbacks bot: MatrixBot = None -async def callback_test_text(room: MatrixRoom, event: RoomMessageText) -> None: - if event.sender == bot.get_client().user_id: - return - await bot.send_text_to_room(room.room_id, f"{html.escape(event.body)}") - async def main() -> None: """Entry point""" global bot @@ -52,8 +44,7 @@ async def main() -> None: storage_directory=Path(cfg.store_dir) ) bot = MatrixBot(matrix_bot_config) - bot.add_event_callback(callback_test_text, RoomMessageText) - bot.add_event_callback(None, nio.events.Event) + bot_callbacks.setup(bot) # start the app bot.start()