新增插件admin,并在models中新增PluginDataManager类

This commit is contained in:
baby20162016
2026-01-02 17:40:57 +08:00
parent 3be150b2c5
commit 026ce8c773
5 changed files with 202 additions and 10 deletions

View File

@@ -1,5 +1,6 @@
from .command_manager import matcher
from .config_loader import global_config
from .plugin_manager import PluginDataManager
from .ws import WS
__all__ = ["WS", "matcher", "global_config"]
__all__ = ["WS", "matcher", "global_config", "PluginDataManager"]

View File

@@ -3,7 +3,9 @@
负责扫描、加载和管理 `base_plugins` 目录下的所有插件。
"""
import importlib
import json
import os
import pkgutil
import sys
@@ -18,10 +20,12 @@ def load_all_plugins():
该函数会遍历 `plugins` 目录下的所有模块:
1. 如果模块已加载,则执行 reload 操作(用于热重载)。
2. 如果模块未加载,则执行 import 操作。
加载过程中会提取插件元数据 `__plugin_meta__` 并注册到 CommandManager。
"""
plugin_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "plugins")
plugin_dir = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "..", "plugins"
)
package_name = "plugins"
print(f" 正在从 {package_name} 加载插件...")
@@ -36,13 +40,84 @@ def load_all_plugins():
else:
module = importlib.import_module(full_module_name)
action = "加载"
# 提取插件元数据
if hasattr(module, "__plugin_meta__"):
meta = getattr(module, "__plugin_meta__")
matcher.plugins[full_module_name] = meta
type_str = "" if is_pkg else "文件"
print(f" [{type_str}] 成功{action}: {module_name}")
except Exception as e:
print(f" {action if 'action' in locals() else '加载'}插件 {module_name} 失败: {e}")
print(
f" {action if 'action' in locals() else '加载'}插件 {module_name} 失败: {e}"
)
class PluginDataManager:
"""
用于管理插件产生的数据文件的类
"""
def __init__(self, plugin_name: str):
"""
初始化插件数据管理器
:param plugin_name: 插件名称
"""
self.plugin_name = plugin_name
self.data_file = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"..",
"plugins",
"data",
self.plugin_name + ".json",
)
self.data = {}
self.load()
def load(self):
"""读取配置文件"""
if not os.path.exists(self.data_file):
with open(self.data_file, "w", encoding="utf-8") as f:
self.set(self.plugin_name, [])
try:
with open(self.data_file, "r", encoding="utf-8") as f:
self.data = json.load(f)
except json.JSONDecodeError:
self.data = {}
def save(self):
"""保存配置到文件"""
with open(self.data_file, "w", encoding="utf-8") as f:
json.dump(self.data, f, indent=2, ensure_ascii=False)
def get(self, key, default=None):
"""获取配置项"""
return self.data.get(key, default)
def set(self, key, value):
"""设置配置项"""
self.data[key] = value
self.save()
def add(self, key, value):
"""添加配置项"""
if key not in self.data:
self.data[key] = []
self.data[key].append(value)
self.save()
def remove(self, key):
"""删除配置项"""
if key in self.data:
del self.data[key]
self.save()
def clear(self):
"""清空所有配置"""
self.data.clear()
self.save()
def get_all(self):
return self.data.copy()