2020-03-16 21:02:05 -04:00
|
|
|
# SPDX-License-Identifier: GPL-2.0-or-later
|
2023-10-16 09:46:31 -04:00
|
|
|
|
|
|
|
from re import escape, search
|
|
|
|
|
|
|
|
from telethon import events
|
|
|
|
|
|
|
|
|
|
|
|
class CommandHandler():
|
2020-04-16 16:26:05 -04:00
|
|
|
def __init__(self, client, logger, settings):
|
|
|
|
self.pattern_template = "(?is)^{0}{1}(?: |$)(.*)"
|
2023-10-16 09:46:31 -04:00
|
|
|
self.outgoing_commands = {}
|
|
|
|
self.incoming_commands = {}
|
|
|
|
self.logger = logger
|
2020-04-16 16:26:05 -04:00
|
|
|
self.settings = settings
|
2023-10-16 09:46:31 -04:00
|
|
|
client.add_event_handler(self.handle_incoming, events.NewMessage(incoming=True))
|
|
|
|
|
2020-04-16 16:26:05 -04:00
|
|
|
async def handle_incoming(self, event):
|
|
|
|
prefix = escape(self.settings.get_config("cmd_prefix") or '.')
|
2023-10-16 09:46:31 -04:00
|
|
|
|
2020-04-16 16:26:05 -04:00
|
|
|
for key, value in self.incoming_commands.items():
|
|
|
|
pattern = self.pattern_template.format("" if value["noprefix"] else prefix, key)
|
2023-10-16 09:46:31 -04:00
|
|
|
|
2020-04-16 16:26:05 -04:00
|
|
|
if search(pattern, event.text):
|
|
|
|
event.pattern_match = search(pattern, event.text)
|
|
|
|
|
|
|
|
if value["sudo"] and str(event.from_id) != self.settings.get_config("owner_id"):
|
|
|
|
print(f"Attempted sudo command ({event.text}) from ID {event.from_id}")
|
|
|
|
return
|
2023-10-16 09:46:31 -04:00
|
|
|
|
|
|
|
try:
|
2020-04-16 16:26:05 -04:00
|
|
|
await value["function"](event)
|
2023-10-16 09:46:31 -04:00
|
|
|
return
|
|
|
|
except Exception as exception:
|
2020-04-16 16:26:05 -04:00
|
|
|
self.logger.warn(f"{value['function'].__name__} - {exception}")
|
|
|
|
await event.reply(f"`An error occurred in {value['function'].__name__}: {exception}`")
|
2020-02-23 15:04:44 -05:00
|
|
|
raise exception
|
2020-04-16 16:26:05 -04:00
|
|
|
|
|
|
|
break
|