-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathChatFilter.py
620 lines (570 loc) · 21.9 KB
/
ChatFilter.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
import copy
import json
import os
import time
import ChatAdmin
import simuse
from ChatClass import json_dump, json_load, pickle_dump, pickle_load
def getconfig():
config = json_load('config.clc')
return config['blackfreq']
def replyanswer(data, sender, filterlist,Accuratedict = None): # 发送答案
nodelist = []
#answer=eval(answer)
for i in filterlist: # 去除答案中的imageId,不去除mirai api http会无法回复
try:
i.pop('imageId')
except:
continue
print('条目共有', len(filterlist), '个', flush=True)
tips = '若显示不完整,或未成功发送,则可在ChatLearning控制台中查看'
simuse.Send_Message(data, sender, 2,
'条目共有' + str(len(filterlist)) + '个' + '\n' + tips, 1)
nodedict = {
'senderId': data['qq'],
'time': int(time.time()),
'senderName': 'ChatLearning',
'messageChain': []
}
tipmessageChain = [{
'type':
'Plain',
'text':
'请输入需删除的标记' + '\n' + '(输入-1可取消,all清空所有,多个用空格隔开):'
}]
nodedict['messageChain'] = tipmessageChain
nodelist.append(nodedict.copy())
#messagechain_c=nodedict['messageChain']
for i in filterlist:
changelist = []
#time.sleep(1)
#print(i)
#num = answer.index(i)
#temp = answer[num]
templist = eval(i)
for k in templist:
#print(type(templist),type(tempdict))
#print(templist)
#print(tempdict)
#print(tempdict)
try:
if k['type'] == 'At':
changelist = [{
'type': 'Plain',
'text': '该条目为@消息,要显示完整请在ChatLearning控制台查看'
}]
#print(k)
#print('-',changelist)
elif k['type'] == 'Quote':
changelist = [{
'type': 'Plain',
'text': '该条目为回复类消息,要显示完整请在ChatLearning控制台查看'
}]
#print(k)
#print('-',changelist)
elif k['type'] == 'AtAll':
changelist = [{
'type': 'Plain',
'text': '该条目为@全员消息,要显示完整请在ChatLearning控制台查看'
}]
#print(k)
#print('-',changelist)
elif k['type'] == 'Poke':
changelist = [{
'type': 'Plain',
'text': '该条目为戳一戳类消息,要显示完整请在ChatLearning控制台查看'
}]
except:
#print('error')
pass
#print(i)
index = {'type': 'Plain', 'text': ''}
try:
accurate = Accuratedict[i]
if accurate == True:
accurate_tip='是'
else:
accurate_tip='否'
except:
accurate_tip = '否'
if Accuratedict!= None:
index['text'] = '\n标记:{}\n精确匹配:{}' .format(str(filterlist.index(i)),accurate_tip)
else:
index['text'] = '\n标记:{}' .format(str(filterlist.index(i)))
if changelist != []:
#print(changelist)
messagechain = copy.deepcopy(changelist)
#print(messagechain)
else:
messagechain = copy.deepcopy(eval(i))
#print(messagechain)
messagechain.append(index.copy())
print(i, '标记:', filterlist.index(i), flush=True)
#messagesign = simuse.Send_Message_Chain(data, sender, 2, messagechain)
nodedict['messageChain'] = messagechain
#nodedict['time']=i['time']
nodelist.append(nodedict.copy())
#print(messagesign)
sendmessagechain = [{'type': 'Forward', 'nodeList': ''}]
sendmessagedict = sendmessagechain[0]
sendmessagedict['nodeList'] = nodelist
simuse.Send_Message_Chain(data, sender, 2, sendmessagechain)
time.sleep(0.7)
#simuse.Send_Message(data, sender, 2, '发送完毕,请在ChatLearning控制台中继续操作', 1)
print('请稍等,程序正在处理……')
return len(filterlist)
def getnode(data, Filterconfig, filterlist, sender,Accuratedict = None):
#await asyncio.sleep(waittime)
#simuse.Send_Message(data, sender, 2, '请输入需删除的答案标记'+'\n'+'(输入-1可取消,all清空所有,多个用空格隔开):', 1)
print('请在聊天窗口发送需删除的标记(发送-1可取消,多个用空格隔开)')
while 1:
node = ChatAdmin.get_admin_command(data, sender=sender)
if node != None:
break
if node == 'all':
filterlist.clear()
if Accuratedict!= None:
try:
Accuratedict.clear()
except:
pass
json_dump(Filterconfig, 'Filter.clc', indent=3, ensure_ascii=False)
time.sleep(0.5)
simuse.Send_Message(data, sender, 2, '已清空', 1)
return None
if node == str(-1) or node == '–1':
time.sleep(0.5)
simuse.Send_Message(data, sender, 2, '取消删除', 1)
print('取消删除')
return None
try:
node = node.replace(',', ',')
node = node.replace(' ', ',')
except:
pass
nodelist = '[{}]'.format(node)
try:
nodelist = eval(nodelist)
if type(nodelist) != type([]):
time.sleep(0.5)
print('参数错误')
simuse.Send_Message(data, sender, 2, '参数错误', 1)
return None
except:
time.sleep(0.5)
print('参数错误')
simuse.Send_Message(data, sender, 2, '参数错误', 1)
return None
simuse.Send_Message(data, sender, 2, '正在执行操作,请稍等', 1)
time.sleep(0.5)
templist = []
sendtext = ''
for i in nodelist:
time.sleep(1)
try:
templist.append(filterlist[i])
except:
print('标记为', i, '的条目不存在')
sendtext = sendtext + str(i) + ' '
#simuse.Send_Message(data, sender, 2, '标记为'+sendtext+'的答案不存在', 1)
for i in templist:
#print(i)
filterlist.remove(i)
if Accuratedict!= None:
try:
Accuratedict.pop(i)
except:
pass
#print(filterlist)
json_dump(Filterconfig, 'Filter.clc', indent=3, ensure_ascii=False)
if templist != []:
if sendtext != '':
simuse.Send_Message(
data, sender, 2, '标记为' + sendtext + '的条目不存在' + '\n' + '删除' +
str(len(templist)) + '个条目成功!', 1)
else:
simuse.Send_Message(data, sender, 2,
'删除' + str(len(templist)) + '个条目成功!', 1)
print('删除', str(len(templist)), '个条目成功!')
return None
else:
simuse.Send_Message(data, sender, 2,
'标记为' + sendtext + '的条目不存在' + '\n' + '删除失败', 1)
print('删除失败')
return None
def replyblack(data, Filterconfig, sender, blackdict):
blackfreq = getconfig()
nodelist = []
nodedict = {
'senderId': data['qq'],
'time': int(time.time()),
'senderName': 'ChatLearning',
'messageChain': []
}
tipmessageChain = [{
'type':
'Plain',
'text':
'请输入需删除的账号' + '\n' +
'(输入-1可取消,all清空所有,多个用空格隔开)\n触发次数大于{}次会被屏蔽:'.format(blackfreq)
}]
nodedict['messageChain'] = tipmessageChain
nodelist.append(nodedict.copy())
for i in blackdict:
messagechain = []
blackindex = {'type': 'Plain', 'text': ''}
blackindex['text'] = str(i) + '\n已触发敏感词次数:' + str(blackdict[i])
messagechain.append(blackindex.copy())
nodedict['messageChain'] = messagechain
nodelist.append(nodedict.copy())
sendmessagechain = [{'type': 'Forward', 'nodeList': ''}]
sendmessagedict = sendmessagechain[0]
sendmessagedict['nodeList'] = nodelist
simuse.Send_Message_Chain(data, sender, 2, sendmessagechain)
while 1:
node = ChatAdmin.get_admin_command(data, sender=sender)
if node != None:
break
if node == 'all':
blackdict.clear()
json_dump(Filterconfig, 'Filter.clc', indent=3, ensure_ascii=False)
time.sleep(0.5)
simuse.Send_Message(data, sender, 2, '已清空', 1)
return None
if node == str(-1) or node == '–1':
time.sleep(0.5)
simuse.Send_Message(data, sender, 2, '取消删除', 1)
print('取消删除')
return None
try:
node = node.replace(',', ',')
node = node.replace(' ', ',')
except:
pass
nodelist = '[{}]'.format(node)
try:
nodelist = eval(nodelist)
if type(nodelist) != type([]):
time.sleep(0.5)
print('参数错误')
simuse.Send_Message(data, sender, 2, '参数错误', 1)
return None
except:
time.sleep(0.5)
print('参数错误')
simuse.Send_Message(data, sender, 2, '参数错误', 1)
return None
poperror = ''
for i in nodelist:
try:
blackdict.pop(str(i))
except:
poperror = poperror + str(i) + ' '
json_dump(Filterconfig, 'Filter.clc', indent=3, ensure_ascii=False)
time.sleep(0.5)
if poperror == '':
time.sleep(0.5)
simuse.Send_Message(data, sender, 2, '删除成功!', 1)
else:
time.sleep(0.5)
simuse.Send_Message(data, sender, 2, '删除完毕!\n账号{}不存在'.format(poperror),
1)
def blackcheck():
try:
file = open('Filter.clc', 'r', encoding='utf-8-sig')
try:
Filterconfig = json.load(file)
except json.decoder.JSONDecodeError:
file.close()
file = open('Filter.clc', 'r', encoding='utf-8-sig')
Filterconfig = eval(file.read())
file.close()
return Filterconfig
except:
Filterconfig = {
'filter': [],
'sensitive': [],
'blackdict': {},
'type': ['At', 'AtAll', 'Quote', 'Poke']
}
json_dump(Filterconfig, 'Filter.clc', indent=3, ensure_ascii=False)
return Filterconfig
def sensitivecheck(question, sender, group):
sender = str(sender)
for i in question:
try:
i.pop('url')
except:
pass
Filterconfig = blackcheck()
if str(question) in Filterconfig['sensitive']:
creatblack(sender)
print('已过滤,原因:与敏感问题匹配,已将发送者加入黑名单', '发送者{}'.format(sender),
'来自群{}'.format(group))
return 0
else:
for i in question:
if i['type'] == 'Plain':
for k in Filterconfig['sensitive']:
k = eval(k)
for j in k:
if j['type'] == 'Plain':
if i['text'].find(j['text']) != -1:
creatblack(sender)
print('已过滤,原因:与敏感问题匹配,已将发送者加入黑名单',
'发送者{}'.format(sender),
'来自群{}'.format(group))
return 0
if sender in Filterconfig['blackdict'].keys():
num = Filterconfig['blackdict']
if num[sender] >= getconfig():
print('该用户在黑名单中超出最大次数,已屏蔽', '发送者{}'.format(sender),
'来自群{}'.format(group))
return 0
return 1
def filtercheck(question, sender='|回复过滤', group='|回复过滤', display=True):
command = ['!learning', 'learning', '!reply', 'reply', '!admin', 'admin','!d','!d']
text = ''
for i in question: # 去除作为问题中的变动因素“url”
try:
i.pop('url')
except:
continue
Filterconfig = blackcheck()
try:
Accuratedict = Filterconfig['Accuratedict']
except KeyError:
Accuratedict = {}
#print(question)
for i in question:
if i['type'] == 'Plain':
text = i['text']
for k in Filterconfig['filter']:
k = eval(k)
for j in k:
if j['type'] == 'Plain':
try:
accurated = Accuratedict[str(k)]
except:
accurated = False
if i['text'].find(j['text']) != -1 and accurated==False:
if display == True:
print('已过滤,原因:与过滤字典模糊匹配',
'发送者{}'.format(sender),
'来自群{}'.format(group))
return 0
if str(question) in Filterconfig['filter']:
if display == True:
print('已过滤,原因:与过滤字典精确匹配', '发送者{}'.format(sender),
'来自群{}'.format(group))
return 0
elif text in command:
if display == True:
print('已过滤,原因:与指令匹配', '发送者{}'.format(sender),
'来自群{}'.format(group))
return 0
else:
for i in question:
if i['type'] in Filterconfig['type']:
if display == True:
print('已过滤,原因:与过滤字典中消息类型匹配', '发送者{}'.format(sender),
'来自群{}'.format(group))
return 0
return 1
def creatfilter(question, addfilterlist=0,accurate=False):
if addfilterlist == 0:
for i in question: # 去除作为问题中的变动因素“url”
try:
i.pop('url')
except:
continue
question = str(question)
Filterconfig = blackcheck()
filterlist = Filterconfig['filter']
try:
Accuratedict = Filterconfig['Accuratedict']
except:
Accuratedict = {}
#print(filterlist)
filterlist.append(question)
filterlist = list(set(filterlist))
Accuratedict[question] = accurate
Filterconfig['Accuratedict'] = Accuratedict
json_dump(Filterconfig, 'Filter.clc', indent=3, ensure_ascii=False)
else:
Filterconfig = blackcheck()
filterlist = Filterconfig['filter']
for i in question:
for k in i:
try:
k.pop('url')
except:
continue
filterlist.append(i['answertext'])
filterlist = list(set(filterlist))
json_dump(Filterconfig, 'Filter.clc', indent=3, ensure_ascii=False)
#print(filterlist)
def creatsensitive(question):
for i in question: # 去除作为问题中的变动因素“url”
try:
i.pop('url')
except:
continue
question = str(question)
Filterconfig = blackcheck()
sensitivelist = Filterconfig['sensitive']
sensitivelist.append(question)
sensitivelist = list(set(sensitivelist))
filterlist = Filterconfig['filter']
filterlist.append(question)
filterlist = list(set(filterlist))
json_dump(Filterconfig, 'Filter.clc', indent=3, ensure_ascii=False)
def creatblack(sender, list=0):
Filterconfig = blackcheck()
blackdict = Filterconfig['blackdict']
if list != 0:
for i in sender:
blackdict[i] = 99999
elif sender in blackdict.keys():
blackdict[sender] += 1
else:
blackdict[sender] = 1
json_dump(Filterconfig, 'Filter.clc', indent=3, ensure_ascii=False)
if list == 0:
return blackdict[sender]
def filtercontrol(data, sender):
ExitChain = [{'type': 'Plain', 'text': 'exit'}]
while 1:
time.sleep(1)
tips = '请选择你的操作\n0.返回\n1.添加需过滤的关键字(模糊)\n2.添加需过滤的关键字(精确)\n3.添加敏感关键字\n4.添加黑名单账号\n5.查看,删除'
simuse.Send_Message(data, sender, 2, tips, 1)
while 1:
command = ChatAdmin.get_admin_command(data, sender=sender)
if command != None:
break
#print(command)
if command == str(1):
simuse.Send_Message(data, sender, 2, '请发送需要过滤的关键字,发送“exit”结束', 1)
while 1:
while 1:
question = ChatAdmin.get_admin_question(data, sender)
if question != None:
break
if question == ExitChain: break
try:
creatfilter(question)
except:
simuse.Send_Message(data, sender, 2, '添加失败', 1)
else:
simuse.Send_Message(data, sender, 2, '添加成功!', 1)
elif command == str(2):
simuse.Send_Message(data, sender, 2, '请发送需要过滤的关键字,发送“exit”结束', 1)
while 1:
while 1:
question = ChatAdmin.get_admin_question(data, sender)
if question != None:
break
if question == ExitChain: break
try:
creatfilter(question,accurate=True)
except:
simuse.Send_Message(data, sender, 2, '添加失败', 1)
else:
simuse.Send_Message(data, sender, 2, '添加成功!', 1)
elif command == str(3):
simuse.Send_Message(data, sender, 2, '请发送敏感的关键字,发送“exit”结束', 1)
while 1:
while 1:
question = ChatAdmin.get_admin_question(data, sender)
if question != None:
break
if question == ExitChain: break
try:
creatsensitive(question)
except:
simuse.Send_Message(data, sender, 2, '添加失败', 1)
else:
simuse.Send_Message(data, sender, 2, '添加成功!', 1)
elif command == str(4):
simuse.Send_Message(data, sender, 2, '请输入需要添加黑名单的账号', 1)
while 1:
member = ChatAdmin.get_admin_command(data, sender=sender)
if member != None:
break
try:
member = member.replace(',', ',')
member = member.replace(' ', ',')
except:
pass
memberlist = '[{}]'.format(member)
try:
memberlist = eval(memberlist)
if type(memberlist) != type([]):
print('参数错误')
simuse.Send_Message(data, sender, 2, '参数错误', 1)
return None
except:
print('参数错误')
simuse.Send_Message(data, sender, 2, '参数错误', 1)
return None
creatblack(memberlist, list=1)
simuse.Send_Message(data, sender, 2, '添加完毕', 1)
elif command == str(5):
while True:
simuse.Send_Message(data, sender, 2,
'请输入需要查看的内容\n0.返回\n1.过滤的关键字\n2.敏感的关键字\n3.黑名单',
1)
while 1:
Filterconfig = blackcheck()
node = ChatAdmin.get_admin_command(data, sender=sender)
if node != None:
break
if node == str(1):
filterlist = Filterconfig['filter']
try:
Accuratedict = Filterconfig['Accuratedict']
except:
Accuratedict = {}
replyanswer(data, sender, filterlist,Accuratedict)
getnode(data, Filterconfig, filterlist, sender,Accuratedict)
elif node == str(2):
sensitivelist = Filterconfig['sensitive']
replyanswer(data, sender, sensitivelist)
getnode(data, Filterconfig, sensitivelist, sender)
elif node == str(3):
blackdict = Filterconfig['blackdict']
replyblack(data, Filterconfig, sender, blackdict)
else:
break
else:
return None
def Merge_Filter():
try:
filelist = os.listdir('Filter')
except:
return None
Filterlist = []
for i in filelist:
if i[-4:] == '.clc':
#print(i)
Filterlist.append(i)
if Filterlist != []:
print('检测到有可合并的过滤词')
Filterconfiglist = []
for filename in Filterlist:
file = open('Filter/' + filename, 'r', encoding='utf-8-sig')
dict = eval(file.read())
file.close()
try:
Filterconfiglist.extend(dict['filter'])
Filterconfiglist = list(set(Filterconfiglist))
except:
print(filename, '合并错误')
else:
print(filename, '合并完成')
FilterConfig = blackcheck()
Filterlist_origin = FilterConfig['filter']
Filterlist_origin.extend(Filterconfiglist)
Filterlist_origin = list(set(Filterlist_origin))
FilterConfig['filter'] = Filterlist_origin
json_dump(FilterConfig, 'Filter.clc', indent=3, ensure_ascii=False)