forked from FloraBotTeam/FloraBot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFloraBot.py
More file actions
423 lines (386 loc) · 29.1 KB
/
Copy pathFloraBot.py
File metadata and controls
423 lines (386 loc) · 29.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
from flask import Flask, request
from websocket_server import WebsocketServer, WebSocketHandler
import logging
from socketserver import TCPServer
import requests
import importlib.util
import os
import json
import threading
import sys
import subprocess
import platform
flora_logo = "\x1b[38;2;255;0;0m█\x1b[38;2;250;0;4m█\x1b[38;2;246;0;8m█\x1b[38;2;242;0;12m█\x1b[38;2;238;0;16m█\x1b[38;2;234;0;20m█\x1b[38;2;229;0;25m█\x1b[38;2;225;0;29m╗\x1b[38;2;221;0;33m \x1b[38;2;217;0;37m█\x1b[38;2;213;0;41m█\x1b[38;2;209;0;45m╗\x1b[38;2;204;0;50m \x1b[38;2;200;0;54m \x1b[38;2;196;0;58m \x1b[38;2;192;0;62m \x1b[38;2;188;0;66m \x1b[38;2;183;0;71m \x1b[38;2;179;0;75m \x1b[38;2;175;0;79m \x1b[38;2;171;0;83m \x1b[38;2;167;0;87m \x1b[38;2;163;0;91m \x1b[38;2;158;0;96m \x1b[38;2;154;0;100m \x1b[38;2;150;0;104m \x1b[38;2;146;0;108m \x1b[38;2;142;0;112m \x1b[38;2;137;0;117m \x1b[38;2;133;0;121m \x1b[38;2;129;0;125m \x1b[38;2;125;0;129m \x1b[38;2;121;0;133m \x1b[38;2;117;0;137m \x1b[38;2;112;0;142m \x1b[38;2;108;0;146m \x1b[38;2;104;0;150m \x1b[38;2;100;0;154m \x1b[38;2;96;0;158m█\x1b[38;2;91;0;163m█\x1b[38;2;87;0;167m█\x1b[38;2;83;0;171m█\x1b[38;2;79;0;175m█\x1b[38;2;75;0;179m█\x1b[38;2;71;0;183m╗\x1b[38;2;66;0;188m \x1b[38;2;62;0;192m \x1b[38;2;58;0;196m \x1b[38;2;54;0;200m \x1b[38;2;50;0;204m \x1b[38;2;45;0;209m \x1b[38;2;41;0;213m \x1b[38;2;37;0;217m \x1b[38;2;33;0;221m \x1b[38;2;29;0;225m \x1b[38;2;25;0;229m \x1b[38;2;20;0;234m \x1b[38;2;16;0;238m \x1b[38;2;12;0;242m \x1b[38;2;8;0;246m \x1b[38;2;4;0;250m \x1b[38;2;0;0;255m \x1b[0m\n\x1b[38;2;255;0;0m█\x1b[38;2;250;0;4m█\x1b[38;2;246;0;8m╔\x1b[38;2;242;0;12m═\x1b[38;2;238;0;16m═\x1b[38;2;234;0;20m═\x1b[38;2;229;0;25m═\x1b[38;2;225;0;29m╝\x1b[38;2;221;0;33m \x1b[38;2;217;0;37m█\x1b[38;2;213;0;41m█\x1b[38;2;209;0;45m║\x1b[38;2;204;0;50m \x1b[38;2;200;0;54m \x1b[38;2;196;0;58m \x1b[38;2;192;0;62m \x1b[38;2;188;0;66m \x1b[38;2;183;0;71m \x1b[38;2;179;0;75m \x1b[38;2;175;0;79m \x1b[38;2;171;0;83m \x1b[38;2;167;0;87m \x1b[38;2;163;0;91m \x1b[38;2;158;0;96m \x1b[38;2;154;0;100m \x1b[38;2;150;0;104m \x1b[38;2;146;0;108m \x1b[38;2;142;0;112m \x1b[38;2;137;0;117m \x1b[38;2;133;0;121m \x1b[38;2;129;0;125m \x1b[38;2;125;0;129m \x1b[38;2;121;0;133m \x1b[38;2;117;0;137m \x1b[38;2;112;0;142m \x1b[38;2;108;0;146m \x1b[38;2;104;0;150m \x1b[38;2;100;0;154m \x1b[38;2;96;0;158m█\x1b[38;2;91;0;163m█\x1b[38;2;87;0;167m╔\x1b[38;2;83;0;171m═\x1b[38;2;79;0;175m═\x1b[38;2;75;0;179m█\x1b[38;2;71;0;183m█\x1b[38;2;66;0;188m╗\x1b[38;2;62;0;192m \x1b[38;2;58;0;196m \x1b[38;2;54;0;200m \x1b[38;2;50;0;204m \x1b[38;2;45;0;209m \x1b[38;2;41;0;213m \x1b[38;2;37;0;217m \x1b[38;2;33;0;221m \x1b[38;2;29;0;225m \x1b[38;2;25;0;229m \x1b[38;2;20;0;234m \x1b[38;2;16;0;238m█\x1b[38;2;12;0;242m█\x1b[38;2;8;0;246m╗\x1b[38;2;4;0;250m \x1b[38;2;0;0;255m \x1b[0m\n\x1b[38;2;255;0;0m█\x1b[38;2;250;0;4m█\x1b[38;2;246;0;8m█\x1b[38;2;242;0;12m█\x1b[38;2;238;0;16m█\x1b[38;2;234;0;20m╗\x1b[38;2;229;0;25m \x1b[38;2;225;0;29m \x1b[38;2;221;0;33m \x1b[38;2;217;0;37m█\x1b[38;2;213;0;41m█\x1b[38;2;209;0;45m║\x1b[38;2;204;0;50m \x1b[38;2;200;0;54m \x1b[38;2;196;0;58m \x1b[38;2;192;0;62m█\x1b[38;2;188;0;66m█\x1b[38;2;183;0;71m█\x1b[38;2;179;0;75m█\x1b[38;2;175;0;79m╗\x1b[38;2;171;0;83m \x1b[38;2;167;0;87m \x1b[38;2;163;0;91m \x1b[38;2;158;0;96m█\x1b[38;2;154;0;100m█\x1b[38;2;150;0;104m█\x1b[38;2;146;0;108m█\x1b[38;2;142;0;112m╗\x1b[38;2;137;0;117m \x1b[38;2;133;0;121m \x1b[38;2;129;0;125m█\x1b[38;2;125;0;129m█\x1b[38;2;121;0;133m█\x1b[38;2;117;0;137m█\x1b[38;2;112;0;142m╗\x1b[38;2;108;0;146m \x1b[38;2;104;0;150m \x1b[38;2;100;0;154m \x1b[38;2;96;0;158m█\x1b[38;2;91;0;163m█\x1b[38;2;87;0;167m█\x1b[38;2;83;0;171m█\x1b[38;2;79;0;175m█\x1b[38;2;75;0;179m█\x1b[38;2;71;0;183m╔\x1b[38;2;66;0;188m╝\x1b[38;2;62;0;192m \x1b[38;2;58;0;196m \x1b[38;2;54;0;200m█\x1b[38;2;50;0;204m█\x1b[38;2;45;0;209m█\x1b[38;2;41;0;213m█\x1b[38;2;37;0;217m╗\x1b[38;2;33;0;221m \x1b[38;2;29;0;225m \x1b[38;2;25;0;229m█\x1b[38;2;20;0;234m█\x1b[38;2;16;0;238m█\x1b[38;2;12;0;242m█\x1b[38;2;8;0;246m█\x1b[38;2;4;0;250m█\x1b[38;2;0;0;255m╗\x1b[0m\n\x1b[38;2;255;0;0m█\x1b[38;2;250;0;4m█\x1b[38;2;246;0;8m╔\x1b[38;2;242;0;12m═\x1b[38;2;238;0;16m═\x1b[38;2;234;0;20m╝\x1b[38;2;229;0;25m \x1b[38;2;225;0;29m \x1b[38;2;221;0;33m \x1b[38;2;217;0;37m█\x1b[38;2;213;0;41m█\x1b[38;2;209;0;45m║\x1b[38;2;204;0;50m \x1b[38;2;200;0;54m \x1b[38;2;196;0;58m█\x1b[38;2;192;0;62m█\x1b[38;2;188;0;66m╔\x1b[38;2;183;0;71m═\x1b[38;2;179;0;75m█\x1b[38;2;175;0;79m█\x1b[38;2;171;0;83m╗\x1b[38;2;167;0;87m \x1b[38;2;163;0;91m█\x1b[38;2;158;0;96m█\x1b[38;2;154;0;100m╔\x1b[38;2;150;0;104m═\x1b[38;2;146;0;108m═\x1b[38;2;142;0;112m╝\x1b[38;2;137;0;117m \x1b[38;2;133;0;121m█\x1b[38;2;129;0;125m█\x1b[38;2;125;0;129m╔\x1b[38;2;121;0;133m═\x1b[38;2;117;0;137m█\x1b[38;2;112;0;142m█\x1b[38;2;108;0;146m╗\x1b[38;2;104;0;150m \x1b[38;2;100;0;154m \x1b[38;2;96;0;158m█\x1b[38;2;91;0;163m█\x1b[38;2;87;0;167m╔\x1b[38;2;83;0;171m═\x1b[38;2;79;0;175m═\x1b[38;2;75;0;179m█\x1b[38;2;71;0;183m█\x1b[38;2;66;0;188m╗\x1b[38;2;62;0;192m \x1b[38;2;58;0;196m█\x1b[38;2;54;0;200m█\x1b[38;2;50;0;204m╔\x1b[38;2;45;0;209m═\x1b[38;2;41;0;213m█\x1b[38;2;37;0;217m█\x1b[38;2;33;0;221m╗\x1b[38;2;29;0;225m \x1b[38;2;25;0;229m \x1b[38;2;20;0;234m╚\x1b[38;2;16;0;238m█\x1b[38;2;12;0;242m█\x1b[38;2;8;0;246m╔\x1b[38;2;4;0;250m═\x1b[38;2;0;0;255m╝\x1b[0m\n\x1b[38;2;255;0;0m█\x1b[38;2;250;0;4m█\x1b[38;2;246;0;8m║\x1b[38;2;242;0;12m \x1b[38;2;238;0;16m \x1b[38;2;234;0;20m \x1b[38;2;229;0;25m \x1b[38;2;225;0;29m \x1b[38;2;221;0;33m \x1b[38;2;217;0;37m█\x1b[38;2;213;0;41m█\x1b[38;2;209;0;45m█\x1b[38;2;204;0;50m╗\x1b[38;2;200;0;54m \x1b[38;2;196;0;58m╚\x1b[38;2;192;0;62m█\x1b[38;2;188;0;66m█\x1b[38;2;183;0;71m█\x1b[38;2;179;0;75m█\x1b[38;2;175;0;79m╔\x1b[38;2;171;0;83m╝\x1b[38;2;167;0;87m \x1b[38;2;163;0;91m█\x1b[38;2;158;0;96m█\x1b[38;2;154;0;100m║\x1b[38;2;150;0;104m \x1b[38;2;146;0;108m \x1b[38;2;142;0;112m \x1b[38;2;137;0;117m \x1b[38;2;133;0;121m╚\x1b[38;2;129;0;125m█\x1b[38;2;125;0;129m█\x1b[38;2;121;0;133m█\x1b[38;2;117;0;137m█\x1b[38;2;112;0;142m█\x1b[38;2;108;0;146m█\x1b[38;2;104;0;150m╗\x1b[38;2;100;0;154m \x1b[38;2;96;0;158m█\x1b[38;2;91;0;163m█\x1b[38;2;87;0;167m█\x1b[38;2;83;0;171m█\x1b[38;2;79;0;175m█\x1b[38;2;75;0;179m█\x1b[38;2;71;0;183m╔\x1b[38;2;66;0;188m╝\x1b[38;2;62;0;192m \x1b[38;2;58;0;196m╚\x1b[38;2;54;0;200m█\x1b[38;2;50;0;204m█\x1b[38;2;45;0;209m█\x1b[38;2;41;0;213m█\x1b[38;2;37;0;217m╔\x1b[38;2;33;0;221m╝\x1b[38;2;29;0;225m \x1b[38;2;25;0;229m \x1b[38;2;20;0;234m \x1b[38;2;16;0;238m█\x1b[38;2;12;0;242m█\x1b[38;2;8;0;246m█\x1b[38;2;4;0;250m╗\x1b[38;2;0;0;255m \x1b[0m\n\x1b[38;2;255;0;0m╚\x1b[38;2;250;0;4m═\x1b[38;2;246;0;8m╝\x1b[38;2;242;0;12m \x1b[38;2;238;0;16m \x1b[38;2;234;0;20m \x1b[38;2;229;0;25m \x1b[38;2;225;0;29m \x1b[38;2;221;0;33m \x1b[38;2;217;0;37m╚\x1b[38;2;213;0;41m═\x1b[38;2;209;0;45m═\x1b[38;2;204;0;50m╝\x1b[38;2;200;0;54m \x1b[38;2;196;0;58m \x1b[38;2;192;0;62m╚\x1b[38;2;188;0;66m═\x1b[38;2;183;0;71m═\x1b[38;2;179;0;75m═\x1b[38;2;175;0;79m╝\x1b[38;2;171;0;83m \x1b[38;2;167;0;87m \x1b[38;2;163;0;91m╚\x1b[38;2;158;0;96m═\x1b[38;2;154;0;100m╝\x1b[38;2;150;0;104m \x1b[38;2;146;0;108m \x1b[38;2;142;0;112m \x1b[38;2;137;0;117m \x1b[38;2;133;0;121m \x1b[38;2;129;0;125m╚\x1b[38;2;125;0;129m═\x1b[38;2;121;0;133m═\x1b[38;2;117;0;137m═\x1b[38;2;112;0;142m═\x1b[38;2;108;0;146m═\x1b[38;2;104;0;150m╝\x1b[38;2;100;0;154m \x1b[38;2;96;0;158m╚\x1b[38;2;91;0;163m═\x1b[38;2;87;0;167m═\x1b[38;2;83;0;171m═\x1b[38;2;79;0;175m═\x1b[38;2;75;0;179m═\x1b[38;2;71;0;183m╝\x1b[38;2;66;0;188m \x1b[38;2;62;0;192m \x1b[38;2;58;0;196m \x1b[38;2;54;0;200m╚\x1b[38;2;50;0;204m═\x1b[38;2;45;0;209m═\x1b[38;2;41;0;213m═\x1b[38;2;37;0;217m╝\x1b[38;2;33;0;221m \x1b[38;2;29;0;225m \x1b[38;2;25;0;229m \x1b[38;2;20;0;234m \x1b[38;2;16;0;238m╚\x1b[38;2;12;0;242m═\x1b[38;2;8;0;246m═\x1b[38;2;4;0;250m╝\x1b[38;2;0;0;255m \x1b[0m\n"
flora_server = Flask("FloraBot", template_folder="FloraBot", static_folder="FloraBot")
connection_type = "HTTP"
flora_host = "127.0.0.1"
flora_port = 3003
framework_address = "127.0.0.1:3000"
bot_id = 0
administrator = []
auto_install = False
flora_version = "V1.11 Beta"
plugins_dict = {} # 插件对象字典
plugins_info_dict = {} # 插件信息字典
def load_config(): # 加载FloraBot配置文件函数
global auto_install, connection_type, flora_host, flora_port, framework_address, bot_id, administrator
if not os.path.isdir("./FloraBot"):
os.makedirs("./FloraBot")
if not os.path.isdir("./FloraBot/Plugins"):
os.makedirs("./FloraBot/Plugins")
if os.path.isfile("./Config.json"): # 若文件存在
with open("./Config.json", "r", encoding="UTF-8") as read_flora_config:
flora_config = json.loads(read_flora_config.read())
update_check = flora_config.get("update_check")
auto_install = flora_config.get("AutoInstallLibraries")
connection_type = flora_config.get("ConnectionType")
flora_api.update({"ConnectionType": connection_type})
flora_host = flora_config.get("FloraHost")
flora_api.update({"FloraHost": flora_host})
flora_port = flora_config.get("FloraPort")
flora_api.update({"FloraPort": flora_port})
framework_address = flora_config.get("FrameworkAddress")
flora_api.update({"FrameworkAddress": framework_address})
bot_id = flora_config.get("BotID")
flora_api.update({"BotID": bot_id})
administrator = flora_config.get("Administrator")
flora_api.update({"Administrator": administrator})
else: # 若文件不存在
print("FloraBot 启动失败, 未找到配置文件 Config.json")
with open("./Config.json", "w", encoding="UTF-8") as write_flora_config:
write_flora_config.write(json.dumps({"AutoInstallLibraries": True, "ConnectionType": "HTTP", "FloraHost": "127.0.0.1", "FloraPort": 3003, "FrameworkAddress": "127.0.0.1:3000", "BotQQ": 0, "Administrator": [0]}, ensure_ascii=False, indent=4))
print("已生成一个新的配置文件 Config.json , 请修改后再次启动 FloraBot")
exit()
def updata_check(update_url, version, update_check_status):
try:
import requests
if update_check_status == True:
print(f"开始检查更新,当前版本:{version}")
requests =requests.get(update_url)
if requests.status_code == 200:
data = requests.json()
if not data['version'] == version:
print(f"发现新版本:{data['version']}")
print(f"更新内容:{data['content']}")
return True
else:
print("当前已是最新版本")
return False
else:
print("更新服务器连接失败,请稍后再试")
return False
else:
print("更新检查未开启")
return False
except Exception as e:
print(f"更新检查失败:{e}")
return False
def send_msg(send_type: str, msg: str, uid: str | int, gid: str | int | None, mid: str | int | None = None, ws_client=None, ws_server=None, send_host: str = "", send_port: int | str = ""):
# 发送消息函数,send_type: 发送类型,决定是用HTTP还是WebSocket发送消息
# msg: 正文,uid: ID,gid: 群号,mid: 消息编号
# ws_client: WebSocket连接实例,ws_server: WebSocket服务端实例(若发送类型为WebSocket这两个参数必填)
# send_host: HTTP协议发送地址,send_port: HTTP协议发送端口(若填这两个参数则使用自定义地址发送)
if send_type == "HTTP":
send_address = framework_address
if send_host != "" and send_port != "":
send_address = f"{send_host}:{send_port}"
url = f"http://{send_address}"
data = {}
if mid is not None: # 当消息编号不为None时,则发送的消息为回复
data.update({"message": f"[CQ:reply,id={mid}]{msg}"})
else: # 反之为普通消息
data.update({"message": msg})
if gid is not None: # 当群号不为None时,则发送给群聊
url += f"/send_group_msg"
data.update({"group_id": gid})
else: # 反之为私聊
url += f"/send_private_msg"
data.update({"user_id": uid})
try:
requests.post(url, json=data, timeout=5) # 提交发送消息
except requests.exceptions.RequestException:
pass
elif send_type == "WebSocket":
data = {}
send_params = {}
if mid is not None: # 当消息编号不为None时,则发送的消息为回复
send_params.update({"message": f"[CQ:reply,id={mid}]{msg}"})
else: # 反之为普通消息
send_params.update({"message": msg})
if gid is not None: # 当群号不为None时,则发送给群聊
data.update({"action": "send_group_msg"})
send_params.update({"group_id": gid})
else: # 反之为私聊
data.update({"action": "send_private_msg"})
send_params.update({"user_id": uid})
data.update({"params": send_params})
try:
if ws_server is not None and ws_client is not None:
ws_server.send_message(ws_client, json.dumps(data, ensure_ascii=False))
except ConnectionError:
pass
except TypeError:
pass
def install_libraries(libraries_name: str):
if importlib.util.find_spec(libraries_name) is None:
print(f"正在安装 {libraries_name} 库...")
try:
subprocess.check_call([sys.executable, "-m", "pip", "install", libraries_name])
print(f"{libraries_name} 库安装完成")
except subprocess.CalledProcessError:
print(f"{libraries_name} 库安装失败")
def load_plugins(): # 加载插件函数
print("正在加载插件, 请稍后...")
plugins_info_dict.clear()
plugins_dict.clear()
for plugin in os.listdir("./FloraBot/Plugins"): # 遍历所有插件
plugin_path = f"FloraBot/Plugins/{plugin}"
if os.path.isfile(f"./{plugin_path}/Plugin.json"):
with open(f"./{plugin_path}/Plugin.json", "r", encoding="UTF-8") as read_plugin_config:
plugin_config = json.loads(read_plugin_config.read())
if os.path.isfile(f"./{plugin_path}/{plugin_config.get('MainPyName')}.py") and plugin_config.get(
"EnablePlugin"): # 如果配置正确则导入插件
plugin_config = plugin_config.copy()
print(f"正在加载插件 {plugin_config.get('PluginName')} ...")
plugin_config.update({"ThePluginPath": plugin_path})
plugins_info_dict.update({plugin_config.get("PluginName"): plugin_config}) # 添加插件信息
if auto_install and plugin_config.get("DependentLibraries") is not None:
print("已开启自动安装依赖库, 正在安装插件所依赖的库...")
for libraries_name in plugin_config.get("DependentLibraries"):
install_libraries(libraries_name)
spec = importlib.util.spec_from_file_location(plugin_config.get("MainPyName"), f"./{plugin_path}/{plugin_config.get('MainPyName')}.py")
module = importlib.util.module_from_spec(spec)
try:
spec.loader.exec_module(module)
except ModuleNotFoundError as error_info:
if auto_install:
install_libraries(str(error_info).split("'")[1])
spec.loader.exec_module(module)
else:
raise ModuleNotFoundError(error_info)
try:
module.flora_api = flora_api.copy() # 传入API参数
except AttributeError:
pass
module.flora_api.update({"ThePluginPath": plugin_path})
try:
threading.Thread(target=module.init).start() # 开线程初始化插件
except AttributeError:
pass
plugins_dict.update({plugin_config.get("PluginName"): module}) # 添加插件对象
update_flora_api()
def broadcast_event(data: dict, send_type: str, ws_client=None, ws_server=None, send_host: str = "", send_port: int | str = ""):
# 广播消息函数,data: 基于OneBot协议的数据
# send_type: 发送类型,告诉插件是用HTTP还是WebSocket发送消息
# ws_client: WebSocket连接实例,ws_server: WebSocket服务端实例(若发送类型为WebSocket这两个参数必填)
# send_host: HTTP协议发送地址,send_port: HTTP协议发送端口(若填这两个参数则使用自定义地址发送)
uid = data.get("user_id")
if uid in administrator: # 判断消息是否来自于管理员(主人)
gid = data.get("group_id")
mid = data.get("message_id")
msg = data.get("raw_message")
if msg is not None:
msg = msg.replace("[", "[").replace("]", "]").replace("&", "&").replace(",", ",") # 消息需要将URL编码替换到正确内容
builtin_function(msg, uid, gid, mid, send_type, ws_client, ws_server)
send_address = {}
if send_type == "HTTP":
send_address.update({"WebSocketClient": None, "WebSocketServer": None, "SendHost": send_host, "SendPort": send_port})
elif send_type == "WebSocket":
send_address.update({"WebSocketClient": ws_client, "WebSocketServer": ws_server, "SendHost": "", "SendPort": ""})
data.update({"SendType": send_type, "SendAddress": send_address})
for plugin in plugins_dict.values(): # 遍历开线程调用所有的插件事件函数
try:
threading.Thread(target=plugin.event, kwargs={"data": data}).start()
except AttributeError:
pass
def update_flora_api(): # 更新API内容函数
# noinspection PyTypeChecker
flora_api.update({"PluginsDict": plugins_dict.copy(), "PluginsInfoDict": plugins_info_dict.copy()})
for plugin in plugins_dict.values():
try:
plugin.flora_api.update(flora_api.copy())
except AttributeError:
pass
for plugin in plugins_dict.values(): # 遍历开线程调用所有的API更新事件函数
try:
threading.Thread(target=plugin.api_update_event).start()
except AttributeError:
pass
flora_api = {"FloraPath": os.path.dirname(os.path.abspath(__file__)), "ConnectionType": connection_type, "FloraHost": flora_host, "FloraPort": flora_port, "FrameworkAddress": framework_address, "BotID": bot_id, "Administrator": administrator, "FloraVersion": flora_version, "FloraServer": flora_server, "UpdateFloraApi": update_flora_api, "LoadPlugins": load_plugins, "BroadcastEvent": broadcast_event, "SendMsg": send_msg}
def builtin_function(msg: str, uid: str | int, gid: str | int | None, mid: str | int | None = None, send_type: str = "HTTP", ws_client=None, ws_server=None): # 一些内置的功能
if msg == "/重载插件":
send_msg(send_type, "正在重载插件, 请稍后...", uid, gid, mid, ws_client, ws_server)
load_plugins()
send_msg(send_type, f"FloraBot {flora_version}\n\n插件重载完成, 共有 {len(plugins_info_dict)} 个插件, 已启用 {len(plugins_dict)} 个插件", uid, gid, mid, ws_client, ws_server)
elif msg == "/插件列表":
plugins = f"FloraBot {flora_version}\n\n插件列表:\n"
for plugin_info in plugins_info_dict.values():
plugin_status = "启用"
if not plugin_info.get("EnablePlugin"):
plugin_status = "禁用"
plugins += f"•{plugin_info.get('PluginName')} [状态: {plugin_status}]\n"
plugins += f"\n共有 {len(plugins_info_dict)} 个插件, 已启用 {len(plugins_dict)} 个插件\n可使用 \"/启用/禁用插件 + [插件名]\" 来启用或者禁用插件\n若未找到插件, 但插件文件已添加, 请试试使用 \"/重载插件\""
send_msg(send_type, plugins, uid, gid, mid, ws_client, ws_server)
elif msg.startswith("/启用插件 "):
msg = msg.replace("/启用插件 ", "", 1)
if plugins_info_dict.get(msg) is not None and not plugins_info_dict.get(msg).get("EnablePlugin"):
plugin_info = plugins_info_dict.get(msg)
plugin_info.update({"EnablePlugin": True})
plugins_info_dict.update({msg: plugin_info})
spec = importlib.util.spec_from_file_location(plugin_info.get("MainPyName"), f"./{plugin_info.get('ThePluginPath')}/{plugin_info.get('MainPyName')}.py")
module = importlib.util.module_from_spec(spec)
try:
spec.loader.exec_module(module)
except ModuleNotFoundError as error_info:
if auto_install:
install_libraries(str(error_info).split("'")[1])
spec.loader.exec_module(module)
else:
raise ModuleNotFoundError(error_info)
try:
module.flora_api = flora_api.copy()
except AttributeError:
pass
module.flora_api.update({"ThePluginPath": plugin_info.get("ThePluginPath")})
try:
threading.Thread(target=module.init).start()
except AttributeError:
pass
plugins_dict.update({plugin_info.get("PluginName"): module})
update_flora_api()
with open(f"./{plugin_info.get('ThePluginPath')}/Plugin.json", "w", encoding="UTF-8") as write_plugin_config:
plugin_info_copy = plugin_info.copy()
plugin_info_copy.pop("ThePluginPath")
write_plugin_config.write(json.dumps(plugin_info_copy, ensure_ascii=False, indent=4))
send_msg(send_type, f"FloraBot {flora_version}\n\n插件 {msg} 已启用, 共有 {len(plugins_info_dict)} 个插件, 已启用 {len(plugins_dict)} 个插件", uid, gid, mid, ws_client, ws_server)
else:
send_msg(send_type, f"FloraBot {flora_version}\n\n未找到或已启用插件 {msg} , 若未找到插件, 但插件文件已添加, 请试试使用 \"/重载插件\"", uid, gid, mid, ws_client, ws_server)
elif msg.startswith("/禁用插件 "):
msg = msg.replace("/禁用插件 ", "", 1)
if plugins_info_dict.get(msg) is not None and plugins_info_dict.get(msg).get("EnablePlugin"):
plugin_info = plugins_info_dict.get(msg)
plugin_info.update({"EnablePlugin": False})
plugins_info_dict.update({msg: plugin_info})
if plugins_dict.get(msg) is not None:
plugins_dict.pop(msg)
update_flora_api()
with open(f"./{plugin_info.get('ThePluginPath')}/Plugin.json", "w",encoding="UTF-8") as write_plugin_config:
plugin_info_copy = plugin_info.copy()
plugin_info_copy.pop("ThePluginPath")
write_plugin_config.write(json.dumps(plugin_info_copy, ensure_ascii=False, indent=4))
send_msg(send_type, f"FloraBot {flora_version}\n\n插件 {msg} 已禁用, 共有 {len(plugins_info_dict)} 个插件, 已启用 {len(plugins_dict)} 个插件", uid, gid, mid, ws_client, ws_server)
else:
send_msg(send_type, f"FloraBot {flora_version}\n\n未找到或已禁用插件 {msg} , 若未找到插件, 但插件文件已添加, 请试试使用 \"/重载插件\"", uid, gid, mid, ws_client, ws_server)
elif msg.startswith("/echo "):
send_msg(send_type, msg.replace("/echo ", "", 1), uid, gid, mid, ws_client, ws_server)
elif msg.startswith("/echo1 "):
send_msg(send_type, msg.replace("/echo1 ", "", 1), uid, gid, None, ws_client, ws_server)
@flora_server.post("/")
def http_message_received(): # HTTP协议消息接收函数,不要主动调用这个函数
data = request.get_json() # 获取提交数据
broadcast_event(data, "HTTP") # 遍历开线程调用所有的插件事件函数
return "OK"
def ws_message_received(client, server, message): # WebSocket消息接收函数,不要主动调用这个函数
try:
data = json.loads(message)
if data.get("meta_event_type") != "heartbeat":
broadcast_event(data, "WebSocket", client, server) # 遍历开线程调用所有的插件事件函数
except json.JSONDecodeError:
pass
def check_privileges():
system = platform.system()
print(f"当前系统为 {system}")
if system == "Windows":
try:
from ctypes import windll
is_admin = windll.shell32.IsUserAnAdmin()
except:
is_admin = False
if is_admin:
print("\033[91m警告: 当前用户具有管理员权限, 若是添加了恶意插件, 后果不堪设想!!!\033[0m")
elif system in ["Linux", "Darwin"]:
if os.geteuid() == 0:
print("\033[91m警告: 当前用户具有 root 权限, 若是添加了恶意插件, 后果不堪设想!!!\033[0m")
logger = logging.getLogger(__name__)
logging.basicConfig()
class FloraWebSocketHandler(WebSocketHandler): # 重写WebSocketHandler类
def read_http_headers(self):
headers = {}
http_get = self.rfile.readline().decode().strip()
if not http_get.upper().startswith("GET"):
logger.warning("框架使用了不正确的 HTTP 方法进行请求 WebSocket 通信")
response = "HTTP/1.1 400 Bad Request\r\n\r\n"
with self._send_lock:
self.request.sendall(response.encode())
self.keep_alive = False
return headers
while True:
header = self.rfile.readline().decode().strip()
if not header:
break
head, value = header.split(":", 1)
headers[head.lower().strip()] = value.strip()
return headers
def handshake(self):
headers = self.read_http_headers()
if "upgrade" in headers:
try:
assert headers["upgrade"].lower() == "websocket"
except AssertionError:
self.keep_alive = False
return
try:
key = headers["sec-websocket-key"]
except KeyError:
logger.warning("框架尝试进行连接, 但缺少密钥")
self.keep_alive = False
return
response = self.make_handshake_response(key)
with self._send_lock:
self.handshake_done = self.request.send(response.encode())
self.valid_client = True
self.server._new_client_(self)
else:
logger.warning("框架使用了不正确的 WebSocket 协议进行通信")
response = "HTTP/1.1 400 Bad Request\r\n\r\n"
with self._send_lock:
self.request.sendall(response.encode())
self.keep_alive = False
class FloraWebsocketServer(WebsocketServer): # 重写WebsocketServer类
def __init__(self, host="127.0.0.1", port=0, loglevel=logging.WARNING, key=None, cert=None):
logger.setLevel(loglevel)
# noinspection PyTypeChecker
TCPServer.__init__(self, (host, port), FloraWebSocketHandler)
self.host = host
self.port = self.socket.getsockname()[1]
self.key = key
self.cert = cert
self.clients = []
self.id_counter = 0
self.thread = None
self._deny_clients = False
def client_connect(client, server):
print(f"框架已通过 WebSocket 连接, 连接ID: {client.get('id')}")
def client_left(client, server):
if client is not None:
print(f"框架已从 WebSocket 连接断开, 连接ID: {client.get('id')}")
if __name__ == "__main__":
print(flora_logo)
check_privileges()
print("正在初始化 FloraBot , 请稍后...")
load_config()
print(f"欢迎使用 FloraBot {flora_version}")
print("\033[93m声明: 插件为第三方内容, 请您自行分辨是否为恶意插件, 若被恶意插件入侵/破坏了您的设备或恶意盗取了您的信息, 造成的损失请自负, FloraBotTeam 概不负责也无义务负责!!!\033[0m")
load_plugins()
logger.info(f"框架连接方式为: {connection_type}")
try:
if connection_type == "HTTP":
flora_server.run(host=flora_host, port=flora_port)
elif connection_type == "WebSocket":
flora_server_ws = FloraWebsocketServer(host=flora_host, port=flora_port)
flora_server_ws.set_fn_new_client(client_connect)
flora_server_ws.set_fn_client_left(client_left)
flora_server_ws.set_fn_message_received(ws_message_received)
flora_server_ws.run_forever()
finally:
os._exit(0)