feat:继续重构插件api
This commit is contained in:
@@ -16,29 +16,36 @@ class DatabaseAPI:
|
||||
"""
|
||||
|
||||
async def store_action_info(
|
||||
self, action_build_into_prompt: bool = False, action_prompt_display: str = "", action_done: bool = True
|
||||
self,
|
||||
action_build_into_prompt: bool = False,
|
||||
action_prompt_display: str = "",
|
||||
action_done: bool = True,
|
||||
thinking_id: str = "",
|
||||
action_data: dict = None
|
||||
) -> None:
|
||||
"""存储action执行信息到数据库
|
||||
|
||||
"""存储action信息到数据库
|
||||
|
||||
Args:
|
||||
action_build_into_prompt: 是否构建到提示中
|
||||
action_prompt_display: 动作显示内容
|
||||
action_done: 动作是否已完成
|
||||
action_prompt_display: 显示的action提示信息
|
||||
action_done: action是否完成
|
||||
thinking_id: 思考ID
|
||||
action_data: action数据,如果不提供则使用空字典
|
||||
"""
|
||||
try:
|
||||
chat_stream = self._services.get("chat_stream")
|
||||
chat_stream = self.get_service("chat_stream")
|
||||
if not chat_stream:
|
||||
logger.error(f"{self.log_prefix} 无法存储action信息:缺少chat_stream服务")
|
||||
return
|
||||
|
||||
action_time = time.time()
|
||||
action_id = f"{action_time}_{self.thinking_id}"
|
||||
action_id = f"{action_time}_{thinking_id}"
|
||||
|
||||
ActionRecords.create(
|
||||
action_id=action_id,
|
||||
time=action_time,
|
||||
action_name=self.__class__.__name__,
|
||||
action_data=str(self.action_data),
|
||||
action_data=str(action_data or {}),
|
||||
action_done=action_done,
|
||||
action_build_into_prompt=action_build_into_prompt,
|
||||
action_prompt_display=action_prompt_display,
|
||||
|
||||
@@ -54,7 +54,10 @@ class PluginAPI(MessageAPI, LLMAPI, DatabaseAPI, ConfigAPI, UtilsAPI, StreamAPI,
|
||||
}
|
||||
|
||||
self.log_prefix = log_prefix
|
||||
|
||||
|
||||
# 存储action上下文信息
|
||||
self._action_context = {}
|
||||
|
||||
# 调用所有父类的初始化
|
||||
super().__init__()
|
||||
|
||||
@@ -88,6 +91,17 @@ class PluginAPI(MessageAPI, LLMAPI, DatabaseAPI, ConfigAPI, UtilsAPI, StreamAPI,
|
||||
"""检查是否有指定的服务对象"""
|
||||
return service_name in self._services and self._services[service_name] is not None
|
||||
|
||||
def set_action_context(self, thinking_id: str = None, shutting_down: bool = False, **kwargs):
|
||||
"""设置action上下文信息"""
|
||||
if thinking_id:
|
||||
self._action_context["thinking_id"] = thinking_id
|
||||
self._action_context["shutting_down"] = shutting_down
|
||||
self._action_context.update(kwargs)
|
||||
|
||||
def get_action_context(self, key: str, default=None):
|
||||
"""获取action上下文信息"""
|
||||
return self._action_context.get(key, default)
|
||||
|
||||
|
||||
# 便捷的工厂函数
|
||||
def create_plugin_api(
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
from typing import Optional, List, Dict, Any
|
||||
from typing import Optional, List, Dict, Any, Tuple
|
||||
from src.common.logger_manager import get_logger
|
||||
from src.chat.message_receive.chat_stream import ChatManager, ChatStream
|
||||
from src.chat.focus_chat.hfc_utils import parse_thinking_id_to_timestamp
|
||||
import asyncio
|
||||
|
||||
logger = get_logger("stream_api")
|
||||
|
||||
@@ -157,3 +159,62 @@ class StreamAPI:
|
||||
except Exception as e:
|
||||
logger.error(f"{self.log_prefix} 异步通过群ID获取聊天流时出错: {e}")
|
||||
return None
|
||||
|
||||
async def wait_for_new_message(self, timeout: int = 1200) -> Tuple[bool, str]:
|
||||
"""等待新消息或超时
|
||||
|
||||
Args:
|
||||
timeout: 超时时间(秒),默认1200秒
|
||||
|
||||
Returns:
|
||||
Tuple[bool, str]: (是否收到新消息, 空字符串)
|
||||
"""
|
||||
try:
|
||||
# 获取必要的服务对象
|
||||
observations = self.get_service("observations")
|
||||
if not observations:
|
||||
logger.warning(f"{self.log_prefix} 无法获取observations服务,无法等待新消息")
|
||||
return False, ""
|
||||
|
||||
# 获取第一个观察对象(通常是ChattingObservation)
|
||||
observation = observations[0] if observations else None
|
||||
if not observation:
|
||||
logger.warning(f"{self.log_prefix} 无观察对象,无法等待新消息")
|
||||
return False, ""
|
||||
|
||||
# 从action上下文获取thinking_id
|
||||
thinking_id = self.get_action_context("thinking_id")
|
||||
if not thinking_id:
|
||||
logger.warning(f"{self.log_prefix} 无thinking_id,无法等待新消息")
|
||||
return False, ""
|
||||
|
||||
logger.info(f"{self.log_prefix} 开始等待新消息... (超时: {timeout}秒)")
|
||||
|
||||
wait_start_time = asyncio.get_event_loop().time()
|
||||
while True:
|
||||
# 检查关闭标志
|
||||
shutting_down = self.get_action_context("shutting_down", False)
|
||||
if shutting_down:
|
||||
logger.info(f"{self.log_prefix} 等待新消息时检测到关闭信号,中断等待")
|
||||
return False, ""
|
||||
|
||||
# 检查新消息
|
||||
thinking_id_timestamp = parse_thinking_id_to_timestamp(thinking_id)
|
||||
if await observation.has_new_messages_since(thinking_id_timestamp):
|
||||
logger.info(f"{self.log_prefix} 检测到新消息")
|
||||
return True, ""
|
||||
|
||||
# 检查超时
|
||||
if asyncio.get_event_loop().time() - wait_start_time > timeout:
|
||||
logger.warning(f"{self.log_prefix} 等待新消息超时({timeout}秒)")
|
||||
return False, ""
|
||||
|
||||
# 短暂休眠
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
logger.info(f"{self.log_prefix} 等待新消息被中断 (CancelledError)")
|
||||
return False, ""
|
||||
except Exception as e:
|
||||
logger.error(f"{self.log_prefix} 等待新消息时发生错误: {e}")
|
||||
return False, f"等待新消息失败: {str(e)}"
|
||||
|
||||
@@ -11,8 +11,8 @@ class BaseAction(ABC):
|
||||
"""Action组件基类
|
||||
|
||||
Action是插件的一种组件类型,用于处理聊天中的动作逻辑
|
||||
|
||||
子类可以通过类属性定义激活条件:
|
||||
|
||||
子类可以通过类属性定义激活条件,这些会在实例化时转换为实例属性:
|
||||
- focus_activation_type: 专注模式激活类型
|
||||
- normal_activation_type: 普通模式激活类型
|
||||
- activation_keywords: 激活关键词列表
|
||||
@@ -22,18 +22,19 @@ class BaseAction(ABC):
|
||||
- random_activation_probability: 随机激活概率
|
||||
- llm_judge_prompt: LLM判断提示词
|
||||
"""
|
||||
|
||||
# 默认激活设置(子类可以覆盖)
|
||||
focus_activation_type: ActionActivationType = ActionActivationType.NEVER
|
||||
normal_activation_type: ActionActivationType = ActionActivationType.NEVER
|
||||
activation_keywords: list = []
|
||||
keyword_case_sensitive: bool = False
|
||||
mode_enable: ChatMode = ChatMode.ALL
|
||||
parallel_action: bool = True
|
||||
random_activation_probability: float = 0.0
|
||||
llm_judge_prompt: str = ""
|
||||
|
||||
def __init__(self, action_data: dict, reasoning: str, cycle_timers: dict, thinking_id: str, **kwargs):
|
||||
|
||||
def __init__(self,
|
||||
action_data: dict,
|
||||
reasoning: str,
|
||||
cycle_timers: dict,
|
||||
thinking_id: str,
|
||||
observations: list = None,
|
||||
expressor = None,
|
||||
replyer = None,
|
||||
chat_stream = None,
|
||||
log_prefix: str = "",
|
||||
shutting_down: bool = False,
|
||||
**kwargs):
|
||||
"""初始化Action组件
|
||||
|
||||
Args:
|
||||
@@ -41,26 +42,74 @@ class BaseAction(ABC):
|
||||
reasoning: 执行该动作的理由
|
||||
cycle_timers: 计时器字典
|
||||
thinking_id: 思考ID
|
||||
**kwargs: 其他参数(包含服务对象)
|
||||
observations: 观察列表
|
||||
expressor: 表达器对象
|
||||
replyer: 回复器对象
|
||||
chat_stream: 聊天流对象
|
||||
log_prefix: 日志前缀
|
||||
shutting_down: 是否正在关闭
|
||||
**kwargs: 其他参数
|
||||
"""
|
||||
self.action_data = action_data
|
||||
self.reasoning = reasoning
|
||||
self.cycle_timers = cycle_timers
|
||||
self.thinking_id = thinking_id
|
||||
|
||||
# 创建API实例
|
||||
self.log_prefix = log_prefix
|
||||
self.shutting_down = shutting_down
|
||||
|
||||
# 设置动作基本信息实例属性(兼容旧系统)
|
||||
self.action_name: str = getattr(self, 'action_name', self.__class__.__name__.lower().replace('action', ''))
|
||||
self.action_description: str = getattr(self, 'action_description', self.__doc__ or "Action组件")
|
||||
self.action_parameters: dict = getattr(self.__class__, 'action_parameters', {}).copy()
|
||||
self.action_require: list[str] = getattr(self.__class__, 'action_require', []).copy()
|
||||
|
||||
# 设置激活类型实例属性(从类属性复制,提供默认值)
|
||||
self.focus_activation_type: str = self._get_activation_type_value('focus_activation_type', 'never')
|
||||
self.normal_activation_type: str = self._get_activation_type_value('normal_activation_type', 'never')
|
||||
self.random_activation_probability: float = getattr(self.__class__, 'random_activation_probability', 0.0)
|
||||
self.llm_judge_prompt: str = getattr(self.__class__, 'llm_judge_prompt', "")
|
||||
self.activation_keywords: list[str] = getattr(self.__class__, 'activation_keywords', []).copy()
|
||||
self.keyword_case_sensitive: bool = getattr(self.__class__, 'keyword_case_sensitive', False)
|
||||
self.mode_enable: str = self._get_mode_value('mode_enable', 'all')
|
||||
self.parallel_action: bool = getattr(self.__class__, 'parallel_action', True)
|
||||
self.associated_types: list[str] = getattr(self.__class__, 'associated_types', []).copy()
|
||||
self.enable_plugin: bool = True # 默认启用
|
||||
|
||||
# 创建API实例,传递所有服务对象
|
||||
self.api = PluginAPI(
|
||||
chat_stream=kwargs.get("chat_stream"),
|
||||
expressor=kwargs.get("expressor"),
|
||||
replyer=kwargs.get("replyer"),
|
||||
observations=kwargs.get("observations"),
|
||||
log_prefix=kwargs.get("log_prefix", ""),
|
||||
chat_stream=chat_stream or kwargs.get("chat_stream"),
|
||||
expressor=expressor or kwargs.get("expressor"),
|
||||
replyer=replyer or kwargs.get("replyer"),
|
||||
observations=observations or kwargs.get("observations", []),
|
||||
log_prefix=log_prefix
|
||||
)
|
||||
|
||||
self.log_prefix = kwargs.get("log_prefix", "")
|
||||
|
||||
|
||||
# 设置API的action上下文
|
||||
self.api.set_action_context(
|
||||
thinking_id=thinking_id,
|
||||
shutting_down=shutting_down
|
||||
)
|
||||
|
||||
logger.debug(f"{self.log_prefix} Action组件初始化完成")
|
||||
|
||||
|
||||
def _get_activation_type_value(self, attr_name: str, default: str) -> str:
|
||||
"""获取激活类型的字符串值"""
|
||||
attr = getattr(self.__class__, attr_name, None)
|
||||
if attr is None:
|
||||
return default
|
||||
if hasattr(attr, 'value'):
|
||||
return attr.value
|
||||
return str(attr)
|
||||
|
||||
def _get_mode_value(self, attr_name: str, default: str) -> str:
|
||||
"""获取模式的字符串值"""
|
||||
attr = getattr(self.__class__, attr_name, None)
|
||||
if attr is None:
|
||||
return default
|
||||
if hasattr(attr, 'value'):
|
||||
return attr.value
|
||||
return str(attr)
|
||||
|
||||
async def send_reply(self, content: str) -> bool:
|
||||
"""发送回复消息
|
||||
|
||||
@@ -89,20 +138,38 @@ class BaseAction(ABC):
|
||||
name = cls.__name__.lower().replace("action", "")
|
||||
if description is None:
|
||||
description = cls.__doc__ or f"{cls.__name__} Action组件"
|
||||
description = description.strip().split("\n")[0] # 取第一行作为描述
|
||||
|
||||
description = description.strip().split('\n')[0] # 取第一行作为描述
|
||||
|
||||
# 安全获取激活类型值
|
||||
def get_enum_value(attr_name, default):
|
||||
attr = getattr(cls, attr_name, None)
|
||||
if attr is None:
|
||||
# 如果没有定义,返回默认的枚举值
|
||||
return getattr(ActionActivationType, default.upper(), ActionActivationType.NEVER)
|
||||
return attr
|
||||
|
||||
def get_mode_value(attr_name, default):
|
||||
attr = getattr(cls, attr_name, None)
|
||||
if attr is None:
|
||||
return getattr(ChatMode, default.upper(), ChatMode.ALL)
|
||||
return attr
|
||||
|
||||
return ActionInfo(
|
||||
name=name,
|
||||
component_type=ComponentType.ACTION,
|
||||
description=description,
|
||||
focus_activation_type=cls.focus_activation_type,
|
||||
normal_activation_type=cls.normal_activation_type,
|
||||
activation_keywords=cls.activation_keywords.copy() if cls.activation_keywords else [],
|
||||
keyword_case_sensitive=cls.keyword_case_sensitive,
|
||||
mode_enable=cls.mode_enable,
|
||||
parallel_action=cls.parallel_action,
|
||||
random_activation_probability=cls.random_activation_probability,
|
||||
llm_judge_prompt=cls.llm_judge_prompt,
|
||||
focus_activation_type=get_enum_value('focus_activation_type', 'never'),
|
||||
normal_activation_type=get_enum_value('normal_activation_type', 'never'),
|
||||
activation_keywords=getattr(cls, 'activation_keywords', []).copy(),
|
||||
keyword_case_sensitive=getattr(cls, 'keyword_case_sensitive', False),
|
||||
mode_enable=get_mode_value('mode_enable', 'all'),
|
||||
parallel_action=getattr(cls, 'parallel_action', True),
|
||||
random_activation_probability=getattr(cls, 'random_activation_probability', 0.0),
|
||||
llm_judge_prompt=getattr(cls, 'llm_judge_prompt', ""),
|
||||
# 使用正确的字段名
|
||||
action_parameters=getattr(cls, 'action_parameters', {}).copy(),
|
||||
action_require=getattr(cls, 'action_require', []).copy(),
|
||||
associated_types=getattr(cls, 'associated_types', []).copy()
|
||||
)
|
||||
|
||||
@abstractmethod
|
||||
@@ -113,3 +180,14 @@ class BaseAction(ABC):
|
||||
Tuple[bool, str]: (是否执行成功, 回复文本)
|
||||
"""
|
||||
pass
|
||||
|
||||
async def handle_action(self) -> Tuple[bool, str]:
|
||||
"""兼容旧系统的handle_action接口,委托给execute方法
|
||||
|
||||
为了保持向后兼容性,旧系统的代码可能会调用handle_action方法。
|
||||
此方法将调用委托给新的execute方法。
|
||||
|
||||
Returns:
|
||||
Tuple[bool, str]: (是否执行成功, 回复文本)
|
||||
"""
|
||||
return await self.execute()
|
||||
@@ -105,7 +105,7 @@ class BasePlugin(ABC):
|
||||
if file_ext == ".toml":
|
||||
with open(config_file_path, "r", encoding="utf-8") as f:
|
||||
self.config = toml.load(f) or {}
|
||||
logger.info(f"{self.log_prefix} 配置已从 {config_file_path} 加载")
|
||||
logger.debug(f"{self.log_prefix} 配置已从 {config_file_path} 加载")
|
||||
else:
|
||||
logger.warning(f"{self.log_prefix} 不支持的配置文件格式: {file_ext},仅支持 .toml")
|
||||
self.config = {}
|
||||
@@ -148,7 +148,7 @@ class BasePlugin(ABC):
|
||||
|
||||
# 注册插件
|
||||
if component_registry.register_plugin(self.plugin_info):
|
||||
logger.info(f"{self.log_prefix} 插件注册成功,包含 {len(registered_components)} 个组件")
|
||||
logger.debug(f"{self.log_prefix} 插件注册成功,包含 {len(registered_components)} 个组件")
|
||||
return True
|
||||
else:
|
||||
logger.error(f"{self.log_prefix} 插件注册失败")
|
||||
|
||||
@@ -69,8 +69,8 @@ class ComponentRegistry:
|
||||
self._register_action_component(component_info, component_class)
|
||||
elif component_type == ComponentType.COMMAND:
|
||||
self._register_command_component(component_info, component_class)
|
||||
|
||||
logger.info(f"已注册{component_type.value}组件: {component_name} ({component_class.__name__})")
|
||||
|
||||
logger.debug(f"已注册{component_type.value}组件: {component_name} ({component_class.__name__})")
|
||||
return True
|
||||
|
||||
def _register_action_component(self, action_info: ActionInfo, action_class: Type):
|
||||
@@ -185,7 +185,7 @@ class ComponentRegistry:
|
||||
return False
|
||||
|
||||
self._plugins[plugin_name] = plugin_info
|
||||
logger.info(f"已注册插件: {plugin_name} (组件数量: {len(plugin_info.components)})")
|
||||
logger.debug(f"已注册插件: {plugin_name} (组件数量: {len(plugin_info.components)})")
|
||||
return True
|
||||
|
||||
def get_plugin_info(self, plugin_name: str) -> Optional[PluginInfo]:
|
||||
@@ -215,7 +215,7 @@ class ComponentRegistry:
|
||||
component_info = self._components[component_name]
|
||||
if isinstance(component_info, ActionInfo):
|
||||
self._default_actions[component_name] = component_info.description
|
||||
logger.info(f"已启用组件: {component_name}")
|
||||
logger.debug(f"已启用组件: {component_name}")
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -226,7 +226,7 @@ class ComponentRegistry:
|
||||
# 如果是Action,从默认动作集中移除
|
||||
if component_name in self._default_actions:
|
||||
del self._default_actions[component_name]
|
||||
logger.info(f"已禁用组件: {component_name}")
|
||||
logger.debug(f"已禁用组件: {component_name}")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
from typing import Dict, List, Optional, Any
|
||||
from typing import Dict, List, Optional, Any, TYPE_CHECKING
|
||||
import os
|
||||
import importlib
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from src.plugin_system.base.base_plugin import BasePlugin
|
||||
|
||||
from src.common.logger_manager import get_logger
|
||||
from src.plugin_system.core.component_registry import component_registry
|
||||
from src.plugin_system.base.component_types import PluginInfo, ComponentType
|
||||
from src.plugin_system.base.component_types import ComponentType, PluginInfo
|
||||
|
||||
logger = get_logger("plugin_manager")
|
||||
|
||||
@@ -18,16 +22,17 @@ class PluginManager:
|
||||
|
||||
def __init__(self):
|
||||
self.plugin_directories: List[str] = []
|
||||
self.loaded_plugins: Dict[str, Any] = {}
|
||||
self.loaded_plugins: Dict[str, 'BasePlugin'] = {}
|
||||
self.failed_plugins: Dict[str, str] = {}
|
||||
|
||||
self.plugin_paths: Dict[str, str] = {} # 记录插件名到目录路径的映射
|
||||
|
||||
logger.info("插件管理器初始化完成")
|
||||
|
||||
def add_plugin_directory(self, directory: str):
|
||||
"""添加插件目录"""
|
||||
if os.path.exists(directory):
|
||||
self.plugin_directories.append(directory)
|
||||
logger.info(f"已添加插件目录: {directory}")
|
||||
logger.debug(f"已添加插件目录: {directory}")
|
||||
else:
|
||||
logger.warning(f"插件目录不存在: {directory}")
|
||||
|
||||
@@ -37,8 +42,8 @@ class PluginManager:
|
||||
Returns:
|
||||
tuple[int, int]: (插件数量, 组件数量)
|
||||
"""
|
||||
logger.info("开始加载所有插件...")
|
||||
|
||||
logger.debug("开始加载所有插件...")
|
||||
|
||||
# 第一阶段:加载所有插件模块(注册插件类)
|
||||
total_loaded_modules = 0
|
||||
total_failed_modules = 0
|
||||
@@ -47,9 +52,9 @@ class PluginManager:
|
||||
loaded, failed = self._load_plugin_modules_from_directory(directory)
|
||||
total_loaded_modules += loaded
|
||||
total_failed_modules += failed
|
||||
|
||||
logger.info(f"插件模块加载完成 - 成功: {total_loaded_modules}, 失败: {total_failed_modules}")
|
||||
|
||||
|
||||
logger.debug(f"插件模块加载完成 - 成功: {total_loaded_modules}, 失败: {total_failed_modules}")
|
||||
|
||||
# 第二阶段:实例化所有已注册的插件类
|
||||
from src.plugin_system.base.base_plugin import get_registered_plugin_classes, instantiate_and_register_plugin
|
||||
|
||||
@@ -58,25 +63,110 @@ class PluginManager:
|
||||
total_failed_registration = 0
|
||||
|
||||
for plugin_name, plugin_class in plugin_classes.items():
|
||||
# 尝试找到插件对应的目录
|
||||
plugin_dir = self._find_plugin_directory(plugin_class)
|
||||
|
||||
# 使用记录的插件目录路径
|
||||
plugin_dir = self.plugin_paths.get(plugin_name)
|
||||
|
||||
# 如果没有记录,则尝试查找(fallback)
|
||||
if not plugin_dir:
|
||||
plugin_dir = self._find_plugin_directory(plugin_class)
|
||||
if plugin_dir:
|
||||
self.plugin_paths[plugin_name] = plugin_dir
|
||||
|
||||
if instantiate_and_register_plugin(plugin_class, plugin_dir):
|
||||
total_registered += 1
|
||||
self.loaded_plugins[plugin_name] = plugin_class
|
||||
|
||||
# 📊 显示插件详细信息
|
||||
plugin_info = component_registry.get_plugin_info(plugin_name)
|
||||
if plugin_info:
|
||||
component_count = len(plugin_info.components)
|
||||
component_types = {}
|
||||
for comp in plugin_info.components:
|
||||
comp_type = comp.component_type.name
|
||||
component_types[comp_type] = component_types.get(comp_type, 0) + 1
|
||||
|
||||
components_str = ", ".join([f"{count}个{ctype}" for ctype, count in component_types.items()])
|
||||
logger.info(f"✅ 插件加载成功: {plugin_name} v{plugin_info.version} ({components_str}) - {plugin_info.description}")
|
||||
else:
|
||||
logger.info(f"✅ 插件加载成功: {plugin_name}")
|
||||
else:
|
||||
total_failed_registration += 1
|
||||
self.failed_plugins[plugin_name] = "插件注册失败"
|
||||
|
||||
logger.info(f"插件注册完成 - 成功: {total_registered}, 失败: {total_failed_registration}")
|
||||
|
||||
logger.error(f"❌ 插件加载失败: {plugin_name}")
|
||||
|
||||
# 获取组件统计信息
|
||||
stats = component_registry.get_registry_stats()
|
||||
logger.info(f"组件注册统计: {stats}")
|
||||
|
||||
|
||||
# 📋 显示插件加载总览
|
||||
if total_registered > 0:
|
||||
action_count = stats.get('action_components', 0)
|
||||
command_count = stats.get('command_components', 0)
|
||||
total_components = stats.get('total_components', 0)
|
||||
|
||||
logger.info("🎉 插件系统加载完成!")
|
||||
logger.info(f"📊 总览: {total_registered}个插件, {total_components}个组件 (Action: {action_count}, Command: {command_count})")
|
||||
|
||||
# 显示详细的插件列表
|
||||
logger.info("📋 已加载插件详情:")
|
||||
for plugin_name, plugin_class in self.loaded_plugins.items():
|
||||
plugin_info = component_registry.get_plugin_info(plugin_name)
|
||||
if plugin_info:
|
||||
# 插件基本信息
|
||||
version_info = f"v{plugin_info.version}" if plugin_info.version else ""
|
||||
author_info = f"by {plugin_info.author}" if plugin_info.author else ""
|
||||
info_parts = [part for part in [version_info, author_info] if part]
|
||||
extra_info = f" ({', '.join(info_parts)})" if info_parts else ""
|
||||
|
||||
logger.info(f" 📦 {plugin_name}{extra_info}")
|
||||
|
||||
# 组件列表
|
||||
if plugin_info.components:
|
||||
action_components = [c for c in plugin_info.components if c.component_type.name == 'ACTION']
|
||||
command_components = [c for c in plugin_info.components if c.component_type.name == 'COMMAND']
|
||||
|
||||
if action_components:
|
||||
action_names = [c.name for c in action_components]
|
||||
logger.info(f" 🎯 Action组件: {', '.join(action_names)}")
|
||||
|
||||
if command_components:
|
||||
command_names = [c.name for c in command_components]
|
||||
logger.info(f" ⚡ Command组件: {', '.join(command_names)}")
|
||||
|
||||
# 依赖信息
|
||||
if plugin_info.dependencies:
|
||||
logger.info(f" 🔗 依赖: {', '.join(plugin_info.dependencies)}")
|
||||
|
||||
# 配置文件信息
|
||||
if plugin_info.config_file:
|
||||
config_status = "✅" if self.plugin_paths.get(plugin_name) else "❌"
|
||||
logger.info(f" ⚙️ 配置: {plugin_info.config_file} {config_status}")
|
||||
|
||||
# 显示目录统计
|
||||
logger.info("📂 加载目录统计:")
|
||||
for directory in self.plugin_directories:
|
||||
if os.path.exists(directory):
|
||||
plugins_in_dir = []
|
||||
for plugin_name in self.loaded_plugins.keys():
|
||||
plugin_path = self.plugin_paths.get(plugin_name, "")
|
||||
if plugin_path.startswith(directory):
|
||||
plugins_in_dir.append(plugin_name)
|
||||
|
||||
if plugins_in_dir:
|
||||
logger.info(f" 📁 {directory}: {len(plugins_in_dir)}个插件 ({', '.join(plugins_in_dir)})")
|
||||
else:
|
||||
logger.info(f" 📁 {directory}: 0个插件")
|
||||
|
||||
# 失败信息
|
||||
if total_failed_registration > 0:
|
||||
logger.info(f"⚠️ 失败统计: {total_failed_registration}个插件加载失败")
|
||||
for failed_plugin, error in self.failed_plugins.items():
|
||||
logger.info(f" ❌ {failed_plugin}: {error}")
|
||||
else:
|
||||
logger.warning("😕 没有成功加载任何插件")
|
||||
|
||||
# 返回插件数量和组件数量
|
||||
return total_registered, stats.get("total_components", 0)
|
||||
|
||||
return total_registered, total_components
|
||||
|
||||
def _find_plugin_directory(self, plugin_class) -> Optional[str]:
|
||||
"""查找插件类对应的目录路径"""
|
||||
try:
|
||||
@@ -85,8 +175,8 @@ class PluginManager:
|
||||
module = inspect.getmodule(plugin_class)
|
||||
if module and hasattr(module, "__file__") and module.__file__:
|
||||
return os.path.dirname(module.__file__)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.debug(f"通过inspect获取插件目录失败: {e}")
|
||||
return None
|
||||
|
||||
def _load_plugin_modules_from_directory(self, directory: str) -> tuple[int, int]:
|
||||
@@ -97,16 +187,17 @@ class PluginManager:
|
||||
if not os.path.exists(directory):
|
||||
logger.warning(f"插件目录不存在: {directory}")
|
||||
return loaded_count, failed_count
|
||||
|
||||
logger.info(f"正在扫描插件目录: {directory}")
|
||||
|
||||
|
||||
logger.debug(f"正在扫描插件目录: {directory}")
|
||||
|
||||
# 遍历目录中的所有Python文件和包
|
||||
for item in os.listdir(directory):
|
||||
item_path = os.path.join(directory, item)
|
||||
|
||||
if os.path.isfile(item_path) and item.endswith(".py") and item != "__init__.py":
|
||||
# 单文件插件
|
||||
if self._load_plugin_module_file(item_path):
|
||||
plugin_name = Path(item_path).stem
|
||||
if self._load_plugin_module_file(item_path, plugin_name, directory):
|
||||
loaded_count += 1
|
||||
else:
|
||||
failed_count += 1
|
||||
@@ -115,17 +206,22 @@ class PluginManager:
|
||||
# 插件包
|
||||
plugin_file = os.path.join(item_path, "plugin.py")
|
||||
if os.path.exists(plugin_file):
|
||||
if self._load_plugin_module_file(plugin_file):
|
||||
plugin_name = item # 使用目录名作为插件名
|
||||
if self._load_plugin_module_file(plugin_file, plugin_name, item_path):
|
||||
loaded_count += 1
|
||||
else:
|
||||
failed_count += 1
|
||||
|
||||
return loaded_count, failed_count
|
||||
|
||||
def _load_plugin_module_file(self, plugin_file: str) -> bool:
|
||||
"""加载单个插件模块文件"""
|
||||
plugin_name = None
|
||||
|
||||
|
||||
def _load_plugin_module_file(self, plugin_file: str, plugin_name: str, plugin_dir: str) -> bool:
|
||||
"""加载单个插件模块文件
|
||||
|
||||
Args:
|
||||
plugin_file: 插件文件路径
|
||||
plugin_name: 插件名称
|
||||
plugin_dir: 插件目录路径
|
||||
"""
|
||||
# 生成模块名
|
||||
plugin_path = Path(plugin_file)
|
||||
if plugin_path.parent.name != "plugins":
|
||||
@@ -144,18 +240,17 @@ class PluginManager:
|
||||
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
# 模块加载成功,插件类会自动通过装饰器注册
|
||||
plugin_name = plugin_path.parent.name if plugin_path.parent.name != "plugins" else plugin_path.stem
|
||||
|
||||
|
||||
# 记录插件名和目录路径的映射
|
||||
self.plugin_paths[plugin_name] = plugin_dir
|
||||
|
||||
logger.debug(f"插件模块加载成功: {plugin_file}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"加载插件模块 {plugin_file} 失败: {e}"
|
||||
logger.error(error_msg)
|
||||
if plugin_name:
|
||||
self.failed_plugins[plugin_name] = error_msg
|
||||
self.failed_plugins[plugin_name] = error_msg
|
||||
return False
|
||||
|
||||
def get_loaded_plugins(self) -> List[PluginInfo]:
|
||||
@@ -174,7 +269,7 @@ class PluginManager:
|
||||
# 启用插件的所有组件
|
||||
for component in plugin_info.components:
|
||||
component_registry.enable_component(component.name)
|
||||
logger.info(f"已启用插件: {plugin_name}")
|
||||
logger.debug(f"已启用插件: {plugin_name}")
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -186,7 +281,7 @@ class PluginManager:
|
||||
# 禁用插件的所有组件
|
||||
for component in plugin_info.components:
|
||||
component_registry.disable_component(component.name)
|
||||
logger.info(f"已禁用插件: {plugin_name}")
|
||||
logger.debug(f"已禁用插件: {plugin_name}")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
Reference in New Issue
Block a user