AstrBot 4.3.2__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.
Files changed (33) hide show
  1. astrbot/core/agent/mcp_client.py +18 -4
  2. astrbot/core/astr_agent_context.py +1 -0
  3. astrbot/core/config/default.py +66 -9
  4. astrbot/core/db/sqlite.py +7 -0
  5. astrbot/core/pipeline/context_utils.py +1 -0
  6. astrbot/core/pipeline/process_stage/method/llm_request.py +32 -14
  7. astrbot/core/pipeline/result_decorate/stage.py +44 -45
  8. astrbot/core/pipeline/scheduler.py +1 -1
  9. astrbot/core/platform/manager.py +4 -0
  10. astrbot/core/platform/sources/satori/satori_event.py +23 -1
  11. astrbot/core/platform/sources/webchat/webchat_adapter.py +0 -1
  12. astrbot/core/platform/sources/wecom_ai_bot/WXBizJsonMsgCrypt.py +289 -0
  13. astrbot/core/platform/sources/wecom_ai_bot/__init__.py +17 -0
  14. astrbot/core/platform/sources/wecom_ai_bot/ierror.py +20 -0
  15. astrbot/core/platform/sources/wecom_ai_bot/wecomai_adapter.py +445 -0
  16. astrbot/core/platform/sources/wecom_ai_bot/wecomai_api.py +378 -0
  17. astrbot/core/platform/sources/wecom_ai_bot/wecomai_event.py +149 -0
  18. astrbot/core/platform/sources/wecom_ai_bot/wecomai_queue_mgr.py +148 -0
  19. astrbot/core/platform/sources/wecom_ai_bot/wecomai_server.py +166 -0
  20. astrbot/core/platform/sources/wecom_ai_bot/wecomai_utils.py +199 -0
  21. astrbot/core/provider/provider.py +2 -1
  22. astrbot/core/provider/sources/anthropic_source.py +13 -7
  23. astrbot/core/provider/sources/dashscope_tts.py +120 -12
  24. astrbot/core/provider/sources/gemini_source.py +21 -17
  25. astrbot/core/provider/sources/openai_source.py +1 -1
  26. astrbot/dashboard/routes/session_management.py +6 -6
  27. astrbot/dashboard/routes/tools.py +14 -0
  28. astrbot/dashboard/routes/update.py +8 -5
  29. {astrbot-4.3.2.dist-info → astrbot-4.3.5.dist-info}/METADATA +64 -44
  30. {astrbot-4.3.2.dist-info → astrbot-4.3.5.dist-info}/RECORD +33 -24
  31. {astrbot-4.3.2.dist-info → astrbot-4.3.5.dist-info}/WHEEL +0 -0
  32. {astrbot-4.3.2.dist-info → astrbot-4.3.5.dist-info}/entry_points.txt +0 -0
  33. {astrbot-4.3.2.dist-info → astrbot-4.3.5.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,289 @@
1
+ #!/usr/bin/env python
2
+ # -*- encoding:utf-8 -*-
3
+
4
+ """对企业微信发送给企业后台的消息加解密示例代码.
5
+ @copyright: Copyright (c) 1998-2020 Tencent Inc.
6
+
7
+ """
8
+ # ------------------------------------------------------------------------
9
+
10
+ import logging
11
+ import base64
12
+ import random
13
+ import hashlib
14
+ import time
15
+ import struct
16
+ from Crypto.Cipher import AES
17
+ import socket
18
+ import json
19
+
20
+ from . import ierror
21
+
22
+ """
23
+ 关于Crypto.Cipher模块,ImportError: No module named 'Crypto'解决方案
24
+ 请到官方网站 https://www.dlitz.net/software/pycrypto/ 下载pycrypto。
25
+ 下载后,按照README中的“Installation”小节的提示进行pycrypto安装。
26
+ """
27
+
28
+
29
+ class FormatException(Exception):
30
+ pass
31
+
32
+
33
+ def throw_exception(message, exception_class=FormatException):
34
+ """my define raise exception function"""
35
+ raise exception_class(message)
36
+
37
+
38
+ class SHA1:
39
+ """计算企业微信的消息签名接口"""
40
+
41
+ def getSHA1(self, token, timestamp, nonce, encrypt):
42
+ """用SHA1算法生成安全签名
43
+ @param token: 票据
44
+ @param timestamp: 时间戳
45
+ @param encrypt: 密文
46
+ @param nonce: 随机字符串
47
+ @return: 安全签名
48
+ """
49
+ try:
50
+ # 确保所有输入都是字符串类型
51
+ if isinstance(encrypt, bytes):
52
+ encrypt = encrypt.decode("utf-8")
53
+
54
+ sortlist = [str(token), str(timestamp), str(nonce), str(encrypt)]
55
+ sortlist.sort()
56
+ sha = hashlib.sha1()
57
+ sha.update("".join(sortlist).encode("utf-8"))
58
+ return ierror.WXBizMsgCrypt_OK, sha.hexdigest()
59
+
60
+ except Exception as e:
61
+ print(e)
62
+ return ierror.WXBizMsgCrypt_ComputeSignature_Error, None
63
+
64
+
65
+ class JsonParse:
66
+ """提供提取消息格式中的密文及生成回复消息格式的接口"""
67
+
68
+ # json消息模板
69
+ AES_TEXT_RESPONSE_TEMPLATE = """{
70
+ "encrypt": "%(msg_encrypt)s",
71
+ "msgsignature": "%(msg_signaturet)s",
72
+ "timestamp": "%(timestamp)s",
73
+ "nonce": "%(nonce)s"
74
+ }"""
75
+
76
+ def extract(self, jsontext):
77
+ """提取出json数据包中的加密消息
78
+ @param jsontext: 待提取的json字符串
79
+ @return: 提取出的加密消息字符串
80
+ """
81
+ try:
82
+ json_dict = json.loads(jsontext)
83
+ return ierror.WXBizMsgCrypt_OK, json_dict["encrypt"]
84
+ except Exception as e:
85
+ print(e)
86
+ return ierror.WXBizMsgCrypt_ParseJson_Error, None
87
+
88
+ def generate(self, encrypt, signature, timestamp, nonce):
89
+ """生成json消息
90
+ @param encrypt: 加密后的消息密文
91
+ @param signature: 安全签名
92
+ @param timestamp: 时间戳
93
+ @param nonce: 随机字符串
94
+ @return: 生成的json字符串
95
+ """
96
+ resp_dict = {
97
+ "msg_encrypt": encrypt,
98
+ "msg_signaturet": signature,
99
+ "timestamp": timestamp,
100
+ "nonce": nonce,
101
+ }
102
+ resp_json = self.AES_TEXT_RESPONSE_TEMPLATE % resp_dict
103
+ return resp_json
104
+
105
+
106
+ class PKCS7Encoder:
107
+ """提供基于PKCS7算法的加解密接口"""
108
+
109
+ block_size = 32
110
+
111
+ def encode(self, text):
112
+ """对需要加密的明文进行填充补位
113
+ @param text: 需要进行填充补位操作的明文(bytes类型)
114
+ @return: 补齐明文字符串(bytes类型)
115
+ """
116
+ text_length = len(text)
117
+ # 计算需要填充的位数
118
+ amount_to_pad = self.block_size - (text_length % self.block_size)
119
+ if amount_to_pad == 0:
120
+ amount_to_pad = self.block_size
121
+ # 获得补位所用的字符
122
+ pad = bytes([amount_to_pad])
123
+ # 确保text是bytes类型
124
+ if isinstance(text, str):
125
+ text = text.encode("utf-8")
126
+ return text + pad * amount_to_pad
127
+
128
+ def decode(self, decrypted):
129
+ """删除解密后明文的补位字符
130
+ @param decrypted: 解密后的明文
131
+ @return: 删除补位字符后的明文
132
+ """
133
+ pad = ord(decrypted[-1])
134
+ if pad < 1 or pad > 32:
135
+ pad = 0
136
+ return decrypted[:-pad]
137
+
138
+
139
+ class Prpcrypt(object):
140
+ """提供接收和推送给企业微信消息的加解密接口"""
141
+
142
+ def __init__(self, key):
143
+ # self.key = base64.b64decode(key+"=")
144
+ self.key = key
145
+ # 设置加解密模式为AES的CBC模式
146
+ self.mode = AES.MODE_CBC
147
+
148
+ def encrypt(self, text, receiveid):
149
+ """对明文进行加密
150
+ @param text: 需要加密的明文
151
+ @return: 加密得到的字符串
152
+ """
153
+ # 16位随机字符串添加到明文开头
154
+ text = text.encode()
155
+ text = (
156
+ self.get_random_str()
157
+ + struct.pack("I", socket.htonl(len(text)))
158
+ + text
159
+ + receiveid.encode()
160
+ )
161
+
162
+ # 使用自定义的填充方式对明文进行补位填充
163
+ pkcs7 = PKCS7Encoder()
164
+ text = pkcs7.encode(text)
165
+ # 加密
166
+ cryptor = AES.new(self.key, self.mode, self.key[:16]) # type: ignore
167
+ try:
168
+ ciphertext = cryptor.encrypt(text)
169
+ # 使用BASE64对加密后的字符串进行编码
170
+ return ierror.WXBizMsgCrypt_OK, base64.b64encode(ciphertext)
171
+ except Exception as e:
172
+ logger = logging.getLogger("astrbot")
173
+ logger.error(e)
174
+ return ierror.WXBizMsgCrypt_EncryptAES_Error, None
175
+
176
+ def decrypt(self, text, receiveid):
177
+ """对解密后的明文进行补位删除
178
+ @param text: 密文
179
+ @return: 删除填充补位后的明文
180
+ """
181
+ try:
182
+ cryptor = AES.new(self.key, self.mode, self.key[:16]) # type: ignore
183
+ # 使用BASE64对密文进行解码,然后AES-CBC解密
184
+ plain_text = cryptor.decrypt(base64.b64decode(text))
185
+ except Exception as e:
186
+ print(e)
187
+ return ierror.WXBizMsgCrypt_DecryptAES_Error, None
188
+ try:
189
+ pad = plain_text[-1]
190
+ # 去掉补位字符串
191
+ # pkcs7 = PKCS7Encoder()
192
+ # plain_text = pkcs7.encode(plain_text)
193
+ # 去除16位随机字符串
194
+ content = plain_text[16:-pad]
195
+ json_len = socket.ntohl(struct.unpack("I", content[:4])[0])
196
+ json_content = content[4 : json_len + 4].decode("utf-8")
197
+ from_receiveid = content[json_len + 4 :].decode("utf-8")
198
+ except Exception as e:
199
+ print(e)
200
+ return ierror.WXBizMsgCrypt_IllegalBuffer, None
201
+ if from_receiveid != receiveid:
202
+ print("receiveid not match", receiveid, from_receiveid)
203
+ return ierror.WXBizMsgCrypt_ValidateCorpid_Error, None
204
+ return 0, json_content
205
+
206
+ def get_random_str(self):
207
+ """随机生成16位字符串
208
+ @return: 16位字符串
209
+ """
210
+ return str(random.randint(1000000000000000, 9999999999999999)).encode()
211
+
212
+
213
+ class WXBizJsonMsgCrypt(object):
214
+ # 构造函数
215
+ def __init__(self, sToken, sEncodingAESKey, sReceiveId):
216
+ try:
217
+ self.key = base64.b64decode(sEncodingAESKey + "=")
218
+ assert len(self.key) == 32
219
+ except Exception as e:
220
+ throw_exception(f"[error]: EncodingAESKey invalid: {e}", FormatException)
221
+ # return ierror.WXBizMsgCrypt_IllegalAesKey,None
222
+ self.m_sToken = sToken
223
+ self.m_sReceiveId = sReceiveId
224
+
225
+ # 验证URL
226
+ # @param sMsgSignature: 签名串,对应URL参数的msg_signature
227
+ # @param sTimeStamp: 时间戳,对应URL参数的timestamp
228
+ # @param sNonce: 随机串,对应URL参数的nonce
229
+ # @param sEchoStr: 随机串,对应URL参数的echostr
230
+ # @param sReplyEchoStr: 解密之后的echostr,当return返回0时有效
231
+ # @return:成功0,失败返回对应的错误码
232
+
233
+ def VerifyURL(self, sMsgSignature, sTimeStamp, sNonce, sEchoStr):
234
+ sha1 = SHA1()
235
+ ret, signature = sha1.getSHA1(self.m_sToken, sTimeStamp, sNonce, sEchoStr)
236
+ if ret != 0:
237
+ return ret, None
238
+ if not signature == sMsgSignature:
239
+ return ierror.WXBizMsgCrypt_ValidateSignature_Error, None
240
+ pc = Prpcrypt(self.key)
241
+ ret, sReplyEchoStr = pc.decrypt(sEchoStr, self.m_sReceiveId)
242
+ return ret, sReplyEchoStr
243
+
244
+ def EncryptMsg(self, sReplyMsg, sNonce, timestamp=None):
245
+ # 将企业回复用户的消息加密打包
246
+ # @param sReplyMsg: 企业号待回复用户的消息,json格式的字符串
247
+ # @param sTimeStamp: 时间戳,可以自己生成,也可以用URL参数的timestamp,如为None则自动用当前时间
248
+ # @param sNonce: 随机串,可以自己生成,也可以用URL参数的nonce
249
+ # sEncryptMsg: 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的json格式的字符串,
250
+ # return:成功0,sEncryptMsg,失败返回对应的错误码None
251
+ pc = Prpcrypt(self.key)
252
+ ret, encrypt = pc.encrypt(sReplyMsg, self.m_sReceiveId)
253
+ encrypt = encrypt.decode("utf-8") # type: ignore
254
+ if ret != 0:
255
+ return ret, None
256
+ if timestamp is None:
257
+ timestamp = str(int(time.time()))
258
+ # 生成安全签名
259
+ sha1 = SHA1()
260
+ ret, signature = sha1.getSHA1(self.m_sToken, timestamp, sNonce, encrypt)
261
+ if ret != 0:
262
+ return ret, None
263
+ jsonParse = JsonParse()
264
+ return ret, jsonParse.generate(encrypt, signature, timestamp, sNonce)
265
+
266
+ def DecryptMsg(self, sPostData, sMsgSignature, sTimeStamp, sNonce):
267
+ # 检验消息的真实性,并且获取解密后的明文
268
+ # @param sMsgSignature: 签名串,对应URL参数的msg_signature
269
+ # @param sTimeStamp: 时间戳,对应URL参数的timestamp
270
+ # @param sNonce: 随机串,对应URL参数的nonce
271
+ # @param sPostData: 密文,对应POST请求的数据
272
+ # json_content: 解密后的原文,当return返回0时有效
273
+ # @return: 成功0,失败返回对应的错误码
274
+ # 验证安全签名
275
+ jsonParse = JsonParse()
276
+ ret, encrypt = jsonParse.extract(sPostData)
277
+ if ret != 0:
278
+ return ret, None
279
+ sha1 = SHA1()
280
+ ret, signature = sha1.getSHA1(self.m_sToken, sTimeStamp, sNonce, encrypt)
281
+ if ret != 0:
282
+ return ret, None
283
+ if not signature == sMsgSignature:
284
+ print("signature not match")
285
+ print(signature)
286
+ return ierror.WXBizMsgCrypt_ValidateSignature_Error, None
287
+ pc = Prpcrypt(self.key)
288
+ ret, json_content = pc.decrypt(encrypt, self.m_sReceiveId)
289
+ return ret, json_content
@@ -0,0 +1,17 @@
1
+ """
2
+ 企业微信智能机器人平台适配器包
3
+ """
4
+
5
+ from .wecomai_adapter import WecomAIBotAdapter
6
+ from .wecomai_api import WecomAIBotAPIClient
7
+ from .wecomai_event import WecomAIBotMessageEvent
8
+ from .wecomai_server import WecomAIBotServer
9
+ from .wecomai_utils import WecomAIBotConstants
10
+
11
+ __all__ = [
12
+ "WecomAIBotAdapter",
13
+ "WecomAIBotAPIClient",
14
+ "WecomAIBotMessageEvent",
15
+ "WecomAIBotServer",
16
+ "WecomAIBotConstants",
17
+ ]
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ #########################################################################
4
+ # Author: jonyqin
5
+ # Created Time: Thu 11 Sep 2014 01:53:58 PM CST
6
+ # File Name: ierror.py
7
+ # Description:定义错误码含义
8
+ #########################################################################
9
+ WXBizMsgCrypt_OK = 0
10
+ WXBizMsgCrypt_ValidateSignature_Error = -40001
11
+ WXBizMsgCrypt_ParseJson_Error = -40002
12
+ WXBizMsgCrypt_ComputeSignature_Error = -40003
13
+ WXBizMsgCrypt_IllegalAesKey = -40004
14
+ WXBizMsgCrypt_ValidateCorpid_Error = -40005
15
+ WXBizMsgCrypt_EncryptAES_Error = -40006
16
+ WXBizMsgCrypt_DecryptAES_Error = -40007
17
+ WXBizMsgCrypt_IllegalBuffer = -40008
18
+ WXBizMsgCrypt_EncodeBase64_Error = -40009
19
+ WXBizMsgCrypt_DecodeBase64_Error = -40010
20
+ WXBizMsgCrypt_GenReturnJson_Error = -40011