From 3f929603fcfe5685d989a8cc67b2b583aad23ecd Mon Sep 17 00:00:00 2001 From: antares Date: Sat, 25 May 2024 21:10:07 +0800 Subject: [PATCH] fix: fix several bugs --- antares_bot/bot_inst.py | 2 +- antares_bot/module_loader.py | 27 +++++++++++++-------------- antares_bot/sqlite/manager.py | 10 ++++++---- 3 files changed, 20 insertions(+), 19 deletions(-) diff --git a/antares_bot/bot_inst.py b/antares_bot/bot_inst.py index 9ea8afc..4534f62 100644 --- a/antares_bot/bot_inst.py +++ b/antares_bot/bot_inst.py @@ -80,7 +80,7 @@ async def exception_handler(update: Any, context: RichCallbackContext): tb = format_traceback(err) log_text = f"{err.__class__}\n{err}\ntraceback:\n{tb}" _LOGGER.error(log_text) - text = Lang.t(Lang.UNKNOWN_ERROR) + f"{err.__class__}\n{err}" + text = Lang.t(Lang.UNKNOWN_ERROR) + f"\n{err.__class__}: {err}" await get_bot_instance().send_to(TelegramBot.get_master_id(), text) except Exception as _e: try: diff --git a/antares_bot/module_loader.py b/antares_bot/module_loader.py index 32b41b9..4deee43 100644 --- a/antares_bot/module_loader.py +++ b/antares_bot/module_loader.py @@ -1,12 +1,13 @@ +import importlib import os import sys from collections import defaultdict from typing import TYPE_CHECKING, Any, Callable, Dict, Generic, List, Optional, Type, TypeVar, cast +from antares_bot.bot_default_cfg import AntaresBotConfig from antares_bot.bot_logging import get_logger from antares_bot.module_base import TelegramBotModuleBase from antares_bot.utils import read_user_cfg -from antares_bot.bot_default_cfg import AntaresBotConfig if TYPE_CHECKING: @@ -69,6 +70,7 @@ def py_module(self): def __repr__(self) -> str: return f"TelegramBotModule: {self.top_name}" + class ModuleKeeper(object): _STR = 1 _TYPE = 2 @@ -162,9 +164,8 @@ def _remove_from_sorted_modules(self, module: TelegramBotModuleDesc[TelegramBotM @staticmethod def _import_all_modules() -> Dict[str, Type[TelegramBotModuleBase]]: - import importlib - def _module_check(_module, _module_top_name: str, module_store_name:str): + def _module_check(_module, _module_top_name: str, module_store_name: str): _names = _module_top_name.split("_") class_name = ''.join([name.capitalize() for name in _names]) kls = getattr(_module, class_name, None) @@ -180,17 +181,16 @@ def _module_check(_module, _module_top_name: str, module_store_name:str): def _import_module(_module_full_name: str): try: - if _module_full_name in sys.modules: - # reload - is_reload = True - module = importlib.reload(sys.modules[_module_full_name]) + if exist_module := sys.modules.get(_module_full_name): + exist = True + module = exist_module else: - is_reload = False + exist = False module = importlib.import_module(_module_full_name) except Exception as e: _LOGGER.error(e) return None - return is_reload, module + return exist, module skip_load_formatter = "SKIP_LOAD_MODULE_{}" skip_load_internal_formatter = "SKIP_LOAD_INTERNAL_MODULE_{}" @@ -228,14 +228,14 @@ def _load_up(_filename: str, is_internal: bool = False, _dirname: str | None = N _import_result = _import_module(module_full_name) if _import_result is None: return - is_reload, module = _import_result + exists, module = _import_result # check kls = _module_check(module, module_top_name, module_store_name) if kls is None: return # finalize - _load_str = "reloaded" if is_reload else "loaded" - _LOGGER.warning(f"{_load_str} module {module_store_name}") + if not exists: + _LOGGER.warning(f"loaded module {module_store_name}") # is_internal: e.g. internal_modules/test.py, internal_modules.test -> Test # not is_internal: e.g. modules/test.py, test -> Test # not is_internal: e.g. modules/sub_dir/sub_test.py, sub_test -> SubTest @@ -251,7 +251,7 @@ def _load_up(_filename: str, is_internal: bool = False, _dirname: str | None = N if filename.endswith(".py") and filename != "__init__.py": _load_up(filename, is_internal=True) continue - + # load user modules for dirname, _, filenames in os.walk("modules"): if dirname.endswith("__pycache__"): @@ -260,7 +260,6 @@ def _load_up(_filename: str, is_internal: bool = False, _dirname: str | None = N if filename.endswith(".py") and filename != "__init__.py": _load_up(filename, _dirname=dirname) continue - return ret diff --git a/antares_bot/sqlite/manager.py b/antares_bot/sqlite/manager.py index f2ec97b..9775d10 100644 --- a/antares_bot/sqlite/manager.py +++ b/antares_bot/sqlite/manager.py @@ -209,13 +209,16 @@ async def select_nolock( return await self.cursor.fetchall() async def insert_nolock(self, table: str, data_dicts: list[SqlRowDict] | SqlRowDict): + if not isinstance(data_dicts, list): + data_dicts = [data_dicts] + if len(data_dicts) == 0: + return + pks = self.get_primary_key_names(table) assert self.table_info columns = list(self.table_info[table].columns.keys()) - if not isinstance(data_dicts, list): - data_dicts = [data_dicts] one_value = "(" + ",".join(["?" for _ in columns]) + ")" many_values = ",\n".join([one_value for _ in data_dicts]) @@ -234,8 +237,7 @@ async def insert_nolock(self, table: str, data_dicts: list[SqlRowDict] | SqlRowD parse_args = [] for data_dict in data_dicts: - for col in columns: - parse_args.append(data_dict[col]) + parse_args.extend(data_dict.get(col) for col in columns) _LOGGER.debug("execute command %s with args: %s", insert_command, parse_args) self._last_command_and_args = (insert_command, parse_args)