|
| 1 | +from typing import TYPE_CHECKING, Any, MutableMapping |
| 2 | + |
| 3 | +import telethon as tg |
| 4 | + |
| 5 | +from .. import command, module, util |
| 6 | +from .bot_mixin_base import MixinBase |
| 7 | + |
| 8 | +if TYPE_CHECKING: |
| 9 | + from .bot import Bot |
| 10 | + |
| 11 | + |
| 12 | +class CommandDispatcher(MixinBase): |
| 13 | + # Initialized during instantiation |
| 14 | + commands: MutableMapping[str, command.Command] |
| 15 | + |
| 16 | + def __init__(self: "Bot", **kwargs: Any) -> None: |
| 17 | + # Initialize command map |
| 18 | + self.commands = {} |
| 19 | + |
| 20 | + # Propagate initialization to other mixins |
| 21 | + super().__init__(**kwargs) |
| 22 | + |
| 23 | + def register_command(self: "Bot", mod: module.Module, name: str, func: command.CommandFunc) -> None: |
| 24 | + cmd = command.Command(name, mod, func) |
| 25 | + |
| 26 | + if name in self.commands: |
| 27 | + orig = self.commands[name] |
| 28 | + raise module.ExistingCommandError(orig, cmd) |
| 29 | + |
| 30 | + self.commands[name] = cmd |
| 31 | + |
| 32 | + for alias in cmd.aliases: |
| 33 | + if alias in self.commands: |
| 34 | + orig = self.commands[alias] |
| 35 | + raise module.ExistingCommandError(orig, cmd, alias=True) |
| 36 | + |
| 37 | + self.commands[alias] = cmd |
| 38 | + |
| 39 | + def unregister_command(self: "Bot", cmd: command.Command) -> None: |
| 40 | + del self.commands[cmd.name] |
| 41 | + |
| 42 | + for alias in cmd.aliases: |
| 43 | + try: |
| 44 | + del self.commands[alias] |
| 45 | + except KeyError: |
| 46 | + continue |
| 47 | + |
| 48 | + def register_commands(self: "Bot", mod: module.Module) -> None: |
| 49 | + for name, func in util.find_prefixed_funcs(mod, "cmd_"): |
| 50 | + done = False |
| 51 | + |
| 52 | + try: |
| 53 | + self.register_command(mod, name, func) |
| 54 | + done = True |
| 55 | + finally: |
| 56 | + if not done: |
| 57 | + self.unregister_commands(mod) |
| 58 | + |
| 59 | + def unregister_commands(self: "Bot", mod: module.Module) -> None: |
| 60 | + # Can't unregister while iterating, so collect commands to unregister afterwards |
| 61 | + to_unreg = [] |
| 62 | + |
| 63 | + for name, cmd in self.commands.items(): |
| 64 | + # Let unregister_command deal with aliases |
| 65 | + if name != cmd.name: |
| 66 | + continue |
| 67 | + |
| 68 | + if cmd.module == mod: |
| 69 | + to_unreg.append(cmd) |
| 70 | + |
| 71 | + # Actually unregister the commands |
| 72 | + for cmd in to_unreg: |
| 73 | + self.unregister_command(cmd) |
| 74 | + |
| 75 | + def command_predicate(self: "Bot", event: tg.events.NewMessage.Event) -> bool: |
| 76 | + if event.raw_text.startswith(self.prefix): |
| 77 | + parts = event.raw_text.split() |
| 78 | + parts[0] = parts[0][len(self.prefix) :] |
| 79 | + |
| 80 | + event.segments = parts |
| 81 | + return True |
| 82 | + |
| 83 | + return False |
| 84 | + |
| 85 | + async def on_command(self: "Bot", msg: tg.events.NewMessage.Event) -> None: |
| 86 | + cmd = None |
| 87 | + |
| 88 | + try: |
| 89 | + # Attempt to get command info |
| 90 | + try: |
| 91 | + cmd = self.commands[msg.segments[0]] |
| 92 | + except KeyError: |
| 93 | + return |
| 94 | + |
| 95 | + # Construct invocation context |
| 96 | + ctx = command.Context(self, msg.message, msg.segments, len(self.prefix) + len(msg.segments[0]) + 1,) |
| 97 | + |
| 98 | + if not (cmd.usage is None or cmd.usage_optional or ctx.input): |
| 99 | + err_base = f"⚠️ Missing parameters: {cmd.usage}" |
| 100 | + |
| 101 | + if cmd.usage_reply: |
| 102 | + if msg.is_reply: |
| 103 | + reply_msg = await msg.get_reply_message() |
| 104 | + if reply_msg.text: |
| 105 | + ctx.input = reply_msg.text |
| 106 | + ctx.parsed_input = reply_msg.raw_text |
| 107 | + else: |
| 108 | + await ctx.respond(f"{err_base}\n__The message you replied to doesn't contain text.__") |
| 109 | + return |
| 110 | + else: |
| 111 | + await ctx.respond(f"{err_base} (replying is also supported)") |
| 112 | + return |
| 113 | + else: |
| 114 | + await ctx.respond(err_base) |
| 115 | + return |
| 116 | + |
| 117 | + # Invoke command function |
| 118 | + try: |
| 119 | + ret = await cmd.func(ctx) |
| 120 | + |
| 121 | + # Response shortcut |
| 122 | + if ret is not None: |
| 123 | + await ctx.respond(ret) |
| 124 | + except Exception as e: |
| 125 | + cmd.module.log.error(f"Error in command '{cmd.name}'", exc_info=e) |
| 126 | + await ctx.respond(f"⚠️ Error executing command:\n```{util.format_exception(e)}```") |
| 127 | + |
| 128 | + await self.dispatch_event("command", cmd, msg) |
| 129 | + except Exception as e: |
| 130 | + if cmd is not None: |
| 131 | + cmd.module.log.error("Error in command handler", exc_info=e) |
| 132 | + |
| 133 | + await self.respond(msg.message, f"⚠️ Error in command handler:\n```{util.format_exception(e)}```") |
0 commit comments