events manager and some typing fix

This commit is contained in:
UnCLAS-Prommer
2025-07-18 14:50:15 +08:00
parent d2b5019c24
commit ffa88b5462
6 changed files with 318 additions and 33 deletions

View File

@@ -1,8 +1,14 @@
from abc import abstractmethod
from typing import List, Tuple, Type, TYPE_CHECKING
from .plugin_base import PluginBase
from src.common.logger import get_logger
from .plugin_base import PluginBase
from .component_types import EventHandlerInfo
if TYPE_CHECKING:
from src.plugin_system.base.base_events_handler import BaseEventHandler
logger = get_logger("base_event_plugin")
class BaseEventPlugin(PluginBase):
"""基于事件的插件基类
@@ -12,3 +18,42 @@ class BaseEventPlugin(PluginBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@abstractmethod
def get_plugin_components(self) -> List[Tuple[EventHandlerInfo, Type[BaseEventHandler]]]:
"""获取插件包含的事件组件
子类必须实现此方法,返回事件组件
Returns:
List[Tuple[ComponentInfo, Type]]: [(组件信息, 组件类), ...]
"""
raise NotImplementedError("子类必须实现 get_plugin_components 方法")
def register_plugin(self) -> bool:
"""注册事件插件"""
from src.plugin_system.core.events_manager import events_manager
components = self.get_plugin_components()
# 检查依赖
if not self._check_dependencies():
logger.error(f"{self.log_prefix} 依赖检查失败,跳过注册")
return False
registered_components = []
for handler_info, handler_class in components:
handler_info.plugin_name = self.plugin_name
if events_manager.register_event_subscriber(handler_info, handler_class):
registered_components.append(handler_info)
else:
logger.error(f"{self.log_prefix} 事件处理器 {handler_info.name} 注册失败")
self.plugin_info.components = registered_components
if events_manager.register_plugins(self.plugin_info):
logger.debug(f"{self.log_prefix} 插件注册成功,包含 {len(registered_components)} 个事件处理器")
return True
else:
logger.error(f"{self.log_prefix} 插件注册失败")
return False

View File

@@ -0,0 +1,34 @@
from abc import ABC, abstractmethod
from typing import Tuple, Optional
from src.common.logger import get_logger
from .component_types import MaiMessages, EventType
logger = get_logger("base_event_handler")
class BaseEventHandler(ABC):
"""事件处理器基类
所有事件处理器都应该继承这个基类,提供事件处理的基本接口
"""
event_type: EventType = EventType.UNKNOWN # 事件类型,默认为未知
handler_name: str = ""
handler_description: str = ""
weight: int = 0 # 权重,数值越大优先级越高
intercept_message: bool = False # 是否拦截消息,默认为否
def __init__(self):
self.log_prefix = "[EventHandler]"
if self.event_type == EventType.UNKNOWN:
raise NotImplementedError("事件处理器必须指定 event_type")
@abstractmethod
async def execute(self, message: MaiMessages) -> Tuple[bool, Optional[str]]:
"""执行事件处理的抽象方法,子类必须实现
Returns:
Tuple[bool, Optional[str]]: (是否执行成功, 可选的返回消息)
"""
raise NotImplementedError("子类必须实现 execute 方法")

View File

@@ -1,6 +1,7 @@
from enum import Enum
from typing import Dict, Any, List
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
from maim_message import Seg
# 组件类型枚举
@@ -12,6 +13,9 @@ class ComponentType(Enum):
SCHEDULER = "scheduler" # 定时任务组件(预留)
LISTENER = "listener" # 事件监听组件(预留)
def __str__(self) -> str:
return self.value
# 动作激活类型枚举
class ActionActivationType(Enum):
@@ -46,12 +50,17 @@ class EventType(Enum):
事件类型枚举类
"""
ON_START = "on_start" # 启动事件,用于调用按时任务
ON_MESSAGE = "on_message"
ON_PLAN = "on_plan"
POST_LLM = "post_llm"
AFTER_LLM = "after_llm"
POST_SEND = "post_send"
AFTER_SEND = "after_send"
UNKNOWN = "unknown" # 未知事件类型
def __str__(self) -> str:
return self.value
@dataclass
@@ -142,6 +151,19 @@ class CommandInfo(ComponentInfo):
self.component_type = ComponentType.COMMAND
@dataclass
class EventHandlerInfo(ComponentInfo):
"""事件处理器组件信息"""
event_type: EventType = EventType.ON_MESSAGE # 监听事件类型
intercept_message: bool = False # 是否拦截消息处理(默认不拦截)
weight: int = 0 # 事件处理器权重,决定执行顺序
def __post_init__(self):
super().__post_init__()
self.component_type = ComponentType.LISTENER
@dataclass
class PluginInfo:
"""插件信息"""
@@ -198,3 +220,42 @@ class PluginInfo:
def get_pip_requirements(self) -> List[str]:
"""获取所有pip安装格式的依赖"""
return [dep.get_pip_requirement() for dep in self.python_dependencies]
@dataclass
class MaiMessages:
"""MaiM插件消息"""
message_segments: List[Seg] = field(default_factory=list)
"""消息段列表,支持多段消息"""
message_base_info: Dict[str, Any] = field(default_factory=dict)
"""消息基本信息,包含平台,用户信息等数据"""
plain_text: str = ""
"""纯文本消息内容"""
raw_message: Optional[str] = None
"""原始消息内容"""
is_group_message: bool = False
"""是否为群组消息"""
is_private_message: bool = False
"""是否为私聊消息"""
stream_id: Optional[str] = None
"""流ID用于标识消息流"""
llm_prompt: Optional[str] = None
"""LLM提示词"""
llm_response: Optional[str] = None
"""LLM响应内容"""
additional_data: Dict[Any, Any] = field(default_factory=dict)
"""附加数据,可以存储额外信息"""
def __post_init__(self):
if self.message_segments is None:
self.message_segments = []