Skip to content

Commit

Permalink
fix: fix several bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
Antares0982 committed May 25, 2024
1 parent 9f763b9 commit 3f92960
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 19 deletions.
2 changes: 1 addition & 1 deletion antares_bot/bot_inst.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
27 changes: 13 additions & 14 deletions antares_bot/module_loader.py
Original file line number Diff line number Diff line change
@@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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_{}"
Expand Down Expand Up @@ -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
Expand All @@ -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__"):
Expand All @@ -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

Expand Down
10 changes: 6 additions & 4 deletions antares_bot/sqlite/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])

Expand All @@ -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)
Expand Down

0 comments on commit 3f92960

Please sign in to comment.