-
Notifications
You must be signed in to change notification settings - Fork 21
/
Chatmain.py
2232 lines (1953 loc) · 78.1 KB
/
Chatmain.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
import asyncio
import base64
import copy
import datetime
import glob
import json
import os
import pickle
import platform
import subprocess
import sys
import time
import traceback
import wave
import nest_asyncio
import requests
from prompt_toolkit import PromptSession
from prompt_toolkit.patch_stdout import patch_stdout
import ChatAdmin
import ChatAllfind
import ChatCheck
import ChatClass
import ChatDelete
import ChatFilter
import ChatLearning
import ChatMerge
import ChatReply
import ChatSubadmin
import ChatStock
import simuse
from ChatClass import (My_Thread, TimeTask, Update, Version, commandclass,
json_dump, json_load, pickle_dump, pickle_load)
nest_asyncio.apply()
def hello():
if not (os.path.exists('AutoTask')):
os.makedirs('AutoTask')
with open('AutoTask/看我看我.txt', 'wb') as file:
str = b'\'\'\'\xe8\xbf\x99\xe6\x98\xaf\xe4\xb8\x80\xe4\xb8\xaa\xe5\xae\x9a\xe6\x97\xb6\xe4\xbb\xbb\xe5\x8a\xa1\xe7\x9a\x84\xe6\xa8\xa1\xe6\x9d\xbf\xef\xbc\x8c\xe7\xa8\x8b\xe5\xba\x8f\xe4\xbc\x9a\xe8\x87\xaa\xe5\x8a\xa8\xe8\xa7\xa3\xe6\x9e\x90\xe5\xb8\xa6\xe6\xa0\x87\xe8\xae\xb0\xe7\x9a\x84\xe8\xa1\x8c\'\'\'\r\n\'\'\'\xe8\xaf\xb7\xe5\x88\x9b\xe5\xbb\xba\xe4\xb8\x80\xe4\xb8\xaa\xe6\x96\xb0\xe7\x9a\x84txt\xe6\x96\x87\xe4\xbb\xb6\xe6\x9d\xa5\xe8\x87\xaa\xe5\xae\x9a\xe4\xb9\x89\xe4\xbd\xa0\xe7\x9a\x84\xe4\xbb\xbb\xe5\x8a\xa1\xef\xbc\x8c\xe6\x96\x87\xe4\xbb\xb6\xe5\x90\x8d\xe5\x8d\xb3\xe6\x98\xaf\xe4\xbb\xbb\xe5\x8a\xa1\xe5\x90\x8d\'\'\'\r\n\r\n\'\'\xe5\xbc\x80\xe5\xa4\xb4\xe4\xbd\xbf\xe7\x94\xa8"#"\x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80\xe5\xa4\xb4\xe4\xbd\xbf\xe7\x94\xa8"/"\xe6\x9d\xa5\xe6\xa0\x87\xe8\xae\xb0\xe4\xbb\xbb\xe5\x8a\xa1\xe6\x89\x80\xe9\x9c\x80\xe6\x89\xa7\xe8\xa1\x8c\xe7\x9a\x84\xe6\x8c\x87\xe4\xbb\xa4\r\n\xe5\xa6\x82(\xe4\xb8\x80\xe4\xb8\xaa\xe6\x8c\x87\xe4\xbb\xa4\xe5\xaf\xb9\xe5\xba\x94\xe4\xb8\x80\xe8\xa1\x8c)\xef\xbc\x9a\r\n/check\r\n/autodelete\r\n\r\n\xe4\xbb\xa5\xe4\xb8\x8b\xe6\x98\xaf\xe7\xa4\xba\xe4\xbe\x8b\xef\xbc\x88\xe6\xaf\x8f\xe5\xa4\xa9\xe7\x9a\x8412\xe7\x82\xb9\xe5\x92\x8c23\xe7\x82\xb959\xe5\x88\x86\xef\xbc\x8c\xe6\x89\xa7\xe8\xa1\x8ccheck\xef\xbc\x8cgrouplist\xe6\x8c\x87\xe4\xbb\xa4\xef\xbc\x8c\xe5\xb9\xb6\xe5\xb0\x86\xe7\xbb\x93\xe6\x9e\x9c\xe5\x8f\x91\xe9\x80\x81\xe7\xbb\x99123456\xef\xbc\x89\xef\xbc\x9a\r\n#everyday\r\n@123456\r\n*12:00 23:59\r\n/check\r\n/grouplist\r\n\r\n\r\n-------------------\r\n\xe5\x9c\xa8\xe8\x87\xaa\xe5\x8a\xa8\xe4\xbb\xbb\xe5\x8a\xa1\xe4\xb8\xad\xe6\x9c\x89\xe4\xb8\x80\xe4\xba\x9b\xe7\x89\xb9\xe6\xae\x8a\xe6\x8c\x87\xe4\xbb\xa4\xef\xbc\x9a\r\n\xe8\x87\xaa\xe5\x8a\xa8\xe6\xb8\x85\xe7\x90\x86\xe8\xaf\x8d\xe5\xba\x93"autodelete"\r\n\xe5\x8f\x91\xe9\x80\x81\xe7\xbe\xa4\xe6\xb6\x88\xe6\x81\xaf"sendgroupmessage <\xe7\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\x9a\r\n\xe5\xbd\x93\xe5\x89\x8d\xe5\xb9\xb4\xef\xbc\x9a{year}\r\n\xe5\xbd\x93\xe5\x89\x8d\xe6\x9c\x88\xef\xbc\x9a{month}\r\n\xe5\xbd\x93\xe5\x89\x8d\xe6\x97\xa5\xef\xbc\x9a{day}\r\n\xe6\x8d\xa2\xe8\xa1\x8c\xef\xbc\x9a{n}\r\n\xe5\xa6\x82\xef\xbc\x9a\r\n/sendgroupmessage 123456 \xe4\xbb\x8a\xe5\xa4\xa9\xe6\x98\xaf{year}\xe5\xb9\xb4{month}\xe6\x9c\x88{day}\xe6\x97\xa5\xef\xbc\x81{n}\xe5\xa4\xa7\xe5\xae\xb6\xe5\xa5\xbd\xe5\x95\x8a\xef\xbc\x81\r\n-------------------\r\n\r\n'
file.write(str)
print('在目录下的AutoTask文件夹内看看定时任务的说明吧!')
#os.system("title ChatLearning")
file = open('config.clc', 'r', encoding='utf-8-sig')
try:
config = json.load(file)
except json.decoder.JSONDecodeError:
file.close()
file = open('config.clc', 'r', encoding='utf-8-sig')
config = eval(file.read())
file.close()
config['reply'] = 0
config['merge'] = 0
config['learning'] = 0
config['admin'] = 0
if ('version' in config.keys()) == False:
update = Update('0.0.0')
update.ClChange()
config['version'] = '2.7.0'
else:
update = Update(config['version'])
update.Cl_version()
config = update.Config_version()
config['version'] = Version()
config['stopsign'] = 0
json_dump(config, 'config.clc', indent=3, ensure_ascii=False)
ChatFilter.Merge_Filter()
print('欢迎使用ChatLearning应用 版本号:', Version())
#print('遇到问题和bug请在mirai论坛回复我或发送至我的邮箱[email protected]')
print('输入help来查看指令列表吧!')
def unknowcommand(command):
print('<-未知指令"{}" 请输入help/?查看帮助'.format(command))
pass
def stop_all_thread():
config = ChatReply.getconfig(16)
config["stopsign"] = 1
json_dump(config,
'config.clc',
indent=3,
ensure_ascii=False)
try:
listen_t.join()
reply_t.join()
merge_t.join()
autotask_t.join()
learning_t.join()
subadmin_t.join()
except NameError:
pass
except RuntimeError:
pass
config = ChatReply.getconfig(16)
config["stopsign"] = 0
json_dump(config,
'config.clc',
indent=3,
ensure_ascii=False)
def exit():
print('等待程序退出……')
stop_all_thread()
sys.exit(0)
def down_new_version():
#global data
if my_name == 'Chatmain.py':
print('该版本暂不支持')
#return None
config = json_load('config.clc')
download = Update(config['version'])
sign = download.down_new_file()
if sign == None:
print('网络连接出错')
elif sign[0] == 0:
print('已是最新版本')
elif sign[0] == 1:
print('新版本已就绪,正在准备重启')
stop_all_thread()
restart(sign[1])
sys.exit()
def restart(version):
new_name = 'ChatLearning_new'
if system == 'Windows':
old_name = 'ChatLearning_v{}.exe'.format(version)
elif system == 'Linux':
old_name = 'ChatLearning_v{}'.format(version)
time.sleep(2)
#os.remove('ChatLearning.exe')
if system == 'Windows':
b = open("upgrade.bat", 'w')
TempList = "@echo off\n"
TempList += "if not exist " + new_name + " exit \n" #判断是否有新版本的程序,没有就退出更新。
TempList += "echo 正在更新至最新版本...\n"
#TempList += "timeout /t 2 /nobreak\n" #等待2秒
TempList += "copy " + new_name + " " + old_name + '\n' #复制新版本程序
TempList += "del " + new_name + "\n" #删除旧程序
TempList += "echo 更新完成,正在启动...\n"
#TempList += "timeout /t 3 /nobreak\n"
TempList += "start " + old_name + "\n" #"start 1.bat\n"
TempList += "exit"
b.write(TempList)
b.close()
shell = subprocess.Popen("upgrade.bat")
elif system == 'Linux':
linux_command = json_load(
'command.json')
start_command = linux_command['start']
per_command = linux_command['permission']
per_command_list = per_command.split(' ')
sh_command = linux_command['shell']
sh_command_list = sh_command.split(' ')
for i in per_command_list:
if i == '{}':
per_command_list[per_command_list.index('{}')] = "upgrade.sh"
for i in sh_command_list:
if i == '{}':
sh_command_list[sh_command_list.index('{}')] = "upgrade.sh"
b = open("upgrade.sh", 'w')
TempList = "if [ ! -f ChatLearning_new ];then exit;fi\n" #判断是否有新版本的程序,没有就退出更新。
TempList += "echo 正在更新至最新版本...\n"
TempList += per_command.format("ChatLearning_new") + "\n"
#TempList += "timeout /t 2 /nobreak\n" #等待2秒
TempList += "cp " + new_name + " " + old_name + '\n' #复制新版本程序
TempList += "rm " + new_name + "\n" #删除旧程序
TempList += "echo 更新完成,正在启动...\n"
TempList += per_command.format(
"ChatLearning_v{}".format(version)) + "\n"
#TempList += "timeout /t 3 /nobreak\n"
TempList += start_command.format(old_name) + "\n" #"start 1.bat\n"
TempList += "exit"
b.write(TempList)
b.close()
subprocess.Popen(per_command_list)
shell = subprocess.Popen(sh_command_list)
while True:
if shell.poll() != None:
break
def cosmatch(fromchat=0):
global data
config = json_load('config.clc')
if config['cosmatch']==0:
config['cosmatch']=1
json_dump(config,'config.clc')
print('已开启问题余弦相似度计算,请注意,将会消耗较多的计算机资源')
if fromchat!=0:
simuse.Send_Message(data, fromchat, 2, '已开启问题余弦相似度计算,请注意,将会消耗较多的计算机资源', 1)
return None
elif config['cosmatch']==1:
config['cosmatch']=0
json_dump(config,'config.clc')
print('已关闭问题余弦相似度计算')
if fromchat!=0:
simuse.Send_Message(data, fromchat, 2, '已关闭问题余弦相似度计算', 1)
return None
def cosmatching(args,fromchat=0):
global data
try:
matching = float(args)
if matching>1 or matching<0:
raise Exception
except:
print('参数错误,匹配率的数值区间为[0-1]')
if fromchat!=0:
simuse.Send_Message(data, fromchat, 2, '参数错误,匹配率的数值区间为[0-1]', 1)
return None
config = json_load('config.clc')
config['cosmatching'] = matching
json_dump(config,'config.clc')
print('已将匹配率阈值设置为{}'.format(matching))
if fromchat!=0:
simuse.Send_Message(data, fromchat, 2, '已将匹配率阈值设置为{}'.format(matching), 1)
def ReplyWait(args: str, fromchat=0):
global data
if args.find(' ') == -1:
print('参数错误')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '参数错误', 1)
return None
try:
BenchmarkTime = float(args[:args.find(' ')])
RandomTime = float(args[args.find(' ') + 1:])
except:
print('参数错误')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '参数错误', 1)
return None
if BenchmarkTime < RandomTime:
print("浮动时间范围不得大于基准时间!")
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, "浮动时间范围不得大于基准时间!", 1)
return None
elif BenchmarkTime > 4 or RandomTime > 2:
print("基准时间不得大于4秒,浮动时间不得大于2秒!")
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, "基准时间不得大于4秒,浮动时间不得大于2秒!", 1)
return None
elif BenchmarkTime < 0 or RandomTime < 0:
print("时间不得为负数!")
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, "时间不得为负数!", 1)
return None
replystoptime = [BenchmarkTime, RandomTime]
config = json_load('config.clc')
config['replywait'] = replystoptime
json_dump(config, 'config.clc', indent=3, ensure_ascii=False)
print('已将回复等待时间设置为{:g}±{:g}秒'.format(BenchmarkTime, RandomTime))
if fromchat != 0:
simuse.Send_Message(
data, fromchat, 2,
'已将回复等待时间设置为{:g}±{:g}秒'.format(BenchmarkTime, RandomTime), 1)
def GetAutoTask():
try:
Taskdict = pickle.load(open('AutoTask/AutoTask.clc', 'rb'))
except:
Taskdict = {}
pickle_dump(Taskdict, 'AutoTask/AutoTask.clc')
return Taskdict
def GetAutoTaskInfo(fromchat=0):
global TaskDict
global data
if TaskDict == {}:
print('当前无定时任务')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '当前无定时任务', 1)
else:
nodelist = []
situationnodedict = {
'senderId': data['qq'],
'time': int(time.time()),
'senderName': 'ChatLearning',
'messageChain': [{
'type': 'Plain',
'text': ''
}]
}
for Task in TaskDict.values():
print(Task.TaskInfo())
InfoChain = [{'type': 'Plain', 'text': Task.TaskInfo()}]
situationnodedict['messageChain'] = InfoChain
nodelist.append(situationnodedict.copy())
if fromchat != 0:
sendmessagechain = [{'type': 'Forward', 'nodeList': ''}]
sendmessagedict = sendmessagechain[0]
sendmessagedict['nodeList'] = nodelist
simuse.Send_Message_Chain(data, fromchat, 2, sendmessagechain)
def RunAutoTask():
global TaskDict
while 1:
if ChatClass.stop_run():
return None
pickle_dump(TaskDict, 'AutoTask/AutoTask.clc')
time.sleep(1)
if TaskDict == {}:
continue
TaskValuesList = list(TaskDict.values())
for Task in TaskValuesList:
if Task.ISTaskTime() == 1:
RunTaskCommand(Task)
def AutoTaskLog(function):
def wrapper(Task):
print('开始执行自动任务"{}"'.format(Task.TaskName))
with open('AutoTask/Tasklog.log', 'a', encoding='utf-8-sig') as file:
nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
file.write(nowtime + ' 开始执行自动任务"{}"'.format(Task.TaskName) + '\n')
try:
function(Task)
except:
print('自动任务"{}"执行出错,异常已记录'.format(Task.TaskName))
with open('AutoTask/Tasklog.log', 'a',
encoding='utf-8-sig') as file:
nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
file.write(nowtime + ' 自动任务"{}"执行出错:\n'.format(Task.TaskName) +
traceback.format_exc() + '\n')
raise
else:
print('自动任务"{}"执行完毕'.format(Task.TaskName))
with open('AutoTask/Tasklog.log', 'a',
encoding='utf-8-sig') as file:
nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
file.write(nowtime + ' 自动任务"{}"执行完毕'.format(Task.TaskName) +
'\n')
return wrapper
@AutoTaskLog
def RunTaskCommand(Task):
for TaskCommand in Task.TaskList:
time.sleep(1)
if TaskCommand == 'admin':
continue
if TaskCommand == 'autodelete':
AutoDelete(Task.SendList)
continue
if TaskCommand[:18] == 'sendfriendmessage ':
sendfriendmessage(TaskCommand[18:].split(' ', 1))
continue
if TaskCommand[:23] == 'sendfriendmessageimage ':
sendfriendmessageimage(TaskCommand[23:].split(' ', 1))
continue
if TaskCommand[:17] == 'sendgroupmessage ':
sendgroupmessage(TaskCommand[17:].split(' ', 1))
continue
if TaskCommand[:22] == 'sendgroupmessageimage ':
sendgroupmessageimage(TaskCommand[22:].split(' ', 1))
continue
if Task.SendList != []:
commandchoice(TaskCommand, fromchat=Task.SendList)
else:
commandchoice(TaskCommand)
if Task.ISDisposable == 1:
TaskDict.pop(Task.TaskName)
def AutoDelete(fromchat):
global data
global adminsendmode
global learningsign
global mergesign
global replysign
learning_close_sign = 0
reply_close_sign = 0
if learningsign == 1:
tempsign = learning(learningsign, mergesign, fromchat)
learningsign = tempsign[0]
mergesign = tempsign[1]
learning_close_sign = 1
if replysign == 1:
time.sleep(0.8)
replysign = reply(replysign, fromchat)
reply_close_sign = 1
time.sleep(1)
ChatDelete.Delete(data, fromchat)
if learning_close_sign == 1:
time.sleep(0.8)
tempsign = learning(learningsign, mergesign, fromchat)
learningsign = tempsign[0]
mergesign = tempsign[1]
if reply_close_sign == 1:
time.sleep(0.8)
replysign = reply(replysign, fromchat)
def sendgroupmessage(arglist):
global data
target = arglist[0]
sendstr = arglist[1]
sendstr = sendstr.replace('{year}', datetime.datetime.now().strftime('%Y'))
sendstr = sendstr.replace('{month}',
datetime.datetime.now().strftime('%m'))
sendstr = sendstr.replace('{day}', datetime.datetime.now().strftime('%d'))
sendstr = sendstr.replace('{n}', '\n')
simuse.Send_Message(data, target, 1, sendstr, 1)
def sendgroupmessageimage(arglist):
global data
target = arglist[0]
sendstr = arglist[1]
simuse.Send_Message(data, target, 1, sendstr, 2, path=1)
def sendfriendmessage(arglist):
global data
target = arglist[0]
sendstr = arglist[1]
sendstr = sendstr.replace('{year}', datetime.datetime.now().strftime('%Y'))
sendstr = sendstr.replace('{month}',
datetime.datetime.now().strftime('%m'))
sendstr = sendstr.replace('{day}', datetime.datetime.now().strftime('%d'))
sendstr = sendstr.replace('{n}', '\n')
simuse.Send_Message(data, target, 2, sendstr, 1)
def sendfriendmessageimage(arglist):
global data
target = arglist[0]
sendstr = arglist[1]
simuse.Send_Message(data, target, 2, sendstr, 2, path=1)
def AutoTaskCommand(fromchat=0):
global data
command = {}
command['autodelete'] = '#自动清理词库'
command['sendfriendmessage <好友QQ> <消息>'] = '#发送好友消息'
command['sendfriendmessageimage <好友QQ> <图片绝对路径>'] = '#发送好友图片消息'
command['sendgroupmessage <群号> <消息>'] = '#发送群聊消息'
command['sendgroupmessageimage <群号> <消息>'] = '#发送群聊图片消息'
print('指令列表:')
sendtext = ''
for i in command:
sendtext = sendtext + i + command[i] + '\n'
print(i, ' ', command[i])
print('\n')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, sendtext, 1)
def uploadwav(data, fromchat=0):
try:
wavsize = os.path.getsize('source.wav')
except:
print('未找到source.wav文件!')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '未找到source.wav文件!', 1)
return None
wav_kb = wavsize / float(1024)
if wav_kb >= 10240:
print('文件大小超过10M!取消上传')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '文件大小超过10M!取消上传', 1)
return None
wavefile = wave.open('source.wav', 'rb')
wav_secs = wavefile.getnframes() / wavefile.getframerate()
if wav_secs >= 20:
print('音频时长大于20秒!取消上传')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '音频时长大于20秒!取消上传', 1)
return None
wavfile = open('source.wav', 'rb')
base64_data = base64.b64encode(wavfile.read())
wavfile.close()
data_in = {'QQ': data['qq'], 'base64': base64_data.decode()}
url = 'http://124.222.165.166:19630/Sourcewav'
try:
print('正在等待服务器响应')
simuse.Send_Message(data, fromchat, 2, '正在等待服务器响应', 1)
res = requests.request('post', url=url, json=data_in, timeout=20)
res = json.loads(res.text)
except:
print('上传失败,服务器未响应')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '上传失败,服务器未响应', 1)
return None
try:
if res['code'] == 1:
print('上传成功!')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '上传成功!', 1)
return None
else:
print('上传失败!')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '上传失败!', 1)
return None
except:
print('上传失败!')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '上传失败!', 1)
return None
def testvoice(data, text, fromchat=0):
if fromchat == 0:
print('请在聊天环境下进行')
return None
if ChatReply.canToVoice(text):
if ChatReply.CanSendTask():
answer = ChatReply.Plain_Voice(data, text)
if answer == None:
print('转换失败')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '转换失败', 1)
return None
else:
simuse.Send_Message_Chain(data, fromchat, 2, answer)
else:
print('转换失败,服务器队列已满')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '转换失败,服务器队列已满', 1)
return None
else:
print('转换失败,存在不支持的字符')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '转换失败,存在不支持的字符', 1)
def SetReplyCd(data, Cd, fromchat=0):
try:
Cd = int(Cd)
except:
print('参数错误')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '参数错误', 1)
return None
if Cd < 1:
print('参数错误')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '参数错误', 1)
return None
config = json_load('config.clc')
config['replycd'] = Cd
json_dump(config,
'config.clc',
indent=3,
ensure_ascii=False)
print('回复的冷却时间已设置为{}秒'.format(Cd))
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '回复的冷却时间已设置为{}秒'.format(Cd), 1)
def setReplyLength(data,length,fromchat):
try:
length = int(length)
if length < 1:
raise Exception('error')
except:
print('参数错误')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '参数错误', 1)
return
config = json_load('config.clc')
config['replylength'] = length
json_dump(config,
'config.clc',
indent=3,
ensure_ascii=False)
print(f'答案最大长度已经设置为 {length}')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, f'答案最大长度已经设置为 {length}', 1)
def atreply(data,fromchat=0):
config = json_load('config.clc')
text = '已{}艾特回复'
if config['atreply'] == 0:
config['atreply'] = 1
text = text.format('开启')
elif config['atreply'] == 1:
config['atreply'] = 0
text = text.format('关闭')
json_dump(config,
'config.clc',
indent=3,
ensure_ascii=False)
print(text)
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, text, 1)
def setbotname(data,botname,fromchat=0):
botname_list = botname.split(' ')
config = json_load('config.clc')
config['botname'] = botname_list
json_dump(config,
'config.clc',
indent=3,
ensure_ascii=False)
print(f'已将bot昵称设置为 {botname_list}')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, f'已将bot昵称设置为 {botname_list}', 1)
def importstock(data,filename,fromchat=0):
try:
res = ChatStock.load_word_stock(filename)
except:
print('打开错误,请检查是否为utf-8格式,如果是cl词库请直接移至WordStock文件夹即可')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '打开错误,请检查是否为utf-8格式,如果是cl词库请直接移至WordStock文件夹即可', 1)
return
if res == None:
print(f'未找到文件"{filename}"')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, f'未找到文件"{filename}"', 1)
return
add_res = ChatStock.create_word_stock(res,filename)
if add_res==None:
print('导入失败,未分析出可导入的词库')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '导入失败,未分析出可导入的词库', 1)
return
print(f'已导入问题{add_res[0]}个,答案{add_res[1]}个,词库已保存至{add_res[2]}')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, f'已导入问题{add_res[0]}个,答案{add_res[1]}个,词库已保存至{add_res[2]}', 1)
def SetTempMessage(data, num, fromchat=0):
config = json_load('config.clc')
try:
num = int(num)
except:
print('参数错误')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '参数错误', 1)
return None
if num < 1:
print('参数错误')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '参数错误', 1)
return None
config['tempmessagenum'] = num
json_dump(config, 'config.clc', indent=3, ensure_ascii=False)
print('每个群的消息缓存已设置为{}条'.format(num))
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '每个群的消息缓存已设置为{}条'.format(num),
1)
def SetFastDeleteAdmin(FastDeletesign, fromchat=0):
global data
if FastDeletesign == 0:
config = json_load('config.clc')
config['fastdelete'] = 1
json_dump(config, 'config.clc', indent=3, ensure_ascii=False)
print('<-快速删除已设置为所有人可用')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '快速删除已设置为所有人可用', 1)
FastDeletesign = 1
return FastDeletesign
else:
FastDeletesign = 0
config = json_load('config.clc')
config['fastdelete'] = 0
json_dump(config, 'config.clc', indent=3, ensure_ascii=False)
print('<-快速删除已设置为仅管理员可用')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '快速删除已设置为仅管理员可用', 1)
return FastDeletesign
def blackfreq(data, num, fromchat=0):
config = json_load('config.clc')
try:
num = int(num)
except:
print('参数错误')
return None
if num < 1:
print('参数错误')
return None
config['blackfreq'] = num
json_dump(config, 'config.clc', indent=3, ensure_ascii=False)
print('黑名单容错次数已设置为{}次'.format(num))
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '黑名单容错次数已设置为{}次'.format(num), 1)
def setvoicept(data, ptname, fromchat=0):
url = "http://124.222.165.166:19630/Ptlist"
try:
print('正在等待服务器响应')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '正在等待服务器响应', 1)
res = requests.request('get', url, timeout=20)
res = json.loads(res.text)
except:
print('设置失败,服务器未响应')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '设置失败,服务器未响应', 1)
return None
ptlist = res['ptlist']
if not (ptname in ptlist):
sendptlist = ''
for i in ptlist:
sendptlist = sendptlist + i + ' '
print('该训练集不存在')
print('服务器中存在的训练集:\n' + sendptlist)
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2,
'该训练集不存在\n服务器中存在的训练集:\n' + sendptlist, 1)
return None
config = json_load('config.clc')
config['synthesizer'] = ptname
json_dump(config, 'config.clc', indent=3, ensure_ascii=False)
print('训练集已更改为{}'.format(ptname))
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '训练集已更改为{}'.format(ptname), 1)
def remerge():
config = json_load('config.clc')
config['merge'] = 1
json_dump(config, 'config.clc', indent=3, ensure_ascii=False)
merge = My_Thread(target=ChatMerge.main)
merge.start()
def globe(globesign=0, get=0, fromchat=0):
global data
config = json_load('config.clc')
if get == 1:
return config['sendmode']
if globesign == 0:
config['sendmode'] = 1
globesign = 1
print('<-已开启全局模式')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '已开启全局模式', 1)
else:
config['sendmode'] = 0
globesign = 0
print('<-已关闭全局模式')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '已关闭全局模式', 1)
json_dump(config, 'config.clc', indent=3, ensure_ascii=False)
return globesign
def setadmin(adminnum, fromchat=0):
global data
adminlist = '[{}]'.format(adminnum)
try:
adminlist = adminlist.replace(',', ',')
adminlist = adminlist.replace(' ', ',')
except:
pass
try:
adminlist = eval(adminlist)
if type(adminlist) != type([]):
print('参数错误')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '参数错误', 1)
return None
except:
print('参数错误')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '参数错误', 1)
return None
config = json_load('config.clc')
config['Administrator'] = adminlist
json_dump(config, 'config.clc', indent=3, ensure_ascii=False)
print('管理员QQ号已设置为', adminlist)
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '管理员QQ号已设置为' + str(adminlist),
1)
def admin(adminsign, fromchat=0):
global adminsendmode
global learningsign
global mergesign
global replysign
learning_close_sign = 0
reply_close_sign = 0
if fromchat == 0:
print('请在管理员私聊bot执行该指令')
return adminsign
if learningsign == 1:
tempsign = learning(learningsign, mergesign, fromchat)
learningsign = tempsign[0]
mergesign = tempsign[1]
learning_close_sign = 1
if replysign == 1:
time.sleep(0.8)
replysign = reply(replysign, fromchat)
reply_close_sign = 1
print('<-进入管理模式')
print('请不要操作控制台!!!')
if adminsign == 0:
while True:
time.sleep(0.8)
#print('拥有词库的群号:')
#print(ChatAdmin.getfilelist())
tips = '请发送需要操作的序号\n0.退出管理模式\n1.在所有群内查找\n2.在指定群内查找\n3.过滤,黑名单设置\n4.自动清理词库\n5.添加自动任务\n6.添加自定义回复'
simuse.Send_Message(data, fromchat, 2, tips, 1)
command = getcommand_chat_foradmin()
choice = command[0]
sender = command[1]
if choice == str(0):
print(('<-退出管理模式'))
simuse.Send_Message(data, fromchat, 2, '退出管理模式', 1)
break
elif choice == str(1):
ChatAllfind.findallcontrol(data, fromchat)
#return adminsign
elif choice == str(2):
if fromchat != 0:
tips = '进入管理模式' + '\n' + '拥有词库的群号' + '\n' + str(
ChatAdmin.getfilelist()) + '\n' + '请发送需要选择的群号'
simuse.Send_Message(data, fromchat, 2, tips, 1)
print('请使用管理员QQ', ChatAdmin.getconfig(1), '向bot发送需要选择的群号')
#adminsendmode=1
time.sleep(0.5)
#adminsendmode=0
command = getcommand_chat_foradmin()
group = command[0]
sender = command[1]
try:
group = str(group)
except:
print('参数错误')
if fromchat != 0:
simuse.Send_Message(data, fromchat, 2, '参数错误', 1)
config = json_load('config.clc')
config['admin'] = 1
json_dump(config, 'config.clc', indent=3, ensure_ascii=False)
ChatAdmin.main(data, config['Administrator'], group, sender)
#admin=My_Thread(target=ChatAdmin.main,args=(config['Administrator'],group))
#adminsign=1
#admin.join()
#listen = My_Thread(target=getcommand_chat)
#listen.start()
#return adminsign
elif choice == str(3):
ChatFilter.filtercontrol(data, fromchat)
#return adminsign
elif choice == str(4):
simuse.Send_Message(
data, fromchat, 2,
'此操作将会删除词库中仅出现过单次的条目和被过滤的条目,且操作不可逆!!\n请输入“确定”确认删除', 1)
command = getcommand_chat_foradmin()
if command[0] == '确定':
sender = command[1]
ChatDelete.Delete(data, sender)
else:
continue
elif choice == str(5):
simuse.Send_Message(data, fromchat, 2, "请输入任务名称", 1)
TaskName = getcommand_chat_foradmin()[0]
simuse.Send_Message(data, fromchat, 2, "请输入自动任务语法", 1)
TaskText = getcommand_chat_foradmin()[0]
print(TaskText)
Task = TimeTask(TaskName, TaskText)
if Task.CheckTask() == 0:
print(Task.ErrorTips)
simuse.Send_Message(data, fromchat, 2, Task.ErrorTips, 1)
continue
TaskDict[TaskName] = copy.deepcopy(Task)
print('添加成功!\n' + Task.TaskInfo())
simuse.Send_Message(data, fromchat, 2,
'添加成功!\n' + Task.TaskInfo(), 1)
continue
elif choice == str(6):
ChatLearning.custom_answer(data, fromchat)
continue
else:
print('参数错误')
continue
if learning_close_sign == 1:
time.sleep(0.8)
tempsign = learning(learningsign, mergesign, fromchat)
learningsign = tempsign[0]
mergesign = tempsign[1]
if reply_close_sign == 1:
time.sleep(0.8)
replysign = reply(replysign, fromchat)
return adminsign
def get_group_perm(data, group):
adminlist = []
memberlist = simuse.Get_Groupmember(data, group)
for i in memberlist:
if i['permission'] == 'OWNER' or i['permission'] == 'ADMINISTRATOR':
adminlist.append(i['id'])
return adminlist
def grouplist(fromchat=0):
global data
config = json_load('config.clc')
learninggrouplist = config['learninggrouplist']
replygrouplist = config['replygrouplist']
unmergegrouplist = config['unmergegrouplist']
Administrator = config['Administrator']
try:
subadmindict = config['subadmin']
except:
subadmindict = {'无': None}
print('管理员QQ号:', Administrator)
print('已开启记录的群:', learninggrouplist)
print('已开启答复的群:', replygrouplist)
print('允许自主管理的群:', list(subadmindict.keys()))
print('不录入总词库的群:', unmergegrouplist)
if fromchat != 0:
sendtext = '管理员QQ号:' + str(Administrator) + '\n' + '已开启记录的群:' + str(
learninggrouplist) + '\n' + '已开启答复的群:' + str(
replygrouplist) + '\n' + '允许自主管理的群:' + str(
list(subadmindict.keys())) + '\n' + '不录入总词库的群:' + str(
unmergegrouplist)
simuse.Send_Message(data, fromchat, 2, sendtext, 1)
def learninginterval(interval, fromchat=0):
global data