AstrBot 4.3.3__py3-none-any.whl → 4.3.5__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,378 @@
1
+ """
2
+ 企业微信智能机器人 API 客户端
3
+ 处理消息加密解密、API 调用等
4
+ """
5
+
6
+ import json
7
+ import base64
8
+ import hashlib
9
+ from typing import Dict, Any, Optional, Tuple, Union
10
+ from Crypto.Cipher import AES
11
+ import aiohttp
12
+
13
+ from .WXBizJsonMsgCrypt import WXBizJsonMsgCrypt
14
+ from .wecomai_utils import WecomAIBotConstants
15
+ from astrbot import logger
16
+
17
+
18
+ class WecomAIBotAPIClient:
19
+ """企业微信智能机器人 API 客户端"""
20
+
21
+ def __init__(self, token: str, encoding_aes_key: str):
22
+ """初始化 API 客户端
23
+
24
+ Args:
25
+ token: 企业微信机器人 Token
26
+ encoding_aes_key: 消息加密密钥
27
+ """
28
+ self.token = token
29
+ self.encoding_aes_key = encoding_aes_key
30
+ self.wxcpt = WXBizJsonMsgCrypt(token, encoding_aes_key, "") # receiveid 为空串
31
+
32
+ async def decrypt_message(
33
+ self, encrypted_data: bytes, msg_signature: str, timestamp: str, nonce: str
34
+ ) -> Tuple[int, Optional[Dict[str, Any]]]:
35
+ """解密企业微信消息
36
+
37
+ Args:
38
+ encrypted_data: 加密的消息数据
39
+ msg_signature: 消息签名
40
+ timestamp: 时间戳
41
+ nonce: 随机数
42
+
43
+ Returns:
44
+ (错误码, 解密后的消息数据字典)
45
+ """
46
+ try:
47
+ ret, decrypted_msg = self.wxcpt.DecryptMsg(
48
+ encrypted_data, msg_signature, timestamp, nonce
49
+ )
50
+
51
+ if ret != WecomAIBotConstants.SUCCESS:
52
+ logger.error(f"消息解密失败,错误码: {ret}")
53
+ return ret, None
54
+
55
+ # 解析 JSON
56
+ if decrypted_msg:
57
+ try:
58
+ message_data = json.loads(decrypted_msg)
59
+ logger.debug(f"解密成功,消息内容: {message_data}")
60
+ return WecomAIBotConstants.SUCCESS, message_data
61
+ except json.JSONDecodeError as e:
62
+ logger.error(f"JSON 解析失败: {e}, 原始消息: {decrypted_msg}")
63
+ return WecomAIBotConstants.PARSE_XML_ERROR, None
64
+ else:
65
+ logger.error("解密消息为空")
66
+ return WecomAIBotConstants.DECRYPT_ERROR, None
67
+
68
+ except Exception as e:
69
+ logger.error(f"解密过程发生异常: {e}")
70
+ return WecomAIBotConstants.DECRYPT_ERROR, None
71
+
72
+ async def encrypt_message(
73
+ self, plain_message: str, nonce: str, timestamp: str
74
+ ) -> Optional[str]:
75
+ """加密消息
76
+
77
+ Args:
78
+ plain_message: 明文消息
79
+ nonce: 随机数
80
+ timestamp: 时间戳
81
+
82
+ Returns:
83
+ 加密后的消息,失败时返回 None
84
+ """
85
+ try:
86
+ ret, encrypted_msg = self.wxcpt.EncryptMsg(plain_message, nonce, timestamp)
87
+
88
+ if ret != WecomAIBotConstants.SUCCESS:
89
+ logger.error(f"消息加密失败,错误码: {ret}")
90
+ return None
91
+
92
+ logger.debug("消息加密成功")
93
+ return encrypted_msg
94
+
95
+ except Exception as e:
96
+ logger.error(f"加密过程发生异常: {e}")
97
+ return None
98
+
99
+ def verify_url(
100
+ self, msg_signature: str, timestamp: str, nonce: str, echostr: str
101
+ ) -> str:
102
+ """验证回调 URL
103
+
104
+ Args:
105
+ msg_signature: 消息签名
106
+ timestamp: 时间戳
107
+ nonce: 随机数
108
+ echostr: 验证字符串
109
+
110
+ Returns:
111
+ 验证结果字符串
112
+ """
113
+ try:
114
+ ret, echo_result = self.wxcpt.VerifyURL(
115
+ msg_signature, timestamp, nonce, echostr
116
+ )
117
+
118
+ if ret != WecomAIBotConstants.SUCCESS:
119
+ logger.error(f"URL 验证失败,错误码: {ret}")
120
+ return "verify fail"
121
+
122
+ logger.info("URL 验证成功")
123
+ return echo_result if echo_result else "verify fail"
124
+
125
+ except Exception as e:
126
+ logger.error(f"URL 验证发生异常: {e}")
127
+ return "verify fail"
128
+
129
+ async def process_encrypted_image(
130
+ self, image_url: str, aes_key_base64: Optional[str] = None
131
+ ) -> Tuple[bool, Union[bytes, str]]:
132
+ """下载并解密加密图片
133
+
134
+ Args:
135
+ image_url: 加密图片的 URL
136
+ aes_key_base64: Base64 编码的 AES 密钥,如果为 None 则使用实例的密钥
137
+
138
+ Returns:
139
+ (是否成功, 图片数据或错误信息)
140
+ """
141
+ try:
142
+ # 下载图片
143
+ logger.info(f"开始下载加密图片: {image_url}")
144
+
145
+ async with aiohttp.ClientSession() as session:
146
+ async with session.get(image_url, timeout=15) as response:
147
+ if response.status != 200:
148
+ error_msg = f"图片下载失败,状态码: {response.status}"
149
+ logger.error(error_msg)
150
+ return False, error_msg
151
+
152
+ encrypted_data = await response.read()
153
+ logger.info(f"图片下载成功,大小: {len(encrypted_data)} 字节")
154
+
155
+ # 准备解密密钥
156
+ if aes_key_base64 is None:
157
+ aes_key_base64 = self.encoding_aes_key
158
+
159
+ if not aes_key_base64:
160
+ raise ValueError("AES 密钥不能为空")
161
+
162
+ # Base64 解码密钥
163
+ aes_key = base64.b64decode(
164
+ aes_key_base64 + "=" * (-len(aes_key_base64) % 4)
165
+ )
166
+ if len(aes_key) != 32:
167
+ raise ValueError("无效的 AES 密钥长度: 应为 32 字节")
168
+
169
+ iv = aes_key[:16] # 初始向量为密钥前 16 字节
170
+
171
+ # 解密图片数据
172
+ cipher = AES.new(aes_key, AES.MODE_CBC, iv)
173
+ decrypted_data = cipher.decrypt(encrypted_data)
174
+
175
+ # 去除 PKCS#7 填充
176
+ pad_len = decrypted_data[-1]
177
+ if pad_len > 32: # AES-256 块大小为 32 字节
178
+ raise ValueError("无效的填充长度 (大于32字节)")
179
+
180
+ decrypted_data = decrypted_data[:-pad_len]
181
+ logger.info(f"图片解密成功,解密后大小: {len(decrypted_data)} 字节")
182
+
183
+ return True, decrypted_data
184
+
185
+ except aiohttp.ClientError as e:
186
+ error_msg = f"图片下载失败: {str(e)}"
187
+ logger.error(error_msg)
188
+ return False, error_msg
189
+
190
+ except ValueError as e:
191
+ error_msg = f"参数错误: {str(e)}"
192
+ logger.error(error_msg)
193
+ return False, error_msg
194
+
195
+ except Exception as e:
196
+ error_msg = f"图片处理异常: {str(e)}"
197
+ logger.error(error_msg)
198
+ return False, error_msg
199
+
200
+
201
+ class WecomAIBotStreamMessageBuilder:
202
+ """企业微信智能机器人流消息构建器"""
203
+
204
+ @staticmethod
205
+ def make_text_stream(stream_id: str, content: str, finish: bool = False) -> str:
206
+ """构建文本流消息
207
+
208
+ Args:
209
+ stream_id: 流 ID
210
+ content: 文本内容
211
+ finish: 是否结束
212
+
213
+ Returns:
214
+ JSON 格式的流消息字符串
215
+ """
216
+ plain = {
217
+ "msgtype": WecomAIBotConstants.MSG_TYPE_STREAM,
218
+ "stream": {"id": stream_id, "finish": finish, "content": content},
219
+ }
220
+ return json.dumps(plain, ensure_ascii=False)
221
+
222
+ @staticmethod
223
+ def make_image_stream(
224
+ stream_id: str, image_data: bytes, finish: bool = False
225
+ ) -> str:
226
+ """构建图片流消息
227
+
228
+ Args:
229
+ stream_id: 流 ID
230
+ image_data: 图片二进制数据
231
+ finish: 是否结束
232
+
233
+ Returns:
234
+ JSON 格式的流消息字符串
235
+ """
236
+ image_md5 = hashlib.md5(image_data).hexdigest()
237
+ image_base64 = base64.b64encode(image_data).decode("utf-8")
238
+
239
+ plain = {
240
+ "msgtype": WecomAIBotConstants.MSG_TYPE_STREAM,
241
+ "stream": {
242
+ "id": stream_id,
243
+ "finish": finish,
244
+ "msg_item": [
245
+ {
246
+ "msgtype": WecomAIBotConstants.MSG_TYPE_IMAGE,
247
+ "image": {"base64": image_base64, "md5": image_md5},
248
+ }
249
+ ],
250
+ },
251
+ }
252
+ return json.dumps(plain, ensure_ascii=False)
253
+
254
+ @staticmethod
255
+ def make_mixed_stream(
256
+ stream_id: str, content: str, msg_items: list, finish: bool = False
257
+ ) -> str:
258
+ """构建混合类型流消息
259
+
260
+ Args:
261
+ stream_id: 流 ID
262
+ content: 文本内容
263
+ msg_items: 消息项列表
264
+ finish: 是否结束
265
+
266
+ Returns:
267
+ JSON 格式的流消息字符串
268
+ """
269
+ plain = {
270
+ "msgtype": WecomAIBotConstants.MSG_TYPE_STREAM,
271
+ "stream": {"id": stream_id, "finish": finish, "msg_item": msg_items},
272
+ }
273
+ if content:
274
+ plain["stream"]["content"] = content
275
+ return json.dumps(plain, ensure_ascii=False)
276
+
277
+ @staticmethod
278
+ def make_text(content: str) -> str:
279
+ """构建文本消息
280
+
281
+ Args:
282
+ content: 文本内容
283
+
284
+ Returns:
285
+ JSON 格式的文本消息字符串
286
+ """
287
+ plain = {"msgtype": "text", "text": {"content": content}}
288
+ return json.dumps(plain, ensure_ascii=False)
289
+
290
+
291
+ class WecomAIBotMessageParser:
292
+ """企业微信智能机器人消息解析器"""
293
+
294
+ @staticmethod
295
+ def parse_text_message(data: Dict[str, Any]) -> Optional[str]:
296
+ """解析文本消息
297
+
298
+ Args:
299
+ data: 消息数据
300
+
301
+ Returns:
302
+ 文本内容,解析失败返回 None
303
+ """
304
+ try:
305
+ return data.get("text", {}).get("content")
306
+ except (KeyError, TypeError):
307
+ logger.warning("文本消息解析失败")
308
+ return None
309
+
310
+ @staticmethod
311
+ def parse_image_message(data: Dict[str, Any]) -> Optional[str]:
312
+ """解析图片消息
313
+
314
+ Args:
315
+ data: 消息数据
316
+
317
+ Returns:
318
+ 图片 URL,解析失败返回 None
319
+ """
320
+ try:
321
+ return data.get("image", {}).get("url")
322
+ except (KeyError, TypeError):
323
+ logger.warning("图片消息解析失败")
324
+ return None
325
+
326
+ @staticmethod
327
+ def parse_stream_message(data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
328
+ """解析流消息
329
+
330
+ Args:
331
+ data: 消息数据
332
+
333
+ Returns:
334
+ 流消息数据,解析失败返回 None
335
+ """
336
+ try:
337
+ stream_data = data.get("stream", {})
338
+ return {
339
+ "id": stream_data.get("id"),
340
+ "finish": stream_data.get("finish"),
341
+ "content": stream_data.get("content"),
342
+ "msg_item": stream_data.get("msg_item", []),
343
+ }
344
+ except (KeyError, TypeError):
345
+ logger.warning("流消息解析失败")
346
+ return None
347
+
348
+ @staticmethod
349
+ def parse_mixed_message(data: Dict[str, Any]) -> Optional[list]:
350
+ """解析混合消息
351
+
352
+ Args:
353
+ data: 消息数据
354
+
355
+ Returns:
356
+ 消息项列表,解析失败返回 None
357
+ """
358
+ try:
359
+ return data.get("mixed", {}).get("msg_item", [])
360
+ except (KeyError, TypeError):
361
+ logger.warning("混合消息解析失败")
362
+ return None
363
+
364
+ @staticmethod
365
+ def parse_event_message(data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
366
+ """解析事件消息
367
+
368
+ Args:
369
+ data: 消息数据
370
+
371
+ Returns:
372
+ 事件数据,解析失败返回 None
373
+ """
374
+ try:
375
+ return data.get("event", {})
376
+ except (KeyError, TypeError):
377
+ logger.warning("事件消息解析失败")
378
+ return None
@@ -0,0 +1,149 @@
1
+ """
2
+ 企业微信智能机器人事件处理模块,处理消息事件的发送和接收
3
+ """
4
+
5
+ from astrbot.api.event import AstrMessageEvent, MessageChain
6
+ from astrbot.api.message_components import (
7
+ Image,
8
+ Plain,
9
+ )
10
+ from astrbot.api import logger
11
+
12
+ from .wecomai_api import WecomAIBotAPIClient
13
+ from .wecomai_queue_mgr import wecomai_queue_mgr
14
+
15
+
16
+ class WecomAIBotMessageEvent(AstrMessageEvent):
17
+ """企业微信智能机器人消息事件"""
18
+
19
+ def __init__(
20
+ self,
21
+ message_str: str,
22
+ message_obj,
23
+ platform_meta,
24
+ session_id: str,
25
+ api_client: WecomAIBotAPIClient,
26
+ ):
27
+ """初始化消息事件
28
+
29
+ Args:
30
+ message_str: 消息字符串
31
+ message_obj: 消息对象
32
+ platform_meta: 平台元数据
33
+ session_id: 会话 ID
34
+ api_client: API 客户端
35
+ """
36
+ super().__init__(message_str, message_obj, platform_meta, session_id)
37
+ self.api_client = api_client
38
+
39
+ @staticmethod
40
+ async def _send(
41
+ message_chain: MessageChain,
42
+ stream_id: str,
43
+ streaming: bool = False,
44
+ ):
45
+ back_queue = wecomai_queue_mgr.get_or_create_back_queue(stream_id)
46
+
47
+ if not message_chain:
48
+ await back_queue.put(
49
+ {
50
+ "type": "end",
51
+ "data": "",
52
+ "streaming": False,
53
+ }
54
+ )
55
+ return ""
56
+
57
+ data = ""
58
+ for comp in message_chain.chain:
59
+ if isinstance(comp, Plain):
60
+ data = comp.text
61
+ await back_queue.put(
62
+ {
63
+ "type": "plain",
64
+ "data": data,
65
+ "streaming": streaming,
66
+ "session_id": stream_id,
67
+ }
68
+ )
69
+ elif isinstance(comp, Image):
70
+ # 处理图片消息
71
+ try:
72
+ image_base64 = await comp.convert_to_base64()
73
+ if image_base64:
74
+ await back_queue.put(
75
+ {
76
+ "type": "image",
77
+ "image_data": image_base64,
78
+ "streaming": streaming,
79
+ "session_id": stream_id,
80
+ }
81
+ )
82
+ else:
83
+ logger.warning("图片数据为空,跳过")
84
+ except Exception as e:
85
+ logger.error("处理图片消息失败: %s", e)
86
+ else:
87
+ logger.warning(f"[WecomAI] 不支持的消息组件类型: {type(comp)}, 跳过")
88
+
89
+ return data
90
+
91
+ async def send(self, message: MessageChain):
92
+ """发送消息"""
93
+ raw = self.message_obj.raw_message
94
+ assert isinstance(raw, dict), (
95
+ "wecom_ai_bot platform event raw_message should be a dict"
96
+ )
97
+ stream_id = raw.get("stream_id", self.session_id)
98
+ await WecomAIBotMessageEvent._send(message, stream_id)
99
+ await super().send(message)
100
+
101
+ async def send_streaming(self, generator, use_fallback=False):
102
+ """流式发送消息,参考webchat的send_streaming设计"""
103
+ final_data = ""
104
+ raw = self.message_obj.raw_message
105
+ assert isinstance(raw, dict), (
106
+ "wecom_ai_bot platform event raw_message should be a dict"
107
+ )
108
+ stream_id = raw.get("stream_id", self.session_id)
109
+ back_queue = wecomai_queue_mgr.get_or_create_back_queue(stream_id)
110
+
111
+ # 企业微信智能机器人不支持增量发送,因此我们需要在这里将增量内容累积起来,积累发送
112
+ increment_plain = ""
113
+ async for chain in generator:
114
+ # 累积增量内容,并改写 Plain 段
115
+ chain.squash_plain()
116
+ for comp in chain.chain:
117
+ if isinstance(comp, Plain):
118
+ comp.text = increment_plain + comp.text
119
+ increment_plain = comp.text
120
+ break
121
+
122
+ if chain.type == "break" and final_data:
123
+ # 分割符
124
+ await back_queue.put(
125
+ {
126
+ "type": "break", # break means a segment end
127
+ "data": final_data,
128
+ "streaming": True,
129
+ "session_id": self.session_id,
130
+ }
131
+ )
132
+ final_data = ""
133
+ continue
134
+
135
+ final_data += await WecomAIBotMessageEvent._send(
136
+ chain,
137
+ stream_id=stream_id,
138
+ streaming=True,
139
+ )
140
+
141
+ await back_queue.put(
142
+ {
143
+ "type": "complete", # complete means we return the final result
144
+ "data": final_data,
145
+ "streaming": True,
146
+ "session_id": self.session_id,
147
+ }
148
+ )
149
+ await super().send_streaming(generator, use_fallback)
@@ -0,0 +1,148 @@
1
+ """
2
+ 企业微信智能机器人队列管理器
3
+ 参考 webchat_queue_mgr.py,为企业微信智能机器人实现队列机制
4
+ 支持异步消息处理和流式响应
5
+ """
6
+
7
+ import asyncio
8
+ from typing import Dict, Any, Optional
9
+ from astrbot.api import logger
10
+
11
+
12
+ class WecomAIQueueMgr:
13
+ """企业微信智能机器人队列管理器"""
14
+
15
+ def __init__(self) -> None:
16
+ self.queues: Dict[str, asyncio.Queue] = {}
17
+ """StreamID 到输入队列的映射 - 用于接收用户消息"""
18
+
19
+ self.back_queues: Dict[str, asyncio.Queue] = {}
20
+ """StreamID 到输出队列的映射 - 用于发送机器人响应"""
21
+
22
+ self.pending_responses: Dict[str, Dict[str, Any]] = {}
23
+ """待处理的响应缓存,用于流式响应"""
24
+
25
+ def get_or_create_queue(self, session_id: str) -> asyncio.Queue:
26
+ """获取或创建指定会话的输入队列
27
+
28
+ Args:
29
+ session_id: 会话ID
30
+
31
+ Returns:
32
+ 输入队列实例
33
+ """
34
+ if session_id not in self.queues:
35
+ self.queues[session_id] = asyncio.Queue()
36
+ logger.debug(f"[WecomAI] 创建输入队列: {session_id}")
37
+ return self.queues[session_id]
38
+
39
+ def get_or_create_back_queue(self, session_id: str) -> asyncio.Queue:
40
+ """获取或创建指定会话的输出队列
41
+
42
+ Args:
43
+ session_id: 会话ID
44
+
45
+ Returns:
46
+ 输出队列实例
47
+ """
48
+ if session_id not in self.back_queues:
49
+ self.back_queues[session_id] = asyncio.Queue()
50
+ logger.debug(f"[WecomAI] 创建输出队列: {session_id}")
51
+ return self.back_queues[session_id]
52
+
53
+ def remove_queues(self, session_id: str):
54
+ """移除指定会话的所有队列
55
+
56
+ Args:
57
+ session_id: 会话ID
58
+ """
59
+ if session_id in self.queues:
60
+ del self.queues[session_id]
61
+ logger.debug(f"[WecomAI] 移除输入队列: {session_id}")
62
+
63
+ if session_id in self.back_queues:
64
+ del self.back_queues[session_id]
65
+ logger.debug(f"[WecomAI] 移除输出队列: {session_id}")
66
+
67
+ if session_id in self.pending_responses:
68
+ del self.pending_responses[session_id]
69
+ logger.debug(f"[WecomAI] 移除待处理响应: {session_id}")
70
+
71
+ def has_queue(self, session_id: str) -> bool:
72
+ """检查是否存在指定会话的队列
73
+
74
+ Args:
75
+ session_id: 会话ID
76
+
77
+ Returns:
78
+ 是否存在队列
79
+ """
80
+ return session_id in self.queues
81
+
82
+ def has_back_queue(self, session_id: str) -> bool:
83
+ """检查是否存在指定会话的输出队列
84
+
85
+ Args:
86
+ session_id: 会话ID
87
+
88
+ Returns:
89
+ 是否存在输出队列
90
+ """
91
+ return session_id in self.back_queues
92
+
93
+ def set_pending_response(self, session_id: str, callback_params: Dict[str, str]):
94
+ """设置待处理的响应参数
95
+
96
+ Args:
97
+ session_id: 会话ID
98
+ callback_params: 回调参数(nonce, timestamp等)
99
+ """
100
+ self.pending_responses[session_id] = {
101
+ "callback_params": callback_params,
102
+ "timestamp": asyncio.get_event_loop().time(),
103
+ }
104
+ logger.debug(f"[WecomAI] 设置待处理响应: {session_id}")
105
+
106
+ def get_pending_response(self, session_id: str) -> Optional[Dict[str, Any]]:
107
+ """获取待处理的响应参数
108
+
109
+ Args:
110
+ session_id: 会话ID
111
+
112
+ Returns:
113
+ 响应参数,如果不存在则返回None
114
+ """
115
+ return self.pending_responses.get(session_id)
116
+
117
+ def cleanup_expired_responses(self, max_age_seconds: int = 300):
118
+ """清理过期的待处理响应
119
+
120
+ Args:
121
+ max_age_seconds: 最大存活时间(秒)
122
+ """
123
+ current_time = asyncio.get_event_loop().time()
124
+ expired_sessions = []
125
+
126
+ for session_id, response_data in self.pending_responses.items():
127
+ if current_time - response_data["timestamp"] > max_age_seconds:
128
+ expired_sessions.append(session_id)
129
+
130
+ for session_id in expired_sessions:
131
+ del self.pending_responses[session_id]
132
+ logger.debug(f"[WecomAI] 清理过期响应: {session_id}")
133
+
134
+ def get_stats(self) -> Dict[str, int]:
135
+ """获取队列统计信息
136
+
137
+ Returns:
138
+ 统计信息字典
139
+ """
140
+ return {
141
+ "input_queues": len(self.queues),
142
+ "output_queues": len(self.back_queues),
143
+ "pending_responses": len(self.pending_responses),
144
+ }
145
+
146
+
147
+ # 全局队列管理器实例
148
+ wecomai_queue_mgr = WecomAIQueueMgr()