Archived
1
0
Fork 0

remove unused function in loader

This commit is contained in:
yzhh 2023-04-19 16:29:46 +08:00
parent 76198e7ba2
commit f11b6c641a
5 changed files with 44 additions and 87 deletions

View file

@ -51,16 +51,23 @@ def load_modules():
openloadercache.write('')
openloadercache.close()
modules = ModulesManager.modules
for m in modules:
module = modules[m]
if module.alias:
ModulesManager.modules_aliases.update(module.alias)
class ModulesManager:
modules: Dict[str, Module] = {}
modulesOrigin: Dict[str, str] = {}
modules_aliases: Dict[str, str] = {}
modules_origin: Dict[str, str] = {}
@staticmethod
def add_module(module: Module, py_module_name: str):
if module.bind_prefix not in ModulesManager.modules:
ModulesManager.modules.update({module.bind_prefix: module})
ModulesManager.modulesOrigin.update({module.bind_prefix: py_module_name})
ModulesManager.modules_origin.update({module.bind_prefix: py_module_name})
else:
raise ValueError(f'Duplicate bind prefix "{module.bind_prefix}"')
@ -70,17 +77,17 @@ class ModulesManager:
if module in ModulesManager.modules:
Logger.info(f'Removing...{module}')
ModulesManager.modules.pop(module)
ModulesManager.modulesOrigin.pop(module)
ModulesManager.modules_origin.pop(module)
else:
raise ValueError(f'Module "{module}" is not exist')
@staticmethod
def search_related_module(module, includeSelf=True):
if module in ModulesManager.modulesOrigin:
if module in ModulesManager.modules_origin:
modules = []
py_module = ModulesManager.return_py_module(module)
for m in ModulesManager.modulesOrigin:
if ModulesManager.modulesOrigin[m].startswith(py_module):
for m in ModulesManager.modules_origin:
if ModulesManager.modules_origin[m].startswith(py_module):
modules.append(m)
if not includeSelf:
modules.remove(module)
@ -90,8 +97,8 @@ class ModulesManager:
@staticmethod
def return_py_module(module):
if module in ModulesManager.modulesOrigin:
return re.match(r'^modules(\.[a-zA-Z0-9_]*)?', ModulesManager.modulesOrigin[module]).group()
if module in ModulesManager.modules_origin:
return re.match(r'^modules(\.[a-zA-Z0-9_]*)?', ModulesManager.modules_origin[module]).group()
else:
return None
@ -119,58 +126,7 @@ class ModulesManager:
returns.update({m: ModulesManager.modules[m]})
return returns
return ModulesManager.modules
@staticmethod
def return_modules_alias_map() -> Dict[str, str]:
"""
返回每个别名映射到的模块
"""
modules = ModulesManager.return_modules_list_as_dict()
alias_map = {}
for m in modules:
module = modules[m]
if module.alias is not None:
alias_map.update(module.alias)
return alias_map
@staticmethod
def return_module_alias(module_name) -> Dict[str, str]:
"""
返回此模块的别名列表
"""
module = ModulesManager.return_modules_list_as_dict()[module_name]
if module.alias is None:
return {}
return module.alias
@staticmethod
def return_modules_developers_map() -> Dict[str, list]:
d = {}
modules = ModulesManager.return_modules_list_as_dict()
for m in modules:
module = modules[m]
if module.developers is not None:
d.update({m: module.developers})
return d
@staticmethod
def return_specified_type_modules(module_type: Module,
targetFrom: str = None) \
-> Dict[str, Module]:
d = {}
modules = ModulesManager.return_modules_list_as_dict()
for m in modules:
module = modules[m]
if isinstance(module, module_type):
if targetFrom is not None:
if isinstance(module, Module):
if targetFrom in module.exclude_from:
continue
if targetFrom in module.available_for or '*' in module.available_for:
d.update({m: module})
else:
d.update({module.bind_prefix: module})
return d
@staticmethod
def reload_module(module_name: str):

View file

@ -81,7 +81,6 @@ async def parser(msg: MessageSession, require_enable_modules: bool = True, prefi
try:
MessageTaskManager.check(msg)
modules = ModulesManager.return_modules_list_as_dict(msg.target.targetFrom)
modulesAliases = ModulesManager.return_modules_alias_map()
display = removeDuplicateSpace(msg.asDisplay()) # 将消息转换为一般显示形式
if len(display) == 0:
@ -138,12 +137,12 @@ async def parser(msg: MessageSession, require_enable_modules: bool = True, prefi
no_alias = True
if not no_alias: # 如果没有匹配到模块,则判断是否匹配命令别名
alias_list = []
for alias in modulesAliases:
if command.startswith(alias) and not command.startswith(modulesAliases[alias]):
for alias in ModulesManager.modules_aliases:
if command.startswith(alias) and not command.startswith(ModulesManager.modules_aliases[alias]):
alias_list.append(alias)
if alias_list:
max_ = max(alias_list, key=len)
command = command.replace(max_, modulesAliases[max_], 1)
command = command.replace(max_, ModulesManager.modules_aliases[max_], 1)
command_split: list = command.split(' ') # 切割消息
msg.trigger_msg = command # 触发该命令的消息,去除消息前缀
command_first_word = command_split[0].lower()

View file

@ -1,5 +1,4 @@
import re
import re
import traceback
from html import escape
from typing import List, Union

View file

@ -45,7 +45,7 @@ async def _(msg: Bot.MessageSession):
async def config_modules(msg: Bot.MessageSession):
alias = ModulesManager.return_modules_alias_map()
alias = ModulesManager.modules_aliases
modules_ = ModulesManager.return_modules_list_as_dict(
targetFrom=msg.target.targetFrom)
enabled_modules_list = BotDBUtil.TargetInfo(msg).enabled_modules
@ -221,7 +221,7 @@ hlp = module('help',
async def bot_help(msg: Bot.MessageSession):
module_list = ModulesManager.return_modules_list_as_dict(
targetFrom=msg.target.targetFrom)
alias = ModulesManager.return_modules_alias_map()
alias = ModulesManager.modules_aliases
if msg.parsed_msg is not None:
msgs = []
help_name = msg.parsed_msg['<module>']

View file

@ -6,35 +6,36 @@ from core.component import module
from core.exceptions import NoReportException
from core.utils.http import get_url
exchange_rate = module('exchange_rate',
desc='{exchange_rate.help.desc}',
alias={'exchangerate': 'exchange_rate',
exchange_rate = module('exchange_rate',
desc='{exchange_rate.help.desc}',
alias={'exchangerate': 'exchange_rate',
'excr': 'exchange_rate'},
developers=['DoroWolf'])
api_key = Config('exchange_rate_api_key')
@exchange_rate.command('<amount> <base> <target> {{exchange_rate.help}}')
async def _(msg: Bot.MessageSession):
base_currency = msg.parsed_msg['<base>'].upper()
target_currency = msg.parsed_msg['<target>'].upper()
# url = f'https://v6.exchangerate-api.com/v6/{api_key}/codes'
# response = requests.get(url)
# if response.status_code == 200:
# data = response.json()
# supported_currencies = data['supported_codes']
# unsupported_currencies = []
# if base_currency not in supported_currencies:
# unsupported_currencies.append(base_currency)
# if target_currency not in supported_currencies:
# unsupported_currencies.append(target_currency)
# if unsupported_currencies:
# await msg.finish(f"{msg.locale.t('exchange_rate.message.error.invalid')}{' '.join(unsupported_currencies)}")
# else:
# data = response.json()
# error_type = data['error-type']
# raise NoReportException(f"{error_type}")
# url = f'https://v6.exchangerate-api.com/v6/{api_key}/codes'
# response = requests.get(url)
# if response.status_code == 200:
# data = response.json()
# supported_currencies = data['supported_codes']
# unsupported_currencies = []
# if base_currency not in supported_currencies:
# unsupported_currencies.append(base_currency)
# if target_currency not in supported_currencies:
# unsupported_currencies.append(target_currency)
# if unsupported_currencies:
# await msg.finish(f"{msg.locale.t('exchange_rate.message.error.invalid')}{' '.join(unsupported_currencies)}")
# else:
# data = response.json()
# error_type = data['error-type']
# raise NoReportException(f"{error_type}")
amount = None
while amount is None:
@ -52,7 +53,9 @@ async def _(msg: Bot.MessageSession):
data = response.json()
exchange_rate = data['conversion_result']
current_time = datetime.datetime.now().strftime("%Y-%m-%d")
await msg.finish(msg.locale.t('exchange_rate.message', amount=amount, base=base_currency, exchange_rate=exchange_rate, target=target_currency, time=current_time))
await msg.finish(
msg.locale.t('exchange_rate.message', amount=amount, base=base_currency, exchange_rate=exchange_rate,
target=target_currency, time=current_time))
else:
data = response.json()
error_type = data['error-type']