forked from TIGillusion/Qbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQbot.py
1081 lines (1014 loc) · 65.6 KB
/
Qbot.py
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
character = 0
pause_private = False
pause_group = False
print('\n欢迎使用由幻日团队-幻日编写的幻蓝AI程序,有疑问请联系q:2141073363或196744797')
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
import time
import random
import requests
import json
import os
from receive import rev_msg
import socket
import re
from threading import Thread
import base64
import jieba.analyse
import shutil
from bs4 import BeautifulSoup
def search(query):
"""
Searches the web for the specified query and returns the results.
"""
response = requests.get(
'https://api.openinterpreter.com/v0/browser/search',
params={"query": query},
)
if response.status_code==200 and response.json()["result"]:
return response.json()["result"]
else:
querys=query.split(" ")
result = bing_search(querys)
if result:
return result
else:
result = bing_search(query)
if result:
return result
else:
return "未搜索到合适结果"
def bing_search(keywords):
q=""
for p_k in keywords:
q+=(p_k+"+")
# 必应搜索结果URL
url = 'https://cn.bing.com/search?q=%s&count=10&qs=n&sp=-1&lq=0&pq=%s'%(q[:-1],q[:-1])
# 请求头,模拟浏览器访问
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
try:
# 发送GET请求
response = requests.get(url, headers=headers)
# 确保请求成功
response.raise_for_status()
# 使用BeautifulSoup解析HTML内容
soup = BeautifulSoup(response.text, 'html.parser')
# 查找搜索结果
search_items = soup.find_all('li', class_='b_algo')
if not search_items:
print("未找到搜索结果,可能是因为HTML结构发生了变化。")
return ""
result = ""
for index, item in enumerate(search_items):
# 提取标题
title = item.find('h2').get_text()
# 提取链接
link = item.find('a')['href']
# 提取摘要
summary_div = item.find('div', class_='b_caption')
if summary_div:
summary_p = summary_div.find_all('p')
if summary_p:
summary = ''.join(p.get_text() for p in summary_p)
else:
summary = summary_div.get_text(strip=True)
else:
summary = ''
# 对于前三个结果,获取详细页面内容
if index < 10:
try:
# 发送GET请求到详细页面
response_detail = requests.get(link, headers=headers)
response_detail.raise_for_status()
soup_detail = BeautifulSoup(response_detail.text, 'html.parser')
# 假设详细页面中的主要内容在 <div id="content"> 中
content_div = soup_detail.find('div', id='content')
if content_div:
content = content_div.get_text(strip=True)
# 保留前500个字符
content = (content[:5000]) if len(content) > 500 else content
else:
content = '无法找到详细内容。'
result+=f'标题:{title}\n链接:{link}\n摘要:{summary}\n详细内容:{content}\n'
print(f'标题:{title}\n链接:{link}\n摘要:{summary}\n详细内容:{content}\n')
except requests.RequestException as e:
print(f'请求详细页面错误:{e}')
else:
# 打印摘要
result+=f'标题:{title}\n链接:{link}\n摘要:{summary}\n详细内容:{content}\n'
print(f'标题:{title}\n链接:{link}\n摘要:{summary}\n')
if len(result) > 5000:
return result
return result
except requests.RequestException as e:
print(f'请求错误:{e}')
except Exception as e:
print(f'解析错误:{e}')
def merge_contents(data):
# 初始化一个新的列表来存储处理后的数据
data=[data[0]]+[{"role":"user","content":" "}]+data[1:]
new_data = []
# 用于临时存储连续相同role的内容
temp_content = ""
# 上一个role的值
prev_role = None
for item in data:
current_role = item['role']
current_content = item['content']
# 如果当前content为空,则将其改为空格
if not current_content.replace(" ",''):
if current_role == "user":
current_content = "[特殊消息]"
else:
current_content = "呜呜,遇到未知错误..."
# 如果当前role与上一个role相同,则合并content
if current_role == prev_role:
temp_content += current_content
else:
# 如果临时内容不为空,则将其作为一个新条目添加到新数据列表中
if temp_content:
new_data.append({'role': prev_role, 'content': temp_content})
# 更新临时内容和上一个role的值
temp_content = current_content
prev_role = current_role
# 添加最后一个临时内容(如果有)
if temp_content:
new_data.append({'role': prev_role, 'content': temp_content})
return new_data
def get_I_memory(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
return "\n[self_impression]\n"+content[-400:]
def get_memory(file_path, keywords, match_n=200, time_n=200, radius=50):
"""
读取整个文件,搜索关键词,合并重叠文段,并返回两个排序的文段列表:
1. 包含关键词个数排名前五的文段。
2. 越靠近文段末尾的排在前面,同样返回五个,且不与第一个列表重复。
:param file_path: 文件路径
:param keywords: 关键词列表
:param radius: 关键词附近要返回的文本字数
:return: 关键词匹配记忆
"""
# 读取整个文件内容
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# 构建正则表达式,用于匹配任意一个关键词
keywords_pattern = '|'.join(map(re.escape, keywords))
matches = list(re.finditer(keywords_pattern, content))
# 合并重叠的文段
merged_blocks = []
for match in matches:
start_index = max(match.start() - radius, 0)
end_index = min(match.end() + radius, len(content))
# 检查是否与现有文段重叠
overlap = False
for block in merged_blocks:
if start_index < block['end'] and end_index > block['start']:
# 合并文段
block['start'] = min(start_index, block['start'])
block['end'] = max(end_index, block['end'])
block['count'] += 1
overlap = True
break
if not overlap:
merged_blocks.append({'start': start_index, 'end': end_index, 'count': 1})
# 提取文段文本并按关键词个数排序
text_blocks = [{'text': content[block['start']:block['end']], 'count': block['count']} for block in merged_blocks]
sorted_by_count = sorted(text_blocks, key=lambda x: x['count'], reverse=True)[:5]
# 提取文段文本并按文段末尾位置排序
text_blocks = [{'text': content[block['start']:block['end']], 'end': block['end']} for block in merged_blocks]
sorted_by_end = sorted(text_blocks, key=lambda x: x['end'], reverse=True)
# 移除与按关键词个数排序的文段重复的部分
non_duplicate_sorted_by_end = [block for block in sorted_by_end if block['text'] not in [b['text'] for b in sorted_by_count]][:5]
main_text = ''
for per_text in non_duplicate_sorted_by_end:
main_text+="--%s\n"%per_text["text"]
if len(main_text) > match_n:
break
for per_text in sorted_by_count:
main_text+="--%s\n"%per_text["text"]
if len(main_text) > match_n+time_n:
break
return main_text[:match_n+time_n+200]
def draw_group(prompt,to):
try:
urldraw=draw_url
headers={
"Content-Type": "application/json",
"Authorization": "Bearer "+draw_key
}
data={
"model":draw_model,##claude-3-opus-vf
"messages":[{"role":"user","content":prompt}],
"stream": True
}
send_msg({'msg_type': 'group', 'number': to, 'msg': '正在绘画[%s]中...'%prompt})
response=requests.post(url=urldraw,headers=headers,stream=True,data=json.dumps(data))
if response.status_code==200:
send_msg({'msg_type': 'group', 'number': to, 'msg': '绘画完毕发送中...'})
processed_d_data_draw=''
for line in response.iter_lines():
try:
decoded=line.decode('utf-8').replace('\n','\\n').replace('\b','\\b').replace('\f','\\f').replace('\r','\\r').replace('\t','\\t')
if decoded != '':
processed_d_data_draw+=json.loads(decoded[5:])["choices"][0]["delta"]["content"]
print(decoded)
except Exception as e:
print(e)
image_url=processed_d_data_draw.split('(')[-1].replace(')','')
print(image_url)
max_n=500
for n in range(0,max_n):
try:
image_response=requests.get(image_url)
name=str(random.randrange(100000,999999))+'.png'
with open("./data/image/%s"%name,'wb') as f_image:
f_image.write(image_response.content)
send_image({'msg_type': 'group', 'number': to, 'msg':name })
break
except:
print(n)
if n==max_n-1:
raise TimeoutError("重试无效")
except Exception as e:
print('绘画错误:',e)
send_msg({'msg_type': 'group', 'number': to, 'msg':'AI绘画操作无法执行'})
def draw_private(prompt,to):
try:
urldraw=draw_url
headers={
"Content-Type": "application/json",
"Authorization": "Bearer "+draw_key
}
data={
"model":draw_model,
"messages":[{"role":"user","content":prompt}],
"stream": True
}
send_msg({'msg_type': 'private', 'number': to, 'msg': '正在绘画[%s]中...'%prompt})
response=requests.post(url=urldraw,headers=headers,stream=True,data=json.dumps(data))
if response.status_code==200:
send_msg({'msg_type': 'private', 'number': to, 'msg': '绘画完毕发送中...'})
processed_d_data_draw=''
for line in response.iter_lines():
try:
decoded=line.decode('utf-8').replace('\n','\\n').replace('\b','\\b').replace('\f','\\f').replace('\r','\\r').replace('\t','\\t')
if decoded != '':
processed_d_data_draw+=json.loads(decoded[5:])["choices"][0]["delta"]["content"]
print(decoded)
except Exception as e:
print(e)
image_url=processed_d_data_draw.split('(')[-1].replace(')','')
print(image_url)
max_n=500
for n in range(0,max_n):
try:
image_response=requests.get(image_url)
name=str(random.randrange(100000,999999))+'.png'
with open("./data/image/%s"%name,'wb') as f_image:
f_image.write(image_response.content)
send_image({'msg_type': 'private', 'number': to, 'msg':name })
break
except:
print(n)
if n==max_n-1:
raise TimeoutError("重试无效")
except Exception as e:
print('绘画错误:',e)
send_msg({'msg_type': 'private', 'number': to, 'msg':'AI绘画操作无法执行'})
def send_msg(resp_dict):
msg_type = resp_dict['msg_type'] # 回复类型(群聊/私聊)
number = resp_dict['number'] # 回复账号(群号/好友号)
msg = resp_dict['msg'].strip() # 要回复的消息
if msg:
if msg_type == 'group':
res=requests.post('http://localhost:3000/send_group_msg', json={
'group_id': number,
'message': msg
})
print("send_group_msg:",msg,json.loads(res.content))
elif msg_type == 'private':
res=requests.post('http://localhost:3000/send_private_msg', json={
'user_id': number,
'message': msg
})
print("send_private_msg:",msg,json.loads(res.content))
return 0
def send_image(resp_dict):
msg_type = resp_dict['msg_type'] # 回复类型(群聊/私聊)
number = resp_dict['number'] # 回复账号(群号/好友号)
msg = resp_dict['msg'] # 要回复的消息
if msg_type == 'group':
res=requests.post('http://localhost:3000/send_group_msg', json={
'group_id': number,
'message': "[CQ:image,file=http://127.0.0.1:4321/data/image/%s]"%msg
})
print("send_group_msg:",msg,json.loads(res.content))
elif msg_type == 'private':
res=requests.post('http://localhost:3000/send_private_msg', json={
'user_id': number,
'message':"[CQ:image,file=http://127.0.0.1:4321/data/image/%s]"%msg
})
print("send_private_msg:",msg,json.loads(res.content))
def send_voice(resp_dict):
msg_type = resp_dict['msg_type'] # 回复类型(群聊/私聊)
number = resp_dict['number'] # 回复账号(群号/好友号)
msg = resp_dict['msg'] # 要回复的消息
if msg_type == 'group':
res=requests.post('http://localhost:3000/send_group_msg', json={
'group_id': number,
'message': "[CQ:record,file=http://127.0.0.1:4321/data/voice/%s]"%msg
})
print("send_group_msg:",msg,json.loads(res.content))
elif msg_type == 'private':
res=requests.post('http://localhost:3000/send_private_msg', json={
'user_id': number,
'message':"[CQ:record,file=http://127.0.0.1:4321/data/voice/%s]"%msg
})
print("send_private_msg:",msg,json.loads(res.content))
def send_image_url(resp_dict):
msg_type = resp_dict['msg_type'] # 回复类型(群聊/私聊)
number = resp_dict['number'] # 回复账号(群号/好友号)
msg = resp_dict['msg'] # 要回复的消息
if msg_type == 'group':
res=requests.post('http://localhost:3000/send_group_msg', json={
'group_id': number,
'message': {
"type": "image",
"data": {
"file": "%s"%msg.replace("%20"," ")
}
}
})
print("send_group_msg:",msg,json.loads(res.content))
elif msg_type == 'private':
res=requests.post('http://localhost:3000/send_private_msg', json={
'user_id': number,
'message': {
"type": "image",
"data": {
"file": "%s"%msg
}
}
})
print("send_private_msg:",msg,json.loads(res.content))
def delete_subfolders(folder_path): # 删文件函数
# 遍历主目录中的每个项目
for item in os.listdir(folder_path):
item_path = os.path.join(folder_path, item) # 构造完整路径
if os.path.isdir(item_path): # 如果是目录
shutil.rmtree(item_path) # 删除该目录及其所有内容
else:
os.remove(item_path) # 如果是文件,则直接删除
if not os.listdir(folder_path): # 如果目录为空
os.rmdir(folder_path)
verification_code = str(random.randrange(100000, 1000000)) #先行定义验证码变量
def choose_model():
w_c_models=[]
for c_model in chat_models:
w_c_models+=[c_model]*c_model["weight"]
model_info = random.choice(w_c_models)
return model_info["model_api"],model_info["model_name"],model_info["model_key"]
def main(rev):
global objdict
global verification_code
global pause_private
global pause_group
global character
user_api,user_chat_model,user_key=choose_model()
try:
timestamp = time.time()
localtime = time.localtime(timestamp)
current_time = time.strftime(
"%Y-%m-%d %H:%M:%S", localtime
)
e_information="[information](准确 有时效性)\n当前时间:%s\n"%current_time
if rev["message_type"] == "private":
if "illue%schat"%rev["sender"]["user_id"] not in objdict.keys():
objdict["illue%schat"%rev["sender"]["user_id"]]=""
if not os.path.exists("./user/p%s"%rev["sender"]["user_id"]):
os.makedirs("./user/p%s"%rev["sender"]["user_id"])
with open("./user/p%s/memory.txt"%rev["sender"]["user_id"],"w") as tpass:
pass
if not os.path.exists("./user/p%s/I_memory.txt"%rev["sender"]["user_id"]):
with open("./user/p%s/I_memory.txt"%rev["sender"]["user_id"],"w") as tpass:
pass
if "[CQ:image," not in rev['raw_message']:
objdict["illue%schat"%rev["sender"]["user_id"]]+=(rev["sender"]["nickname"]+":"+rev['raw_message'].replace('[CQ:at,qq=%d]'%rev['self_id'],'')+'\n\n')
objdict["illue%schat"%rev["sender"]["user_id"]]=objdict["illue%schat"%rev["sender"]["user_id"]][-50:]
if True:
a=objdict["illue%schat"%rev["sender"]["user_id"]]
print(a)
self_id=random.randrange(100000,999999)
objdict["illue%sgeneing"%rev["sender"]["user_id"]]=[self_id]
rev['raw_message']=rev['raw_message'].replace('[CQ:at,qq=%d]'%rev['self_id'],'')
if '#sudo' in rev['raw_message']:
verification_code = str(random.randrange(100000, 1000000))
send_msg({'msg_type': 'private', 'number': root_id, 'msg': verification_code})
print("发信ID:",rev["sender"]["user_id"])
if '#暂停' in rev['raw_message'] and (verification_code in rev['raw_message'] or rev['sender']["user_id"]==root_id):
pause_private = True
verification_code = str(random.randrange(100000, 1000000))
if '#继续' in rev['raw_message'] and (verification_code in rev['raw_message'] or rev['sender']["user_id"]==root_id):
pause_private = False
verification_code = str(random.randrange(100000, 1000000))
if "illue%s"%rev["sender"]["user_id"] not in objdict.keys():
objdict["illue%s"%rev["sender"]["user_id"]]=[[{'role':'system','content':system}]]
if '#reset' in rev['raw_message']:
objdict["illue%s"%rev["sender"]["user_id"]]=[[{'role':'system','content':system}]]
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': '已清空对话历史'}) #私聊直接重置
if '#clear' in rev['raw_message']:
delete_subfolders("./user/p%s"%rev["sender"]["user_id"])
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': '已清空个人私聊记忆'}) # 清空个人记忆无需确认
if '#erase' in rev['raw_message'] and (verification_code in rev['raw_message'] or rev['sender']["user_id"]==root_id):
delete_subfolders("./user/")
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': '已清空所有记忆'})
verification_code = str(random.randrange(100000, 1000000)) #清空记忆验证码确认
else:
processed_d_data="强制切换意图"
if weihu:
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': "维护中..."})
raise KeyboardInterrupt("维护ing")
print(processed_d_data)
if not processed_d_data:
processed_d_data='.'
if pause_private != True:
turl=user_api
headers={
"Content-Type": "application/json",
"Authorization": "Bearer "+user_key
}
messages=objdict["illue%s"%rev["sender"]["user_id"]][0]+[{"role":"user","content":objdict["illue%schat"%rev["sender"]["user_id"]],"message_id=":rev['message_id']}]
keywords = jieba.analyse.extract_tags(rev['raw_message'].replace(AI_name,""), topK=50)
s_memory=get_memory("./user/p%s/memory.txt"%rev["sender"]["user_id"],keywords)
s_memory+=get_I_memory("./user/p%s/I_memory.txt"%rev["sender"]["user_id"])
char_memory=get_memory("./data/char.txt",keywords)
print(s_memory)
data={
"model": user_chat_model,##claude-3-opus-vf
"messages":merge_contents([{"role":"system","content":messages[0]["content"]+"[memory](经验 无时效性)\n%s\n"%char_memory+"[memory](模糊 无时效性)\n%s\n"%s_memory+e_information}]+messages[1:]),
"stream": True,
"use_search": False
}
is_return=True
while is_return:
is_return=False
response=requests.post(url=turl,headers=headers,stream=True,data=json.dumps(data))
temp_tts_list=[]
processed_d_data1=''
for line in response.iter_lines():
try:
decoded=line.decode('utf-8').replace('\n','\\n').replace('\b','\\b').replace('\f','\\f').replace('\r','\\r').replace('\t','\\t')
if decoded != '':
processed_d_data1+=json.loads(decoded[5:])["choices"][0]["delta"]["content"]
except Exception as e:
continue
pass
lastlen=len(temp_tts_list)
temp_tts_list=processed_d_data1.split("#cut#")
if not temp_tts_list:
temp_tts_list=temp_tts_list[:-1]
if self_id not in objdict["illue%sgeneing"%rev["sender"]["user_id"]]:
objdict["illue%s"%rev["sender"]["user_id"]][0]=objdict["illue%s"%rev["sender"]["user_id"]][0]+[{'role':'user','content':rev['raw_message']},{'role':'assistant','content':processed_d_data1}]
raise InterruptedError("新消息中断") # 防人工刷屏
if len(temp_tts_list)>1 and lastlen < len(temp_tts_list):
if '#voice/' in temp_tts_list[-2]:
try:
voice=temp_tts_list[-2].split('#voice/')[-1].replace("#",'')
tts_data = {
"cha_name": "illuevoice",
"text": voice.replace("...", "…").replace("…", ","),
"character_emotion":random.choice(['default','angry','excited','narration-relaxed','depressed'])
}
b_wav = requests.post(
url='http://127.0.0.1:5000/tts', json=tts_data
)
n=random.randrange(10000,99999)
name='%stts%d.wav'%((time.strftime('%F')+'-'+time.strftime('%T').replace(':','-')),n)
to_path='./data/voice/%s'%name
with open(to_path,'wb') as wbf:
wbf.write(b_wav.content)
send_voice({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg':name })
except Exception as e:
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': "语音合成失败"})
print("暂不支持语音合成")
elif '#picture/' in temp_tts_list[-2]:
picture=temp_tts_list[-2].split('#picture/')[-1].replace("#",'')
print(picture)
draw_private(picture,rev["sender"]["user_id"])
elif '#search/' in temp_tts_list[-2]:
response.close()
temp_tts_list=temp_tts_list[:-1]
break
elif '#default#' in temp_tts_list[-2] and character != 0:
character = 0
mode(character)
temp_tts_list=temp_tts_list[-1].split('#default#')[-1].replace("#default#",'')
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': temp_tts_list[-2].replace("%s:"%AI_name,"").replace("%s:"%AI_name,"")})
elif '#fire#' in temp_tts_list[-2] and character != 1:
character = 1
mode(character)
temp_tts_list=temp_tts_list[-1].split('#fire#')[-1].replace("#fire#",'')
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': temp_tts_list[-2].replace("%s:"%AI_name,"").replace("%s:"%AI_name,"")})
elif '#memory/' in temp_tts_list[-2]:
memory=temp_tts_list[-1].split('#memory/')[-1].replace("#",'')
print("写入记忆:",memory)
with open("./user/p%s/I_memory.txt"%rev["sender"]["user_id"],"a",encoding="utf-8") as mem:
mem.write(" "+memory)
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': "[写入记忆]"})
elif "#pass/" in temp_tts_list[-2]:
response.close()
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': "[pass]"})
raise KeyboardInterrupt("AI认为应该跳过此回复!")
elif "#emotion/" in temp_tts_list[-2]:
t_emotion=temp_tts_list[-2].split("#emotion/")[-1].replace("#",'')
e_image_list=os.listdir("./data/image/%s"%t_emotion)
e_image=random.choice(e_image_list)
send_image({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg':"%s/%s"%(t_emotion,e_image)})
elif "#music/" in temp_tts_list[-2]:
t_music_n=temp_tts_list[-2].split("#music/")[-1].replace("#",'')
smusic_l=os.listdir("./data/voice/smusic")
if t_music_n in smusic_l:
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': "《%s》"%t_music_n})
send_voice({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg':"smusic/"+t_music_n})
else:
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': "[未找到合适歌曲]"})
else:
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': temp_tts_list[-2].replace("%s:"%AI_name,"").replace("%s:"%AI_name,"")})
if "抱歉" in temp_tts_list[-1]:
objdict["illue%s"%rev["sender"]["user_id"]][0]=[objdict["illue%s"%rev["sender"]["user_id"]][0][0]]
print("催眠失败,重置记忆")
else:
if '#voice/' in temp_tts_list[-1]:
voice=temp_tts_list[-1].split('#voice/')[-1].replace("#",'')
tts_data = {
"cha_name": "illuevoice",
"text": voice.replace("...", "…").replace("…", ","),
"character_emotion":random.choice(['default','angry','excited','narration-relaxed','depressed'])
}
b_wav = requests.post(
url='http://127.0.0.1:5000/tts', json=tts_data
)
n=random.randrange(10000,99999)
name='%stts%d.wav'%((time.strftime('%F')+'-'+time.strftime('%T').replace(':','-')),n)
to_path='./data/voice/%s'%name
with open(to_path,'wb') as wbf:
wbf.write(b_wav.content)
send_voice({'msg_type': 'private', 'number':rev["sender"]["user_id"], 'msg':name })
elif '#picture/' in temp_tts_list[-1]:
picture=temp_tts_list[-1].split('#picture/')[-1].replace("#",'')
print(picture)
draw_private(picture,rev["sender"]["user_id"])
elif '#search/' in temp_tts_list[-1]:
s_prompt=temp_tts_list[-1].split('#search/')[-1].replace("#",'')
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': "正在联网搜索:%s"%s_prompt})
search_result=search(s_prompt)
print(search_result)
objdict["illue%s"%rev["sender"]["user_id"]][0]+=[{'role':'user','content':rev['raw_message']},{'role':'assistant','content':processed_d_data1+"""\nsystem[搜索结果不可见]:正在联网搜索:%s\n搜索结果:\n%s\n由于system返回的搜索结果你应该看不见,我将用自己的话详细,具体的讲述一下搜索结果。"""%(s_prompt,search_result)},{"role":"user","content":"开始详细具体的讲述吧"}]
messages=objdict["illue%s"%rev["sender"]["user_id"]][0]
data={
"model": user_chat_model,##claude-3-opus-vf
"messages":merge_contents([{"role":"system","content":system_prompt+"[order]\n1. 每句话之间使用#cut#分割开,每段话直接也使用#cut#分割开,你如:“#cut#你好。群友。#cut#幻日老爹在不?#cut#”\n"+e_information}]+messages[1:]),
"stream": True,
"use_search": False
}
is_return=True
continue
elif '#memory/' in temp_tts_list[-1]:
memory=temp_tts_list[-1].split('#memory/')[-1].replace("#",'')
print("写入记忆:",memory)
with open("./user/p%s/I_memory.txt"%rev["sender"]["user_id"],"a",encoding="utf-8") as mem:
mem.write(" "+memory)
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': "[写入记忆]"})
elif "#pass/" in temp_tts_list[-1]:
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': "[pass]"})
raise KeyboardInterrupt("AI认为应该跳过此回复!")
elif "#emotion/" in temp_tts_list[-1]:
t_emotion=temp_tts_list[-1].split("#emotion/")[-1].replace("#",'')
e_image_list=os.listdir("./data/image/%s"%t_emotion)
e_image=random.choice(e_image_list)
send_image({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg':"%s/%s"%(t_emotion,e_image)})
elif "#music/" in temp_tts_list[-1]:
t_music_n=temp_tts_list[-1].split("#music/")[-1].replace("#",'')
smusic_l=os.listdir("./data/voice/smusic")
if t_music_n in smusic_l:
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': "《%s》"%t_music_n})
send_voice({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg':"smusic/"+t_music_n})
else:
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': "[未找到合适歌曲]"})
else:
send_msg({'msg_type': 'private', 'number': rev["sender"]["user_id"], 'msg': temp_tts_list[-1].replace("%s:"%AI_name,"").replace("%s:"%AI_name,"")})
print(processed_d_data1)
objdict["illue%s"%rev["sender"]["user_id"]][0]=objdict["illue%s"%rev["sender"]["user_id"]][0]+[{'role':'user','content':rev['raw_message']},{'role':'assistant','content':processed_d_data1}]
with open(
"./user/p%s/memory.txt"%rev["sender"]["user_id"],
"a",
encoding="utf-8",
) as txt:
timestamp = time.time()
localtime = time.localtime(timestamp)
current_time = time.strftime(
"%Y-%m-%d %H:%M:%S", localtime
)
txt.write(
"[%s]我说:%s\n" % (current_time, rev['raw_message'])
)
txt.write(
"[%s]你回复:%s\n"
% (current_time, processed_d_data1)
)
print("未发现新消息...运行时间:%f"%(time.time()-startT))
if len(objdict["illue%s"%rev["sender"]["user_id"]][0])> 10:
objdict["illue%s"%rev["sender"]["user_id"]][0]=[objdict["illue%s"%rev["sender"]["user_id"]][0][0]]+objdict["illue%s"%rev["sender"]["user_id"]][0][-6:]
objdict["illue%schat"%rev["sender"]["user_id"]]=''
elif rev["message_type"] == "group":
if ("团子" in rev["sender"]["nickname"] or "芙芙" in rev["sender"]["nickname"] or "炼丹师" in rev["sender"]["nickname"]) and "[CQ:image," in rev['raw_message']:
time.sleep(5+random.randrange(0,5))
message_id=rev['message_id']
res=requests.post('http://localhost:3000/delete_msg', json={
'message_id': message_id, #撤回机器人图片(需群管理员权限)
})
print("delete_msg:",rev['raw_message'],json.loads(res.content))
pass_ban=False
for ban_name in ban_names:
if ban_name in rev["sender"]["nickname"]:
pass_ban = True
break
if pass_ban:
raise RuntimeError("break limitless turn")#屏蔽指定名称qq
if "illue%schat"%rev['group_id'] not in objdict.keys():#创建目录
objdict["illue%schat"%rev['group_id']]=""
if not os.path.exists("./user/g%s"%rev['group_id']):
os.makedirs("./user/g%s"%rev['group_id'])
with open("./user/g%s/memory.txt"%rev['group_id'],"w") as tpass:
pass
if not os.path.exists("./user/g%s/I_memory.txt"%rev['group_id']):
with open("./user/g%s/I_memory.txt"%rev['group_id'],"w") as tpass:
pass
if "[CQ:image," not in rev['raw_message']:#组建单次回复上下文
objdict["illue%schat"%rev['group_id']]=objdict["illue%schat"%rev['group_id']][-30:]
objdict["illue%schat"%rev['group_id']]+=(rev["sender"]["nickname"]+":"+rev['raw_message'].replace('[CQ:at,qq=%d]'%rev['self_id'],'')+'\n\n')
if "#settitle:" in rev['raw_message']:#自动设置头衔(暂时无效)
title=rev['raw_message'].split(':',1)[-1][:5]
res=requests.post('http://localhost:3000/set_group_special_title', json={
'group_id': rev['group_id'],
'user_id': rev['user_id'],
'special_title':title,
'duration':-1
})
print("set_group_special_title:",rev['raw_message'].split(':',1)[-1][:5],json.loads(res.content))
is_trigger=False#比对触发词
for trigger in triggers:
if trigger in rev['raw_message']:
is_trigger = True
break
if (is_trigger or '[CQ:at,qq=%d]'%rev['self_id'] in rev['raw_message'] or random.randrange(0,random_trigger)==0):#触发回复
a=objdict["illue%schat"%rev['group_id']]
print(a)
self_id=random.randrange(100000,999999)
objdict["illue%sgeneing"%rev['group_id']]=[self_id]
rev['raw_message']=rev['raw_message'].replace('[CQ:at,qq=%d]'%rev['self_id'],'')
if '#sudo' in rev['raw_message']:
verification_code = str(random.randrange(100000, 1000000))
send_msg({'msg_type': 'private', 'number': root_id, 'msg': verification_code})
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg':f"[CQ:at,qq={rev['sender']['user_id']},name={rev['sender']['nickname']}]验证码已发送"})
print("发信ID:",rev["sender"]["user_id"])
if '#暂停' in rev['raw_message'] and (verification_code in rev['raw_message'] or rev['sender']["user_id"]==root_id):
pause_group = True
verification_code = str(random.randrange(100000, 1000000))
if '#继续' in rev['raw_message'] and (verification_code in rev['raw_message'] or rev['sender']["user_id"]==root_id):
pause_group = False
verification_code = str(random.randrange(100000, 1000000))
if "illue%s"%rev['group_id'] not in objdict.keys():
objdict["illue%s"%rev['group_id']]=[[{'role':'system','content':system}]]
if '#reset' in rev['raw_message'] and (verification_code in rev['raw_message'] or rev['sender']["user_id"]==root_id):
objdict["illue%s"%rev['group_id']]=[[{'role':'system','content':system}]]
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg': '已清空对话历史'})
verification_code = str(random.randrange(100000, 1000000)) #重置验证码确认
if '#clear' in rev['raw_message']:
delete_subfolders("./user/g%s"%rev['group_id'])
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg':f'[CQ:at,qq={rev['sender']['user_id']},name={rev['sender']['nickname']}]已清空个人群聊记忆'}) # 清空个人记忆无需确认
if '#erase' in rev['raw_message'] and (verification_code in rev['raw_message'] or rev['sender']["user_id"]==root_id):
delete_subfolders("./user/")
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg': '已清空全部记忆'})
verification_code = str(random.randrange(100000, 1000000)) #清空记忆验证码确认
else:
processed_d_data="强制切换意图"
if weihu:
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg': "[维护中...]"})
raise KeyboardInterrupt("维护ing")
print(processed_d_data)
if not processed_d_data:
processed_d_data='.'
if pause_group != True:
turl=user_api
headers={
"Content-Type": "application/json",
"Authorization": "Bearer "+user_key
}
messages=objdict["illue%s"%rev['group_id']][0]+[{"role":"user","content":objdict["illue%schat"%rev['group_id']]}]
keywords = jieba.analyse.extract_tags(rev['raw_message'].replace(AI_name,""), topK=50)
s_memory=get_memory("./user/g%s/memory.txt"%rev['group_id'],keywords)
s_memory+=get_I_memory("./user/g%s/I_memory.txt"%rev['group_id'])
char_memory=get_memory("./data/char.txt",keywords)
print(s_memory)
print(char_memory)
data={
"model": user_chat_model,
"messages":merge_contents([{"role":"system","content":messages[0]["content"]+"[memory](经验 无时效性)\n%s\n"%char_memory+"[memory](模糊 无时效性)\n%s\n"%s_memory+e_information}]+messages[1:]),
"stream": True,
"use_search": False
}
is_return=True
while is_return:
is_return=False
response=requests.post(url=turl,headers=headers,stream=True,data=json.dumps(data))
temp_tts_list=[]
processed_d_data1=''
for line in response.iter_lines():
try:
decoded=line.decode('utf-8').replace('\n','\\n').replace('\b','\\b').replace('\f','\\f').replace('\r','\\r').replace('\t','\\t')
if decoded != '':
processed_d_data1+=json.loads(decoded[5:])["choices"][0]["delta"]["content"]
except Exception as e:
print(decoded,e)
continue
pass
lastlen=len(temp_tts_list)
temp_tts_list=processed_d_data1.split("#cut#")
if not temp_tts_list:
temp_tts_list=temp_tts_list[:-1]
if self_id not in objdict["illue%sgeneing"%rev['group_id']]:
objdict["illue%s"%rev['group_id']][0]=objdict["illue%s"%rev['group_id']][0]+[{'role':'user','content':rev['raw_message']},{'role':'assistant','content':processed_d_data1}]
raise InterruptedError("新消息中断") # 防人工刷屏
if len(temp_tts_list)>1 and lastlen < len(temp_tts_list):
if '#voice/' in temp_tts_list[-2]:
try:
voice=temp_tts_list[-2].split('#voice/')[-1].replace("#",'')
tts_data = {
"cha_name": "illuevoice",
"text": voice.replace("...", "…").replace("…", ","),
"character_emotion":random.choice(['default','angry','excited','narration-relaxed','depressed'])
}
b_wav = requests.post(
url='http://127.0.0.1:5000/tts', json=tts_data
)
n=random.randrange(10000,99999)
name='%stts%d.wav'%((time.strftime('%F')+'-'+time.strftime('%T').replace(':','-')),n)
to_path='./data/voice/%s'%name
with open(to_path,'wb') as wbf:
wbf.write(b_wav.content)
send_voice({'msg_type': 'group', 'number': rev['group_id'], 'msg':name })
except Exception as e:
print("暂不支持语音合成")
elif '#picture/' in temp_tts_list[-2]:
picture=temp_tts_list[-2].split('#picture/')[-1].replace("#",'')
print(picture)
draw_group(picture,rev['group_id'])
elif '#search/' in temp_tts_list[-2]:
response.close()
temp_tts_list=temp_tts_list[:-1]
break
elif '#default#' in temp_tts_list[-2] and character != 0:
character = 0
mode(character)
temp_tts_list=temp_tts_list[-1].split('#default#')[-1].replace("#default#",'')
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg': temp_tts_list[-2].replace("%s:"%AI_name,"").replace("%s:"%AI_name,"")})
elif '#fire#' in temp_tts_list[-2] and character != 1:
character = 1
mode(character)
temp_tts_list=temp_tts_list[-1].split('#fire#')[-1].replace("#fire#",'')
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg': temp_tts_list[-2].replace("%s:"%AI_name,"").replace("%s:"%AI_name,"")})
elif '#memory/' in temp_tts_list[-2]:
memory=temp_tts_list[-2].split('#memory/')[-1].replace("#",'')
print("写入记忆:",memory)
with open("./user/g%s/I_memory.txt"%rev['group_id'],"a",encoding="utf-8") as mem:
mem.write(" "+memory)
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg': "[写入记忆]"})
elif "#pass/" in temp_tts_list[-2]:
response.close()
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg': "[pass]"})
raise KeyboardInterrupt("AI认为应该跳过此回复!")
elif "#emotion/" in temp_tts_list[-2]:
t_emotion=temp_tts_list[-2].split("#emotion/")[-1].replace("#",'')
e_image_list=os.listdir("./data/image/%s"%t_emotion)
e_image=random.choice(e_image_list)
send_image({'msg_type': 'group', 'number': rev['group_id'], 'msg':"%s/%s"%(t_emotion,e_image)})
elif "#music/" in temp_tts_list[-2]:
t_music_n=temp_tts_list[-2].split("#music/")[-1].replace("#",'')
smusic_l=os.listdir("./data/voice/smusic")
if t_music_n in smusic_l:
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg': "《%s》"%t_music_n})
send_voice({'msg_type': 'group', 'number': rev['group_id'], 'msg':"smusic/"+t_music_n})
else:
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg': "[未找到合适歌曲]"})
else:
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg': temp_tts_list[-2].replace("%s:"%AI_name,"").replace("%s:"%AI_name,"")})
if "抱歉" in temp_tts_list[-1]:
objdict["illue%s"%rev['group_id']][0]=[objdict["illue%s"%rev['group_id']][0][0]]
print("催眠失败,重置记忆")
else:
if '#voice/' in temp_tts_list[-1]:
voice=temp_tts_list[-1].split('#voice/')[-1].replace("#",'')
tts_data = {
"cha_name": "illuevoice",
"text": voice.replace("...", "…").replace("…", ","),
"character_emotion":random.choice(['default','angry','excited','narration-relaxed','depressed'])
}
b_wav = requests.post(
url='http://127.0.0.1:5000/tts', json=tts_data
)
n=random.randrange(10000,99999)
name='%stts%d.wav'%((time.strftime('%F')+'-'+time.strftime('%T').replace(':','-')),n)
to_path='./data/voice/%s'%name
with open(to_path,'wb') as wbf:
wbf.write(b_wav.content)
send_voice({'msg_type': 'group', 'number': rev['group_id'], 'msg':name })
elif '#picture/' in temp_tts_list[-1]:
picture=temp_tts_list[-1].split('#picture/')[-1].replace("#",'')
print(picture)
draw_group(picture,rev['group_id'])
elif '#search/' in temp_tts_list[-1]:
s_prompt=temp_tts_list[-1].split('#search/')[-1].replace("#",'')
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg': "正在联网搜索:%s"%s_prompt})
search_result=search(s_prompt)
print(search_result)
objdict["illue%s"%rev['group_id']][0]+=[{'role':'user','content':rev['raw_message']},{'role':'assistant','content':processed_d_data1+"""\nsystem[搜索结果不可见]:正在联网搜索:%s\n搜索结果:\n%s\n由于system返回的搜索结果你应该看不见,我将用自己的话详细,具体的讲述一下搜索结果。"""%(s_prompt,search_result)},{"role":"user","content":"开始详细具体的讲述吧"}]
messages=objdict["illue%s"%rev['group_id']][0]
data={
"model": user_chat_model,
"messages":merge_contents([{"role":"system","content":system_prompt+"[order]\n1. 每句话之间使用#cut#分割开,每段话直接也使用#cut#分割开,你如:“#cut#你好。群友。#cut#幻日老爹在不?#cut#”\n"+e_information}]+messages[1:]),
"stream": True,
"use_search": False
}
is_return=True
continue
elif '#memory/' in temp_tts_list[-1]:
memory=temp_tts_list[-1].split('#memory/')[-1].replace("#",'')
print("写入记忆:",memory)
with open("./user/g%s/I_memory.txt"%rev['group_id'],"a",encoding="utf-8") as mem:
mem.write(" "+memory)
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg': "[写入记忆]"})
elif "#pass/" in temp_tts_list[-1]:
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg': "[pass]"})
raise KeyboardInterrupt("AI认为应该跳过此回复!")
elif "#emotion/" in temp_tts_list[-1]:
t_emotion=temp_tts_list[-1].split("#emotion/")[-1].replace("#",'')
e_image_list=os.listdir("./data/image/%s"%t_emotion)
e_image=random.choice(e_image_list)
send_image({'msg_type': 'group', 'number': rev['group_id'], 'msg':"%s/%s"%(t_emotion,e_image)})
elif "#music/" in temp_tts_list[-1]:
t_music_n=temp_tts_list[-1].split("#music/")[-1].replace("#",'')
smusic_l=os.listdir("./data/voice/smusic")
if t_music_n in smusic_l:
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg': "《%s》"%t_music_n})
send_voice({'msg_type': 'group', 'number': rev['group_id'], 'msg':"smusic/"+t_music_n})
else:
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg': "[未找到合适歌曲]"})
else:
send_msg({'msg_type': 'group', 'number': rev['group_id'], 'msg': temp_tts_list[-1].replace("%s:"%AI_name,"").replace("%s:"%AI_name,"")})
print(processed_d_data1)
print(user_chat_model)
objdict["illue%s"%rev['group_id']][0]=objdict["illue%s"%rev['group_id']][0]+[{'role':'user','content':rev['raw_message']},{'role':'assistant','content':processed_d_data1}]
with open(
"./user/g%s/memory.txt"%rev['group_id'],
"a",
encoding="utf-8",
) as txt:
timestamp = time.time()
localtime = time.localtime(timestamp)
current_time = time.strftime(
"%Y-%m-%d %H:%M:%S", localtime
)
txt.write(
"[%s]%s\n" % (current_time, objdict["illue%schat"%rev['group_id']])
)
txt.write(
"[%s]你回复:%s\n"
% (current_time, processed_d_data1)
)
objdict["illue%schat"%rev['group_id']]=''
print("未发现新消息...运行时间:%f"%(time.time()-startT))
if len(objdict["illue%s"%rev['group_id']][0])> 10:
objdict["illue%s"%rev['group_id']][0]=[objdict["illue%s"%rev['group_id']][0][0]]+objdict["illue%s"%rev['group_id']][0][-6:]
except Exception as e:
try:
objdict["illue%schat"%rev['group_id']]=''
except Exception as ee:
print(user_chat_model)
print(ee)
if debug:
print(e)
print(user_chat_model)
pass
# file.py
from flask import Flask, send_from_directory
from flask_cors import CORS
from waitress import serve
import os
import threading
app = Flask(__name__)
CORS(app)
@app.route('/data/image/<filename>', methods=['GET', 'POST'])
def image_files(filename):
print("用户请求文件:", filename)
if os.path.exists(os.path.join('./data/image/', filename)):
return send_from_directory('./data/image/', filename, as_attachment=True)
else:
return 'File not found', 404
@app.route('/data/voice/<filename>', methods=['GET', 'POST'])
def voice_files(filename):
print("用户请求文件:", filename)
if os.path.exists(os.path.join('./data/voice/', filename)):
return send_from_directory('./data/voice/', filename, as_attachment=True)
else:
return 'File not found', 404
@app.route('/data/voice/smusic/<filename>', methods=['GET', 'POST'])
def music_files(filename):
print("用户请求文件:", filename)
if os.path.exists(os.path.join('./data/voice/smusic/', filename)):
return send_from_directory('./data/voice/smusic/', filename, as_attachment=True)
else:
return 'File not found', 404
@app.route('/data/image/<emotion>/<filename>', methods=['GET', 'POST'])
def emoji_files(emotion,filename):
print("用户请求文件:", emotion,"/",filename)
if os.path.exists('./data/image/%s/%s'%(emotion,filename)):
return send_from_directory('./data/image/%s'%emotion, filename, as_attachment=True)
else:
return 'File not found', 404
# 定义一个函数来启动Flask应用