ErisPulse 2.1.15.dev3__py3-none-any.whl → 2.2.0.dev1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,48 @@
1
+ """
2
+ ErisPulse 事件处理模块
3
+
4
+ 提供统一的事件处理接口,支持命令、消息、通知、请求和元事件处理
5
+ """
6
+
7
+ from .cmd import command
8
+ from .message import message
9
+ from .notice import notice
10
+ from .request import request
11
+ from .meta import meta
12
+ from .manager import event_manager
13
+ from . import exceptions
14
+ from .. import config
15
+
16
+ # 初始化默认配置
17
+ def _setup_default_config():
18
+ """
19
+ 设置默认配置
20
+
21
+ {!--< internal-use >!--}
22
+ 内部使用的方法,用于初始化默认配置
23
+ """
24
+ default_config = {
25
+ "command": {
26
+ "prefix": "/",
27
+ "case_sensitive": True
28
+ },
29
+ "message": {
30
+ "ignore_self": True
31
+ }
32
+ }
33
+
34
+ current_config = config.getConfig("ErisPulse.event")
35
+ if current_config is None:
36
+ config.setConfig("ErisPulse.event", default_config)
37
+
38
+ _setup_default_config()
39
+
40
+ __all__ = [
41
+ "command",
42
+ "message",
43
+ "notice",
44
+ "request",
45
+ "meta",
46
+ "event_manager",
47
+ "exceptions"
48
+ ]
@@ -0,0 +1,117 @@
1
+ """
2
+ ErisPulse 事件处理基础模块
3
+
4
+ 提供事件处理的核心功能,包括事件注册、处理和中间件支持
5
+ """
6
+
7
+ from .. import adapter, logger
8
+ from typing import Callable, Any, Dict, List, Optional, Union
9
+ import asyncio
10
+
11
+ class BaseEventHandler:
12
+ """
13
+ 基础事件处理器
14
+
15
+ 提供事件处理的基本功能,包括处理器注册、中间件支持等
16
+ """
17
+
18
+ def __init__(self, event_type: str, module_name: str = None):
19
+ """
20
+ 初始化事件处理器
21
+
22
+ :param event_type: 事件类型
23
+ :param module_name: 模块名称
24
+ """
25
+ self.event_type = event_type
26
+ self.module_name = module_name
27
+ self.handlers: List[Dict] = []
28
+ self.middlewares: List[Callable] = []
29
+
30
+ def middleware(self, func: Callable) -> Callable:
31
+ """
32
+ 添加中间件
33
+
34
+ :param func: 中间件函数
35
+ :return: 中间件函数
36
+ """
37
+ self.middlewares.append(func)
38
+ return func
39
+
40
+ def register(self, handler: Callable, priority: int = 0, condition: Callable = None):
41
+ """
42
+ 注册事件处理器
43
+
44
+ :param handler: 事件处理器函数
45
+ :param priority: 处理器优先级,数值越小优先级越高
46
+ :param condition: 处理器条件函数,返回True时才会执行处理器
47
+ """
48
+ handler_info = {
49
+ "func": handler,
50
+ "priority": priority,
51
+ "condition": condition,
52
+ "module": self.module_name
53
+ }
54
+ self.handlers.append(handler_info)
55
+ # 按优先级排序
56
+ self.handlers.sort(key=lambda x: x["priority"])
57
+
58
+ # 注册到适配器
59
+ if self.event_type:
60
+ adapter.on(self.event_type)(self._process_event)
61
+
62
+ def __call__(self, priority: int = 0, condition: Callable = None):
63
+ """
64
+ 装饰器方式注册事件处理器
65
+
66
+ :param priority: 处理器优先级
67
+ :param condition: 处理器条件函数
68
+ :return: 装饰器函数
69
+ """
70
+ def decorator(func: Callable):
71
+ self.register(func, priority, condition)
72
+ return func
73
+ return decorator
74
+
75
+ async def _process_event(self, event: Dict[str, Any]):
76
+ """
77
+ 处理事件
78
+
79
+ {!--< internal-use >!--}
80
+ 内部使用的方法,用于处理事件
81
+
82
+ :param event: 事件数据
83
+ """
84
+ # 执行中间件
85
+ processed_event = event
86
+ for middleware in self.middlewares:
87
+ try:
88
+ if asyncio.iscoroutinefunction(middleware):
89
+ processed_event = await middleware(processed_event)
90
+ else:
91
+ processed_event = middleware(processed_event)
92
+ except Exception as e:
93
+ logger.error(f"中间件执行错误: {e}")
94
+
95
+ # 执行处理器
96
+ for handler_info in self.handlers:
97
+ condition = handler_info.get("condition")
98
+ # 检查条件
99
+ if condition and not condition(processed_event):
100
+ continue
101
+
102
+ handler = handler_info["func"]
103
+ try:
104
+ if asyncio.iscoroutinefunction(handler):
105
+ await handler(processed_event)
106
+ else:
107
+ handler(processed_event)
108
+ except Exception as e:
109
+ logger.error(f"事件处理器执行错误: {e}")
110
+
111
+ def unregister(self, handler: Callable):
112
+ """
113
+ 注销事件处理器
114
+
115
+ :param handler: 要注销的事件处理器
116
+ """
117
+ self.handlers = [h for h in self.handlers if h["func"] != handler]
@@ -0,0 +1,210 @@
1
+ """
2
+ ErisPulse 命令处理模块
3
+
4
+ 提供基于装饰器的命令注册和处理功能
5
+ """
6
+
7
+ from .base import BaseEventHandler
8
+ from .manager import event_manager
9
+ from .. import config, logger
10
+ from typing import Callable, Union, List, Dict, Any, Optional
11
+ import asyncio
12
+
13
+ class CommandHandler:
14
+ """
15
+ 命令处理器
16
+
17
+ 提供命令注册、解析和执行功能
18
+ """
19
+
20
+ def __init__(self):
21
+ """
22
+ 初始化命令处理器
23
+ """
24
+ self.commands: Dict[str, Dict] = {}
25
+ self.aliases: Dict[str, str] = {} # 别名映射
26
+ self.groups: Dict[str, List[str]] = {} # 命令组
27
+ self.prefix = config.getConfig("ErisPulse.event.command.prefix", "/")
28
+ self.handler = event_manager.create_event_handler("message", "command")
29
+
30
+ # 注册消息处理器
31
+ self.handler.register(self._handle_message)
32
+
33
+ def __call__(self,
34
+ name: Union[str, List[str]] = None,
35
+ aliases: List[str] = None,
36
+ group: str = None,
37
+ priority: int = 0,
38
+ help: str = None,
39
+ usage: str = None):
40
+ """
41
+ 命令装饰器
42
+
43
+ :param name: 命令名称,可以是字符串或字符串列表
44
+ :param aliases: 命令别名列表
45
+ :param group: 命令组名称
46
+ :param priority: 处理器优先级
47
+ :param help: 命令帮助信息
48
+ :param usage: 命令使用方法
49
+ :return: 装饰器函数
50
+ """
51
+ def decorator(func: Callable):
52
+ cmd_names = []
53
+ if isinstance(name, str):
54
+ cmd_names = [name]
55
+ elif isinstance(name, list):
56
+ cmd_names = name
57
+ else:
58
+ # 使用函数名作为命令名
59
+ cmd_names = [func.__name__]
60
+
61
+ main_name = cmd_names[0]
62
+
63
+ # 添加别名
64
+ alias_list = aliases or []
65
+ if len(cmd_names) > 1:
66
+ alias_list.extend(cmd_names[1:])
67
+
68
+ # 注册命令
69
+ for cmd_name in cmd_names:
70
+ self.commands[cmd_name] = {
71
+ "func": func,
72
+ "help": help,
73
+ "usage": usage,
74
+ "group": group,
75
+ "main_name": main_name
76
+ }
77
+
78
+ # 注册别名映射
79
+ if cmd_name != main_name:
80
+ self.aliases[cmd_name] = main_name
81
+
82
+ # 添加到命令组
83
+ if group:
84
+ if group not in self.groups:
85
+ self.groups[group] = []
86
+ for cmd_name in cmd_names:
87
+ if cmd_name not in self.groups[group]:
88
+ self.groups[group].append(cmd_name)
89
+
90
+ return func
91
+ return decorator
92
+
93
+ async def _handle_message(self, event: Dict[str, Any]):
94
+ """
95
+ 处理消息事件中的命令
96
+
97
+ {!--< internal-use >!--}
98
+ 内部使用的方法,用于从消息中解析并执行命令
99
+
100
+ :param event: 消息事件数据
101
+ """
102
+ # 检查是否为文本消息
103
+ if event.get("type") != "message":
104
+ return
105
+
106
+ message_segments = event.get("message", [])
107
+ text_content = ""
108
+ for segment in message_segments:
109
+ if segment.get("type") == "text":
110
+ text_content = segment.get("data", {}).get("text", "")
111
+ break
112
+
113
+ if not text_content:
114
+ return
115
+
116
+ # 检查前缀
117
+ if not text_content.startswith(self.prefix):
118
+ return
119
+
120
+ # 解析命令和参数
121
+ command_text = text_content[len(self.prefix):].strip()
122
+ parts = command_text.split()
123
+ if not parts:
124
+ return
125
+
126
+ cmd_name = parts[0]
127
+ args = parts[1:] if len(parts) > 1 else []
128
+
129
+ # 处理别名
130
+ actual_cmd_name = self.aliases.get(cmd_name, cmd_name)
131
+
132
+ # 查找命令处理器
133
+ if actual_cmd_name in self.commands:
134
+ cmd_info = self.commands[actual_cmd_name]
135
+ handler = cmd_info["func"]
136
+
137
+ # 添加命令相关信息到事件
138
+ command_info = {
139
+ "name": actual_cmd_name,
140
+ "main_name": cmd_info["main_name"],
141
+ "args": args,
142
+ "raw": command_text,
143
+ "help": cmd_info["help"],
144
+ "usage": cmd_info["usage"],
145
+ "group": cmd_info["group"]
146
+ }
147
+
148
+ event["command"] = command_info
149
+
150
+ try:
151
+ if asyncio.iscoroutinefunction(handler):
152
+ await handler(event)
153
+ else:
154
+ handler(event)
155
+ except Exception as e:
156
+ logger.error(f"命令执行错误: {e}")
157
+ # 可以发送错误信息给用户
158
+
159
+ def get_command(self, name: str) -> Optional[Dict]:
160
+ """
161
+ 获取命令信息
162
+
163
+ :param name: 命令名称
164
+ :return: 命令信息字典,如果不存在则返回None
165
+ """
166
+ actual_name = self.aliases.get(name, name)
167
+ return self.commands.get(actual_name)
168
+
169
+ def get_commands(self) -> Dict[str, Dict]:
170
+ """
171
+ 获取所有命令
172
+
173
+ :return: 命令信息字典
174
+ """
175
+ return self.commands
176
+
177
+ def get_group_commands(self, group: str) -> List[str]:
178
+ """
179
+ 获取命令组中的命令
180
+
181
+ :param group: 命令组名称
182
+ :return: 命令名称列表
183
+ """
184
+ return self.groups.get(group, [])
185
+
186
+ def help(self, command_name: str = None) -> str:
187
+ """
188
+ 生成帮助信息
189
+
190
+ :param command_name: 命令名称,如果为None则生成所有命令的帮助
191
+ :return: 帮助信息字符串
192
+ """
193
+ if command_name:
194
+ cmd_info = self.get_command(command_name)
195
+ if cmd_info:
196
+ help_text = cmd_info.get("help", "无帮助信息")
197
+ usage = cmd_info.get("usage", f"{self.prefix}{command_name}")
198
+ return f"命令: {command_name}\n用法: {usage}\n说明: {help_text}"
199
+ else:
200
+ return f"未找到命令: {command_name}"
201
+ else:
202
+ # 生成所有命令的帮助
203
+ help_lines = ["可用命令:"]
204
+ for cmd_name, cmd_info in self.commands.items():
205
+ if cmd_name == cmd_info["main_name"]: # 只显示主命令
206
+ help_text = cmd_info.get("help", "无说明")
207
+ help_lines.append(f" {self.prefix}{cmd_name} - {help_text}")
208
+ return "\n".join(help_lines)
209
+
210
+ command = CommandHandler()
@@ -0,0 +1,37 @@
1
+ """
2
+ ErisPulse 事件系统异常处理模块
3
+
4
+ 提供事件系统中可能发生的各种异常类型定义
5
+ """
6
+
7
+ class EventException(Exception):
8
+ """
9
+ 事件系统基础异常
10
+
11
+ 所有事件系统相关异常的基类
12
+ """
13
+ pass
14
+
15
+ class CommandException(EventException):
16
+ """
17
+ 命令处理异常
18
+
19
+ 当命令处理过程中发生错误时抛出
20
+ """
21
+ pass
22
+
23
+ class EventHandlerException(EventException):
24
+ """
25
+ 事件处理器异常
26
+
27
+ 当事件处理器执行过程中发生错误时抛出
28
+ """
29
+ pass
30
+
31
+ class EventNotFoundException(EventException):
32
+ """
33
+ 事件未找到异常
34
+
35
+ 当尝试获取不存在的事件处理器时抛出
36
+ """
37
+ pass
@@ -0,0 +1,127 @@
1
+ """
2
+ ErisPulse 事件管理器
3
+
4
+ 提供全局事件管理功能,包括事件处理器创建、模块事件管理等
5
+ """
6
+
7
+ from .. import logger
8
+ from .base import BaseEventHandler
9
+ from .exceptions import EventNotFoundException
10
+ from typing import Dict, List, Optional, Callable, Any
11
+ import asyncio
12
+
13
+ class EventManager:
14
+ """
15
+ 事件管理器
16
+
17
+ 管理所有事件处理器,提供全局事件处理功能
18
+ """
19
+
20
+ def __init__(self):
21
+ """
22
+ 初始化事件管理器
23
+ """
24
+ self.event_handlers: Dict[str, BaseEventHandler] = {}
25
+ self.module_events: Dict[str, List[str]] = {}
26
+ self.global_middlewares: List[Callable] = []
27
+
28
+ def create_event_handler(self, event_type: str, module_name: str = None) -> BaseEventHandler:
29
+ """
30
+ 创建事件处理器
31
+
32
+ :param event_type: 事件类型
33
+ :param module_name: 模块名称
34
+ :return: 事件处理器实例
35
+ """
36
+ if event_type not in self.event_handlers:
37
+ handler = BaseEventHandler(event_type, module_name)
38
+ self.event_handlers[event_type] = handler
39
+ return self.event_handlers[event_type]
40
+
41
+ def get_event_handler(self, event_type: str) -> Optional[BaseEventHandler]:
42
+ """
43
+ 获取事件处理器
44
+
45
+ :param event_type: 事件类型
46
+ :return: 事件处理器实例,如果不存在则返回None
47
+ """
48
+ return self.event_handlers.get(event_type)
49
+
50
+ def register_module_event(self, module_name: str, event_type: str):
51
+ """
52
+ 注册模块事件
53
+
54
+ :param module_name: 模块名称
55
+ :param event_type: 事件类型
56
+ """
57
+ if module_name not in self.module_events:
58
+ self.module_events[module_name] = []
59
+ if event_type not in self.module_events[module_name]:
60
+ self.module_events[module_name].append(event_type)
61
+
62
+ def middleware(self, func: Callable):
63
+ """
64
+ 添加全局中间件
65
+
66
+ :param func: 中间件函数
67
+ :return: 中间件函数
68
+ """
69
+ self.global_middlewares.append(func)
70
+ return func
71
+
72
+ async def emit(self, event_type: str, event_data: Dict[str, Any]):
73
+ """
74
+ 触发事件
75
+
76
+ :param event_type: 事件类型
77
+ :param event_data: 事件数据
78
+ """
79
+ # 执行全局中间件
80
+ processed_data = event_data
81
+ for middleware in self.global_middlewares:
82
+ try:
83
+ if asyncio.iscoroutinefunction(middleware):
84
+ processed_data = await middleware(processed_data)
85
+ else:
86
+ processed_data = middleware(processed_data)
87
+ except Exception as e:
88
+ logger.error(f"全局中间件执行错误: {e}")
89
+
90
+ # 触发事件处理器
91
+ if event_type in self.event_handlers:
92
+ handler = self.event_handlers[event_type]
93
+ await handler._process_event(processed_data)
94
+
95
+ # 触发通配符处理器
96
+ if "*" in self.event_handlers:
97
+ handler = self.event_handlers["*"]
98
+ await handler._process_event(processed_data)
99
+
100
+ def get_module_events(self, module_name: str) -> List[str]:
101
+ """
102
+ 获取模块注册的事件
103
+
104
+ :param module_name: 模块名称
105
+ :return: 事件类型列表
106
+ """
107
+ return self.module_events.get(module_name, [])
108
+
109
+ def cleanup_module_events(self, module_name: str):
110
+ """
111
+ 清理模块事件
112
+
113
+ :param module_name: 模块名称
114
+ """
115
+ if module_name in self.module_events:
116
+ event_types = self.module_events[module_name]
117
+ for event_type in event_types:
118
+ if event_type in self.event_handlers:
119
+ # 移除该模块注册的处理器
120
+ handler = self.event_handlers[event_type]
121
+ handler.handlers = [
122
+ h for h in handler.handlers
123
+ if h.get("module") != module_name
124
+ ]
125
+ del self.module_events[module_name]
126
+
127
+ event_manager = EventManager()
@@ -0,0 +1,89 @@
1
+ """
2
+ ErisPulse 消息处理模块
3
+
4
+ 提供基于装饰器的消息事件处理功能
5
+ """
6
+
7
+ from .base import BaseEventHandler
8
+ from .manager import event_manager
9
+ from typing import Callable, Dict, Any
10
+ import asyncio
11
+
12
+ class MessageHandler:
13
+ """
14
+ 消息处理器
15
+
16
+ 提供不同类型消息事件的处理功能
17
+ """
18
+
19
+ def __init__(self):
20
+ """
21
+ 初始化消息处理器
22
+ """
23
+ self.handler = event_manager.create_event_handler("message", "message")
24
+
25
+ def on_message(self, priority: int = 0):
26
+ """
27
+ 消息事件装饰器
28
+
29
+ :param priority: 处理器优先级
30
+ :return: 装饰器函数
31
+ """
32
+ def decorator(func: Callable):
33
+ self.handler.register(func, priority)
34
+ return func
35
+ return decorator
36
+
37
+ def on_private_message(self, priority: int = 0):
38
+ """
39
+ 私聊消息事件装饰器
40
+
41
+ :param priority: 处理器优先级
42
+ :return: 装饰器函数
43
+ """
44
+ def condition(event: Dict[str, Any]) -> bool:
45
+ return event.get("detail_type") == "private"
46
+
47
+ def decorator(func: Callable):
48
+ self.handler.register(func, priority, condition)
49
+ return func
50
+ return decorator
51
+
52
+ def on_group_message(self, priority: int = 0):
53
+ """
54
+ 群聊消息事件装饰器
55
+
56
+ :param priority: 处理器优先级
57
+ :return: 装饰器函数
58
+ """
59
+ def condition(event: Dict[str, Any]) -> bool:
60
+ return event.get("detail_type") == "group"
61
+
62
+ def decorator(func: Callable):
63
+ self.handler.register(func, priority, condition)
64
+ return func
65
+ return decorator
66
+
67
+ def on_at_message(self, priority: int = 0):
68
+ """
69
+ @消息事件装饰器
70
+
71
+ :param priority: 处理器优先级
72
+ :return: 装饰器函数
73
+ """
74
+ def condition(event: Dict[str, Any]) -> bool:
75
+ # 检查消息中是否有@机器人
76
+ message_segments = event.get("message", [])
77
+ self_id = event.get("self", {}).get("user_id")
78
+
79
+ for segment in message_segments:
80
+ if segment.get("type") == "mention" and segment.get("data", {}).get("user_id") == self_id:
81
+ return True
82
+ return False
83
+
84
+ def decorator(func: Callable):
85
+ self.handler.register(func, priority, condition)
86
+ return func
87
+ return decorator
88
+
89
+ message = MessageHandler()