diff --git a/docs/plugin_detailed_guide.md b/docs/plugin_detailed_guide.md new file mode 100644 index 000000000..1af9fee3b --- /dev/null +++ b/docs/plugin_detailed_guide.md @@ -0,0 +1,752 @@ +# MaiBot 插件详细解析指南 + +## 📋 目录 + +1. [插件基类详解](#插件基类详解) +2. [Action组件深入](#action组件深入) +3. [Command组件深入](#command组件深入) +4. [API系统详解](#api系统详解) +5. [配置系统](#配置系统) +6. [注册中心机制](#注册中心机制) +7. [高级功能](#高级功能) +8. [最佳实践](#最佳实践) + +--- + +## 插件基类详解 + +### BasePlugin 核心功能 + +`BasePlugin` 是所有插件的基类,提供插件的生命周期管理和基础功能。 + +```python +@register_plugin +class MyPlugin(BasePlugin): + # 必需的基本信息 + plugin_name = "my_plugin" # 插件唯一标识 + plugin_description = "插件功能描述" # 简短描述 + plugin_version = "1.0.0" # 版本号 + plugin_author = "作者名称" # 作者信息 + enable_plugin = True # 是否启用 + + # 可选配置 + dependencies = ["other_plugin"] # 依赖的其他插件 + config_file_name = "config.toml" # 配置文件名 + + def get_plugin_components(self) -> List[Tuple[ComponentInfo, Type]]: + """返回插件包含的组件列表(必须实现)""" + return [ + (MyAction.get_action_info(), MyAction), + (MyCommand.get_command_info(), MyCommand) + ] +``` + +### 插件生命周期 + +1. **加载阶段** - 插件管理器扫描插件目录 +2. **实例化阶段** - 创建插件实例,传入 `plugin_dir` +3. **配置加载** - 自动加载配置文件(如果指定) +4. **依赖检查** - 验证依赖的插件是否存在 +5. **组件注册** - 注册所有组件到注册中心 +6. **运行阶段** - 组件响应用户交互 + +### 配置访问 + +```python +class MyPlugin(BasePlugin): + config_file_name = "config.toml" + + def some_method(self): + # 获取配置值 + max_retry = self.get_config("network.max_retry", 3) + api_key = self.get_config("api.key", "") + + # 配置支持嵌套结构 + db_config = self.get_config("database", {}) +``` + +--- + +## Action组件深入 + +### Action激活机制 + +Action组件支持多种激活方式,可以组合使用: + +#### 1. 关键词激活 + +```python +class KeywordAction(BaseAction): + focus_activation_type = ActionActivationType.KEYWORD + normal_activation_type = ActionActivationType.KEYWORD + activation_keywords = ["天气", "weather", "温度"] + keyword_case_sensitive = False # 是否区分大小写 + + async def execute(self) -> Tuple[bool, str]: + # 获取触发的关键词 + triggered_keyword = self.action_data.get("triggered_keyword") + return True, f"检测到关键词: {triggered_keyword}" +``` + +#### 2. LLM智能判断 + +```python +class SmartAction(BaseAction): + focus_activation_type = ActionActivationType.LLM_JUDGE + llm_judge_prompt = """ + 判断用户消息是否表达了情感支持的需求。 + 如果用户显得沮丧、焦虑或需要安慰,返回True,否则返回False。 + """ + + async def execute(self) -> Tuple[bool, str]: + # LLM判断为需要情感支持 + user_emotion = self.action_data.get("emotion", "neutral") + return True, "我理解你现在的感受,有什么可以帮助你的吗? 🤗" +``` + +#### 3. 随机激活 + +```python +class RandomAction(BaseAction): + focus_activation_type = ActionActivationType.RANDOM + random_activation_probability = 0.1 # 10%概率触发 + + async def execute(self) -> Tuple[bool, str]: + import random + responses = ["今天天气不错呢!", "你知道吗,刚才想到一个有趣的事...", "随便聊聊吧!"] + return True, random.choice(responses) +``` + +#### 4. 始终激活 + +```python +class AlwaysAction(BaseAction): + focus_activation_type = ActionActivationType.ALWAYS + parallel_action = True # 允许与其他Action并行 + + async def execute(self) -> Tuple[bool, str]: + # 记录所有消息到数据库 + await self.api.store_user_data("last_message", self.action_data.get("message")) + return True, "" # 静默执行,不发送回复 +``` + +### Action数据访问 + +```python +class DataAction(BaseAction): + async def execute(self) -> Tuple[bool, str]: + # 访问消息数据 + message = self.action_data.get("message", "") + username = self.action_data.get("username", "用户") + user_id = self.action_data.get("user_id", "") + platform = self.action_data.get("platform", "") + + # 访问系统数据 + thinking_id = self.thinking_id + reasoning = self.reasoning # 执行该动作的理由 + + # 访问计时器信息 + timers = self.cycle_timers + + return True, f"处理来自 {platform} 的用户 {username} 的消息" +``` + +### 聊天模式支持 + +```python +class ModeAwareAction(BaseAction): + mode_enable = ChatMode.PRIVATE # 只在私聊中启用 + # mode_enable = ChatMode.GROUP # 只在群聊中启用 + # mode_enable = ChatMode.ALL # 在所有模式中启用 + + async def execute(self) -> Tuple[bool, str]: + current_mode = self.action_data.get("chat_mode", ChatMode.PRIVATE) + return True, f"当前聊天模式: {current_mode.name}" +``` + +--- + +## Command组件深入 + +### 高级正则表达式模式 + +Command使用正则表达式进行精确匹配,支持复杂的参数提取: + +#### 1. 基础命令 + +```python +class BasicCommand(BaseCommand): + command_pattern = r"^/hello$" + command_help = "简单的问候命令" + + async def execute(self) -> Tuple[bool, Optional[str]]: + await self.send_reply("Hello!") + return True, "Hello!" +``` + +#### 2. 带参数命令 + +```python +class ParameterCommand(BaseCommand): + command_pattern = r"^/user\s+(?Padd|remove|list)\s+(?P\w+)?$" + command_help = "用户管理命令,用法:/user [用户名]" + command_examples = ["/user add alice", "/user remove bob", "/user list"] + + async def execute(self) -> Tuple[bool, Optional[str]]: + action = self.matched_groups.get("action") + name = self.matched_groups.get("name") + + if action == "add" and name: + # 添加用户逻辑 + await self.api.store_user_data(f"user_{name}", {"name": name, "created": self.api.get_current_time()}) + response = f"用户 {name} 已添加" + elif action == "remove" and name: + # 删除用户逻辑 + await self.api.delete_user_data(f"user_{name}") + response = f"用户 {name} 已删除" + elif action == "list": + # 列出用户逻辑 + users = await self.api.get_user_data_pattern("user_*") + response = f"用户列表: {', '.join(users.keys())}" + else: + response = "参数错误,请查看帮助信息" + + await self.send_reply(response) + return True, response +``` + +#### 3. 复杂参数解析 + +```python +class AdvancedCommand(BaseCommand): + command_pattern = r"^/remind\s+(?P