Files
Mofox-Core/src/plugin_system/base/base_command.py
minecraft1024a d7f8a8de26 refactor(plugin): 引入旧版Command兼容层并重构基类
为了平滑过渡到新的`PlusCommand`插件架构,本次重构引入了一个兼容层。

`BaseCommand`现在继承自`PlusCommand`,并剥离了大部分重复的功能实现(如消息发送、配置获取等),转而依赖`PlusCommand`的基类实现。这大大简化了`BaseCommand`,使其专注于作为旧版插件的兼容适配器。

在组件注册流程中,增加了对旧版`BaseCommand`的识别。当检测到旧版命令时,会自动使用`create_legacy_command_adapter`工厂函数将其包装成一个标准的`PlusCommand`实例。这使得旧插件无需修改代码即可在新架构下运行,同时会在启动时打印警告,鼓励开发者迁移。
2025-11-19 23:30:36 +08:00

73 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from abc import abstractmethod
from typing import TYPE_CHECKING
from src.common.data_models.database_data_model import DatabaseMessages
from src.common.logger import get_logger
from src.plugin_system.base.component_types import ChatType, CommandInfo, ComponentType
from src.plugin_system.base.plus_command import PlusCommand
if TYPE_CHECKING:
from src.chat.message_receive.chat_stream import ChatStream
logger = get_logger("base_command")
class BaseCommand(PlusCommand):
"""旧版Command组件基类兼容层
此类作为旧版插件的兼容层新的插件开发请使用PlusCommand
子类可以通过类属性定义命令模式:
- command_pattern: 命令匹配的正则表达式
"""
# 旧版命令标识
_is_legacy: bool = True
command_name: str = ""
"""Command组件的名称"""
command_description: str = ""
"""Command组件的描述"""
# 默认命令设置
command_pattern: str = r""
"""命令匹配的正则表达式"""
# 用于存储正则匹配组
matched_groups: dict[str, str] = {}
def __init__(self, message: DatabaseMessages, plugin_config: dict | None = None):
"""初始化Command组件"""
# 调用PlusCommand的初始化
super().__init__(message, plugin_config)
# 旧版属性兼容
self.log_prefix = "[Command]"
self.matched_groups = {} # 初始化为空
def set_matched_groups(self, groups: dict[str, str]) -> None:
"""设置正则表达式匹配的命名组"""
self.matched_groups = groups
@abstractmethod
async def execute(self) -> tuple[bool, str | None, bool]:
"""执行Command的抽象方法子类必须实现
Returns:
Tuple[bool, Optional[str], bool]: (是否执行成功, 可选的回复消息, 是否拦截消息)
"""
pass
@classmethod
def get_command_info(cls) -> "CommandInfo":
"""从类属性生成CommandInfo"""
if "." in cls.command_name:
logger.error(f"Command名称 '{cls.command_name}' 包含非法字符 '.',请使用下划线替代")
raise ValueError(f"Command名称 '{cls.command_name}' 包含非法字符 '.',请使用下划线替代")
return CommandInfo(
name=cls.command_name,
component_type=ComponentType.COMMAND,
description=cls.command_description,
command_pattern=cls.command_pattern,
chat_type_allow=getattr(cls, "chat_type_allow", ChatType.ALL),
)