调整目录结构,将框架内容放到base里面
This commit is contained in:
0
base/__init__.py
Normal file
0
base/__init__.py
Normal file
1
base/event_system/__init__.py
Normal file
1
base/event_system/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
# 事件系统包初始化文件
|
||||
62
base/event_system/event_manager.py
Normal file
62
base/event_system/event_manager.py
Normal file
@@ -0,0 +1,62 @@
|
||||
from loguru import logger
|
||||
from typing import Dict, List, Type, Callable, Any
|
||||
from threading import Lock
|
||||
|
||||
|
||||
class Event:
|
||||
"""事件基类"""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
for key, value in kwargs.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
|
||||
class EventManager:
|
||||
"""事件管理器,单例模式"""
|
||||
_instance = None
|
||||
_lock = Lock()
|
||||
|
||||
@classmethod
|
||||
def get_instance(cls):
|
||||
"""获取事件管理器实例"""
|
||||
if cls._instance is None:
|
||||
with cls._lock:
|
||||
if cls._instance is None:
|
||||
cls._instance = cls()
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
if EventManager._instance is not None:
|
||||
raise RuntimeError("EventManager 是单例类,请使用 get_instance() 方法获取实例")
|
||||
|
||||
self.handlers: Dict[Type[Event], List[Callable]] = {}
|
||||
self.LOG = logger
|
||||
|
||||
def register(self, event_type: Type[Event], handler: Callable) -> None:
|
||||
"""注册事件处理器"""
|
||||
if event_type not in self.handlers:
|
||||
self.handlers[event_type] = []
|
||||
|
||||
if handler not in self.handlers[event_type]:
|
||||
self.handlers[event_type].append(handler)
|
||||
self.LOG.debug(f"注册事件处理器: {event_type.__name__} -> {handler.__name__}")
|
||||
|
||||
def unregister(self, event_type: Type[Event], handler: Callable) -> None:
|
||||
"""取消注册事件处理器"""
|
||||
if event_type in self.handlers and handler in self.handlers[event_type]:
|
||||
self.handlers[event_type].remove(handler)
|
||||
self.LOG.debug(f"取消注册事件处理器: {event_type.__name__} -> {handler.__name__}")
|
||||
|
||||
def publish(self, event_type: Type[Event], event_data: Dict[str, Any] = None) -> None:
|
||||
"""发布事件"""
|
||||
if event_data is None:
|
||||
event_data = {}
|
||||
|
||||
event = event_type(**event_data)
|
||||
|
||||
if event_type in self.handlers:
|
||||
for handler in self.handlers[event_type]:
|
||||
try:
|
||||
handler(event)
|
||||
except Exception as e:
|
||||
self.LOG.error(f"事件处理器 {handler.__name__} 处理 {event_type.__name__} 事件出错: {e}")
|
||||
0
base/event_system/events/__init__.py
Normal file
0
base/event_system/events/__init__.py
Normal file
58
base/event_system/events/plugin_events.py
Normal file
58
base/event_system/events/plugin_events.py
Normal file
@@ -0,0 +1,58 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, Any, Optional
|
||||
from datetime import datetime
|
||||
|
||||
from base.event_system.event_manager import Event
|
||||
|
||||
|
||||
@dataclass
|
||||
class PluginCallStartEvent(Event):
|
||||
"""插件调用开始事件"""
|
||||
plugin_name: str # 插件名称
|
||||
command: str # 触发的命令
|
||||
full_command: str # 完整命令内容
|
||||
user_id: str # 用户ID
|
||||
group_id: Optional[str] = None # 群组ID,私聊为None
|
||||
is_group: bool = False # 是否群聊
|
||||
message: Dict[str, Any] = None # 原始消息内容
|
||||
timestamp: datetime = None # 事件时间戳
|
||||
|
||||
def __post_init__(self):
|
||||
if self.timestamp is None:
|
||||
self.timestamp = datetime.now()
|
||||
|
||||
|
||||
@dataclass
|
||||
class PluginCallEndEvent(Event):
|
||||
"""插件调用结束事件"""
|
||||
plugin_name: str # 插件名称
|
||||
command: str # 触发的命令
|
||||
user_id: str # 用户ID
|
||||
group_id: Optional[str] = None # 群组ID,私聊为None
|
||||
is_group: bool = False # 是否群聊
|
||||
process_result: bool = True # 处理结果:True成功,False失败
|
||||
result_message: Optional[str] = None # 处理结果消息
|
||||
process_time: int = 0 # 处理耗时(毫秒)
|
||||
timestamp: datetime = None # 事件时间戳
|
||||
|
||||
def __post_init__(self):
|
||||
if self.timestamp is None:
|
||||
self.timestamp = datetime.now()
|
||||
|
||||
|
||||
@dataclass
|
||||
class PluginCallErrorEvent(Event):
|
||||
"""插件调用错误事件"""
|
||||
plugin_name: str # 插件名称
|
||||
command: str # 触发的命令
|
||||
user_id: str # 用户ID
|
||||
group_id: Optional[str] # 群组ID,私聊为None
|
||||
is_group: bool # 是否群聊
|
||||
error_message: str # 错误信息
|
||||
stack_trace: Optional[str] = None # 堆栈跟踪
|
||||
process_time: int = 0 # 处理耗时(毫秒)
|
||||
timestamp: datetime = None # 事件时间戳
|
||||
|
||||
def __post_init__(self):
|
||||
if self.timestamp is None:
|
||||
self.timestamp = datetime.now()
|
||||
0
base/plugin_common/__init__.py
Normal file
0
base/plugin_common/__init__.py
Normal file
85
base/plugin_common/event_system.py
Normal file
85
base/plugin_common/event_system.py
Normal file
@@ -0,0 +1,85 @@
|
||||
from enum import Enum, auto
|
||||
from typing import Dict, Any, Callable, List
|
||||
import threading
|
||||
|
||||
|
||||
class EventType(Enum):
|
||||
"""事件类型枚举"""
|
||||
SYSTEM_STARTUP = auto()
|
||||
SYSTEM_SHUTDOWN = auto()
|
||||
PLUGIN_LOADED = auto()
|
||||
PLUGIN_UNLOADED = auto()
|
||||
MESSAGE_RECEIVED = auto()
|
||||
MESSAGE_PROCESSED = auto()
|
||||
CUSTOM_EVENT = auto()
|
||||
|
||||
|
||||
class EventSystem:
|
||||
"""事件系统,用于插件间通信"""
|
||||
_instance = None
|
||||
_lock = threading.Lock()
|
||||
|
||||
def __new__(cls):
|
||||
with cls._lock:
|
||||
if cls._instance is None:
|
||||
cls._instance = super(EventSystem, cls).__new__(cls)
|
||||
cls._instance._subscribers = {}
|
||||
cls._instance._initialized = False
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
if not self._initialized:
|
||||
self._subscribers = {}
|
||||
self._initialized = True
|
||||
|
||||
def subscribe(self, event_type: EventType, callback: Callable[[Dict[str, Any]], None]) -> None:
|
||||
"""
|
||||
订阅事件
|
||||
|
||||
Args:
|
||||
event_type: 事件类型
|
||||
callback: 回调函数,接收事件数据
|
||||
"""
|
||||
if event_type not in self._subscribers:
|
||||
self._subscribers[event_type] = []
|
||||
|
||||
if callback not in self._subscribers[event_type]:
|
||||
self._subscribers[event_type].append(callback)
|
||||
|
||||
def unsubscribe(self, event_type: EventType, callback: Callable[[Dict[str, Any]], None]) -> None:
|
||||
"""
|
||||
取消订阅事件
|
||||
|
||||
Args:
|
||||
event_type: 事件类型
|
||||
callback: 回调函数
|
||||
"""
|
||||
if event_type in self._subscribers and callback in self._subscribers[event_type]:
|
||||
self._subscribers[event_type].remove(callback)
|
||||
|
||||
def publish(self, event_type: EventType, data: Dict[str, Any]) -> None:
|
||||
"""
|
||||
发布事件
|
||||
|
||||
Args:
|
||||
event_type: 事件类型
|
||||
data: 事件数据
|
||||
"""
|
||||
if event_type in self._subscribers:
|
||||
for callback in self._subscribers[event_type]:
|
||||
try:
|
||||
callback(data)
|
||||
except Exception as e:
|
||||
print(f"事件处理错误: {e}")
|
||||
|
||||
def get_subscribers(self, event_type: EventType) -> List[Callable]:
|
||||
"""
|
||||
获取事件订阅者
|
||||
|
||||
Args:
|
||||
event_type: 事件类型
|
||||
|
||||
Returns:
|
||||
订阅者列表
|
||||
"""
|
||||
return self._subscribers.get(event_type, [])
|
||||
53
base/plugin_common/message_plugin_interface.py
Normal file
53
base/plugin_common/message_plugin_interface.py
Normal file
@@ -0,0 +1,53 @@
|
||||
from typing import Dict, Any, Tuple, Optional, List
|
||||
from base.plugin_common.plugin_interface import PluginInterface
|
||||
from wechat_ipad import WechatAPIClient
|
||||
|
||||
|
||||
class MessagePluginInterface(PluginInterface):
|
||||
"""消息处理插件接口"""
|
||||
|
||||
@property
|
||||
def command_prefix(self) -> Optional[str]:
|
||||
"""命令前缀,如 '/'"""
|
||||
return None
|
||||
|
||||
@property
|
||||
def commands(self) -> List[str]:
|
||||
"""支持的命令列表"""
|
||||
return []
|
||||
|
||||
# 需要完成jobs 的业务,所以完成bot注入
|
||||
def set_bot(self, bot: WechatAPIClient) -> None:
|
||||
self.bot: WechatAPIClient = bot
|
||||
|
||||
def can_process(self, message: Dict[str, Any]) -> bool:
|
||||
"""
|
||||
检查插件是否可以处理该消息
|
||||
|
||||
Args:
|
||||
message: 消息字典,包含消息的各种属性
|
||||
|
||||
Returns:
|
||||
是否可以处理
|
||||
"""
|
||||
# 默认实现:检查是否是命令
|
||||
if self.command_prefix and self.commands:
|
||||
content = message.get("content", "")
|
||||
if content.startswith(self.command_prefix):
|
||||
command = content[len(self.command_prefix):].split()[0]
|
||||
return command in self.commands
|
||||
return False
|
||||
|
||||
def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""
|
||||
处理消息
|
||||
|
||||
Args:
|
||||
message: 消息字典,包含消息的各种属性,以及发送消息所需的对象
|
||||
- wcf: WcfAPI对象,可用于发送消息
|
||||
- message_util: 消息工具类,提供更高级的消息处理功能
|
||||
|
||||
Returns:
|
||||
(是否已处理, 处理结果)
|
||||
"""
|
||||
raise NotImplementedError("子类必须实现此方法")
|
||||
203
base/plugin_common/plugin_interface.py
Normal file
203
base/plugin_common/plugin_interface.py
Normal file
@@ -0,0 +1,203 @@
|
||||
import os
|
||||
import toml
|
||||
from abc import ABC, abstractmethod
|
||||
from loguru import logger
|
||||
from enum import Enum
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
|
||||
|
||||
class PluginStatus(Enum):
|
||||
"""插件状态枚举"""
|
||||
UNLOADED = 0 # 未加载
|
||||
LOADED = 1 # 已加载但未启动
|
||||
RUNNING = 2 # 运行中
|
||||
STOPPED = 3 # 已停止
|
||||
ERROR = 4 # 错误状态
|
||||
|
||||
|
||||
class PluginInterface(ABC):
|
||||
"""插件基础接口,所有插件必须实现此接口"""
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def name(self) -> str:
|
||||
"""插件名称"""
|
||||
pass
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def version(self) -> str:
|
||||
"""插件版本"""
|
||||
pass
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def description(self) -> str:
|
||||
"""插件描述"""
|
||||
pass
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def author(self) -> str:
|
||||
"""插件作者"""
|
||||
pass
|
||||
|
||||
@property
|
||||
def dependencies(self) -> List[str]:
|
||||
"""插件依赖,返回依赖的其他插件名称列表"""
|
||||
return []
|
||||
|
||||
@property
|
||||
def status(self) -> PluginStatus:
|
||||
"""获取插件当前状态"""
|
||||
return self._status
|
||||
|
||||
@status.setter
|
||||
def status(self, value: PluginStatus):
|
||||
"""设置插件状态"""
|
||||
self._status = value
|
||||
|
||||
def __init__(self):
|
||||
"""初始化插件"""
|
||||
self._status = PluginStatus.UNLOADED
|
||||
self._config = {}
|
||||
self._plugin_path = ""
|
||||
# 初始化日志记录器
|
||||
self.LOG = logger
|
||||
self.bot = None
|
||||
|
||||
def load_config(self) -> bool:
|
||||
"""
|
||||
从插件目录下的config.toml加载配置
|
||||
|
||||
Returns:
|
||||
加载是否成功
|
||||
"""
|
||||
try:
|
||||
config_path = os.path.join(self._plugin_path, "config.toml")
|
||||
if os.path.exists(config_path):
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
plugin_config = toml.load(f)
|
||||
self.LOG.debug(f"从 {config_path} 加载插件{self.name}配置:{plugin_config}")
|
||||
self._config.update(plugin_config)
|
||||
self.LOG.debug(f"从 {config_path} 加载插件配置成功")
|
||||
return True
|
||||
else:
|
||||
self.LOG.info(f"插件配置文件 {config_path} 不存在,使用默认配置")
|
||||
return True # 配置文件不存在也视为成功,使用默认配置
|
||||
except Exception as e:
|
||||
self.LOG.info(f"加载插件配置失败: {e}")
|
||||
return False
|
||||
|
||||
def set_plugin_path(self, path: str) -> None:
|
||||
"""
|
||||
设置插件路径
|
||||
|
||||
Args:
|
||||
path: 插件路径
|
||||
"""
|
||||
self._plugin_path = path
|
||||
|
||||
def get_plugin_path(self) -> str:
|
||||
"""
|
||||
获取插件路径
|
||||
|
||||
Returns:
|
||||
插件路径
|
||||
"""
|
||||
return self._plugin_path
|
||||
|
||||
@abstractmethod
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""
|
||||
初始化插件
|
||||
|
||||
Args:
|
||||
context: 插件上下文,包含系统环境和配置信息
|
||||
|
||||
Returns:
|
||||
初始化是否成功
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def start(self) -> bool:
|
||||
"""
|
||||
启动插件
|
||||
|
||||
Returns:
|
||||
启动是否成功
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def stop(self) -> bool:
|
||||
"""
|
||||
停止插件
|
||||
|
||||
Returns:
|
||||
停止是否成功
|
||||
"""
|
||||
pass
|
||||
|
||||
def configure(self, config: Dict[str, Any]) -> bool:
|
||||
"""
|
||||
配置插件
|
||||
|
||||
Args:
|
||||
config: 插件配置
|
||||
|
||||
Returns:
|
||||
配置是否成功
|
||||
"""
|
||||
self._config.update(config)
|
||||
return True
|
||||
|
||||
def get_config(self) -> Dict[str, Any]:
|
||||
"""
|
||||
获取插件配置
|
||||
|
||||
Returns:
|
||||
插件配置
|
||||
"""
|
||||
return self._config
|
||||
|
||||
def cleanup(self) -> bool:
|
||||
"""
|
||||
清理插件资源,在卸载前调用
|
||||
|
||||
Returns:
|
||||
清理是否成功
|
||||
"""
|
||||
return True
|
||||
|
||||
def get_config_path(self) -> str:
|
||||
return os.path.join(self._plugin_path, 'config.toml')
|
||||
|
||||
def can_process(self, data: Any) -> bool:
|
||||
"""检查插件是否可以处理给定的数据
|
||||
|
||||
这是一个通用方法,用于检查插件是否可以处理特定类型的数据。
|
||||
子类可以根据需要重写此方法。
|
||||
|
||||
Args:
|
||||
data: 要检查的数据
|
||||
|
||||
Returns:
|
||||
如果插件可以处理该数据,则返回True,否则返回False
|
||||
"""
|
||||
return False
|
||||
|
||||
async def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""
|
||||
处理消息
|
||||
|
||||
Args:
|
||||
message: 消息字典,包含消息的各种属性,以及发送消息所需的对象
|
||||
- wcf: WcfAPI对象,可用于发送消息
|
||||
- message_util: 消息工具类,提供更高级的消息处理功能
|
||||
|
||||
Returns:
|
||||
(是否已处理, 处理结果)
|
||||
"""
|
||||
raise NotImplementedError("子类必须实现此方法")
|
||||
585
base/plugin_common/plugin_manager.py
Normal file
585
base/plugin_common/plugin_manager.py
Normal file
@@ -0,0 +1,585 @@
|
||||
import importlib
|
||||
import inspect
|
||||
import os
|
||||
import sys
|
||||
from typing import Dict, List, Any, Optional, Tuple
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from base.plugin_common.plugin_interface import PluginInterface, PluginStatus
|
||||
from base.plugin_common.message_plugin_interface import MessagePluginInterface
|
||||
from base.plugin_common.scheduled_plugin_interface import ScheduledPluginInterface
|
||||
from base.plugin_common.plugin_registry import PluginRegistry
|
||||
from base.plugin_common.event_system import EventSystem, EventType
|
||||
from wechat_ipad import WechatAPIClient
|
||||
|
||||
|
||||
class PluginManager:
|
||||
"""插件管理器,负责加载、卸载、启动、停止插件"""
|
||||
|
||||
# 单例实例
|
||||
_instance = None
|
||||
|
||||
@classmethod
|
||||
def get_instance(cls, plugin_dir=None):
|
||||
"""获取单例实例
|
||||
|
||||
Args:
|
||||
plugin_dir: 插件目录,如果已有实例则忽略此参数
|
||||
|
||||
Returns:
|
||||
PluginManager实例
|
||||
"""
|
||||
if cls._instance is None:
|
||||
cls._instance = cls(plugin_dir=plugin_dir or "plugins")
|
||||
return cls._instance
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
"""实现单例模式"""
|
||||
if cls._instance is None:
|
||||
cls._instance = super(PluginManager, cls).__new__(cls)
|
||||
cls._instance._initialized = False
|
||||
return cls._instance
|
||||
|
||||
def __init__(self, plugin_dir: str = "plugins"):
|
||||
"""
|
||||
初始化插件管理器
|
||||
|
||||
Args:
|
||||
plugin_dir: 插件目录
|
||||
"""
|
||||
self.plugin_dir = plugin_dir
|
||||
self.plugins: Dict[str, PluginInterface] = {} # 插件实例字典,键为display_name
|
||||
self.plugin_modules = {} # 插件模块字典,键为module_name
|
||||
self.module_to_display = {} # 模块名到显示名的映射
|
||||
self.system_context = {} # 系统上下文
|
||||
|
||||
self.LOG = logger
|
||||
# 确保插件目录存在
|
||||
if not os.path.exists(self.plugin_dir):
|
||||
os.makedirs(self.plugin_dir)
|
||||
|
||||
# 将插件目录添加到Python路径
|
||||
if self.plugin_dir not in sys.path:
|
||||
sys.path.insert(0, self.plugin_dir)
|
||||
|
||||
def set_system_context(self, context: Dict[str, Any]):
|
||||
"""
|
||||
设置系统上下文
|
||||
|
||||
Args:
|
||||
context: 系统上下文
|
||||
"""
|
||||
self.system_context = context
|
||||
|
||||
def discover_plugins(self) -> List[str]:
|
||||
"""
|
||||
发现可用插件
|
||||
|
||||
Returns:
|
||||
插件模块名称列表(module_name)
|
||||
"""
|
||||
module_names = []
|
||||
|
||||
# 遍历插件目录
|
||||
for item in os.listdir(self.plugin_dir):
|
||||
if os.path.isdir(os.path.join(self.plugin_dir, item)) and not item.startswith("__"):
|
||||
# 检查是否有main.py文件
|
||||
if os.path.exists(os.path.join(self.plugin_dir, item, "main.py")):
|
||||
module_names.append(item)
|
||||
elif item.endswith(".py") and not item.startswith("__"):
|
||||
# 单文件插件
|
||||
module_names.append(item[:-3])
|
||||
self.LOG.debug(f"PluginManager:发现插件模块: {module_names}")
|
||||
return module_names
|
||||
|
||||
def load_all_plugins(self) -> Dict[str, PluginInterface]:
|
||||
"""
|
||||
加载所有插件
|
||||
|
||||
Returns:
|
||||
插件实例字典,键为display_name
|
||||
"""
|
||||
module_names = self.discover_plugins()
|
||||
loaded_modules = []
|
||||
failed_modules = []
|
||||
|
||||
# 记录开始加载的插件列表
|
||||
self.LOG.debug(f"PluginManager:开始加载插件列表: {module_names}")
|
||||
|
||||
for module_name in module_names:
|
||||
try:
|
||||
plugin = self.load_plugin(module_name)
|
||||
if plugin:
|
||||
loaded_modules.append(module_name)
|
||||
# 自动启动插件
|
||||
self.start_plugin(plugin.name)
|
||||
else:
|
||||
failed_modules.append(module_name)
|
||||
except Exception as e:
|
||||
self.LOG.error(f"PluginManager:加载插件模块 {module_name} 时发生错误: {str(e)}", exc_info=True)
|
||||
failed_modules.append(module_name)
|
||||
|
||||
# 验证所有已加载插件的模块映射
|
||||
for display_name, plugin in self.plugins.items():
|
||||
try:
|
||||
# 尝试从类模块路径获取模块名
|
||||
module_name = self._get_module_name_from_plugin(plugin)
|
||||
if module_name and module_name not in self.module_to_display:
|
||||
self.module_to_display[module_name] = display_name
|
||||
self.LOG.debug(f"PluginManager:补充缺失的模块映射 {module_name} -> {display_name}")
|
||||
except Exception as e:
|
||||
self.LOG.warning(f"PluginManager:获取插件 {display_name} 的模块名时出错: {e}")
|
||||
# 使用插件显示名称作为备选模块名
|
||||
folder_name = display_name.lower().replace(' ', '_')
|
||||
if folder_name not in self.module_to_display:
|
||||
self.module_to_display[folder_name] = display_name
|
||||
self.LOG.debug(f"PluginManager:使用目录名作为模块映射 {folder_name} -> {display_name}")
|
||||
|
||||
# 检查是否有重复或无效的映射
|
||||
invalid_mappings = []
|
||||
for module_name, display_name in self.module_to_display.items():
|
||||
if display_name not in self.plugins:
|
||||
invalid_mappings.append(module_name)
|
||||
self.LOG.warning(f"PluginManager:发现无效的模块映射 {module_name} -> {display_name}")
|
||||
|
||||
# 清理无效的映射
|
||||
for module_name in invalid_mappings:
|
||||
del self.module_to_display[module_name]
|
||||
self.LOG.debug(f"PluginManager:清理无效的模块映射 {module_name}")
|
||||
|
||||
# 记录最终状态
|
||||
self.LOG.debug(f"PluginManager:加载成功的插件模块: {loaded_modules}")
|
||||
if failed_modules:
|
||||
self.LOG.warning(f"PluginManager:加载失败的插件模块: {failed_modules}")
|
||||
self.LOG.debug(f"PluginManager:当前已加载的插件实例: {list(self.plugins.keys())}")
|
||||
self.LOG.debug(f"PluginManager:最终的模块映射关系: {self.module_to_display}")
|
||||
|
||||
return self.plugins
|
||||
|
||||
def _get_module_name_from_plugin(self, plugin: PluginInterface) -> Optional[str]:
|
||||
"""
|
||||
从插件实例获取模块名
|
||||
|
||||
Args:
|
||||
plugin: 插件实例
|
||||
|
||||
Returns:
|
||||
模块名,获取失败返回None
|
||||
"""
|
||||
try:
|
||||
# 获取完整模块路径
|
||||
full_module = plugin.__class__.__module__
|
||||
module_parts = full_module.split('.')
|
||||
|
||||
# 处理不同的模块路径情况
|
||||
if len(module_parts) >= 2 and module_parts[0] == 'plugins':
|
||||
# 对于目录插件,模块名在第二个位置
|
||||
return module_parts[1]
|
||||
elif len(module_parts) >= 2:
|
||||
# 其他情况,取倒数第二个
|
||||
return module_parts[-2]
|
||||
else:
|
||||
# 单文件插件,直接返回
|
||||
return full_module
|
||||
except (IndexError, AttributeError) as e:
|
||||
self.LOG.warning(f"获取插件 {plugin.name} 的模块名时出错: {e}")
|
||||
return None
|
||||
|
||||
def load_plugin(self, module_name: str) -> Optional[PluginInterface]:
|
||||
"""
|
||||
加载插件
|
||||
|
||||
Args:
|
||||
module_name: 插件模块名
|
||||
|
||||
Returns:
|
||||
插件实例,加载失败返回None
|
||||
"""
|
||||
try:
|
||||
# 检查是否已有同名模块的插件加载
|
||||
for display_name, plugin in self.plugins.items():
|
||||
try:
|
||||
plugin_module_name = self._get_module_name_from_plugin(plugin)
|
||||
if plugin_module_name == module_name:
|
||||
self.LOG.debug(f"PluginManager:插件模块 {module_name} 已加载为 {display_name}")
|
||||
# 确保模块名到显示名的映射存在
|
||||
if module_name not in self.module_to_display:
|
||||
self.module_to_display[module_name] = display_name
|
||||
self.LOG.debug(f"PluginManager:添加缺失的模块映射 {module_name} -> {display_name}")
|
||||
return plugin
|
||||
except Exception as e:
|
||||
self.LOG.warning(f"获取插件 {display_name} 的模块名时出错: {e}")
|
||||
continue
|
||||
|
||||
# 确定插件路径和模块路径
|
||||
plugin_path = os.path.join(self.plugin_dir, module_name)
|
||||
|
||||
# 加载模块
|
||||
if os.path.isdir(plugin_path) and os.path.exists(os.path.join(plugin_path, "main.py")):
|
||||
# 目录插件,从main.py加载
|
||||
module_path = f"plugins.{module_name}.main"
|
||||
try:
|
||||
module = importlib.import_module(module_path)
|
||||
self.plugin_modules[module_name] = module
|
||||
except ImportError as e:
|
||||
self.LOG.error(f"PluginManager:导入插件模块 {module_path} 失败: {e}")
|
||||
return None
|
||||
else:
|
||||
# 单文件插件
|
||||
plugin_path = self.plugin_dir
|
||||
try:
|
||||
module = importlib.import_module(module_name)
|
||||
self.plugin_modules[module_name] = module
|
||||
except ImportError as e:
|
||||
self.LOG.error(f"PluginManager:导入单文件插件 {module_name} 失败: {e}")
|
||||
return None
|
||||
|
||||
# 查找插件类
|
||||
plugin_class = None
|
||||
for name, obj in inspect.getmembers(module):
|
||||
if (inspect.isclass(obj) and
|
||||
issubclass(obj, PluginInterface) and
|
||||
obj != PluginInterface and
|
||||
obj != MessagePluginInterface and
|
||||
obj != ScheduledPluginInterface):
|
||||
plugin_class = obj
|
||||
break
|
||||
|
||||
# 如果没有找到插件类,尝试查找get_plugin函数
|
||||
if plugin_class is None:
|
||||
get_plugin_func = getattr(module, "get_plugin", None)
|
||||
if callable(get_plugin_func):
|
||||
plugin = get_plugin_func()
|
||||
if isinstance(plugin, PluginInterface):
|
||||
# 设置插件路径
|
||||
plugin.set_plugin_path(plugin_path)
|
||||
|
||||
# 加载插件配置
|
||||
if not plugin.load_config():
|
||||
self.LOG.error(f"PluginManager:插件模块 {module_name} 加载配置失败")
|
||||
return None
|
||||
|
||||
# 初始化插件
|
||||
if not plugin.initialize(self.system_context):
|
||||
self.LOG.error(f"PluginManager:插件模块 {module_name} 初始化失败")
|
||||
return None
|
||||
|
||||
# 注册插件
|
||||
PluginRegistry().register(plugin)
|
||||
|
||||
# 获取显示名称
|
||||
display_name = plugin.name
|
||||
|
||||
# 存储插件实例
|
||||
self.plugins[display_name] = plugin
|
||||
|
||||
# 添加模块名到显示名的映射
|
||||
self.module_to_display[module_name] = display_name
|
||||
# self.LOG.info(f"PluginManager:添加模块映射 {module_name} -> {display_name}")
|
||||
|
||||
# 发布插件加载事件
|
||||
EventSystem().publish(EventType.PLUGIN_LOADED, {"plugin": plugin})
|
||||
|
||||
return plugin
|
||||
else:
|
||||
self.LOG.error(f"PluginManager:插件模块 {module_name} 的 get_plugin() 返回的不是有效的插件实例")
|
||||
else:
|
||||
self.LOG.error(f"PluginManager:插件模块 {module_name} 中未找到有效的插件类或 get_plugin 函数")
|
||||
return None
|
||||
|
||||
# 实例化插件
|
||||
plugin = plugin_class()
|
||||
plugin.status = PluginStatus.LOADED
|
||||
|
||||
# 设置插件路径
|
||||
plugin.set_plugin_path(plugin_path)
|
||||
|
||||
# 在load_plugin方法中,找到加载配置后的位置(约在第298行)
|
||||
# 加载插件配置
|
||||
if not plugin.load_config():
|
||||
self.LOG.error(f"PluginManager:插件模块 {module_name} 加载配置失败")
|
||||
return None
|
||||
|
||||
# 修改检查enable状态的代码:遍历所有配置节点
|
||||
for section in plugin._config.values():
|
||||
if isinstance(section, dict) and not section.get("enable", True):
|
||||
self.LOG.debug(f"PluginManager:插件 {module_name} 已禁用,跳过加载")
|
||||
return None
|
||||
|
||||
# 初始化插件
|
||||
if not plugin.initialize(self.system_context):
|
||||
self.LOG.error(f"PluginManager:插件模块 {module_name} 初始化失败")
|
||||
return None
|
||||
|
||||
# 注册插件
|
||||
PluginRegistry().register(plugin)
|
||||
|
||||
# 获取显示名称
|
||||
display_name = plugin.name
|
||||
|
||||
# 存储插件实例
|
||||
self.plugins[display_name] = plugin
|
||||
|
||||
# 添加模块名到显示名的映射
|
||||
self.module_to_display[module_name] = display_name
|
||||
# self.LOG.info(f"PluginManager:添加模块映射 {module_name} -> {display_name}")
|
||||
|
||||
# 发布插件加载事件
|
||||
EventSystem().publish(EventType.PLUGIN_LOADED, {"plugin": plugin})
|
||||
|
||||
return plugin
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"PluginManager:加载插件模块 {module_name} 失败: {e}", exc_info=True)
|
||||
return None
|
||||
|
||||
def unload_plugin(self, name: str) -> bool:
|
||||
"""
|
||||
卸载插件
|
||||
|
||||
Args:
|
||||
name: 插件名称(可以是模块名或显示名称)
|
||||
|
||||
Returns:
|
||||
卸载是否成功
|
||||
"""
|
||||
# 查找插件
|
||||
display_name, plugin = self.find_plugin_by_name(name)
|
||||
|
||||
if not plugin:
|
||||
self.LOG.debug(f"PluginManager:插件 {name} 未加载")
|
||||
return False
|
||||
|
||||
# 停止插件
|
||||
if plugin.status == PluginStatus.RUNNING:
|
||||
if not plugin.stop():
|
||||
self.LOG.debug(f"PluginManager:停止插件 {display_name} 失败")
|
||||
return False
|
||||
plugin.status = PluginStatus.STOPPED # 确保状态更新
|
||||
|
||||
# 清理插件资源
|
||||
if not plugin.cleanup():
|
||||
self.LOG.debug(f"PluginManager:清理插件 {display_name} 资源失败")
|
||||
return False
|
||||
|
||||
# 设置状态为未加载
|
||||
plugin.status = PluginStatus.UNLOADED
|
||||
|
||||
# 注销插件
|
||||
PluginRegistry().unregister(display_name)
|
||||
|
||||
# 获取模块名,用于清理映射
|
||||
module_name = self._get_module_name_from_plugin(plugin)
|
||||
if module_name and module_name in self.module_to_display:
|
||||
del self.module_to_display[module_name]
|
||||
self.LOG.debug(f"PluginManager:清理模块映射 {module_name} -> {display_name}")
|
||||
|
||||
# 移除插件实例
|
||||
del self.plugins[display_name]
|
||||
|
||||
# 发布插件卸载事件
|
||||
EventSystem().publish(EventType.PLUGIN_UNLOADED, {"plugin_name": display_name})
|
||||
|
||||
return True
|
||||
|
||||
def reload_plugin(self, name: str) -> Optional[PluginInterface]:
|
||||
"""
|
||||
重新加载插件
|
||||
|
||||
Args:
|
||||
name: 插件名称(可以是模块名或显示名称)
|
||||
|
||||
Returns:
|
||||
插件实例,重新加载失败返回None
|
||||
"""
|
||||
# 查找插件
|
||||
display_name, plugin = self.find_plugin_by_name(name)
|
||||
|
||||
if not plugin:
|
||||
self.LOG.debug(f"PluginManager:插件 {name} 未加载,无法重载")
|
||||
return None
|
||||
|
||||
# 记录原插件状态和模块名
|
||||
was_running = plugin.status == PluginStatus.RUNNING
|
||||
module_name = self._get_module_name_from_plugin(plugin)
|
||||
|
||||
if not module_name:
|
||||
self.LOG.error(f"无法获取插件 {display_name} 的模块名,重载失败")
|
||||
return None
|
||||
|
||||
# 卸载插件
|
||||
if not self.unload_plugin(display_name):
|
||||
self.LOG.debug(f"卸载插件 {display_name} 失败,无法重载")
|
||||
return None
|
||||
|
||||
# 重新导入模块
|
||||
if module_name in self.plugin_modules:
|
||||
try:
|
||||
importlib.reload(self.plugin_modules[module_name])
|
||||
except Exception as e:
|
||||
self.LOG.debug(f"重新导入插件模块 {module_name} 失败: {e}")
|
||||
return None
|
||||
|
||||
# 加载插件
|
||||
plugin = self.load_plugin(module_name)
|
||||
|
||||
# 如果原来是运行状态,则重新启动
|
||||
if plugin and was_running:
|
||||
self.start_plugin(plugin.name)
|
||||
|
||||
return plugin
|
||||
|
||||
def start_plugin(self, name: str) -> bool:
|
||||
"""
|
||||
启动插件
|
||||
|
||||
Args:
|
||||
name: 插件名称(可以是模块名或显示名称)
|
||||
|
||||
Returns:
|
||||
启动是否成功
|
||||
"""
|
||||
# 查找插件
|
||||
display_name, plugin = self.find_plugin_by_name(name)
|
||||
|
||||
if not plugin:
|
||||
self.LOG.debug(f"PluginManager:插件 {name} 未加载")
|
||||
return False
|
||||
|
||||
if plugin.status == PluginStatus.RUNNING:
|
||||
self.LOG.debug(f"PluginManager:插件 {display_name} 已经在运行")
|
||||
return True
|
||||
|
||||
if plugin.start():
|
||||
plugin.status = PluginStatus.RUNNING
|
||||
self.LOG.debug(f"PluginManager:插件 {display_name} 状态变更为在运行")
|
||||
return True
|
||||
else:
|
||||
plugin.status = PluginStatus.ERROR
|
||||
self.LOG.debug(f"PluginManager:插件 {display_name} 状态变更为异常")
|
||||
return False
|
||||
|
||||
def stop_plugin(self, name: str) -> bool:
|
||||
"""
|
||||
停止插件
|
||||
|
||||
Args:
|
||||
name: 插件名称(可以是模块名或显示名称)
|
||||
|
||||
Returns:
|
||||
停止是否成功
|
||||
"""
|
||||
# 查找插件
|
||||
display_name, plugin = self.find_plugin_by_name(name)
|
||||
|
||||
if not plugin:
|
||||
self.LOG.debug(f"插件 {name} 未加载")
|
||||
return False
|
||||
|
||||
if plugin.status != PluginStatus.RUNNING:
|
||||
self.LOG.debug(f"插件 {display_name} 未在运行")
|
||||
return True
|
||||
|
||||
if plugin.stop():
|
||||
plugin.status = PluginStatus.STOPPED
|
||||
self.LOG.debug(f"插件 {display_name} 状态变更为已停止")
|
||||
return True
|
||||
else:
|
||||
plugin.status = PluginStatus.ERROR
|
||||
self.LOG.debug(f"插件 {display_name} 状态变更为异常")
|
||||
return False
|
||||
|
||||
def shutdown_plugins(self) -> bool:
|
||||
"""
|
||||
卸载所有插件
|
||||
|
||||
Returns:
|
||||
是否全部成功卸载
|
||||
"""
|
||||
success = True
|
||||
# 创建插件名称的副本,因为在卸载过程中会修改self.plugins字典
|
||||
display_names = list(self.plugins.keys())
|
||||
|
||||
for display_name in display_names:
|
||||
if not self.unload_plugin(display_name):
|
||||
self.LOG.error(f"卸载插件 {display_name} 失败")
|
||||
success = False
|
||||
|
||||
# 清空插件模块字典
|
||||
self.plugin_modules.clear()
|
||||
self.module_to_display.clear()
|
||||
|
||||
# 确保插件字典为空
|
||||
if self.plugins:
|
||||
self.LOG.warning(f"插件卸载后仍有 {len(self.plugins)} 个插件残留")
|
||||
success = False
|
||||
|
||||
return success
|
||||
|
||||
def find_plugin_by_name(self, name: str) -> Tuple[Optional[str], Optional[PluginInterface]]:
|
||||
"""
|
||||
根据插件名称或模块名查找插件
|
||||
|
||||
Args:
|
||||
name: 插件名称或模块名
|
||||
|
||||
Returns:
|
||||
(插件显示名称, 插件实例) 元组,未找到返回 (None, None)
|
||||
"""
|
||||
# 直接通过显示名称查找
|
||||
if name in self.plugins:
|
||||
return name, self.plugins[name]
|
||||
|
||||
# 通过模块名查找
|
||||
if name in self.module_to_display:
|
||||
display_name = self.module_to_display[name]
|
||||
return display_name, self.plugins.get(display_name)
|
||||
|
||||
# 遍历所有插件查找匹配的模块名
|
||||
for display_name, plugin in self.plugins.items():
|
||||
try:
|
||||
module_name = self._get_module_name_from_plugin(plugin)
|
||||
if module_name and module_name == name:
|
||||
# 顺便更新映射
|
||||
if module_name not in self.module_to_display:
|
||||
self.module_to_display[module_name] = display_name
|
||||
self.LOG.debug(f"PluginManager:添加缺失的模块映射 {module_name} -> {display_name}")
|
||||
return display_name, plugin
|
||||
|
||||
# 不区分大小写比较
|
||||
if module_name and module_name.lower() == name.lower():
|
||||
if module_name not in self.module_to_display:
|
||||
self.module_to_display[module_name] = display_name
|
||||
return display_name, plugin
|
||||
|
||||
# 检查名称是否包含在模块名中(不区分大小写)
|
||||
if module_name and name.lower() in module_name.lower():
|
||||
return display_name, plugin
|
||||
|
||||
# 检查模块名是否包含在名称中(不区分大小写)
|
||||
if module_name and module_name.lower() in name.lower():
|
||||
return display_name, plugin
|
||||
|
||||
# 检查名称是否包含在显示名称中(不区分大小写)
|
||||
if name.lower() in display_name.lower():
|
||||
return display_name, plugin
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# 记录未找到插件的详细信息,帮助调试
|
||||
self.LOG.warning(f"未找到插件: {name},当前已加载插件: {list(self.plugins.keys())}")
|
||||
self.LOG.warning(f"模块映射: {self.module_to_display}")
|
||||
|
||||
return None, None
|
||||
|
||||
def inject_bot(self, bot: WechatAPIClient):
|
||||
self.system_context["bot"] = bot
|
||||
for name, plugin in self.plugins.items():
|
||||
# self.LOG.debug(f"plugin name{name}, plugin: {plugin}")
|
||||
if hasattr(plugin, "set_bot"):
|
||||
try:
|
||||
plugin.set_bot(bot)
|
||||
self.LOG.debug(f"已成功注入 bot 到插件 {name}")
|
||||
except Exception as e:
|
||||
self.LOG.error(f"注入 bot 到插件 {name} 失败: {e}")
|
||||
94
base/plugin_common/plugin_registry.py
Normal file
94
base/plugin_common/plugin_registry.py
Normal file
@@ -0,0 +1,94 @@
|
||||
from typing import Dict, List, Optional, Type
|
||||
from base.plugin_common.plugin_interface import PluginInterface, PluginStatus
|
||||
|
||||
|
||||
class PluginRegistry:
|
||||
"""插件注册表,维护已加载插件的信息和状态"""
|
||||
|
||||
_instance = None
|
||||
|
||||
def __new__(cls):
|
||||
"""单例模式"""
|
||||
if cls._instance is None:
|
||||
cls._instance = super(PluginRegistry, cls).__new__(cls)
|
||||
cls._instance._plugins = {}
|
||||
return cls._instance
|
||||
|
||||
def register(self, plugin: PluginInterface) -> bool:
|
||||
"""
|
||||
注册插件
|
||||
|
||||
Args:
|
||||
plugin: 插件实例
|
||||
|
||||
Returns:
|
||||
注册是否成功
|
||||
"""
|
||||
if plugin.name in self._plugins:
|
||||
print(f"插件 {plugin.name} 已存在")
|
||||
return False
|
||||
|
||||
self._plugins[plugin.name] = plugin
|
||||
return True
|
||||
|
||||
def unregister(self, plugin_name: str) -> bool:
|
||||
"""
|
||||
注销插件
|
||||
|
||||
Args:
|
||||
plugin_name: 插件名称
|
||||
|
||||
Returns:
|
||||
注销是否成功
|
||||
"""
|
||||
if plugin_name not in self._plugins:
|
||||
print(f"插件 {plugin_name} 不存在")
|
||||
return False
|
||||
|
||||
del self._plugins[plugin_name]
|
||||
return True
|
||||
|
||||
def get_plugin(self, plugin_name: str) -> Optional[PluginInterface]:
|
||||
"""
|
||||
获取插件实例
|
||||
|
||||
Args:
|
||||
plugin_name: 插件名称
|
||||
|
||||
Returns:
|
||||
插件实例,不存在返回None
|
||||
"""
|
||||
return self._plugins.get(plugin_name)
|
||||
|
||||
def get_all_plugins(self) -> Dict[str, PluginInterface]:
|
||||
"""
|
||||
获取所有插件
|
||||
|
||||
Returns:
|
||||
插件字典,键为插件名称,值为插件实例
|
||||
"""
|
||||
return self._plugins.copy()
|
||||
|
||||
def get_plugins_by_status(self, status: PluginStatus) -> List[PluginInterface]:
|
||||
"""
|
||||
获取指定状态的插件
|
||||
|
||||
Args:
|
||||
status: 插件状态
|
||||
|
||||
Returns:
|
||||
插件列表
|
||||
"""
|
||||
return [p for p in self._plugins.values() if p.status == status]
|
||||
|
||||
def get_plugins_by_type(self, plugin_type: Type) -> List[PluginInterface]:
|
||||
"""
|
||||
获取指定类型的插件
|
||||
|
||||
Args:
|
||||
plugin_type: 插件类型
|
||||
|
||||
Returns:
|
||||
插件列表
|
||||
"""
|
||||
return [p for p in self._plugins.values() if isinstance(p, plugin_type)]
|
||||
55
base/plugin_common/scheduled_plugin_interface.py
Normal file
55
base/plugin_common/scheduled_plugin_interface.py
Normal file
@@ -0,0 +1,55 @@
|
||||
from abc import abstractmethod
|
||||
from typing import Dict, Any, List, Tuple, Callable
|
||||
|
||||
from base.plugin_common.plugin_interface import PluginInterface
|
||||
|
||||
|
||||
class ScheduledPluginInterface(PluginInterface):
|
||||
"""定时任务插件接口,用于执行定时任务"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._jobs = [] # 存储注册的定时任务
|
||||
|
||||
@abstractmethod
|
||||
def register_jobs(self) -> List[Tuple[str, Callable, Dict[str, Any]]]:
|
||||
"""
|
||||
注册定时任务
|
||||
|
||||
Returns:
|
||||
任务列表,每个任务是一个元组 (job_id, job_func, job_params)
|
||||
job_id: 任务ID
|
||||
job_func: 任务函数
|
||||
job_params: 任务参数,如{"trigger": "interval", "seconds": 60}
|
||||
"""
|
||||
pass
|
||||
|
||||
def start(self) -> bool:
|
||||
"""
|
||||
启动插件,注册定时任务
|
||||
|
||||
Returns:
|
||||
启动是否成功
|
||||
"""
|
||||
try:
|
||||
self._jobs = self.register_jobs()
|
||||
# 实际注册任务的逻辑将由插件管理器实现
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"启动定时任务插件 {self.name} 失败: {e}")
|
||||
return False
|
||||
|
||||
def stop(self) -> bool:
|
||||
"""
|
||||
停止插件,取消定时任务
|
||||
|
||||
Returns:
|
||||
停止是否成功
|
||||
"""
|
||||
try:
|
||||
# 实际取消任务的逻辑将由插件管理器实现
|
||||
self._jobs = []
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"停止定时任务插件 {self.name} 失败: {e}")
|
||||
return False
|
||||
Reference in New Issue
Block a user