Archived
1
0
Fork 0
This commit is contained in:
yzhh 2023-07-07 16:07:13 +08:00
parent 1e4c55026a
commit 2f4a27ffbf
3 changed files with 103 additions and 28 deletions

View file

@ -14,11 +14,15 @@ from core.types.module.component_meta import CommandMeta, RegexMeta, ScheduleMet
from core.utils.i18n import load_locale_file
load_dir_path = os.path.abspath('./modules/')
all_modules = []
current_unloaded_modules = []
err_modules = []
def load_modules():
unloaded_modules = Config('unloaded_modules')
if not unloaded_modules:
unloaded_modules = []
err_prompt = []
locale_err = load_locale_file()
if locale_err:
@ -38,8 +42,9 @@ def load_modules():
fun_file = file_name[:-3]
if fun_file is not None:
Logger.info(f'Loading modules.{fun_file}...')
all_modules.append(fun_file)
if fun_file in unloaded_modules:
Logger.info(f'Skipped modules.{fun_file}!')
Logger.warn(f'Skipped modules.{fun_file}!')
current_unloaded_modules.append(fun_file)
continue
modules = 'modules.' + fun_file
@ -50,6 +55,7 @@ def load_modules():
errmsg = f'Failed to load modules.{fun_file}: \n{tb}'
Logger.error(errmsg)
err_prompt.append(errmsg)
err_modules.append(fun_file)
loadercache = os.path.abspath(PrivateAssets.path + '/.cache_loader')
openloadercache = open(loadercache, 'w')
if err_prompt:
@ -160,12 +166,23 @@ class ModulesManager:
return False
modules = 'modules.' + module_name
if modules in sys.modules:
cls.return_py_module(module_name)
cls.reload_py_module(modules)
current_unloaded_modules.remove(module_name)
else:
importlib.import_module(modules)
Logger.info(f'Succeeded loaded modules.{module_name}!')
try:
importlib.import_module(modules)
Logger.info(f'Succeeded loaded modules.{module_name}!')
if module_name in err_modules:
err_modules.remove(module_name)
current_unloaded_modules.remove(module_name)
except Exception:
tb = traceback.format_exc()
errmsg = f'Failed to load modules.{module_name}: \n{tb}'
Logger.error(errmsg)
if module_name not in err_modules:
err_modules.append(module_name)
return False
cls._return_cache.clear()
current_unloaded_modules.remove(module_name)
return True
@classmethod
@ -177,7 +194,7 @@ class ModulesManager:
unbind_modules = cls.search_related_module(module_name)
cls.remove_modules(unbind_modules)
cls._return_cache.clear()
current_unloaded_modules.append(origin_module)
current_unloaded_modules.append(module_name)
return True
@classmethod
@ -195,9 +212,13 @@ class ModulesManager:
cnt += cls.reload_py_module(mod)
importlib.reload(module)
Logger.info(f'Succeeded reloaded {module_name}')
if (m := re.match(r'^modules(\.[a-zA-Z0-9_]*)?', module_name)) and m.group(1) in err_modules:
err_modules.remove(m.group(1))
return cnt + 1
except BaseException:
tb = traceback.format_exc()
errmsg = f'Failed to reload {module_name}: \n{tb}'
Logger.error(errmsg)
if (m := re.match(r'^modules(\.[a-zA-Z0-9_]*)?', module_name)) and m.group(1) not in err_modules:
err_modules.append(m.group(1))
return -999

View file

@ -8,7 +8,7 @@ from config import Config
from core.builtins import command_prefix, ExecutionLockList, ErrorMessage, MessageTaskManager, Url, Bot
from core.exceptions import AbuseWarning, FinishedException, InvalidCommandFormatError, InvalidHelpDocTypeError, \
WaitCancelException, NoReportException, SendMessageFailed
from core.loader import ModulesManager, current_unloaded_modules
from core.loader import ModulesManager, current_unloaded_modules, err_modules
from core.logger import Logger
from core.parser.command import CommandParser
from core.tos import warn_target
@ -346,6 +346,8 @@ async def parser(msg: Bot.MessageSession, require_enable_modules: bool = True, p
str(Url(Config('bug_report_url'))))
if command_first_word in current_unloaded_modules and msg.checkSuperUser():
await msg.sendMessage(f"{command_first_word} 当前未加载,使用 {msg.prefixes[0]}module load {command_first_word} 命令重新加载。")
elif command_first_word in err_modules:
await msg.sendMessage(f"{command_first_word} 模块加载失败,请联系开发者解决问题。")
return msg
if running_mention:

View file

@ -1,11 +1,11 @@
import re
import traceback
from config import Config
from config import Config, CFG
from core.builtins import Image, Plain, Bot
from core.component import module
from core.exceptions import InvalidHelpDocTypeError
from core.loader import ModulesManager
from core.loader import ModulesManager, current_unloaded_modules, err_modules
from core.parser.command import CommandParser
from core.utils.image_table import ImageTable, image_table_render
from database import BotDBUtil
@ -25,6 +25,8 @@ m = module('module',
'disable <module>... {{core.help.module.disable}}',
'disable all {{core.help.module.disable_all}}',
'reload <module> ... {{core.help.module.reload}}',
'load <module> ... {{core.help.module.load}}',
'unload <module> ... {{core.help.module.unload}}',
'list {{core.help.module.list}}'], exclude_from=['QQ|Guild'])
async def _(msg: Bot.MessageSession):
if msg.parsed_msg.get('list', False):
@ -32,11 +34,13 @@ async def _(msg: Bot.MessageSession):
await config_modules(msg)
@m.command(['enable <module>... {{core.help.module.enable}}',
@m.command(['enable <module> ... {{core.help.module.enable}}',
'enable all {{core.help.module.enable_all}}',
'disable <module>... {{core.help.module.disable}}',
'disable <module> ... {{core.help.module.disable}}',
'disable all {{core.help.module.disable_all}}',
'reload <module> ... {{core.help.module.reload}}',
'load <module> ... {{core.help.module.load}}',
'unload <module> ... {{core.help.module.unload}}',
'list {{core.help.module.list}}'], options_desc={'-g': '{core.help.option.tion.tion.tion.tion.module.g}'},
available_for=['QQ|Guild'])
async def _(msg: Bot.MessageSession):
@ -169,29 +173,77 @@ async def config_modules(msg: Bot.MessageSession):
return f'{msg.locale.t("core.message.module.reload.success", modules=module)}' + ('\n' if len(extra_modules) != 0 else '') + \
'\n'.join(extra_modules) + msg.locale.t("core.message.module.reload.with", reloadCnt=reloadCnt - 1)
elif reloadCnt == 1:
return f'{msg.locale.t("core.message.module.reload.success", modules=module)}' + ('\n' if len(extra_modules) != 0 else '') + \
'\n'.join(extra_modules) + msg.locale.t("core.message.module.reload.no_more")
return f'{msg.locale.t("core.message.module.reload.success", modules=module)}' + (
'\n' if len(extra_modules) != 0 else '') + '\n'.join(extra_modules) + msg.locale.t("core.message.module.reload.no_more")
else:
return f'{msg.locale.t("core.message.module.reload.failed")}'
if '-f' in msg.parsed_msg and msg.parsed_msg['-f']:
msglist.append(module_reload(module_))
elif module_ not in modules_:
msglist.append(msg.locale.t("core.message.module.reload.unbound", module=module_))
else:
if modules_[module_].base:
msglist.append(msg.locale.t("core.message.module.reload.base", module=module_))
for module_ in wait_config_list:
if '-f' in msg.parsed_msg and msg.parsed_msg['-f']:
msglist.append(module_reload(module_, []))
elif module_ not in modules_:
msglist.append(msg.locale.t("core.message.module.reload.unbound", module=module_))
else:
extra_reload_modules = ModulesManager.search_related_module(module_, False)
if len(extra_reload_modules):
confirm = await msg.waitConfirm(msg.locale.t("core.message.module.reload.confirm",
modules='\n'.join(extra_reload_modules)))
if not confirm:
await msg.finish()
return
msglist.append(module_reload(module_, extra_reload_modules))
if modules_[module_].base:
msglist.append(msg.locale.t("core.message.module.reload.base", module=module_))
else:
extra_reload_modules = ModulesManager.search_related_module(module_, False)
if len(extra_reload_modules):
confirm = await msg.waitConfirm(msg.locale.t("core.message.module.reload.confirm",
modules='\n'.join(extra_reload_modules)))
if not confirm:
continue
msglist.append(module_reload(module_, extra_reload_modules))
else:
msglist.append(msg.locale.t("core.message.module.reload.permission.denied"))
elif msg.parsed_msg.get('load', False):
if msg.checkSuperUser():
for module_ in wait_config_list:
if module_ not in current_unloaded_modules:
msglist.append("发生错误:该模块已经加载或不存在。")
continue
if ModulesManager.load_module(module_):
msglist.append("成功加载模块。")
unloaded_list = CFG.get('unloaded_modules')
if module_ in unloaded_list:
unloaded_list.remove(module_)
CFG.write('unloaded_modules', unloaded_list)
else:
msglist.append("发生错误:模块加载失败,请检查后台日志。")
else:
msglist.append(msg.locale.t("parser.superuser.permission.denied"))
elif msg.parsed_msg.get('unload', False):
if msg.checkSuperUser():
for module_ in wait_config_list:
if module_ not in modules_:
if module_ in err_modules:
if await msg.waitConfirm("此模块已经由于加载错误而无法加载,此操作将会在下一次重启后彻底禁用此模块,是否继续?"):
unloaded_list = CFG.get('unloaded_modules')
if not unloaded_list:
unloaded_list = []
unloaded_list.append(module_)
CFG.write('unloaded_modules', unloaded_list)
msglist.append("成功卸载模块。")
else:
msglist.append("发生错误:该模块不存在。")
continue
if await msg.waitConfirm("此操作将会卸载与其相关的所有模块,并在下一次重启后彻底禁用(不包含互相引用的模块),是否继续?"):
if ModulesManager.unload_module(module_):
msglist.append("成功卸载模块。")
unloaded_list = CFG.get('unloaded_modules')
if not unloaded_list:
unloaded_list = []
unloaded_list.append(module_)
CFG.write('unloaded_modules', unloaded_list)
else:
msglist.append(msg.locale.t("parser.superuser.permission.denied"))
if msglist is not None:
if not recommend_modules_help_doc_list:
await msg.finish('\n'.join(msglist))