def __init__(self, name="0000000", count=0, makeRooms=[]): self.robot = Robot() self.http = Http() self.name = name self.count = count #编号 self.listMsgQue = [] #消息发送队列 self.timeDetaMsgSend = 1.1 #最小发送消息间隔s self.makeRooms = makeRooms self.roomIndex = {} #房间号 及其<用户>信息 self.roomMsg = {} #消息 记录 self.roomId = "" #当前房号 ############### 心情模块 self.statusMin = 20 self.statusMax = 95 self.statusDefault = 80 self.status = 90 #说话欲望值 0-100 self.statusOnDeta = 15 #开心 self.statusOffDeta = 15 #难过 self.statusDownDeta = 40 #闭嘴 self.getMsgDetaTime = 1 #抓取消息间隔 self.lastMsgTime = int( time.time() * 10000) * 1.0 / 10000 #上一次更新房间聊天记录时间 self.lastEchoTime = tool.getNowTime() #上次说话时间 self.maxDetaTime = 1000 * 60 * 3 # 最大沉默时间 self.lastMusicTime = tool.getNowTime() self.maxMusicTime = 1000 * 60 * 4 #音乐间隔 暂不解析音乐文件时长控制 self.musicNow = {} self.musicPlayType = -1 self.ifOnMusic = True self.tail = " の... "
def sayHello(self): while (True): if (self.roomId != ""): self.out("开启定时发言,最大发言间隔" + str(self.maxDetaTime / 1000) + "s") dt = 0 while (self.roomId != ""): try: # message = "Now Time is "+ time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) detaTime = tool.getNowTime() - self.lastEchoTime # ms if (detaTime > self.maxDetaTime): message = "/me " + time.strftime("%Y%m%d %H:%M:%S") self.send(message) self.out(str(i) + "\t" + message) detaTime = tool.getNowTime() - self.lastMusicTime # ms if (self.ifOnMusic and detaTime > self.maxMusicTime and len(self.getRoomUsers(self.roomId)) > 1): #音乐开启 且 太久没放歌曲 且当前房间有至少两个人(包括自己robot) self.playMusic() if (dt % 300 == 0): self.getRooms() #定时获取房间最新信息 time.sleep(10) dt = dt + 10 dt = dt % 3600 except Exception as e: self.out(traceback.format_exc()) # self.out("当前房间roomId:" + self.roomId + " 未加入房间 暂时停止sayHello ") time.sleep(3)
def doSend(self, message): if (message == ""): return self.out("Send." + message) responce = self.http.doPost( "http://drrr.com/room/?ajax=1", { "message": message, # [0:self.musicPlayType * 4], "url": "", }) # self.out("发送[" + message + "]" + re[0:66]) self.lastEchoTime = tool.getNowTime() return
def send(self, ttt, data, deta=-1): if(deta == -1): deta = tools.getRandom(self.detaTime, self.detaTimeMin) sendTime = tool.getNowTime() preTime = sendTime + deta sendTimeT = tool.parseTime(sendTime/1000, "%D %H:%M:%S") preTimeT = tool.parseTime(preTime/1000, "%D %H:%M:%S") # self.sendList1.append((sendTime, deta, preTime, type, data)) # sendTime添加时间, type消息类型, msg发送消息体, deta间隔发送时间, preTime预期发送时间节点 self.db.execute("insert into cochat values(?,?,?,?,?,?,?,?,?)", str(self.id), str(sendTime),str(sendTimeT), str(deta), str(preTime),str(preTimeT), str(ttt), str(data),'0') return
def login(self): self.out("访问主页 获取 token session") # http://content.icbc.com.cn/site1/a5f9ff6d068a46e68d363426ca69bd07/login_unfirst.html?pageOrder=login_unfirst.html;index.html&_mp_cmp_ttime=1548294412328 # "http://content.icbc.com.cn/site1/a5f9ff6d068a46e68d363426ca69bd07/login_unfirst.html?pageOrder=login_unfirst.html;index.html&_mp_cmp_ttime=1545268253550" #http://content.icbc.com.cn/site1/a5f9ff6d068a46e68d363426ca69bd07/login_unfirst.html?pageOrder=login_unfirst.html;index.html&_mp_cmp_ttime=1552005766720 ttt = str(tool.getNowTime()) kkk = 'a5f9ff6d068a46e68d363426ca69bd07' url = "http://content.icbc.com.cn/site1/" + kkk + "/login_unfirst.html?pageOrder=login_unfirst.html;index.html&_mp_cmp_ttime=" + ttt #BIGipServerwifi_ContextPlat_80_Pool 2097346570.20480.0000 N/A N/A N/A 59 #cmp_glb_param 98f7808c851a9f53da5f0c3f1639b678 N/A N/A N/A 46 #layerNettimeType true N/A N/A N/A 23 #layerPosterType true N/A N/A N/A 22 #layerSafeType true N/A N/A N/A 20 #Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 #Accept-Encoding: gzip, deflate #Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7 #Connection: keep-alive header = { "Cookie" : "BIGipServerwifi_ContextPlat_80_Pool=2097346570.20480.0000; layerSafeType=true; layerPosterType=true; layerNettimeType=true; cmp_glb_param=98f7808c851a9f53da5f0c3f1639b678" } self.http.addHeader(header) self.http.show() responce = self.http.doGet(url) re = responce.read() soup =BeautifulSoup.BeautifulSoup(re) nameList = soup.findAll('button',{'id':{'login_btn'}}) if(len(nameList) > 0): self.out(nameList) self.out("抓取成功: ") self.http.show(responce) self.out("模拟登录") # http://content.icbc.com.cn/cmp/AuthSkipController.do?method=authSkip&ajaxRequest=true url = "http://content.icbc.com.cn/cmp/AuthSkipController.do?method=authSkip&ajaxRequest=true" #{"msg":"GlbInfo检查不通过","retCode":1,"success":false,"data":{"needJump":"http%3A%2F%2Fwww.baidu.com%2F"}} json=self.http.doJson(url) self.out((json)) self.out(json["msg"]) self.out(json["data"]["needJump"]) else: self.out("error! 没能抓取到token") return False
def timeSend(self): self.out("开启定时任务 发送队列!") self.nowNight = 0 while (True): time.sleep(5) #每分钟扫描 只对非凌晨时间处理 延时一小时发送 timeNow = tool.getNowTime() hour = tool.parseTime(timeNow / 1000, "%H:%M") if (hour >= "23:30" or hour <= "07:40" or self.ifOk == False): if (self.nowNight != 1): self.out("不是白天 或者 没有登录 now:" + str(hour)) self.nowNight = 1 continue self.nowNight = 0 try: # self.sendList1.append((sendTime, deta, preTime, type, data)) self.sendList = self.db.executeQuery( "select * from cochat where preTime<=? and flag=0 and id=?", timeNow, str(self.id)) i = len(self.sendList) - 1 while (i >= 0): obj = self.sendList[i] sendTime = int(obj.get("sendTime", 0)) # deta = int(obj.get("deta", 0)) preTime = int(obj.get("preTime", 0)) type = str(obj.get("type", "")) data = ast.literal_eval((str(obj.get("msg", "")))) info = "" hour = tool.parseTime(preTime / 1000, "%D %H:%M:%S") info = str(timeNow) + "->" + str(preTime) + " 推送时刻:" + str( hour) if (timeNow >= preTime): info += " 触发" self.sendTrue(type, data) # self.sendList.pop(i) else: info += " " self.out( tool.parseTime(timeNow / 1000, "%D %H:%M:%S") + "." + str(type) + "." + str(data) + "." + info) i = i - 1 self.db.execute( "update cochat set flag='1' where preTime<=? and flag=0 and id=? ", timeNow, str(self.id)) except Exception as e: self.out(traceback.format_exc()) return
def doHello(self): while (True): if (self.roomId != ""): self.out("开启消息发送队列 deta=" + str(self.timeDetaMsgSend) + "ms") # self.listMsgQue = [] while (self.roomId != ""): try: detaTime = tool.getNowTime() - self.lastEchoTime if (detaTime > self.timeDetaMsgSend): # 发送时差大于最小发送间隔 if (len(self.listMsgQue) > 0): msg = self.listMsgQue.pop(0) self.doSend(msg) time.sleep(self.timeDetaMsgSend) except Exception as e: self.out("消息发送异常 消息队列:") self.out(self.listMsgQue) self.out(traceback.format_exc()) # self.out("当前房间roomId:" + self.roomId + " 未加入房间 暂时停止sayHello ") time.sleep(3)
def playMusic(self, url="", name="", fromName=""): self.musicPlayType = 0 #重置为随机播放 if (url[0:4] != "http"): #无地址url则是定向点播 if (name == ""): #无名字 则自动换 music = self.robot.turnMusic(self.musicPlayType) else: self.send("/me 正在搜索歌曲[" + name + "]" + self.tail) music = self.robot.getMusic(name, fromName) url = music.get("url", "") name = music.get("name", "") fromName = music.get("fromName", "") if (fromName != ""): msg = "" rooms = self.getUserRoom(fromName) if (len(rooms) > 0): room = rooms[0] if (room.get("id", "") == self.roomId): #在当前房间 pass # msg = "/me 一首[" + name + "]送给" + fromName + "" + self.tail else: pass # msg = "/me Share " + room.get("name")[0:4] + "/" + fromName + "'s[" + name + "]" + "" + self.tail else: #不在线 pass # msg = "/me Then play" + fromName + " ordered [" + name + "]" + "" + self.tail self.send(msg) self.out("分享歌曲url=" + url + " name=" + name + " fromName=" + fromName) if (url == ""): # self.send("/me 怼不起,没有找到类似的歌曲,瑟瑟发抖"+self.tail) return responce = self.http.doPost("http://drrr.com/room/?ajax=1", { "music": "music", "name": name, "url": url, }) self.musicNow = {"url": url, "name": name, "fromName": fromName} self.lastMusicTime = tool.getNowTime() return
def makeHello(self, obj): res = "" try: # tool.line() # self.out("抓取到消息obj") # self.out(obj) newTime = obj.get("update", self.lastMsgTime) newTime = int(newTime) # print(newTime) self.lastMsgTime = newTime talks = obj.get('talks', "") users = obj.get('users', "") if (users != ""): room = self.roomIndex.get(self.roomId, "") if (room != ""): self.roomIndex[self.roomId]['users'] = users else: self.roomIndex[self.roomId] = obj if (talks != ""): onceDocount = 0 for item in talks: # self.out(item) msgTime = item.get("time", tool.getNowTime()) msgId = item.get('id', " ") msgType = item.get('type', 'message') msgData = "" msgFromName = item.get('from', {}).get('name', "") if (msgFromName == ""): msgFromName = item.get('user', {}).get('name', "") if (msgType == 'me'): msgData = item.get('content', "") elif (msgType == 'message'): msgData = item.get('message', "") elif (msgType == 'join'): # msgFromName = item.get('user', {}).get('name', "") msgData = '欢迎' + msgFromName + self.tail elif (msgType == 'leave'): msgData = ' ' + msgFromName + ' 默默的离开了 ' + self.tail elif (msgType == 'music'): music = item.get('music', {}) name = music.get('name', '') url = music.get('url', '') # msgData = '悄悄的的把[' + name + ']给记在小本子上 ' + self.tail ######################################################## 不处理 if (self.roomMsg.get(msgId, "") != ""): #已经处理过 或者是自己发送的 或者取出发送者失败 # self.out("旧消息 " + msgId + " type:" + msgType + " data:" + msgData) break if (msgType == "me" or msgType == "message"): #只记录聊天消息 self.robot.addMsg(msgId, msgFromName, msgData, msgTime) if (msgFromName == self.name or msgFromName == ""): break ############################################################# if (msgType == 'music'): music = { "name": name, "url": url, "fromName": msgFromName } res = self.robot.addMusic(music) #添加用户分享记录 if (res == 1): #更新则不提示 msgData = "" self.musicNow = music self.lastMusicTime = tool.getNowTime() self.roomMsg[msgId] = item #标记未已经处理 历史消息 if (self.status > self.statusMax): self.status = self.statusMax elif (self.status < self.statusMin): self.status = self.statusMin detaTime = tool.getNowTime() - self.lastEchoTime # ms 60s olRan = tool.getRandom( 0, self.maxDetaTime) / 1000 #0-180 过于久没有发过消息了 权重高则可能自回复 weight = (self.maxDetaTime - detaTime) / 1000 #多久没说话了 最大多长时间必须说话 ran = int(1.0 * olRan * (1 + 1.0 * (self.status - 60) / 100)) self.out("新消息 " + msgId + " 发言权" + tool.fill(str(weight) + "", ' ', 6) + " 随机数" + tool.fill(str(olRan) + "->" + str(ran), ' ', 6) + " from:" + tool.fill(msgFromName, ' ', 12) + " type:" + tool.fill(msgType, ' ', 6) + " data:" + msgData) flag = 0 #不回复 if (msgType == 'message' or msgType == 'me'): #普通聊天消息 if (re.search('@' + self.name + " ", msgData) != None): #有@自己 且权重不太低 msgData = re.sub('@' + self.name + " ", "", msgData) #摘除@自己 ran = tool.getRandom(0, 100) if (ran < self.status): flag = 1 else: self.out("@me 随机数=" + str(ran) + " 小于 说话欲望=" + str(self.status) + " ") flag = 2 msg = "生气程度:" + str( 100 - self.status) + "%,不想搭理" + self.tail elif (ran > weight and re.search('@', msgData) == None): # 没有@ 且 权重高 主动搭话概率 flag = 1 else: #事件 flag = 2 res = "" if (self.filterFlag(msgData, msgFromName)): #最高级 权限是否黑名单过滤 if (flag == 1): if (self.robot.getUser(msgFromName).get( "flag", "0") != "0"): self.out("不想搭理" + msgFromName) else: if (self.filterCmd( msgData, msgFromName)): #若过滤器未处理 则继续交由下面处理 robotRes = self.robot.do( msgData, self.name) code = str(robotRes.get("code", "")) if (code[0:1] != '4'): res = '@' + str( msgFromName) + " " + robotRes.get( "text", "") else: self.out("robot接口调用失败 code=" + code) elif (flag == 2): res = msg if (res != "" and flag != 0 and onceDocount < 6): # 最多一次抓取发送3个 res = '/me ' + res onceDocount = onceDocount + 1 self.send(res) except Exception as e: self.out("Exception:" + str(e)) # tool.line() return res
def message(self, *args): # 普通消息 try: # print("收到message ") # print(args) # tool.line() # print("转换") args = self.turnArray(args) # print(args[0]) # print(args[1]) if(len(args) <= 1): return data = args[1] #{} mtype = args[0] #message null fun if(mtype == 'message'): data = tool.toJson(data) fro = data.get("from", {}) to = data.get("to", {}) contact = data.get("contact", {}) msg = data.get("body") fullId = contact.get("fullId") sessionName = contact.get("nickName", "") uid = self.data.get("uuid") tTag = data.get("timeMillis", tool.getNowTime()) tool.line() self.out("Msg:" + fro.get("nickName","from") + ">>" + msg + ">>" + to.get("nickName","to") + " time:" + data.get("time")) # self.out(msg); # 自发消息不需要处理 if(fro.get("nickName","from").find(self.loginUser.get("ORG_VARS", {}).get("@USER_NAME@", "")) >= 0): return ttt = self.detaTime reg = re.match(r'^\d+$', str(msg)) if(reg is not None): ttt = int(msg) * 1000 self.send("updateConversationStatus", { 'contactFullId': fullId, 'clientId': uid, 'timeTag': tTag }, ttt) self.send("updateMsgStatus", { "messages":data.get("id","") }, ttt) # 自发言 且 只有自己auto回复 if(self.id != "18408249138"): return # 过滤 ff = sessionName.find("陈鹏辉") hh = fro.get("nickName","from").find("许欢") zz = fro.get("nickName","from").find("赵振国") cdf = fro.get("nickName","from").find("迪") d1 = sessionName.find("迪") d2 = sessionName.find("祝") d3 = sessionName.find("纯") if(ff < 0 or d1 >= 0 or d2 >= 0 or d3 >= 0): self.out("未命中自己title 命中特殊 不回复") return point = 76 if(hh >= 0 or zz >= 0): point = 33 self.sendTrue("updateMsgStatus", { "messages":data.get("id","") }) if(tool.getRandom(0,100) < point): self.out("概率不自动回复" + str(point)) return # data["body"] = str(data["body"]) + "." # self.send("message", data) obj = {} # if(contact.get("type") == "GROUP"): # unicode(self.robot.do(msg, fro.get("nickName"))) msg = self.robot.do(msg, fro.get("nickName")) msg = msg.get("text", ''); if(msg == ''): return obj["body"] = msg #"666" + str(tool.getNowTime()) obj["bodyType"] = "text" obj["clientId"] = str(uuid.uuid1()) obj["retry"] = 1 obj["from"] = {} obj["from"]["fullId"] = "u__" + self.data.get("userName") obj["from"]["id"] = self.data.get("userName") obj["from"]["nickName"] = "fromnickname" obj["to"] = {} if(contact.get("type") == "GROUP"): obj["to"]["fullId"] = contact.get("fullId") else: obj["to"]["fullId"] = fro.get("fullId") obj["to"]["nickName"] = "tonickname" obj["from"]["nickName"] = self.loginUser["ORG_VARS"]["@USER_NAME@"] # "from-nickName" obj["to"]["nickName"] = "to-nickName" self.sendTrue("message", obj) elif(str(mtype) == 'fun'): pass elif(str(mtype) == 'event'): pass else: self.out("其他:" + str(mtype)) print(data) # print(args) # tool.line() except Exception as e: self.out(traceback.format_exc()) return