From d0a09488583aa7243517f6a0056f62d9efa386aa Mon Sep 17 00:00:00 2001 From: 1121917292 <1121917292@qq.com> Date: Wed, 6 Apr 2022 13:24:40 +0800 Subject: [PATCH] update 2.8.0 --- ChatAdmin.py | 31 +-- ChatAllfind.py | 165 ++++++++++----- ChatCheck.py | 70 +++++-- ChatClass.py | 72 ++++++- ChatDelete.py | 129 ++++++++++++ ChatFilter.py | 72 +++++-- ChatLearning.py | 26 ++- ChatMerge.py | 51 ++++- ChatReply.py | 259 +++++++++++++++-------- ChatSubadmin.py | 12 +- Chatmain.py | 537 ++++++++++++++++++++++++++++++++++++++++++------ README.md | 17 ++ simuse.py | 2 + 13 files changed, 1164 insertions(+), 279 deletions(-) create mode 100644 ChatDelete.py diff --git a/ChatAdmin.py b/ChatAdmin.py index db76acc..89979d0 100644 --- a/ChatAdmin.py +++ b/ChatAdmin.py @@ -4,32 +4,32 @@ import pickle import threading import time -import pickle #import nest_asyncio from prompt_toolkit import PromptSession from prompt_toolkit.patch_stdout import patch_stdout import ChatFilter +import ChatMerge import simuse #nest_asyncio.apply() -def get_admin_question(data, sender,group=0): +def get_admin_question(data, sender, group=0): message = simuse.Fetch_Message(data) if type(message) == type(0): time.sleep(0.5) return None for i in message: - if group==0: + if group == 0: if i['type'] == 'FriendMessage' and i[ 'sender'] == sender: # 判断监听到的消息是否为群消息 messagechain = i['messagechain'] messagechain.pop(0) question = messagechain return question - elif group!=0: + elif group != 0: if i['type'] == 'GroupMessage' and i[ 'sender'] == sender: # 判断监听到的消息是否为群消息 messagechain = i['messagechain'] @@ -39,13 +39,13 @@ def get_admin_question(data, sender,group=0): return None -def get_admin_command(data, adminlist=0, sender=0,group=0): +def get_admin_command(data, adminlist=0, sender=0, group=0): message = simuse.Fetch_Message(data) if type(message) == type(0): time.sleep(0.5) return None for i in message: - if sender != 0 and group==0: + if sender != 0 and group == 0: if i['type'] == 'FriendMessage' and i[ 'sender'] == sender: # 判断监听到的消息是否为群消息 messagechain = i['messagechain'] @@ -54,7 +54,7 @@ def get_admin_command(data, adminlist=0, sender=0,group=0): #node = command['text'] return command['text'] return None - elif sender!=0 and group!=0: + elif sender != 0 and group != 0: if i['type'] == 'GroupMessage' and i[ 'sender'] == sender: # 判断监听到的消息是否为群消息 messagechain = i['messagechain'] @@ -106,7 +106,7 @@ def getnode(data, tempdict, answerlist, group, sender, question): time.sleep(0.8) tempdict.pop(question) filename = str(group) + '.cl' # 读取已缓存的词库 - pickle.dump(tempdict,open(filename, 'wb')) + pickle.dump(tempdict, open('WordStock/' + filename, 'wb')) simuse.Send_Message(data, sender, 2, '已清空', 1) return None if node == str(-1) or node == '–1': @@ -155,7 +155,7 @@ def getnode(data, tempdict, answerlist, group, sender, question): if answerlist == []: tempdict.pop(question) filename = str(group) + '.cl' # 读取已缓存的词库 - pickle.dump(tempdict,open(filename, 'wb')) + pickle.dump(tempdict, open('WordStock/' + filename, 'wb')) if templist != []: if sendtext != '': simuse.Send_Message( @@ -303,7 +303,7 @@ def getanswer(data, sender, group, question): # 从词库中获取答案 continue question = str(question) filename = str(group) + '.cl' # 读取已缓存的词库 - tempdict=pickle.load(open(filename, 'rb')) + tempdict = pickle.load(open('WordStock/' + filename, 'rb')) try: # 检索问题,若词库中无该问题,则函数返回-1,若有,则返回所有答案(答案列表) #print(question) questiondict = tempdict[question] @@ -364,10 +364,15 @@ def tui(data, adminlist, group): def getfilelist(): - filelist = os.listdir() + filelist = os.listdir('WordStock') + tagdict = ChatMerge.getconfig()[3] + Taglist = [] + for i in tagdict.values(): + Taglist.extend(i) + Taglist = list(set(Taglist)) cllist = [] for i in filelist: - if i[-3:] == '.cl': + if i[-3:] == '.cl' and not (i[:-3] in Taglist): #print(i) cllist.append(i) try: @@ -376,7 +381,7 @@ def getfilelist(): pass grouplist = [] for i in cllist: - grouplist.append(int(i[:-3])) + grouplist.append((i[:-3])) return grouplist diff --git a/ChatAllfind.py b/ChatAllfind.py index cac75f7..22c2344 100644 --- a/ChatAllfind.py +++ b/ChatAllfind.py @@ -8,15 +8,21 @@ from qcloud_cos import CosConfig, CosS3Client import ChatAdmin +import ChatMerge import simuse from ChatClass import Version def getcllist(): - filelist = os.listdir() + tagdict = ChatMerge.getconfig()[3] + filelist = os.listdir('WordStock') cllist = [] + Taglist = [] + for i in tagdict.values(): + Taglist.extend(i) + Taglist = list(set(Taglist)) for i in filelist: - if i[-3:] == '.cl' and i != 'Merge.cl': + if i[-3:] == '.cl' and i != 'Merge.cl' and not (i[:-3] in Taglist): #print(i) cllist.append(i) return cllist @@ -254,17 +260,17 @@ def uploadcos(data, filename): #删除词库 -def delcl(data, sender, lines_dict, nodelist,target_type=0,group=0): - if group!=0: - target=group +def delcl(data, sender, lines_dict, nodelist, target_type=0, group=0): + if group != 0: + target = group else: - target=sender + target = sender tipsmessagechain = [{'type': 'Forward', 'nodeList': nodelist}] simuse.Send_Message_Chain(data, target, target_type, tipsmessagechain) while 1: errorlines = 0 seerrorlines = 0 - command = ChatAdmin.get_admin_command(data, sender=sender,group=group) + command = ChatAdmin.get_admin_command(data, sender=sender, group=group) if command != None: if command == str(-1) or command == '–1': print('取消删除') @@ -320,11 +326,12 @@ def delcl(data, sender, lines_dict, nodelist,target_type=0,group=0): break elif errorlines != 0: print('行数错误,请重新输入\n最小行数为2') - simuse.Send_Message(data, target, target_type, '行数错误,请重新输入\n最小行数为2', 1) + simuse.Send_Message(data, target, target_type, + '行数错误,请重新输入\n最小行数为2', 1) elif errorlines == 0 and seerrorlines != 0: print('行数错误,请重新输入\n结束行应大于起始行') - simuse.Send_Message(data, target, target_type, '行数错误,请重新输入\n结束行应大于起始行', - 1) + simuse.Send_Message(data, target, target_type, + '行数错误,请重新输入\n结束行应大于起始行', 1) else: continue @@ -349,7 +356,8 @@ def delcl(data, sender, lines_dict, nodelist,target_type=0,group=0): delsign = 0 for group in changedict: - cldict_orign=pickle.load(open(str(group) + '.cl', 'rb')) + cldict_orign = pickle.load( + open('WordStock/' + str(group) + '.cl', 'rb')) cldict = copy.deepcopy(cldict_orign) questionlist = list(cldict_orign.keys()) changelist = changedict[group] @@ -369,10 +377,12 @@ def delcl(data, sender, lines_dict, nodelist,target_type=0,group=0): if answerlist == []: cldict.pop(question) cldict_orign = cldict - pickle.dump(cldict_orign,open(str(group) + '.cl', 'wb')) + pickle.dump(cldict_orign, open('WordStock/' + str(group) + '.cl', + 'wb')) if changedict != {} and nofoundlines == []: print('删除{}个条目成功'.format(delsign)) - simuse.Send_Message(data, target, target_type, '删除{}个条目成功'.format(delsign), 1) + simuse.Send_Message(data, target, target_type, + '删除{}个条目成功'.format(delsign), 1) elif nofoundlines != []: tips = '' for i in nofoundlines: @@ -382,15 +392,22 @@ def delcl(data, sender, lines_dict, nodelist,target_type=0,group=0): '删除{}个条目成功\n未找到行{}'.format(delsign, tips), 1) else: print('删除失败') - simuse.Send_Message(data, target, target_type, '删除失败'.format(delsign), 1) + simuse.Send_Message(data, target, target_type, '删除失败'.format(delsign), + 1) #查找问题 -def findallquestion(data, sender, cllist, question, allquestion=0,group=0,target_type=0): - if group!=0: - target=group +def findallquestion(data, + sender, + cllist, + question, + allquestion=0, + group=0, + target_type=0): + if group != 0: + target = group else: - target=sender + target = sender simuse.Send_Message(data, target, target_type, '查找中……', 1) #findquestion={'群号':'问题字典'} findquestion = {} @@ -403,7 +420,7 @@ def findallquestion(data, sender, cllist, question, allquestion=0,group=0,target findquestiondict = {} findquestion[i[:-3]] = findquestiondict try: - cldict=pickle.load(open(i, 'rb')) + cldict = pickle.load(open('WordStock/' + i, 'rb')) questionlist = list(cldict.keys()) except: print('该群无词库') @@ -504,12 +521,18 @@ def findallquestion(data, sender, cllist, question, allquestion=0,group=0,target os.remove(filename + '.xls') return None time.sleep(1) - delcl(data, sender, lines_dict, nodelist,target_type=target_type,group=group) + delcl(data, + sender, + lines_dict, + nodelist, + target_type=target_type, + group=group) return None time.sleep(1) - simuse.Send_Message(data, target, target_type, '请输入你的选择\n1.返回查找结果\n2.继续查找\n3.返回', 1) + simuse.Send_Message(data, target, target_type, + '请输入你的选择\n1.返回查找结果\n2.继续查找\n3.返回', 1) while 1: - command = ChatAdmin.get_admin_command(data, sender=sender,group=group) + command = ChatAdmin.get_admin_command(data, sender=sender, group=group) if command == str(1): try: nodelist = uploadcos(data, filename) @@ -519,7 +542,12 @@ def findallquestion(data, sender, cllist, question, allquestion=0,group=0,target os.remove(filename + '.xls') break time.sleep(1) - delcl(data, sender, lines_dict, nodelist,target_type=target_type,group=group) + delcl(data, + sender, + lines_dict, + nodelist, + target_type=target_type, + group=group) break elif command == str(2): os.remove(filename + '.xls') @@ -532,11 +560,11 @@ def findallquestion(data, sender, cllist, question, allquestion=0,group=0,target #查找答案 -def findallanswer(data, sender, cllist, answer,group=0,target_type=0): - if group!=0: - target=group +def findallanswer(data, sender, cllist, answer, group=0, target_type=0): + if group != 0: + target = group else: - target=sender + target = sender simuse.Send_Message(data, target, target_type, '查找中……', 1) findquestion = {} for i in answer: @@ -547,7 +575,7 @@ def findallanswer(data, sender, cllist, answer,group=0,target_type=0): for i in cllist: findquestiondict = {} findquestion[i[:-3]] = findquestiondict - cldict=pickle.load(open(i, 'rb')) + cldict = pickle.load(open('WordStock/' + i, 'rb')) for l in answer: for k in cldict: questiondict = cldict[k] @@ -594,9 +622,10 @@ def findallanswer(data, sender, cllist, answer,group=0,target_type=0): filename = filename_lines_dict[0] lines_dict = filename_lines_dict[1] time.sleep(1) - simuse.Send_Message(data, target, target_type, '请输入你的选择\n1.返回查找结果\n2.继续查找\n3.返回', 1) + simuse.Send_Message(data, target, target_type, + '请输入你的选择\n1.返回查找结果\n2.继续查找\n3.返回', 1) while 1: - command = ChatAdmin.get_admin_command(data, sender=sender,group=group) + command = ChatAdmin.get_admin_command(data, sender=sender, group=group) if command == str(1): try: nodelist = uploadcos(data, filename) @@ -606,7 +635,12 @@ def findallanswer(data, sender, cllist, answer,group=0,target_type=0): os.remove(filename + '.xls') break time.sleep(1) - delcl(data, sender, lines_dict, nodelist,target_type=target_type,group=group) + delcl(data, + sender, + lines_dict, + nodelist, + target_type=target_type, + group=group) break elif command == str(2): os.remove(filename + '.xls') @@ -618,34 +652,44 @@ def findallanswer(data, sender, cllist, answer,group=0,target_type=0): continue -def findallcontrol(data, sender,group=0): - if group==0: +def findallcontrol(data, sender, group=0): + if group == 0: cllist = getcllist() - target=sender - target_type=2 + target = sender + target_type = 2 else: - cllist=[str(group)+'.cl'] - target=group - target_type=1 + cllist = [str(group) + '.cl'] + target = group + target_type = 1 while 1: time.sleep(1) - if group==0: + if group == 0: tips = '请选择你的操作\n1.查找问题\n2.查找答案\n3.查看某个群的所有词库\n4.退出管理模式' else: - tips='进入管理模式\n请选择你的操作\n1.查找问题\n2.查找答案\n3.查看所有词库\n4.退出管理模式' + tips = '进入管理模式\n请选择你的操作\n1.查找问题\n2.查找答案\n3.查看所有词库\n4.退出管理模式' simuse.Send_Message(data, target, target_type, tips, 1) while 1: - command = ChatAdmin.get_admin_command(data, sender=sender,group=group) + command = ChatAdmin.get_admin_command(data, + sender=sender, + group=group) if command != None: break if command == str(1): simuse.Send_Message(data, target, target_type, '请发送关键字', 1) while 1: time.sleep(0.5) - question = ChatAdmin.get_admin_question(data, sender=sender,group=group) + question = ChatAdmin.get_admin_question(data, + sender=sender, + group=group) if question != None: - if findallquestion(data, sender, cllist, question,group=group,target_type=target_type) == 2: - simuse.Send_Message(data, target, target_type, '请发送关键字', 1) + if findallquestion(data, + sender, + cllist, + question, + group=group, + target_type=target_type) == 2: + simuse.Send_Message(data, target, target_type, + '请发送关键字', 1) continue else: break @@ -653,18 +697,22 @@ def findallcontrol(data, sender,group=0): simuse.Send_Message(data, target, target_type, '请发送关键字', 1) while 1: time.sleep(0.5) - question = ChatAdmin.get_admin_question(data, sender=sender,group=group) + question = ChatAdmin.get_admin_question(data, + sender=sender, + group=group) if question != None: - if findallanswer(data, sender, cllist, question,group,target_type) == 2: - simuse.Send_Message(data, target, target_type, '请发送关键字', 1) + if findallanswer(data, sender, cllist, question, group, + target_type) == 2: + simuse.Send_Message(data, target, target_type, + '请发送关键字', 1) continue else: break - elif command == str(3) and group==0: + elif command == str(3) and group == 0: grouplist = [] for i in cllist: - grouplist.append(int(i[:-3])) + grouplist.append(i[:-3]) simuse.Send_Message(data, sender, 2, '以下是拥有词库的群\n' + str(grouplist) + '\n请发送群号', 1) while 1: @@ -672,7 +720,7 @@ def findallcontrol(data, sender,group=0): choicegroup = ChatAdmin.get_admin_command(data, sender=sender) if choicegroup != None: try: - choicegroup = int(choicegroup) + choicegroup = str(choicegroup) except: simuse.Send_Message(data, sender, 2, '参数错误', 1) break @@ -686,12 +734,23 @@ def findallcontrol(data, sender,group=0): 'type': 'Plain', 'text': 'AllFind' }], - allquestion=1,group=group,target_type=target_type) + allquestion=1, + group=group, + target_type=target_type) break else: simuse.Send_Message(data, sender, 2, '群不存在', 1) break - elif command==str(3) and group!=0: - findallquestion(data,sender,cllist,question=[{'type': 'Plain','text': 'AllFind'}],allquestion=1,group=group,target_type=target_type) + elif command == str(3) and group != 0: + findallquestion(data, + sender, + cllist, + question=[{ + 'type': 'Plain', + 'text': 'AllFind' + }], + allquestion=1, + group=group, + target_type=target_type) else: return None diff --git a/ChatCheck.py b/ChatCheck.py index c22a7a5..317d824 100644 --- a/ChatCheck.py +++ b/ChatCheck.py @@ -1,6 +1,6 @@ -import pickle import json import os +import pickle import time from wsgiref.simple_server import server_version @@ -28,16 +28,16 @@ def checkversion(): now_version = int(Version().replace('.', '')) server_version = int(res['version'].replace('.', '')) if server_version > now_version: - return 1,res['version'],Version() + return 1, res['version'], Version() else: - return 0,Version() + return 0, Version() def clcheck(filename, data, fromchat): question_num = 0 answer_num = 0 allanswerlist = [] - cldict=pickle.load(open(filename, 'rb')) + cldict = pickle.load(open('WordStock/' + filename, 'rb')) for i in cldict: question_num += 1 questioninfo = cldict[i] @@ -48,8 +48,14 @@ def clcheck(filename, data, fromchat): answer_num += 1 except: pass + config = getallconfig() + Tagdict = config['tag'] group = filename[:-3] - print('群', group, '收集到问题', question_num, '个', ' 答案', answer_num, '个') + try: + print('词库', group, '收集到问题', question_num, '个', ' 答案', answer_num, '个', + 'Tag:{}'.format(' '.join(Tagdict[group]))) + except: + print('词库', group, '收集到问题', question_num, '个', ' 答案', answer_num, '个') if fromchat != 0: nodedict = { 'senderId': data['qq'], @@ -62,15 +68,21 @@ def clcheck(filename, data, fromchat): } messagechain = nodedict['messageChain'] messagedict = messagechain[0] - messagedict['text'] = '群' + str(group) + '收集到问题' + str( - question_num) + '个' + ' 答案' + str(answer_num) + '个' + try: + messagedict['text'] = '词库' + str(group) + '收集到问题' + str( + question_num) + '个' + ' 答案' + str( + answer_num) + '个' + '\nTag:{}'.format(' '.join( + Tagdict[group])) + except: + messagedict['text'] = '词库' + str(group) + '收集到问题' + str( + question_num) + '个' + ' 答案' + str(answer_num) + '个' return nodedict #simuse.Send_Message(data, fromchat, 2, '群'+str(group)+'收集到问题'+str(question_num)+'个'+' 答案'+str(answer_num)+'个', 1) #time.sleep(1) def main(data, fromchat): - filelist = os.listdir() + filelist = os.listdir('WordStock') cllist = [] nodelist = [] for i in filelist: @@ -114,15 +126,39 @@ def main(data, fromchat): mergetimetip = '总词库合成间隔:{}秒'.format(config['mergetime']) intervaltip = '词库链间隔:{}秒'.format(config['interval']) blackfreqtip = '黑名单容错次数:{}次'.format(config['blackfreq']) + typefreqtip = '回复阈值设定:\n' + singlereplytip = '指定群回复触发概率:\n' + singlevoicereplytip = '指定群回复概率(语音):\n' + typefreqdict = config['typefreq'] + replydict = config['singlereplychance'] + voicereplydict = config['singlevoicereplychance'] + if replydict == {}: + singlereplytip = '' + if voicereplydict == {}: + singlevoicereplytip = '' + if typefreqdict == {}: + typefreqtip = '' + for i in typefreqdict: + typefreqtip = typefreqtip + '{}:{}次\n'.format(i, typefreqdict[i]) + for i in replydict: + singlereplytip = singlereplytip + '群{}:{}%\n'.format(i, replydict[i]) + for i in voicereplydict: + singlevoicereplytip = singlevoicereplytip + '群{}:{}%\n'.format( + i, voicereplydict[i]) check_version = checkversion() if check_version[0] == 1: - versiontip = "已连接至ChatLearning服务器\n检测到有新版本:{}\n当前版本:{}".format(check_version[1],check_version[2]) + versiontip = "已连接至ChatLearning服务器\n检测到有新版本:{}\n当前版本:{}".format( + check_version[1], check_version[2]) elif check_version[0] == 0: - versiontip = "已连接至ChatLearning服务器\n当前已是最新版本:{}".format(check_version[1]) + versiontip = "已连接至ChatLearning服务器\n当前已是最新版本:{}".format( + check_version[1]) else: versiontip = "未连接至ChatLearning服务器" - situation = learningtip + '\n' + replytip + '\n' + voicereplytip + '\n' + golbetip + '\n' + replychancetip + '\n' + voicereplychancetip + '\n' + synthesizertip + '\n' + mergetimetip + '\n' + intervaltip + '\n' + blackfreqtip + situation = learningtip + '\n' + replytip + '\n' + voicereplytip + '\n' + golbetip + '\n' + replychancetip + '\n' + voicereplychancetip + '\n' + synthesizertip + '\n' + mergetimetip + '\n' + intervaltip + '\n' + blackfreqtip situationchain = [{'type': 'Plain', 'text': situation}] + typefreq_message = [{'type': 'Plain', 'text': typefreqtip}] + siglereply_message = [{'type': 'Plain', 'text': singlereplytip}] + singlevoicereply_message = [{'type': 'Plain', 'text': singlevoicereplytip}] version_message = [{'type': 'Plain', 'text': versiontip}] situationnodedict = { 'senderId': data['qq'], @@ -135,14 +171,22 @@ def main(data, fromchat): } situationnodedict['messageChain'] = situationchain nodelist.append(situationnodedict.copy()) - situationnodedict['messageChain']=version_message + situationnodedict['messageChain'] = typefreq_message + nodelist.append(situationnodedict.copy()) + situationnodedict['messageChain'] = siglereply_message + nodelist.append(situationnodedict.copy()) + situationnodedict['messageChain'] = singlevoicereply_message + nodelist.append(situationnodedict.copy()) + situationnodedict['messageChain'] = version_message 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) - print(situation,'\n'+versiontip) + print( + situation, '\n' + typefreqtip + '\n' + singlereplytip + '\n' + + singlevoicereplytip + '\n' + versiontip) return None #os.system('pause') diff --git a/ChatClass.py b/ChatClass.py index 392ab59..5f65f6e 100644 --- a/ChatClass.py +++ b/ChatClass.py @@ -1,12 +1,14 @@ +import os import pickle import re +import shutil import threading import time import traceback -import os + import simuse -version = '2.7.1' +version = '2.8.0' # 控制台指令类 @@ -18,17 +20,24 @@ class commandclass(): commandtips['voicereply'] = '#开启/关闭文字转语音回复' commandtips['learning <秒>'] = '#设定词库链间隔时间' commandtips['reply <%>'] = '#设定回复的触发几率' + commandtips['reply -s <%> <群号>'] = '#单独设定回复触发几率' + commandtips['reply -d <群号>'] = '#清除单独设定的回复触发几率' commandtips['voicereply <%>'] = '#设定文字转语音回复几率' + commandtips['voicereply -s <%> <群号>'] = '#单独设定文字转语音触发几率' + commandtips['voicereply -d <群号>'] = '#清除单独设定的文字转语音触发几率' commandtips['merge <秒>'] = '#设定总词库更新时间' + commandtips['typefreq <消息类型> <次数>'] = '#设定消息发送阈值' commandtips['add learning <群号>'] = '#添加开启记录的群' commandtips['add learnings <群号>'] = '#同时添加开启记录和回复的群' commandtips['add reply <群号>'] = '#添加开启回复的群' commandtips['add subadmin <群号>'] = '#添加可自行管理的群' commandtips['add unmerge <群号>'] = '#添加不录入总词库的群' + commandtips['add tag <标签> <群号>'] = '#添加群标签' commandtips['remove learning <群号>'] = '#移除开启记录的群' commandtips['remove reply <群号>'] = '#移除开启回复的群' commandtips['remove subadmin <群号>'] = '#移除可自行管理的群' commandtips['remove unmerge <群号>'] = '#移除不录入总词库的群' + commandtips['remove tag <群号>'] = '#移除群标签' commandtips['check'] = '#查看设置情况' commandtips['grouplist'] = '#查看开启记录/回复的群列表' commandtips['globe'] = '#开启/关闭全局模式' @@ -98,8 +107,8 @@ def commandhelp(self, fromchat): # 多线程类的复写 class My_Thread(threading.Thread): - daemon=True - + daemon = True + def run(self): # 常驻为守护线程 try: @@ -117,14 +126,19 @@ def run(self): finally: del self._target, self._args, self._kwargs + # 返回版本号 def Version(): global version return version + # 2.7.0前版本更新需要更换词库的缓存形式 def ClChange(): - filelist = os.listdir() # 获取词库列表 + try: + filelist = os.listdir('WordStock') # 获取词库列表 + except: + filelist = os.listdir() # 获取词库列表 cllist = [] for i in filelist: if i[-3:] == '.cl': @@ -134,10 +148,50 @@ def ClChange(): print('正在为更新做一些准备,请稍等') print('期间请勿关闭程序,否则将导致数据丢失!') for i in cllist: - file=open(i,'r',encoding='utf-8-sig') - dicts=file.read() - dicts=eval(dicts) + file = open(i, 'r', encoding='utf-8-sig') + dicts = file.read() + dicts = eval(dicts) file.close() - pickle.dump(dicts,open(i,'wb')) + pickle.dump(dicts, open(i, 'wb')) print('准备完毕!') + +def Cl_version(version): + version = int(version.replace('.', '')) + try: + filelist = os.listdir('WordStock') # 获取词库列表 + except: + filelist = os.listdir() + cllist = [] + if not (os.path.exists('WordStock')): + os.mkdir('WordStock') + for i in filelist: + if i[-3:] == '.cl': + #print(i) + cllist.append(i) + #print(cllist) + # 2.8.0前版本更新需要为词库Key添加"freq"次数键 + if version < 280: + print('正在更新词库版本,{} -> 280 请勿中途退出'.format(version)) + for i in cllist: + dicts = pickle.load(open(i, 'rb')) + for k in dicts.keys(): + questiondict = dicts[k] + if not ('freq' in questiondict.keys()): + questiondict['freq'] = 1 + pickle.dump(dicts, open(i, 'wb')) + shutil.move(i, 'WordStock/' + i) + + +def Config_version(version): + version = int(version.replace('.', '')) + file = open('config.clc', 'r', encoding='utf-8-sig') + config = eval(file.read()) + file.close() + if version < 280: + print('正在更新config, -> 280 请勿中途退出') + config['tag'] = {} + config['singlereplychance'] = {} + config['singlevoicereplychance'] = {} + config['typefreq'] = {} + return config diff --git a/ChatDelete.py b/ChatDelete.py new file mode 100644 index 0000000..fea1f92 --- /dev/null +++ b/ChatDelete.py @@ -0,0 +1,129 @@ +import copy +import os +import pickle +import time + +import ChatFilter +import ChatMerge +import simuse + + +def Delete(data, sender): + simuse.Send_Message(data, sender, 2, '清理中……', 1) + tagdict = ChatMerge.getconfig()[3] + Taglist = [] + for i in tagdict.values(): + Taglist.extend(i) + Taglist = list(set(Taglist)) + filelist = os.listdir('WordStock') + cllist = [] + for i in filelist: + if i[-3:] == '.cl': + #print(i) + cllist.append(i) + #print(cllist) + Mergedict = {} + for i in cllist: + if Mergedict == None: + print('清理失败') + simuse.Send_Message(data, sender, 2, '清理失败,存在不同版本的词库', 1) + time.sleep(0.8) + return None + if i == 'Merge.cl': + continue + elif i[:-3] in Taglist: + continue + Mergedict = Merge(Mergedict, i) + + deltipdict = {} + + for i in cllist: + delnumlist = [] + if i == 'Merge.cl': + continue + elif i[:-3] in Taglist: + continue + delnumlist.append(Delete_freq(Mergedict, i)) + delnumlist.append(Delete_Filter(i)) + deltipdict[i] = delnumlist + tips = '' + for i in deltipdict: + tiplist = deltipdict[i] + if tiplist[0] != 0 and tiplist[1] != 0: + tips = tips + '已清理{}低频条目{}个,过滤条目{}个\n'.format( + i, tiplist[0], tiplist[1]) + elif tiplist[0] != 0 and tiplist[1] == 0: + tips = tips + '已清理{}低频条目{}个\n'.format(i, tiplist[0]) + elif tiplist[0] == 0 and tiplist[1] != 0: + tips = tips + '已清理{}过滤条目{}个\n'.format(i, tiplist[1]) + if tips != '': + print(tips) + simuse.Send_Message(data, sender, 2, tips, 1) + else: + print('无需清理') + simuse.Send_Message(data, sender, 2, '无需清理', 1) + time.sleep(0.8) + + +def Merge(Mergedict, filename): + version_error = 0 + cldict = pickle.load(open('WordStock/' + filename, 'rb')) + #print(Mergedict) + try: + repeatquestion = Mergedict.keys() & cldict.keys() + for i in repeatquestion: + tempquestiondict = cldict[i] + newquestiondict = Mergedict[i] + try: + newquestiondict['freq'] += tempquestiondict['freq'] + except: + version_error = 1 + #print(newanswer) + newanswer = newquestiondict['answer'] + tempanswer = tempquestiondict['answer'] + newanswer.extend(tempanswer) + del cldict[i] + #print('相同问题已合并') + except: + pass + Mergedict.update(cldict) + if version_error == 1: + print('问题次数无法合并,请确认是否存在2.8.0版本以下的词库? 错误词库:{}'.format(filename)) + return None + return Mergedict + + +def Delete_freq(Mergedict, filename): + cldict = pickle.load(open('WordStock/' + filename, 'rb')) + freqdel_num = 0 + for question in Mergedict: + questiondict = Mergedict[question] + if questiondict['freq'] < 2: + try: + cldict.pop(question) + freqdel_num += 1 + except: + continue + pickle.dump(cldict, open('WordStock/' + filename, 'wb')) + return freqdel_num + + +def Delete_Filter(filename): + cldict = pickle.load(open('WordStock/' + filename, 'rb')) + question_list = list(cldict.keys()) + filterdel_num = 0 + for question in question_list: + if ChatFilter.filtercheck(eval(question), display=False) == 0: + cldict.pop(question) + filterdel_num += 1 + for question in cldict: + questiondict = cldict[question] + answerlist_origin = questiondict['answer'] + answerlist = copy.deepcopy(questiondict['answer']) + for answerdict in answerlist: + answertext = answerdict['answertext'] + if ChatFilter.filtercheck(eval(answertext), display=False) == 0: + answerlist_origin.remove(answerdict) + filterdel_num += 1 + pickle.dump(cldict, open('WordStock/' + filename, 'wb')) + return filterdel_num diff --git a/ChatFilter.py b/ChatFilter.py index 3a1455d..ad59d80 100644 --- a/ChatFilter.py +++ b/ChatFilter.py @@ -1,4 +1,5 @@ import copy +import os import time import ChatAdmin @@ -287,7 +288,7 @@ def blackcheck(): return Filterconfig -def sensitivecheck(question, sender,group): +def sensitivecheck(question, sender, group): for i in question: try: i.pop('url') @@ -297,7 +298,8 @@ def sensitivecheck(question, sender,group): if str(question) in Filterconfig['sensitive']: creatblack(sender) - print('已过滤,原因:与敏感问题匹配,已将发送者加入黑名单','发送者{}'.format(sender),'来自群{}'.format(group)) + print('已过滤,原因:与敏感问题匹配,已将发送者加入黑名单', '发送者{}'.format(sender), + '来自群{}'.format(group)) return 0 else: for i in question: @@ -308,19 +310,22 @@ def sensitivecheck(question, sender,group): if j['type'] == 'Plain': if i['text'].find(j['text']) != -1: creatblack(sender) - print('已过滤,原因:与敏感问题匹配,已将发送者加入黑名单','发送者{}'.format(sender),'来自群{}'.format(group)) + 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)) + print('该用户在黑名单中超出最大次数,已屏蔽', '发送者{}'.format(sender), + '来自群{}'.format(group)) return 0 return 1 -def filtercheck(question,sender,group): - command=['!learning','learning','!reply','reply','!admin','admin'] - text='' +def filtercheck(question, sender='|回复过滤', group='|回复过滤', display=True): + command = ['!learning', 'learning', '!reply', 'reply', '!admin', 'admin'] + text = '' for i in question: # 去除作为问题中的变动因素“url” try: i.pop('url') @@ -330,24 +335,33 @@ def filtercheck(question,sender,group): #print(question) for i in question: if i['type'] == 'Plain': - text=i['text'] + text = i['text'] for k in Filterconfig['filter']: k = eval(k) for j in k: if j['type'] == 'Plain': if i['text'].find(j['text']) != -1: - print('已过滤,原因:与过滤名单模糊匹配','发送者{}'.format(sender),'来自群{}'.format(group)) + if display == True: + print('已过滤,原因:与过滤名单模糊匹配', + '发送者{}'.format(sender), + '来自群{}'.format(group)) return 0 if str(question) in Filterconfig['filter']: - print('已过滤,原因:与过滤名单匹配','发送者{}'.format(sender),'来自群{}'.format(group)) + if display == True: + print('已过滤,原因:与过滤名单匹配', '发送者{}'.format(sender), + '来自群{}'.format(group)) return 0 elif text in command: - print('已过滤,原因:与指令匹配','发送者{}'.format(sender),'来自群{}'.format(group)) + if display == True: + print('已过滤,原因:与指令匹配', '发送者{}'.format(sender), + '来自群{}'.format(group)) return 0 else: for i in question: if i['type'] in Filterconfig['type']: - print('已过滤,原因:与过滤名单中消息类型匹配','发送者{}'.format(sender),'来自群{}'.format(group)) + if display == True: + print('已过滤,原因:与过滤名单中消息类型匹配', '发送者{}'.format(sender), + '来自群{}'.format(group)) return 0 return 1 @@ -504,3 +518,37 @@ def filtercontrol(data, sender): 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, '合并错误') + FilterConfig = blackcheck() + Filterlist_origin = FilterConfig['filter'] + Filterlist_origin.extend(Filterconfiglist) + Filterlist_origin = list(set(Filterlist_origin)) + FilterConfig['filter'] = Filterlist_origin + file = open('Filter.clc', 'w', encoding='utf-8-sig') + file.write(str(FilterConfig)) + file.close() + if Filterlist != []: + print('合并完成') diff --git a/ChatLearning.py b/ChatLearning.py index 24439b8..a26c2ba 100644 --- a/ChatLearning.py +++ b/ChatLearning.py @@ -2,9 +2,9 @@ import copy import pickle import time -import ChatFilter from re import I +import ChatFilter import simuse @@ -31,25 +31,29 @@ def creatquestion(question, group): # 记录问题 except: continue - - question = str(question) filename = str(group) + ".cl" try: # 读取已缓存的词库 - tempdict=pickle.load(open(filename, 'rb')) + tempdict = pickle.load(open('WordStock/' + filename, 'rb')) except: tempdict = {} if not (question in tempdict.keys()): # 判断词库中问题是否存在,若不存在则记录问题 questiondict = {} questiontime = int(time.time()) answerlist = [] + questiondict["freq"] = 1 questiondict["time"] = questiontime questiondict["answer"] = answerlist tempdict[question] = questiondict print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "\n问题已记录", filename) + else: + questiondict = tempdict[question] + questiondict["freq"] += 1 + print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), + "\n相同问题 已记录重复", filename) #print(tempdict) - pickle.dump(tempdict,open(filename, 'wb')) + pickle.dump(tempdict, open('WordStock/' + filename, 'wb')) return tempquestion # 返回未去除“url”的消息链,为记录答案做准备 @@ -64,7 +68,7 @@ def creatanswer(question, answer, group): # 记录答案 question = str(question) answer = str(answer) filename = str(group) + ".cl" - tempdict=pickle.load(open(filename, 'rb')) # 读取缓存的词库 + tempdict = pickle.load(open('WordStock/' + filename, 'rb')) # 读取缓存的词库 answertime = int(time.time()) answerdict = {"answertext": "", "time": ""} answerdict["answertext"] = answer @@ -108,7 +112,7 @@ def creatanswer(question, answer, group): # 记录答案 else: # 答案列表为空时一定是新答案,所以直接记录 questiondict["answer"].append(answerdict.copy()) tempdict[question] = questiondict - pickle.dump(tempdict,open(filename, 'wb')) + pickle.dump(tempdict, open('WordStock/' + filename, 'wb')) print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "\n答案已记录", filename) @@ -124,11 +128,13 @@ def extractmessage(data, tempdict): # 将消息链转化为字典格式(key continue except: pass - checkmessage=copy.deepcopy(i['messagechain']) + checkmessage = copy.deepcopy(i['messagechain']) checkmessage.pop(0) - if ChatFilter.sensitivecheck(checkmessage,i['sender'],i['group'])==0: + if ChatFilter.sensitivecheck(checkmessage, i['sender'], + i['group']) == 0: continue - elif ChatFilter.filtercheck(checkmessage,i['sender'],i['group'])==0: + elif ChatFilter.filtercheck(checkmessage, i['sender'], + i['group']) == 0: continue if i['group'] in tempdict.keys(): diff --git a/ChatMerge.py b/ChatMerge.py index bfd8829..ebfe524 100644 --- a/ChatMerge.py +++ b/ChatMerge.py @@ -3,27 +3,38 @@ import time + + def getconfig(): file = open('config.clc', 'r', encoding='utf-8-sig') config = file.read() file.close() config = eval(config) #print(config) - return config['merge'], config['mergetime'], config['unmergegrouplist'] + try: + return config['merge'], config['mergetime'], config[ + 'unmergegrouplist'], config['tag'] + except: + return config['merge'], config['mergetime'], config['unmergegrouplist'] def Merge(Mergedict, filename): + version_error = 0 repeatquestion_num = 0 - cldict=pickle.load(open(filename, 'rb')) + cldict = pickle.load(open('WordStock/' + filename, 'rb')) #print(Mergedict) try: repeatquestion = Mergedict.keys() & cldict.keys() for i in repeatquestion: - tempanswer = cldict[i] - newanswer = Mergedict[i] + tempquestiondict = cldict[i] + newquestiondict = Mergedict[i] + try: + newquestiondict['freq'] += tempquestiondict['freq'] + except: + version_error = 1 #print(newanswer) - newanswer = newanswer['answer'] - tempanswer = tempanswer['answer'] + newanswer = newquestiondict['answer'] + tempanswer = tempquestiondict['answer'] newanswer.extend(tempanswer) del cldict[i] repeatquestion_num += 1 @@ -33,11 +44,18 @@ def Merge(Mergedict, filename): Mergedict.update(cldict) if repeatquestion_num != 0: print('已合并', filename, repeatquestion_num, '个相同问题') + if version_error == 1: + print('问题次数无法合并,请确认是否存在2.8.0版本以下的词库? 错误词库:{}'.format(filename)) return Mergedict def getfile(): - filelist = os.listdir() + tagdict = getconfig()[3] + Taglist = [] + for i in tagdict.values(): + Taglist.extend(i) + Taglist = list(set(Taglist)) + filelist = os.listdir('WordStock') cllist = [] for i in filelist: if i[-3:] == '.cl': @@ -48,13 +66,26 @@ def getfile(): for i in cllist: if i == 'Merge.cl': continue + elif i[:-3] in Taglist: + continue try: - if int(i[:-3]) in getconfig()[2]: + if i[:-3] in str(getconfig()[2]): continue except: pass - Mergedict = Merge(Mergedict, i) - pickle.dump(Mergedict,open('Merge.cl', 'wb')) + if not (i[:-3] in tagdict.keys()): + Mergedict = Merge(Mergedict, i) + pickle.dump(Mergedict, open('WordStock/' + 'Merge.cl', 'wb')) + for i in Taglist: + print('Tag:{} 合并'.format(i)) + Mergedict_Tag = {} + for k in cllist: + if k[:-3] in str(tagdict.keys()): + if i in tagdict[k[:-3]]: + Mergedict_Tag = Merge(Mergedict_Tag, k) + pickle.dump(Mergedict_Tag, open('WordStock/' + '{}.cl'.format(i), + 'wb')) + print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), '词库合并完成') #print('->',end='') #os.system('pause') diff --git a/ChatReply.py b/ChatReply.py index ed7e0f8..0d173a3 100644 --- a/ChatReply.py +++ b/ChatReply.py @@ -1,109 +1,143 @@ # Demo阶段 -import os +import copy +import json import pickle import random import time -import simuse +import traceback + import requests -import json -nowtime=time.time() -def talkvoice(data,group,messagechain): +import ChatFilter +import simuse + +nowtime = time.time() + + +def DelType(tempdict, answerlist): + freqdict = getconfig(10) + num = 0 + deltype = '' + new_answerlist = copy.deepcopy(answerlist) + for answerdict in answerlist: + answertext = eval(answerdict['answertext']) + for i in answertext: + try: + i.pop('url') + except: + pass + try: + questiondict = tempdict[str(answertext)] + except: + new_answerlist.remove(answerdict) + continue + try: + if questiondict['freq'] < freqdict[i['type']]: + new_answerlist.remove(answerdict) + num += 1 + deltype = deltype + i['type'] + ' ' + continue + except: + continue + if num != 0: + print('已过滤{}个不符合发送要求的{}'.format(num, deltype)) + return new_answerlist + + +def talkvoice(data, group, messagechain): global nowtime try: - atmessage=messagechain[0] + atmessage = messagechain[0] except: print('转换语音失败') return None - if atmessage['type']=='At' and str(atmessage['target'])==data['qq']: + if atmessage['type'] == 'At' and str(atmessage['target']) == data['qq']: try: - textmessage=messagechain[1] - text=textmessage['text'] + textmessage = messagechain[1] + text = textmessage['text'] try: - text=text.strip(' ') + text = text.strip(' ') except: pass - if text[:3]=='快说 ': - text=text[3:] - if len(text)>50: + if text[:3] == '快说 ': + text = text[3:] + if len(text) > 50: print('超过长度限制') - simuse.Send_Message(data,group,1,'超过长度限制',1) - return None + simuse.Send_Message(data, group, 1, '超过长度限制', 1) + return None if canToVoice(text): try: - if CanSendTask(nowtime,10): - answer_message=Plain_Voice(data,text) - if answer_message==None: + if CanSendTask(nowtime, 10): + answer_message = Plain_Voice(data, text) + if answer_message == None: print('转换语音失败') return None - simuse.Send_Message_Chain(data,group,1,answer_message) - nowtime=time.time() + simuse.Send_Message_Chain(data, group, 1, + answer_message) + nowtime = time.time() return 1 else: print('转换冷却中') - simuse.Send_Message(data,group,1,'能不能让我休息下喝口水再说啊?',1) + simuse.Send_Message(data, group, 1, + '能不能让我休息下喝口水再说啊?', 1) return 1 except: print('转换语音失败') return None else: print('存在违规字符,转换失败') - simuse.Send_Message(data,group,1,'存在违规字符,转换失败',1) + simuse.Send_Message(data, group, 1, '存在违规字符,转换失败', 1) return None except: return None - - - - - def canToVoice(text): - usualchar=[',',',','.','。','!','!','?','?',' '] - chinesehave=0 - anotherchar=0 + usualchar = [',', ',', '.', '。', '!', '!', '?', '?', ' '] + chinesehave = 0 + anotherchar = 0 for i in text: - if '\u4e00'<=i<='\u9fa5': - chinesehave=1 + if '\u4e00' <= i <= '\u9fa5': + chinesehave = 1 else: - if not(i in usualchar): - anotherchar=1 - if chinesehave==1 and anotherchar==0: - cansign=1 + if not (i in usualchar): + anotherchar = 1 + if chinesehave == 1 and anotherchar == 0: + cansign = 1 else: - cansign=0 + cansign = 0 return cansign -def CanSendTask(nowtime,cd): - if time.time()-nowtime>=cd: + +def CanSendTask(nowtime, cd): + if time.time() - nowtime >= cd: return 1 else: return 0 -def Plain_Voice(data,text): - url='http://124.222.165.166:19630/ToVoice' - data_in={'text':text,'QQ':data['qq'],'synthesizer':getconfig(7)} +def Plain_Voice(data, text): + url = 'http://124.222.165.166:19630/ToVoice' + data_in = {'text': text, 'QQ': data['qq'], 'synthesizer': getconfig(7)} try: - res=requests.request('post',url,json=data_in) - res=json.loads(res.text) + res = requests.request('post', url, json=data_in) + res = json.loads(res.text) except: return None - if res['code']==0: + if res['code'] == 0: return None - base64_data=res['base64'] - messagechain=[{'type':'Voice','base64':base64_data}] + base64_data = res['base64'] + messagechain = [{'type': 'Voice', 'base64': base64_data}] return messagechain def runchance(replychance): - ranom_num=random.uniform(0,1) - replychance=replychance*0.01 - if ranom_num<=replychance: - chance=1 + ranom_num = random.uniform(0, 1) + replychance = replychance * 0.01 + if ranom_num <= replychance: + chance = 1 else: - chance=0 + chance = 0 return chance @@ -125,15 +159,27 @@ def getconfig(choice): elif choice == 4: replychance = config['replychance'] return replychance - elif choice==5: - voicereply=config['voicereply'] + elif choice == 5: + voicereply = config['voicereply'] return voicereply - elif choice==6: - voicereplychance=config['voicereplychance'] + elif choice == 6: + voicereplychance = config['voicereplychance'] return voicereplychance - elif choice==7: - synthesizer_name=config['synthesizer'] + elif choice == 7: + synthesizer_name = config['synthesizer'] return synthesizer_name + elif choice == 8: + Tagdict = config['tag'] + return Tagdict + elif choice == 9: + replydict = config['singlereplychance'] + return replydict + elif choice == 10: + imagefreq = config['typefreq'] + return imagefreq + elif choice == 11: + voicereplydict = config['singlevoicereplychance'] + return voicereplydict def getanswer(group, question): # 从词库中获取答案 @@ -143,28 +189,58 @@ def getanswer(group, question): # 从词库中获取答案 except: continue if getconfig(2) == 1: - group = 'Merge' + Tagdict = getconfig(8) + if str(group) in Tagdict.keys(): + group = Tagdict[str(group)] + else: + group = 'Merge' question = str(question) - filename = str(group) + '.cl' # 读取已缓存的词库 - try: - tempdict=pickle.load(open(filename, 'rb')) - except: - return None - try: # 检索问题,若词库中无该问题,则函数返回-1,若有,则返回所有答案(答案列表) - #print(question) - questiondict = tempdict[question] - answerlist = questiondict['answer'] - except: - return -1 + if type(group) == type([]): + answerlist = [] + for i in group: + filename = str(i) + '.cl' # 读取已缓存的词库 + try: + tempdict = pickle.load(open('WordStock/' + filename, 'rb')) + except: + return None + try: # 检索问题,若词库中无该问题,则函数返回-1,若有,则返回所有答案(答案列表) + #print(question) + questiondict = tempdict[question] + answerlist.extend( + copy.deepcopy(DelType(tempdict, questiondict['answer']))) + except: + continue + + else: + filename = str(group) + '.cl' # 读取已缓存的词库 + try: + tempdict = pickle.load(open('WordStock/' + filename, 'rb')) + except: + return None + try: # 检索问题,若词库中无该问题,则函数返回-1,若有,则返回所有答案(答案列表) + #print(question) + questiondict = tempdict[question] + answerlist = DelType(tempdict, questiondict['answer']) + except: + return -1 + #print(answerlist) + if answerlist == []: + return -1 return answerlist def replyanswer(data, group, answer): # 发送答案 global nowtime - if runchance(getconfig(4)) == 0: + replydict = getconfig(9) + if str(group) in replydict.keys(): + if runchance(replydict[str(group)]) == 0: + print('已获取答案,但不发送') + return None + elif runchance(getconfig(4)) == 0: print('已获取答案,但不发送') return None + try: answer = random.choice(answer) # 尝试从答案列表中随机抽取一个答案,若答案列表为空,则不回复 answer = answer['answertext'] @@ -172,7 +248,6 @@ def replyanswer(data, group, answer): # 发送答案 print('无答案,不给予回复') #print('->',end='') return None - print(answer, end='') try: answer = eval(answer) except: @@ -185,36 +260,46 @@ def replyanswer(data, group, answer): # 发送答案 continue #print(answer) #Voice Test - voicereplysign=0 - if getconfig(5)==1 and runchance(getconfig(6))==1: + voicereplysign = 0 + chance_True = 0 + if ChatFilter.filtercheck(copy.deepcopy(answer)) == 0: + return None + print(answer, end='') + if getconfig(5) == 1: + voicereplydict = getconfig(11) + if str(group) in voicereplydict.keys(): + if runchance(voicereplydict[str(group)]) == 1: + chance_True = 1 + elif runchance(getconfig(6)) == 1: + chance_True = 1 + if chance_True == 1: for i in answer: - if i['type']=='Plain': + if i['type'] == 'Plain': if canToVoice(i['text']): - if len(i['text'])>55: + if len(i['text']) > 55: break try: - if CanSendTask(nowtime,10): - answer_new_message=Plain_Voice(data,i['text']) - if answer_new_message==None: + if CanSendTask(nowtime, 10): + answer_new_message = Plain_Voice(data, i['text']) + if answer_new_message == None: print('转换语音失败') break - answer=answer_new_message - voicereplysign=1 - nowtime=time.time() + answer = answer_new_message + voicereplysign = 1 + nowtime = time.time() else: break except: print('转换语音失败') break - number = simuse.Send_Message_Chain(data, group, 1, answer) # 让bot发送随机抽取中的答案 if number != None: - if voicereplysign==0: + if voicereplysign == 0: print('答案已发送', number) else: - print('答案已发送(语音)',number) + print('答案已发送(语音)', number) #print('->',end='') else: print('答案发送失败') @@ -237,11 +322,11 @@ def listening(data): continue messagechain = i['messagechain'] messagechain.pop(0) - if talkvoice(data,group,messagechain)==1: + if talkvoice(data, group, messagechain) == 1: continue question = messagechain answer = getanswer(group, question) # 获取答案 - if answer != -1 and answer!=None: + if answer != -1 and answer != None: replyanswer(data, group, answer) # 让bot回复 time.sleep(0.5) diff --git a/ChatSubadmin.py b/ChatSubadmin.py index f913e5d..e22b6b5 100644 --- a/ChatSubadmin.py +++ b/ChatSubadmin.py @@ -61,23 +61,23 @@ def Subadmin(group, sender): data = simuse.Get_Session(data) learning_config = ChatLearning.getconfig() reply_config = [ChatReply.getconfig(3), ChatReply.getconfig(1)] - learning_close_sign=0 - reply_close_sign=0 + learning_close_sign = 0 + reply_close_sign = 0 if learning_config[1] == 1 and group in learning_config[2]: Sublearning(data, group) - learning_close_sign=1 + learning_close_sign = 1 time.sleep(0.8) if reply_config[0] == 1 and group in reply_config[1]: Subreply(data, group) - reply_close_sign=1 + reply_close_sign = 1 time.sleep(0.8) ChatAllfind.findallcontrol(data, sender, group=group) print('群{}退出管理模式,操作者:{}'.format(group, sender)) simuse.Send_Message(data, group, 1, '退出管理模式', 1) - if learning_close_sign==1: + if learning_close_sign == 1: time.sleep(0.8) Sublearning(data, group) - if reply_close_sign==1: + if reply_close_sign == 1: time.sleep(0.8) Subreply(data, group) diff --git a/Chatmain.py b/Chatmain.py index 29f0a1b..65b5643 100644 --- a/Chatmain.py +++ b/Chatmain.py @@ -2,9 +2,9 @@ import base64 import json import os +import sys import time import wave -import sys import nest_asyncio import requests @@ -14,13 +14,15 @@ import ChatAdmin import ChatAllfind import ChatCheck +import ChatDelete import ChatFilter import ChatLearning import ChatMerge import ChatReply import ChatSubadmin import simuse -from ChatClass import My_Thread, Version, commandclass,ClChange +from ChatClass import (Cl_version, ClChange, Config_version, My_Thread, + Version, commandclass) nest_asyncio.apply() @@ -37,10 +39,14 @@ def hello(): config['admin'] = 0 if ('version' in config.keys()) == False: ClChange() - config['version']=Version() + config['version'] = '2.7.0' + Cl_version(config['version']) + config=Config_version(config['version']) + config['version'] = Version() file = open('config.clc', 'w', encoding='utf-8-sig') file.write(str(config)) file.close() + ChatFilter.Merge_Filter() print('欢迎使用ChatLearning应用 版本号:', Version()) #print('遇到问题和bug请在mirai论坛回复我或发送至我的邮箱1121917292@qq.com') print('输入help来查看指令列表吧!') @@ -50,11 +56,11 @@ def unknowcommand(command): print('<-未知指令"{}" 请输入help/?查看帮助'.format(command)) pass + def exit(): sys.exit(0) - def uploadwav(data, fromchat=0): try: wavsize = os.path.getsize('source.wav') @@ -69,9 +75,9 @@ def uploadwav(data, fromchat=0): if fromchat != 0: simuse.Send_Message(data, fromchat, 2, '文件大小超过10M!取消上传', 1) return None - wavefile=wave.open('source.wav', 'rb') + wavefile = wave.open('source.wav', 'rb') wav_secs = wavefile.getnframes() / wavefile.getframerate() - if wav_secs>=20: + if wav_secs >= 20: print('音频时长大于20秒!取消上传') if fromchat != 0: simuse.Send_Message(data, fromchat, 2, '音频时长大于20秒!取消上传', 1) @@ -268,8 +274,8 @@ def admin(adminsign, fromchat=0): global learningsign global mergesign global replysign - learning_close_sign=0 - reply_close_sign=0 + learning_close_sign = 0 + reply_close_sign = 0 if fromchat == 0: print('请在聊天环境中执行该指令') return adminsign @@ -277,18 +283,18 @@ def admin(adminsign, fromchat=0): tempsign = learning(learningsign, mergesign, fromchat) learningsign = tempsign[0] mergesign = tempsign[1] - learning_close_sign=1 + learning_close_sign = 1 if replysign == 1: time.sleep(0.8) replysign = reply(replysign, fromchat) - reply_close_sign=1 + reply_close_sign = 1 if adminsign == 0: time.sleep(0.8) print('<-进入管理模式') print('请不要操作控制台!!!') #print('拥有词库的群号:') #print(ChatAdmin.getfilelist()) - tips = '请发送需要操作的序号\n1.在所有群内查找\n2.在指定群内查找\n3.过滤设置' + tips = '请发送需要操作的序号\n1.在所有群内查找\n2.在指定群内查找\n3.过滤设置\n4.自动清理词库' simuse.Send_Message(data, fromchat, 2, tips, 1) command = getcommand_chat_foradmin() choice = command[0] @@ -311,7 +317,7 @@ def admin(adminsign, fromchat=0): group = command[0] sender = command[1] try: - group = int(group) + group = str(group) except: print('参数错误') print('<-退出管理模式') @@ -338,18 +344,31 @@ def admin(adminsign, fromchat=0): print('<-退出管理模式') simuse.Send_Message(data, fromchat, 2, '退出管理模式', 1) #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) + print('<-退出管理模式') + simuse.Send_Message(data, fromchat, 2, '退出管理模式', 1) + else: + print('<-退出管理模式') + simuse.Send_Message(data, fromchat, 2, '退出管理模式', 1) else: print('参数错误') print('<-退出管理模式') if fromchat != 0: simuse.Send_Message(data, fromchat, 2, '参数错误,退出管理模式', 1) #return adminsign - if learning_close_sign==1: + 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: + if reply_close_sign == 1: time.sleep(0.8) replysign = reply(replysign, fromchat) return adminsign @@ -421,56 +440,272 @@ def learninginterval(interval, fromchat=0): def replychance(chance, fromchat=0): global data - try: - chance = int(chance) - except: - print('参数错误') + if chance[:chance.find(' ')] == '-s': + args = chance[chance.find(' ') + 1:] + if args.find(' ') != -1: + single_chance = args[:args.find(' ')] + else: + print('参数错误,群号为空') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '参数错误,群号为空', 1) + return None + try: + single_chance = int(single_chance) + except: + print('参数错误') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '参数错误', 1) + return None + if single_chance <= 0 or single_chance > 100: + print('参数错误') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '参数错误', 1) + return None + grouplist = '[{}]'.format(args[args.find(' ') + 1:]) + try: + grouplist = grouplist.replace(',', ',') + grouplist = grouplist.replace(' ', ',') + except: + pass + try: + grouplist = eval(grouplist) + if type(grouplist) != 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 + try: + file = open('config.clc', 'r', encoding='utf-8-sig') + config = file.read() + config = eval(config) + file.close() + replydict = config['singlereplychance'] + except: + replydict = {} + for i in grouplist: + replydict[str(i)] = single_chance + config['singlereplychance'] = replydict + file = open('config.clc', 'w', encoding='utf-8-sig') + file.write(str(config)) + file.close() + print('<-添加完毕') if fromchat != 0: - simuse.Send_Message(data, fromchat, 2, '参数错误', 1) - return None - if chance <= 0 or chance > 100: - print('参数错误') + simuse.Send_Message(data, fromchat, 2, '添加完毕', 1) + + elif chance[:chance.find(' ')] == '-d': + args = chance[chance.find(' ') + 1:] + grouplist = '[{}]'.format(args) + try: + grouplist = grouplist.replace(',', ',') + grouplist = grouplist.replace(' ', ',') + except: + pass + try: + grouplist = eval(grouplist) + if type(grouplist) != 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 + file = open('config.clc', 'r', encoding='utf-8-sig') + config = file.read() + config = eval(config) + file.close() + try: + replydict = config['singlereplychance'] + except: + print('请先添加!') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '请先添加!', 1) + return None + pass + sendtext = '' + for i in grouplist: + try: + replydict.pop(str(i)) + except: + print('群', i, '不存在') + sendtext = sendtext + str(i) + '\n' + continue + if sendtext != '': + simuse.Send_Message(data, fromchat, 2, '群' + sendtext + '不存在', 1) + config['singlereplychance'] = replydict + file = open('config.clc', 'w', encoding='utf-8-sig') + file.write(str(config)) + file.close() + print('<-移除完毕') if fromchat != 0: - simuse.Send_Message(data, fromchat, 2, '参数错误', 1) - return None - print('<-已设置回复的触发概率', chance, '%') - if fromchat != 0: - simuse.Send_Message(data, fromchat, 2, - '已设置回复的触发概率' + str(chance) + '%', 1) - file = open('config.clc', 'r', encoding='utf-8-sig') - config = file.read() - config = eval(config) - file.close() - config['replychance'] = chance - file2 = open('config.clc', 'w', encoding='utf-8-sig') - file2.write(str(config)) + simuse.Send_Message(data, fromchat, 2, '移除完毕', 1) + else: + try: + chance = int(chance) + except: + print('参数错误') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '参数错误', 1) + return None + if chance <= 0 or chance > 100: + print('参数错误') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '参数错误', 1) + return None + print('<-已设置回复的触发概率', chance, '%') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, + '已设置回复的触发概率' + str(chance) + '%', 1) + file = open('config.clc', 'r', encoding='utf-8-sig') + config = file.read() + config = eval(config) + file.close() + config['replychance'] = chance + file2 = open('config.clc', 'w', encoding='utf-8-sig') + file2.write(str(config)) def voicereplychance(chance, fromchat=0): global data - try: - chance = int(chance) - except: - print('参数错误') + if chance[:chance.find(' ')] == '-s': + args = chance[chance.find(' ') + 1:] + if args.find(' ') != -1: + single_chance = args[:args.find(' ')] + else: + print('参数错误,群号为空') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '参数错误,群号为空', 1) + return None + try: + single_chance = int(single_chance) + except: + print('参数错误') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '参数错误', 1) + return None + if single_chance <= 0 or single_chance > 100: + print('参数错误') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '参数错误', 1) + return None + grouplist = '[{}]'.format(args[args.find(' ') + 1:]) + try: + grouplist = grouplist.replace(',', ',') + grouplist = grouplist.replace(' ', ',') + except: + pass + try: + grouplist = eval(grouplist) + if type(grouplist) != 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 + try: + file = open('config.clc', 'r', encoding='utf-8-sig') + config = file.read() + config = eval(config) + file.close() + replydict = config['singlevoicereplychance'] + except: + replydict = {} + for i in grouplist: + replydict[str(i)] = single_chance + config['singlevoicereplychance'] = replydict + file = open('config.clc', 'w', encoding='utf-8-sig') + file.write(str(config)) + file.close() + print('<-添加完毕') if fromchat != 0: - simuse.Send_Message(data, fromchat, 2, '参数错误', 1) - return None - if chance <= 0 or chance > 100: - print('参数错误') + simuse.Send_Message(data, fromchat, 2, '添加完毕', 1) + + elif chance[:chance.find(' ')] == '-d': + args = chance[chance.find(' ') + 1:] + grouplist = '[{}]'.format(args) + try: + grouplist = grouplist.replace(',', ',') + grouplist = grouplist.replace(' ', ',') + except: + pass + try: + grouplist = eval(grouplist) + if type(grouplist) != 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 + file = open('config.clc', 'r', encoding='utf-8-sig') + config = file.read() + config = eval(config) + file.close() + try: + replydict = config['singlevoicereplychance'] + except: + print('请先添加!') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '请先添加!', 1) + return None + pass + sendtext = '' + for i in grouplist: + try: + replydict.pop(str(i)) + except: + print('群', i, '不存在') + sendtext = sendtext + str(i) + '\n' + continue + if sendtext != '': + simuse.Send_Message(data, fromchat, 2, '群' + sendtext + '不存在', 1) + config['singlevoicereplychance'] = replydict + file = open('config.clc', 'w', encoding='utf-8-sig') + file.write(str(config)) + file.close() + print('<-移除完毕') if fromchat != 0: - simuse.Send_Message(data, fromchat, 2, '参数错误', 1) - return None - print('<-已设置语音回复的触发概率', chance, '%') - if fromchat != 0: - simuse.Send_Message(data, fromchat, 2, - '已设置语音回复的触发概率' + str(chance) + '%', 1) - file = open('config.clc', 'r', encoding='utf-8-sig') - config = file.read() - config = eval(config) - file.close() - config['voicereplychance'] = chance - file2 = open('config.clc', 'w', encoding='utf-8-sig') - file2.write(str(config)) + simuse.Send_Message(data, fromchat, 2, '移除完毕', 1) + + else: + try: + chance = int(chance) + except: + print('参数错误') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '参数错误', 1) + return None + if chance <= 0 or chance > 100: + print('参数错误') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '参数错误', 1) + return None + print('<-已设置语音回复的触发概率', chance, '%') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, + '已设置语音回复的触发概率' + str(chance) + '%', 1) + file = open('config.clc', 'r', encoding='utf-8-sig') + config = file.read() + config = eval(config) + file.close() + config['voicereplychance'] = chance + file2 = open('config.clc', 'w', encoding='utf-8-sig') + file2.write(str(config)) + file2.close() def addgroup(args, fromchat=0): @@ -620,12 +855,66 @@ def addgroup(args, fromchat=0): print('<-添加完毕') if fromchat != 0: simuse.Send_Message(data, fromchat, 2, '添加完毕', 1) + elif args[:4] == 'tag ': + tempargs = args[4:] + tag = tempargs[:tempargs.find(' ')] + if tempargs.find(' ') == -1: + print('参数错误,群号为空') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '参数错误,群号为空', 1) + return None + grouplist = '[{}]'.format(tempargs[tempargs.find(' ') + 1:]) + try: + grouplist = grouplist.replace(',', ',') + grouplist = grouplist.replace(' ', ',') + except: + pass + try: + grouplist = eval(grouplist) + if type(grouplist) != 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 + try: + file = open('config.clc', 'r', encoding='utf-8-sig') + config = file.read() + config = eval(config) + file.close() + Tagdict = config['tag'] + except: + Tagdict = {} + for i in grouplist: + try: + Taglist = Tagdict[str(i)] + except: + Taglist = [] + Taglist.append(tag) + Tagdict[str(i)] = list(set(Taglist)) + config['tag'] = Tagdict + file = open('config.clc', 'w', encoding='utf-8-sig') + file.write(str(config)) + file.close() + print('<-添加完毕') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '添加完毕', 1) + try: + ChatMerge.getfile() + except: + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, + '词库合并错误,请关闭Learning/Reply后重新操作', 1) + print('词库合并错误,请关闭Learning/Reply后重新操作') else: print('参数错误') if fromchat != 0: simuse.Send_Message(data, fromchat, 2, '参数错误', 1) return None - pass def removegroup(args, fromchat=0): @@ -782,7 +1071,6 @@ def removegroup(args, fromchat=0): if fromchat != 0: simuse.Send_Message(data, fromchat, 2, '请先添加!', 1) return None - pass sendtext = '' for i in grouplist: @@ -797,16 +1085,82 @@ def removegroup(args, fromchat=0): config['subadmin'] = subadmindict file = open('config.clc', 'w', encoding='utf-8-sig') file.write(str(config)) + file.close() print('<-移除完毕') if fromchat != 0: simuse.Send_Message(data, fromchat, 2, '移除完毕', 1) pass + + elif args[:4] == 'tag ': + grouplist = '[{}]'.format(args[4:]) + try: + grouplist = grouplist.replace(',', ',') + grouplist = grouplist.replace(' ', ',') + except: + pass + try: + grouplist = eval(grouplist) + if type(grouplist) != 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 + file = open('config.clc', 'r', encoding='utf-8-sig') + config = file.read() + config = eval(config) + file.close() + try: + Tagdict = config['tag'] + except: + print('请先添加!') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '请先添加!', 1) + return None + pass + sendtext = '' + Taglist = [] + for i in Tagdict.values(): + Taglist.extend(i) + Taglist = list(set(Taglist)) + for i in Taglist: + try: + os.remove('WordStock/' + '{}.cl'.format(i)) + except: + pass + for i in grouplist: + try: + Tagdict.pop(str(i)) + except: + print('群', i, '不存在') + sendtext = sendtext + str(i) + '\n' + continue + if sendtext != '': + simuse.Send_Message(data, fromchat, 2, '群' + sendtext + '不存在', 1) + config['tag'] = Tagdict + file = open('config.clc', 'w', encoding='utf-8-sig') + file.write(str(config)) + file.close() + print('<-移除完毕') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '移除完毕', 1) + try: + ChatMerge.getfile() + except: + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, + '词库合并错误,请关闭Learning/Reply后重新操作', 1) + print('词库合并错误,请关闭Learning/Reply后重新操作') + else: print('参数错误') if fromchat != 0: simuse.Send_Message(data, fromchat, 2, '参数错误', 1) return None - pass def learning(learningsign, mergesign, fromchat=0): @@ -932,6 +1286,7 @@ def merge(time, fromchat=0): config['mergetime'] = time file2 = open('config.clc', 'w', encoding='utf-8-sig') file2.write(str(config)) + file2.close() def check(fromchat=0): @@ -939,7 +1294,52 @@ def check(fromchat=0): check = My_Thread(target=ChatCheck.main, args=(data, fromchat)) check.start() check.join() - + + +def typefreq(data, args, fromchat=0): + typelist = [ + 'Plain', 'Image', 'Face', 'FlashImage', 'Voice', 'Forward', 'App', + 'Xml', 'Json' + ] + type = args[:args.find(' ')] + freq = args[args.find(''):][args[args.find(''):].find(' ') + 1:] + for i in typelist: + if type == i.lower(): + type = i + break + else: + typetip = '支持的类型:\n' + for types in typelist: + typetip += types + ' ' + print('<-消息类型错误\n' + typetip) + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '消息类型错误\n' + typetip, 1) + return None + try: + freq = int(freq) + except: + print('<-参数错误') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '参数错误', 1) + return None + if freq <= 0: + print('<-参数错误') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, '参数错误', 1) + return None + file = open('config.clc', 'r', encoding='utf-8-sig') + config = file.read() + config = eval(config) + file.close() + freqdict = config['typefreq'] + freqdict[type] = freq + file = open('config.clc', 'w', encoding='utf-8-sig') + file.write(str(config)) + file.close() + print('<-已设置{}回复阈值'.format(type), freq, '次') + if fromchat != 0: + simuse.Send_Message(data, fromchat, 2, + '已设置{}回复阈值'.format(type) + str(freq) + '次', 1) def getcommand_chat(): @@ -998,9 +1398,12 @@ async def getcommand_tui(): try: with patch_stdout(): command = await session.prompt_async('\nChatLearning ->') - except: + except KeyboardInterrupt: print('ChatLearning控制台无法加载,可能是置于后台运行,或是程序退出') return None + except: + time.sleep(10) + continue commandchoice(command) @@ -1075,7 +1478,9 @@ def commandchoice(command, fromchat=0): blackfreq(command[10:]) elif command[:11] == 'setvoicept ': setvoicept(data, command[11:], fromchat) - elif command=='exit': + elif command[:9] == 'typefreq ': + typefreq(data, command[9:], fromchat) + elif command == 'exit': exit() elif command == 'help' or command == '?' or command == '?': commandlist.printhelp(fromchat) @@ -1097,13 +1502,13 @@ def commandchoice(command, fromchat=0): data = simuse.Get_data() data = simuse.Get_Session(data) hello() - if learningsign==1: - learningsign=0 + if learningsign == 1: + learningsign = 0 tempsign = learning(learningsign, mergesign, 0) learningsign = tempsign[0] mergesign = tempsign[1] - if replysign==1: - replysign=0 + if replysign == 1: + replysign = 0 time.sleep(0.8) replysign = reply(replysign, 0) loop = asyncio.get_event_loop() diff --git a/README.md b/README.md index 2b59d55..ba52469 100644 --- a/README.md +++ b/README.md @@ -52,12 +52,14 @@ | `voicereply` | 开启/关闭文字转语音回复 | | `setadmin ` | 设置管理员QQ号,有多个用空格隔开 | | `blackfreq <次数>` | 设置黑名单容错次数 | +| typefreq <消息类型> <次数> | 为消息类型设置回复阈值 | | `merge <单位/秒>` | 设定总词库更新时间 | | `check` | 查看词库的问答个数和属性设置 | | `grouplist` | 查看开启记录/回复的群列表 | | `add/remove learning <群号>` | 添加/移除开启记录的群,有多个用空格隔开 | | `add/remove learnings <群号>` | 同时添加/移除开启记录和回复的群,有多个用空格隔开 | | `add/remove reply <群号>` | 添加/移除开启回复的群,有多个用空格隔开 | +| add/remove tag <标签> <群号>> | 添加/移除群标签(移除时不需要带上标签参数) | | `add/remove subadmin <群号>` | 添加/移除可自行管理的群,有多个用空格隔开 | | `add/remove unmerge <群号>` | 添加/移除不录入总词库的群,有多个用空格隔开 | | `setvoicept <训练集>` | 选择音源合成时的训练模型 | @@ -65,11 +67,14 @@ + + ## 管理模式 - 词库管理:模糊 `搜索/查看/删除` `所有群/指定群` 的词库 - 过滤:自定义无用关键词,也可以通过在删除答案时前加add来直接添加进过滤列表 - 黑名单:自定义敏感关键词,不记录且将对象拉入黑名单,用 blackfreq <次数> 自定义容错次数。 +- 自动清理词库:删除词库中仅出现过单次的条目和被过滤的条目 @@ -113,6 +118,18 @@ ------ +**Q**:什么是回复阈值? + +**A**:ChatLearning获取到答案时,需要这个答案在词库中**重复出现**的次数**大于或者等于这个阈值**时,才会回复 + +------ + +**Q**:为群添加标签有何作用? + +**A**:群往往带有一些**属性**,例如xxx游戏群,xxx交流群,这时候可以为群添加相应的标签,在记录词库时,会**记录在相应标签的词库**内,这样在回复时,只会在**相应标签词库内寻找答案**,一个群可以拥有**多个标签,支持中文** + +------ + **Q**:什么是词库链间隔时间? **A:ChatLearning**将第一个人的消息定义为一个词库链的头,他的消息只会被记录为问题,不会被记录为答案,而第一个人在**ChatLearning**中的定义是间隔一定时间无人发言后,**第一个发言的人**,你可以自行调整这个间隔时间,默认为900秒 diff --git a/simuse.py b/simuse.py index 2fe8c8d..02c7bfa 100644 --- a/simuse.py +++ b/simuse.py @@ -73,6 +73,8 @@ def Get_Session(data, getsession=0): #接收消息 (若传入deal=0,则表示返回不经过简化的原消息信息和事件) def Fetch_Message(data, deal=1): + if type(data) == type(0): + raise ConnectionError('未与api-http取得连接,或mirai未登录') host = data['host'] session = data['session'] url = 'http://' + host + '/fetchMessage' + '?sessionKey=' + session + '&count=10'