From 3f1ca37e53989197026ad5094702ddb44f72dfe8 Mon Sep 17 00:00:00 2001 From: F4ria Date: Tue, 9 Jul 2024 23:07:40 +0800 Subject: [PATCH] Add priority attribute to handler, sort and load handler by priority. - Set a low load priority in handlers/useful.py to ensure it loads last. (ensure 'latest_handle_messages' registered last to prevent other commands from failing.) --- handlers/__init__.py | 10 +++++++++- handlers/useful.py | 5 ++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/handlers/__init__.py b/handlers/__init__.py index 5466dc9..a3ac5ff 100644 --- a/handlers/__init__.py +++ b/handlers/__init__.py @@ -22,6 +22,8 @@ markdown_symbol.link = "🔗" # If you want, Customizing the link symbol T = TypeVar("T", bound=Callable) +DEFAULT_LOAD_PRIORITY = 10 + BOT_MESSAGE_LENGTH = 4000 REPLY_MESSAGE_CACHE = ExpiringDict(max_len=1000, max_age_seconds=300) @@ -146,12 +148,18 @@ def wrap_handler(handler: T, bot: TeleBot) -> T: def load_handlers(bot: TeleBot, disable_commands: list[str]) -> None: # import all submodules + modules_with_priority = [] for name in list_available_commands(): if name in disable_commands: continue module = importlib.import_module(f".{name}", __package__) + load_priority = getattr(module, "load_priority", DEFAULT_LOAD_PRIORITY) + modules_with_priority.append((module, name, load_priority)) + + modules_with_priority.sort(key=lambda x: x[-1]) + for module, name, priority in modules_with_priority: if hasattr(module, "register"): - print(f"Loading {name} handlers.") + print(f"Loading {name} handlers with priority {priority}.") module.register(bot) print("Loading handlers done.") diff --git a/handlers/useful.py b/handlers/useful.py index 513669e..5b73637 100644 --- a/handlers/useful.py +++ b/handlers/useful.py @@ -13,6 +13,9 @@ from . import * from telegramify_markdown.customize import markdown_symbol +# Define the load priority, lower numbers have higher priority +load_priority = 1000 + # If you want, Customizing the head level 1 symbol markdown_symbol.head_level_1 = "📌" markdown_symbol.link = "🔗" # If you want, Customizing the link symbol @@ -196,7 +199,7 @@ def latest_handle_messages(message: Message, bot: TeleBot): elif message.text.startswith( ( "md", - "chatgpt", + "gpt", "gemini", "qwen", "map",