style: restrict line-length

This commit is contained in:
Junyan Qin
2025-05-10 18:04:58 +08:00
parent b30016ed08
commit 055b389353
134 changed files with 1096 additions and 2595 deletions

View File

@@ -165,9 +165,7 @@ class APIHost:
langbot_version = ''
try:
langbot_version = (
self.ap.ver_mgr.get_current_version()
) # 从updater模块获取版本号
langbot_version = self.ap.ver_mgr.get_current_version() # 从updater模块获取版本号
except Exception:
return False
@@ -237,9 +235,7 @@ class EventContext:
message_source=self.event.query.message_event, message=message_chain
)
async def send_message(
self, target_type: str, target_id: str, message: platform_message.MessageChain
):
async def send_message(self, target_type: str, target_id: str, message: platform_message.MessageChain):
"""主动发送消息
Args:
@@ -247,9 +243,7 @@ class EventContext:
target_id (str): 目标ID
message (platform.types.MessageChain): 源平台的消息链,若用户使用的不是源平台适配器,程序也能自动转换为目标平台消息链
"""
await self.event.query.adapter.send_message(
target_type=target_type, target_id=target_id, message=message
)
await self.event.query.adapter.send_message(target_type=target_type, target_id=target_id, message=message)
def prevent_postorder(self):
"""阻止后续插件执行"""
@@ -378,8 +372,7 @@ class RuntimeContainer(pydantic.BaseModel):
'priority': self.priority,
'config_schema': self.config_schema,
'event_handlers': {
event_name.__name__: handler.__name__
for event_name, handler in self.event_handlers.items()
event_name.__name__: handler.__name__ for event_name, handler in self.event_handlers.items()
},
'tools': [
{

View File

@@ -58,9 +58,7 @@ class GitHubRepoInstaller(installer.PluginInstaller):
ssl=ssl_context, # 使用自定义SSL上下文来验证证书
) as resp:
if resp.status != 200:
raise errors.PluginInstallerError(
f'下载源码失败: {await resp.text()}'
)
raise errors.PluginInstallerError(f'下载源码失败: {await resp.text()}')
zip_resp = await resp.read()
if await aiofiles_os.path.exists('temp/' + target_path):
@@ -101,9 +99,7 @@ class GitHubRepoInstaller(installer.PluginInstaller):
):
"""安装插件"""
task_context.trace('下载插件源码...', 'install-plugin')
repo_label = await self.download_plugin_source_code(
plugin_source, 'plugins/', task_context
)
repo_label = await self.download_plugin_source_code(plugin_source, 'plugins/', task_context)
task_context.trace('安装插件依赖...', 'install-plugin')
await self.install_requirements('plugins/' + repo_label)
task_context.trace('完成.', 'install-plugin')

View File

@@ -35,16 +35,12 @@ class PluginLoader(loader.PluginLoader):
def register(
self, name: str, description: str, version: str, author: str
) -> typing.Callable[
[typing.Type[context.BasePlugin]], typing.Type[context.BasePlugin]
]:
) -> typing.Callable[[typing.Type[context.BasePlugin]], typing.Type[context.BasePlugin]]:
self.ap.logger.debug(f'注册插件 {name} {version} by {author}')
container = context.RuntimeContainer(
plugin_name=name,
plugin_label=discover_engine.I18nString(en_US=name, zh_CN=name),
plugin_description=discover_engine.I18nString(
en_US=description, zh_CN=description
),
plugin_description=discover_engine.I18nString(en_US=description, zh_CN=description),
plugin_version=version,
plugin_author=author,
plugin_repository='',
@@ -64,16 +60,12 @@ class PluginLoader(loader.PluginLoader):
# 过时
# 最早将于 v3.4 版本移除
def on(
self, event: typing.Type[events.BaseEventModel]
) -> typing.Callable[[typing.Callable], typing.Callable]:
def on(self, event: typing.Type[events.BaseEventModel]) -> typing.Callable[[typing.Callable], typing.Callable]:
"""注册过时的事件处理器"""
self.ap.logger.debug(f'注册事件处理器 {event.__name__}')
def wrapper(func: typing.Callable) -> typing.Callable:
async def handler(
plugin: context.BasePlugin, ctx: context.EventContext
) -> None:
async def handler(plugin: context.BasePlugin, ctx: context.EventContext) -> None:
args = {
'host': ctx.host,
'event': ctx,
@@ -104,15 +96,9 @@ class PluginLoader(loader.PluginLoader):
def wrapper(func: typing.Callable) -> typing.Callable:
function_schema = funcschema.get_func_schema(func)
function_name = (
self._current_container.plugin_name
+ '-'
+ (func.__name__ if name is None else name)
)
function_name = self._current_container.plugin_name + '-' + (func.__name__ if name is None else name)
async def handler(
plugin: context.BasePlugin, query: core_entities.Query, *args, **kwargs
):
async def handler(plugin: context.BasePlugin, query: core_entities.Query, *args, **kwargs):
return func(*args, **kwargs)
llm_function = tools_entities.LLMFunction(
@@ -129,9 +115,7 @@ class PluginLoader(loader.PluginLoader):
return wrapper
def handler(
self, event: typing.Type[events.BaseEventModel]
) -> typing.Callable[[typing.Callable], typing.Callable]:
def handler(self, event: typing.Type[events.BaseEventModel]) -> typing.Callable[[typing.Callable], typing.Callable]:
"""注册事件处理器"""
self.ap.logger.debug(f'注册事件处理器 {event.__name__}')
@@ -161,11 +145,7 @@ class PluginLoader(loader.PluginLoader):
return func
function_schema = funcschema.get_func_schema(func)
function_name = (
self._current_container.plugin_name
+ '-'
+ (func.__name__ if name is None else name)
)
function_name = self._current_container.plugin_name + '-' + (func.__name__ if name is None else name)
llm_function = tools_entities.LLMFunction(
name=function_name,
@@ -193,9 +173,7 @@ class PluginLoader(loader.PluginLoader):
else:
try:
self._current_pkg_path = 'plugins/' + path_prefix
self._current_module_path = (
'plugins/' + path_prefix + item.name + '.py'
)
self._current_module_path = 'plugins/' + path_prefix + item.name + '.py'
self._current_container = None
@@ -205,9 +183,7 @@ class PluginLoader(loader.PluginLoader):
self.plugins.append(self._current_container)
self.ap.logger.debug(f'插件 {self._current_container} 已加载')
except Exception:
self.ap.logger.error(
f'加载插件模块 {prefix + item.name} 时发生错误'
)
self.ap.logger.error(f'加载插件模块 {prefix + item.name} 时发生错误')
traceback.print_exc()
async def load_plugins(self):

View File

@@ -19,9 +19,7 @@ class PluginManifestLoader(loader.PluginLoader):
def __init__(self, ap: app.Application):
super().__init__(ap)
def handler(
self, event: typing.Type[events.BaseEventModel]
) -> typing.Callable[[typing.Callable], typing.Callable]:
def handler(self, event: typing.Type[events.BaseEventModel]) -> typing.Callable[[typing.Callable], typing.Callable]:
"""注册事件处理器"""
self.ap.logger.debug(f'注册事件处理器 {event.__name__}')
@@ -41,11 +39,7 @@ class PluginManifestLoader(loader.PluginLoader):
def wrapper(func: typing.Callable) -> typing.Callable:
function_schema = funcschema.get_func_schema(func)
function_name = (
self._current_container.plugin_name
+ '-'
+ (func.__name__ if name is None else name)
)
function_name = self._current_container.plugin_name + '-' + (func.__name__ if name is None else name)
llm_function = tools_entities.LLMFunction(
name=function_name,
@@ -70,11 +64,7 @@ class PluginManifestLoader(loader.PluginLoader):
for plugin_manifest in plugin_manifests:
try:
config_schema = (
plugin_manifest.spec['config']
if 'config' in plugin_manifest.spec
else []
)
config_schema = plugin_manifest.spec['config'] if 'config' in plugin_manifest.spec else []
current_plugin_container = context.RuntimeContainer(
plugin_name=plugin_manifest.metadata.name,
@@ -83,9 +73,7 @@ class PluginManifestLoader(loader.PluginLoader):
plugin_version=plugin_manifest.metadata.version,
plugin_author=plugin_manifest.metadata.author,
plugin_repository=plugin_manifest.metadata.repository,
main_file=os.path.join(
plugin_manifest.rel_dir, plugin_manifest.execution.python.path
),
main_file=os.path.join(plugin_manifest.rel_dir, plugin_manifest.execution.python.path),
pkg_path=plugin_manifest.rel_dir,
config_schema=config_schema,
event_handlers={},
@@ -104,7 +92,5 @@ class PluginManifestLoader(loader.PluginLoader):
self.plugins.append(current_plugin_container)
except Exception:
self.ap.logger.error(
f'加载插件 {plugin_manifest.metadata.name} 时发生错误'
)
self.ap.logger.error(f'加载插件 {plugin_manifest.metadata.name} 时发生错误')
traceback.print_exc()

View File

@@ -83,20 +83,12 @@ class PluginManager:
self.ap.logger.debug(f'优先级排序后的插件列表 {self.plugin_containers}')
async def load_plugin_settings(
self, plugin_containers: list[context.RuntimeContainer]
):
async def load_plugin_settings(self, plugin_containers: list[context.RuntimeContainer]):
for plugin_container in plugin_containers:
result = await self.ap.persistence_mgr.execute_async(
sqlalchemy.select(persistence_plugin.PluginSetting)
.where(
persistence_plugin.PluginSetting.plugin_author
== plugin_container.plugin_author
)
.where(
persistence_plugin.PluginSetting.plugin_name
== plugin_container.plugin_name
)
.where(persistence_plugin.PluginSetting.plugin_author == plugin_container.plugin_author)
.where(persistence_plugin.PluginSetting.plugin_name == plugin_container.plugin_name)
)
setting = result.first()
@@ -111,9 +103,7 @@ class PluginManager:
}
await self.ap.persistence_mgr.execute_async(
sqlalchemy.insert(persistence_plugin.PluginSetting).values(
**new_setting_data
)
sqlalchemy.insert(persistence_plugin.PluginSetting).values(**new_setting_data)
)
continue
else:
@@ -121,20 +111,12 @@ class PluginManager:
plugin_container.priority = setting.priority
plugin_container.plugin_config = setting.config
async def dump_plugin_container_setting(
self, plugin_container: context.RuntimeContainer
):
async def dump_plugin_container_setting(self, plugin_container: context.RuntimeContainer):
"""保存单个插件容器的设置到数据库"""
await self.ap.persistence_mgr.execute_async(
sqlalchemy.update(persistence_plugin.PluginSetting)
.where(
persistence_plugin.PluginSetting.plugin_author
== plugin_container.plugin_author
)
.where(
persistence_plugin.PluginSetting.plugin_name
== plugin_container.plugin_name
)
.where(persistence_plugin.PluginSetting.plugin_author == plugin_container.plugin_author)
.where(persistence_plugin.PluginSetting.plugin_name == plugin_container.plugin_name)
.values(
enabled=plugin_container.enabled,
priority=plugin_container.priority,
@@ -247,20 +229,14 @@ class PluginManager:
emitted_plugins: list[context.RuntimeContainer] = []
for plugin in self.plugins(
enabled=True, status=context.RuntimeContainerStatus.INITIALIZED
):
for plugin in self.plugins(enabled=True, status=context.RuntimeContainerStatus.INITIALIZED):
if event.__class__ in plugin.event_handlers:
self.ap.logger.debug(
f'插件 {plugin.plugin_name} 处理事件 {event.__class__.__name__}'
)
self.ap.logger.debug(f'插件 {plugin.plugin_name} 处理事件 {event.__class__.__name__}')
is_prevented_default_before_call = ctx.is_prevented_default()
try:
await plugin.event_handlers[event.__class__](
plugin.plugin_inst, ctx
)
await plugin.event_handlers[event.__class__](plugin.plugin_inst, ctx)
except Exception as e:
self.ap.logger.error(
f'插件 {plugin.plugin_name} 处理事件 {event.__class__.__name__} 时发生错误: {e}'
@@ -270,23 +246,17 @@ class PluginManager:
emitted_plugins.append(plugin)
if not is_prevented_default_before_call and ctx.is_prevented_default():
self.ap.logger.debug(
f'插件 {plugin.plugin_name} 阻止了默认行为执行'
)
self.ap.logger.debug(f'插件 {plugin.plugin_name} 阻止了默认行为执行')
if ctx.is_prevented_postorder():
self.ap.logger.debug(
f'插件 {plugin.plugin_name} 阻止了后序插件的执行'
)
self.ap.logger.debug(f'插件 {plugin.plugin_name} 阻止了后序插件的执行')
break
for key in ctx.__return_value__.keys():
if hasattr(ctx.event, key):
setattr(ctx.event, key, ctx.__return_value__[key][0])
self.ap.logger.debug(
f'事件 {event.__class__.__name__}({ctx.eid}) 处理完成,返回值 {ctx.__return_value__}'
)
self.ap.logger.debug(f'事件 {event.__class__.__name__}({ctx.eid}) 处理完成,返回值 {ctx.__return_value__}')
# TODO statistics
@@ -330,9 +300,7 @@ class PluginManager:
for plugin in self.plugin_containers:
await self.dump_plugin_container_setting(plugin)
async def set_plugin_config(
self, plugin_container: context.RuntimeContainer, new_config: dict
):
async def set_plugin_config(self, plugin_container: context.RuntimeContainer, new_config: dict):
plugin_container.plugin_config = new_config
plugin_container.plugin_inst.config = new_config