Files
NeoBot/core/managers/plugin_manager.py
K2cr2O1 3cbf5328bb refactor(core): 优化权限管理和事件模型
- 重构 AdminManager 和 PermissionManager 以 Redis 为主要数据源
- 为所有事件模型添加 slots=True 提升性能
- 更新文档说明 Mypyc 编译注意事项
- 清理测试和调试文件
- 移动静态资源到 web_static 目录
2026-01-13 08:35:54 +08:00

103 lines
3.7 KiB
Python

"""
插件管理器模块
负责扫描、加载和管理 `plugins` 目录下的所有插件。
"""
import importlib
import os
import pkgutil
import sys
from typing import Set
from .command_manager import CommandManager
from ..utils.exceptions import SyncHandlerError
from ..utils.logger import logger
# 确保logger在模块级别可见
__all__ = ['PluginManager', 'logger']
class PluginManager:
"""
插件管理器类
"""
def __init__(self, command_manager: "CommandManager") -> None:
"""
初始化插件管理器
:param command_manager: CommandManager的实例
"""
self.command_manager = command_manager
self.loaded_plugins: Set[str] = set()
def load_all_plugins(self) -> None:
"""
扫描并加载 `plugins` 目录下的所有插件。
"""
# 使用 pathlib 获取更可靠的路径
# 当前文件: core/managers/plugin_manager.py
# 目标: plugins/
current_dir = os.path.dirname(os.path.abspath(__file__))
# 回退两级到项目根目录 (core/managers -> core -> root)
root_dir = os.path.dirname(os.path.dirname(current_dir))
plugin_dir = os.path.join(root_dir, "plugins")
package_name = "plugins"
if not os.path.exists(plugin_dir):
logger.error(f"插件目录不存在: {plugin_dir}")
return
logger.info(f"正在从 {package_name} 加载插件 (路径: {plugin_dir})...")
for _, module_name, is_pkg in pkgutil.iter_modules([plugin_dir]):
full_module_name = f"{package_name}.{module_name}"
action = "加载" # 初始化默认值
try:
if full_module_name in self.loaded_plugins:
self.command_manager.unload_plugin(full_module_name)
module = importlib.reload(sys.modules[full_module_name])
action = "重载"
else:
module = importlib.import_module(full_module_name)
action = "加载"
if hasattr(module, "__plugin_meta__"):
meta = getattr(module, "__plugin_meta__")
self.command_manager.plugins[full_module_name] = meta
self.loaded_plugins.add(full_module_name)
type_str = "" if is_pkg else "文件"
logger.success(f" [{type_str}] 成功{action}: {module_name}")
except SyncHandlerError as e:
logger.error(f" 插件 {module_name} 加载失败: {e} (跳过此插件)")
except Exception as e:
logger.exception(
f" 加载插件 {module_name} 失败: {e}"
)
def reload_plugin(self, full_module_name: str) -> None:
"""
精确重载单个插件。
"""
if full_module_name not in self.loaded_plugins:
logger.warning(f"尝试重载一个未被加载的插件: {full_module_name},将按首次加载处理。")
if full_module_name not in sys.modules:
logger.error(f"重载失败: 模块 {full_module_name} 未在 sys.modules 中找到。")
return
try:
self.command_manager.unload_plugin(full_module_name)
module = importlib.reload(sys.modules[full_module_name])
if hasattr(module, "__plugin_meta__"):
meta = getattr(module, "__plugin_meta__")
self.command_manager.plugins[full_module_name] = meta
logger.success(f"插件 {full_module_name} 已成功重载。")
except Exception as e:
logger.exception(f"重载插件 {full_module_name} 时发生错误: {e}")