添加聊天类型限制功能,支持根据聊天类型过滤命令和动作,新增私聊和群聊专用命令及动作,优化相关日志记录。

This commit is contained in:
minecraft1024a
2025-08-16 13:21:13 +08:00
parent 955478ec27
commit e19106b5b0
9 changed files with 172 additions and 9 deletions

View File

@@ -6,7 +6,7 @@ from typing import Tuple, Optional
from src.common.logger import get_logger
from src.chat.message_receive.chat_stream import ChatStream
from src.plugin_system.base.component_types import ActionActivationType, ChatMode, ActionInfo, ComponentType
from src.plugin_system.base.component_types import ActionActivationType, ChatMode, ActionInfo, ComponentType, ChatType
from src.plugin_system.apis import send_api, database_api, message_api
@@ -91,6 +91,7 @@ class BaseAction(ABC):
self.mode_enable: ChatMode = getattr(self.__class__, "mode_enable", ChatMode.ALL)
self.parallel_action: bool = getattr(self.__class__, "parallel_action", True)
self.associated_types: list[str] = getattr(self.__class__, "associated_types", []).copy()
self.chat_type_allow: ChatType = getattr(self.__class__, "chat_type_allow", ChatType.ALL)
# =============================================================================
# 便捷属性 - 直接在初始化时获取常用聊天信息(带类型注解)
@@ -146,6 +147,38 @@ class BaseAction(ABC):
logger.debug(
f"{self.log_prefix} 聊天信息: 类型={'群聊' if self.is_group else '私聊'}, 平台={self.platform}, 目标={self.target_id}"
)
# 验证聊天类型限制
if not self._validate_chat_type():
logger.warning(
f"{self.log_prefix} Action '{self.action_name}' 不支持当前聊天类型: "
f"{'群聊' if self.is_group else '私聊'}, 允许类型: {self.chat_type_allow.value}"
)
def _validate_chat_type(self) -> bool:
"""验证当前聊天类型是否允许执行此Action
Returns:
bool: 如果允许执行返回True否则返回False
"""
if self.chat_type_allow == ChatType.ALL:
return True
elif self.chat_type_allow == ChatType.GROUP and self.is_group:
return True
elif self.chat_type_allow == ChatType.PRIVATE and not self.is_group:
return True
else:
return False
def is_chat_type_allowed(self) -> bool:
"""检查当前聊天类型是否允许执行此Action
这是一个公开的方法,供外部调用检查聊天类型限制
Returns:
bool: 如果允许执行返回True否则返回False
"""
return self._validate_chat_type()
async def wait_for_new_message(self, timeout: int = 1200) -> Tuple[bool, str]:
"""等待新消息或超时
@@ -389,6 +422,7 @@ class BaseAction(ABC):
action_parameters=getattr(cls, "action_parameters", {}).copy(),
action_require=getattr(cls, "action_require", []).copy(),
associated_types=getattr(cls, "associated_types", []).copy(),
chat_type_allow=getattr(cls, "chat_type_allow", ChatType.ALL),
)
@abstractmethod

View File

@@ -1,7 +1,7 @@
from abc import ABC, abstractmethod
from typing import Dict, Tuple, Optional
from src.common.logger import get_logger
from src.plugin_system.base.component_types import CommandInfo, ComponentType
from src.plugin_system.base.component_types import CommandInfo, ComponentType, ChatType
from src.chat.message_receive.message import MessageRecv
from src.plugin_system.apis import send_api
@@ -26,6 +26,8 @@ class BaseCommand(ABC):
# 默认命令设置
command_pattern: str = r""
"""命令匹配的正则表达式"""
chat_type_allow: ChatType = ChatType.ALL
"""允许的聊天类型,默认为所有类型"""
def __init__(self, message: MessageRecv, plugin_config: Optional[dict] = None):
"""初始化Command组件
@@ -40,7 +42,18 @@ class BaseCommand(ABC):
self.log_prefix = "[Command]"
# 从类属性获取chat_type_allow设置
self.chat_type_allow = getattr(self.__class__, "chat_type_allow", ChatType.ALL)
logger.debug(f"{self.log_prefix} Command组件初始化完成")
# 验证聊天类型限制
if not self._validate_chat_type():
is_group = hasattr(self.message, 'is_group_message') and self.message.is_group_message
logger.warning(
f"{self.log_prefix} Command '{self.command_name}' 不支持当前聊天类型: "
f"{'群聊' if is_group else '私聊'}, 允许类型: {self.chat_type_allow.value}"
)
def set_matched_groups(self, groups: Dict[str, str]) -> None:
"""设置正则表达式匹配的命名组
@@ -50,6 +63,35 @@ class BaseCommand(ABC):
"""
self.matched_groups = groups
def _validate_chat_type(self) -> bool:
"""验证当前聊天类型是否允许执行此Command
Returns:
bool: 如果允许执行返回True否则返回False
"""
if self.chat_type_allow == ChatType.ALL:
return True
# 检查是否为群聊消息
is_group = hasattr(self.message, 'is_group_message') and self.message.is_group_message
if self.chat_type_allow == ChatType.GROUP and is_group:
return True
elif self.chat_type_allow == ChatType.PRIVATE and not is_group:
return True
else:
return False
def is_chat_type_allowed(self) -> bool:
"""检查当前聊天类型是否允许执行此Command
这是一个公开的方法,供外部调用检查聊天类型限制
Returns:
bool: 如果允许执行返回True否则返回False
"""
return self._validate_chat_type()
@abstractmethod
async def execute(self) -> Tuple[bool, Optional[str], bool]:
"""执行Command的抽象方法子类必须实现
@@ -225,4 +267,5 @@ class BaseCommand(ABC):
component_type=ComponentType.COMMAND,
description=cls.command_description,
command_pattern=cls.command_pattern,
chat_type_allow=getattr(cls, "chat_type_allow", ChatType.ALL),
)

View File

@@ -47,6 +47,18 @@ class ChatMode(Enum):
return self.value
# 聊天类型枚举
class ChatType(Enum):
"""聊天类型枚举,用于限制插件在不同聊天环境中的使用"""
GROUP = "group" # 仅群聊可用
PRIVATE = "private" # 仅私聊可用
ALL = "all" # 群聊和私聊都可用
def __str__(self):
return self.value
# 事件类型枚举
class EventType(Enum):
"""
@@ -124,6 +136,7 @@ class ActionInfo(ComponentInfo):
# 模式和并行设置
mode_enable: ChatMode = ChatMode.ALL
parallel_action: bool = False
chat_type_allow: ChatType = ChatType.ALL # 允许的聊天类型
def __post_init__(self):
super().__post_init__()
@@ -143,6 +156,7 @@ class CommandInfo(ComponentInfo):
"""命令组件信息"""
command_pattern: str = "" # 命令匹配模式(正则表达式)
chat_type_allow: ChatType = ChatType.ALL # 允许的聊天类型
def __post_init__(self):
super().__post_init__()