def SendMessage(content, member=None): # from * import * # 消息过滤 try: from qqbot import _bot as bot bot.Login(['-q', '549537094']) # change except BaseException: SendEmail('SendMessage', BaseException) # 日志记录 return 0 try: from time import sleep if member: for group in member: message = bot.SendTo(group, content) if '失败' in message: pass # 日志记录 sleep(0.5) else: for group in bot.List('group'): message = bot.SendTo(group, content) if '失败' in message: pass # 日志记录 sleep(0.5) # 日志记录 except Exception as e: pass
def onQQMessage(bot, contact, member, content): groupName = contact.__dict__["name"] if groupName == "丨丶倚月听风" or groupName == "盟主你醒一醒啊!!" or groupName == "工作": if '@ME' in content: bot.SendTo(contact, member.name + ',正在上班,稍后回复你.') # Text消息之@指定用户 at_mobiles = ['18574631095'] msg = time.strftime( '%Y-%m-%d %H:%M:%S', time.localtime()) + ' 来自QQ群<%s> 成员<%s> 的@信息: "%s"' % ( groupName, member.name, content) xiaoding.send_text(msg=msg, at_mobiles=at_mobiles) if getattr(member, 'uin', None) == bot.conf.qq: # 注意:不要使用 member.uin print('你在 %s 内发言' % contact) print("***********************", content) message = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime( )) + ' 来自 群<%s> 成员<%s> 的消息: "%s"' % (groupName, member.name, content) f = open('./message', 'a', encoding='utf-8') f.write(message + "\r") f.close() # print(tuling(content)) message = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime( )) + ' 来自 群<%s> 成员<%s> 的消息: "%s"' % (groupName, member.name, content) f = open('./message2', 'a', encoding='utf-8') f.write(message + "\r") f.close() if content == '-hello': bot.SendTo(contact, '你好,有事吗?') elif content == '-stop': bot.SendTo(contact, '已下线') bot.Stop()
def send(self, qqNum, sendObj): """ 发送微语\n args:\n qqNum:发送者QQ号码 sendObj:发送对象 """ if not isinstance(sendObj, SendObj): raise TypeError('sendObj should be SendObj Type,not ' + type(sendObj)) bot.Login(['-q', '%s' % qqNum]) mes = self.get_content() for bu in sendObj.buddy: bl = bot.List('buddy', str(bu)) if bl: b = bl[0] bot.SendTo(b, mes) for gr in sendObj.group: bl = bot.List('group', str(gr)) if bl: b = bl[0] bot.SendTo(b, mes) for dis in sendObj.discuss: bl = bot.List('discuss', str(dis)) if bl: b = bl[0] bot.SendTo(b, mes)
def onQQMessage(bot, contact, member, content): #text_1 = mytask(bot) if content == 'market': text_1 = ('更新时间: ' + str(get_time()) + '\n' + 'BTC: ' + str(ticker_btc()) + ';\n' + 'LTC: ' + str(ticker_ltc()) + ';\n' + 'ETH: ' + str(ticker_eth())) bot.SendTo(contact, text_1) elif content == 'stop': bot.SendTo(contact, 'iRobot is shut down.') bot.Stop() else: bot.SendTo(contact, text_2)
def onQQMessage(bot, contact, member, content): if '周巍' == member.name: bot.SendTo(contact, '打你哦') return if content == '-hello': bot.SendTo(contact, '你好,我是QQ机器人') elif content == '在': bot.SendTo(contact, '我一直在呢,嘻嘻') elif content == '-stop': bot.SendTo(contact, 'QQ机器人已关闭') bot.Stop()
def onQQMessage(bot, contact, member, content): if '@Repeater' in content: bot.SendTo(contact, '@' + member.name) else: if not getattr(member, 'uin', None) == '249215026': try: cursor.execute("INSERT INTO REPETED(ID,WORDS) VALUES('" + member.name + "','" + content + "') ") bot.SendTo(contact, content) except sqlite3.IntegrityError: pass
def _send(self,group_name, member_name, message): logger.debug("准备发往QQ的消息,群[%s],人[%s]:%s", group_name, member_name, message) contact = self.find_group_discuss(group_name) if contact is None: logger.error("找不到QQ群或者讨论组,名字是%s",group_name) return logger.debug("找到了群组:%r", contact) # member = find_member(contact,member_name) bot.SendTo(contact, message) time.sleep(1) # 间隔一秒,防止被封 bot.SendTo(contact, '@' + member_name)
def send_msg_by_qq(msg): if msg: print('发送消息给 %s ' % QQ_TARGET_BTR) bl = bot.List('buddy', QQ_TARGET_BTR) if bl: b = bl[0] bot.SendTo(b, msg)
def parse_member_weibo(self, response, limit=5): response = filter(lambda x: x["card_type"] == 9, response.json()["cards"])[:limit] for i in response: is_top = 0 message = '' id = i["mblog"]["id"] if "isTop" in i["mblog"].keys(): is_top = i["mblog"]["isTop"] created_at = i["mblog"]["created_at"] name = i["mblog"]["user"]["screen_name"] text = re.compile(r'<[^>]+>', re.S).sub('', i["mblog"]["text"]) is_top_str = "【置顶】" if is_top == 1 else "" message += "%s【%s】\n%s: %s\n" % (is_top_str, created_at, name, text) if "data-url" in i["mblog"]["text"]: match = re.compile(r'data-url="(.*?)"', re.I).search(text) if match: video_url = match.groups()[0] message += "%s\n" % video_url if "pics" in i["mblog"].keys(): for pic in i["mblog"]["pics"]: message += "%s\n" % (pic["url"]) bot.SendTo(bot.List('group', self.group_id)[0], message) time.sleep(0.05)
def QQBotTest(): from qqbot import _bot as bot qqID = '761282619' # QQ号 group_name = 'hxr粉丝群' # 监听的群s bot.Login(['-q', qqID]) group = bot.List('group', group_name)[0] bot.SendTo(group, '测试一下Bot')
def sendMsgToGroup(msg, groupList, bot): for group in groupList: if group != None and group != "": print("group", group) bg = bot.List('group', group) print(bg) if bg is not None: bot.SendTo(bg[0], msg)
def tuling_reply(bot, contact, member, content): # 为了保证在图灵Key出现问题的时候仍旧可以回复,这里设置一个默认回复 # print(msg["Text"][0:4]) print(content) b1 = bot.List('buddy','任') b = b1[0] reply = get_response(content) reply = reply + '\n<自动回复>' bot.SendTo(b,reply)
def parse_memberLive_msg(self, response): message = "" if "liveList" in response["content"].keys(): DEBUG("获得直播列表") live_list = response["content"]["liveList"] message = message + "当前共有%s人在直播:\n\n" % (len(live_list)) for live_info in live_list: idol_name = live_info["title"] subtitle = live_info["subTitle"] streamPath = live_info["streamPath"] live_id = live_info["liveId"] member_id = live_info["memberId"] live_url = 'https://h5.48.cn/2017appshare/memberLiveShare/index.html?id=%s' % live_id message += ('%s : %s\n %s\n\n' % (idol_name, subtitle, live_url)) bot.SendTo(bot.List('group', self.group_id)[0], message) else: bot.SendTo(bot.List('group', self.group_id)[0], "当前没有小偶像在直播~~")
def send_g(bot): # 盟主你醒一醒啊!! bg = bot.List('group', "盟主你醒一醒啊!!") print(bg) while True: str = input() if str is not None and str != "": if bg is not None: tuling(str) bot.SendTo(bg[0], str)
def main(bot): # bot.SendTo('2861451012','dd') friends = bot.List('buddy') groups = bot.List('group') # print(friends) # print('-========') # print(groups) zhouwei = bot.List('buddy', '周巍') if zhouwei: zw = zhouwei[0] bot.SendTo(zw, 'hello')
def contract(exchange): data = pd.read_csv(exchange + today1 + "InstrumentInfo.csv", encoding='gbk') contractL = [] for indexs in data.index: boardingdate = data.loc[indexs].values[11] if str(boardingdate) == nextdate1: contractL.append(data.loc[indexs].values[1]) str1 = ''.join(contractL) print u'【' + exchange + u'新合约】 ' + str1 + '' bot.SendTo(bl[0], u'【' + exchange + u'新合约】 ' + str1 + '')
def sendMessageOnline(): while True: time.sleep(2) #print (friendDict) #print (players_list) for qqNickName in friendDict: for friend in friendDict[qqNickName]: if friend[0] in players_list: if friend[1] == 0: last_players_list = players_list myQQId = bot.List('buddy', qqNickName)[0] #print(myQQId) bot.SendTo(myQQId, "你的好友{}上线了。".format(friend[0])) friend[1] = 1 else: pass else: if friend[1] == 1: bot.SendTo(myQQId, "你的好友{}下线了。".format(friend[0])) friend[1] = 0
def sendMessageReply(): while True: time.sleep(2) # this line always blocks the process fromType, groupNumber, fromNumber, content = bot.poll() print(fromType, groupNumber, fromNumber, content) keywordInContent = False if groupNumber == mainGroup.uin: sendtoGroup = mainGroup print("来自主群的消息") isChatGroup = False elif groupNumber == chatGroup.uin: sendtoGroup = chatGroup print("来自闲聊群的消息") isChatGroup = True #这里改为你的ID if "大家好" in content: bot.SendTo(sendtoGroup, "欢迎新人~如果有什么游戏相关的问题可以带上问号“?”并且@我向我提问~") if "help" in content: bot.SendTo( sendtoGroup, "如果有什么游戏相关的问题,可以用包含关键词和问号“?”的句子并且@我向我提问~项目地址:https://github.com/QingGo/ddnetQQbot" ) if "@brainfullyTEE" in content: print("@我的消息") if "player" in content: if len(players_list) == 0: sendStr = "目前没人在线." else: sendStr = ("目前在线玩家数为{},分别为:".format( len(players_list))) + (", ".join(players_list)) bot.SendTo(sendtoGroup, sendStr) elif "?" in content or "?" in content: for keyword in replyDict: if keyword.lower() in content.lower(): bot.SendTo(sendtoGroup, replyDict[keyword]) keywordInContent = True if not keywordInContent: bot.SendTo( sendtoGroup, "不好意思,你所说的关键词尚未收录。快去https://github.com/QingGo/ddnetQQbot 贡献词库吧。如果要进行普通对话请不要带问号。" ) else: if isChatGroup: requestJson["info"] = content.replace( "@brainfullyTEE ", "") requestJson["userid"] = fromNumber respone = requests.post(chatAPI, requestJson) responeContent = json.loads(respone.text) bot.SendTo( sendtoGroup, responeContent["text"] + responeContent.get("url", "")) else: bot.SendTo(sendtoGroup, "询问关键词的话请加上问号")
def parse_watchMemberLive_msg(self, response, by_hand=False): all_live_ids = [] if "liveList" in response["content"].keys(): live_list = response["content"]["liveList"] for live_info in live_list: member_id = str(live_info["memberId"]) idol_name = live_info["title"] subtitle = live_info["subTitle"] streamPath = live_info["streamPath"] live_id = live_info["liveId"] live_url = 'https://h5.48.cn/2017appshare/memberLiveShare/index.html?id=%s' % live_id all_live_ids.append(member_id) if member_id in self.liveWatch_ids: if member_id not in self.member_live_msg_ids: DEBUG("%s开始直播!" % member_id) message = '你关注的小偶像正在直播!\n\n' message += ('%s : %s\n %s' % (idol_name, subtitle, live_url)) bot.SendTo( bot.List('group', self.group_id)[0], message) self.member_live_msg_ids.append(member_id) elif by_hand: message = '你关注的小偶像正在直播!\n\n' message += ('%s : %s\n %s' % (idol_name, subtitle, live_url)) bot.SendTo( bot.List('group', self.group_id)[0], message) else: DEBUG("%s在直播列表中!" % member_id) if not self.member_live_msg_ids: DEBUG("没有关注的小偶像在直播!") for member_id in self.member_live_msg_ids: if member_id not in all_live_ids: self.member_live_msg_ids.remove(member_id) DEBUG('%s关掉了直播' % member_id) return self.member_live_msg_ids
def onQQMessage(bot, contact, member, content): print(contact, member, content) if bot.isMe(contact, member): print('自己发送的') return toUsers = bot.List('buddy', '*****') print('收到消息' + content) if toUsers: toUser = toUsers[0] bot.SendTo(toUser, u'[%s]:%s' % (contact, content)) itchat.send_msg(u"收到好友@%s 的信息:%s\n" % (contact, content), toUserName='******')
def parse_name_wdsList(self, response): if response["status"] == "-1": DEBUG("fail to get wds list") bot.SendTo(bot.List('group', self.group_id)[0], "查不到小偶像的集资链接~~") return current_timestamps = int(time.time()) wds_cnt = 0 message = '' for des in response["des"]: id = des["id"] name = des["name"] goal = des["goal"] all_amount = des["all_amount"] end_timestamps = convert_timestr_to_timestamp(des["end_time"]) url = "https://wds.modian.com/show_weidashang_pro/%s"%id if current_timestamps < end_timestamps: wds_cnt += 1 message += ("%s: \n目标:%s,已集:%s \n链接:%s\n\n")%(name, goal, all_amount, url) message = "你查询的小偶像有%s个进行中的集资:\n\n"%(wds_cnt) + message bot.SendTo(bot.List('group', self.group_id)[0], message)
def notify(contact, build, isCreate): if not build or filter_message(build): return url = build['url'] name = build['name'] number = build['number'] try: build_info = jenkins_server.get_build_info(name, number) build_user = get_build_user(build_info) except Exception: print(build_info) build_user = '******' warning_msg = '前方高能!!!' if 'soa' in name and isCreate else '' bot.SendTo( contact, '%s %s %s %s\n%s' % (warning_msg, build_user, get_operation_message(build_info, isCreate), name, url))
def Notice(self, nickname='jack', content='Hello World'): try: bot.Login([ '-q', self.qq_num_sender, '-ip', self.ip, '-hp', self.port, '--daemon', '-r' ]) nickname = 'jack' if nickname == '' else nickname content = 'Hello World' if content == '' else content bl = bot.List('buddy', nickname) if bl: b = bl[0] bot.SendTo(b, content) return "Notice '{ct}' sent to {nickname} successfully!".format( ct=content, nickname=nickname) return 'Get buddy error!' except: return 'Notice Error!'
def parse_memberReviewLive_msg(self, response, limit=5): message = "" if "reviewList" in response["content"].keys(): DEBUG("获得录播列表") live_list = response["content"]["reviewList"] live_list = live_list[:limit] message += "小偶像的录播:\n\n" for live_info in live_list: idol_name = live_info["title"] subtitle = live_info["subTitle"] streamPath = live_info["streamPath"] startTime = convert_timestamp_to_timestr( live_info["startTime"]) live_id = live_info["liveId"] member_id = live_info["memberId"] message += ('%s : %s [%s]\n %s\n\n' % (idol_name, subtitle, startTime, streamPath)) bot.SendTo(bot.List('group', self.group_id)[0], message)
def km_get(qbot, group): url = 'https://redisq.zkillboard.com/listen.php' alliance_list = [99007362] # RR联盟ID km_dict = {} while(True): res = urllib.request.urlopen(url) res = json.loads(res.read().decode('utf-8')) debug_flag = True if(res['package'] == None): continue else: try: if(debug_flag or ('alliance_id' in res['package']['killmail']['victim'] and res['package']['killmail']['victim']['alliance_id'] in alliance_list)): character_url = 'https://esi.evetech.net/latest/characters/{}/?datasource=tranquility'.format(res['package']['killmail']['victim']['character_id']) character_res = urllib.request.urlopen(character_url) character_res = json.loads(character_res.read().decode('utf-8')) corporation_url = 'https://esi.evetech.net/latest/corporations/{}/?datasource=tranquility'.format(res['package']['killmail']['victim']['corporation_id']) corporation_res = json.loads(urllib.request.urlopen(corporation_url).read().decode('utf-8')) system_url = 'https://esi.evetech.net/latest/universe/systems/{}/?datasource=tranquility&language=en-us'.format(res['package']['killmail']['solar_system_id']) system_res = json.loads(urllib.request.urlopen(system_url).read().decode('utf-8')) ship_url = 'https://esi.evetech.net/latest/universe/types/{}/?datasource=tranquility&language=en-us'.format(res['package']['killmail']['victim']['ship_type_id']) ship_res = json.loads(urllib.request.urlopen(ship_url).read().decode('utf-8')) totalValue = res['package']['zkb']['totalValue'] if(character_res['name'] not in km_dict or totalValue not in km_dict[character_res['name']]): km_msg = '[熊当当KM报告] {0} 军团 {1} 驾驶的 {2} 惨死于 {3} ,损失了 {4:.2f}亿 isk.\n https://zkillboard.com/kill/{5}'.format( corporation_res['name'], character_res['name'], ship_res['name'], system_res['name'], res['package']['zkb']['totalValue']/100000000.0, res['package']['killID']) if(not debug_flag): qbot.SendTo(group, km_msg) print(km_msg) if(character_res['name'] not in km_dict): km_dict[character_res['name']] = [] km_dict[character_res['name']].append(totalValue) except Exception as e: pprint(e.args) continue
def film_name(a): s_words = etree.HTML(a) for num_list in range(25): num_list += 1 cn_name = s_words.xpath('//*[@id="content"]/div/div[1]/ol/li[' + str(num_list) + ']/div/div[2]/div[1]/a/span[1]/text()') # 电影名 words = s_words.xpath('//*[@id="content"]/div/div[1]/ol/li[' + str(num_list) + ']/div/div[2]/div[2]/p[2]/span/text()') # 一句话 str_name_not = str(cn_name) #同下 str_name_yes = str_name_not[2:-2] #参考下面 str_words_not = str(words) #转换类型 str_words_yes = str_words_not[2:-2] #去掉多余的东西 str_sent = str_name_yes + '——' + str_words_yes #拼接字符串 for qqfriend in sent_list: bl = bot.List('buddy', qqfriend) #发送给谁 if bl: #不知道在这里判断了什么 (-‸ლ)无语 b = bl[0] bot.SendTo(b, str_sent) time.sleep(5400) #休眠,三小时发送一次 休眠到底加在哪里!!!!!
def sendMessage(bot, group, content): bot.Update('group') gl = bot.List('group', group) print gl[0].qq if gl: qq_item = { 'xnr_qq_number': bot.session.qq, 'xnr_nickname': bot.session.nick, 'timestamp': int(round(time.time())), 'speaker_qq_number': bot.session.qq, 'text': content, 'speaker_nickname': bot.session.nick, 'qq_group_number': gl[0].qq, 'qq_group_nickname': group } qq_json = json.dumps(qq_item) print qq_json conMD5 = string_md5(content) nowDate = datetime.datetime.now().strftime('%Y-%m-%d') index_name = sent_group_message_index_name_pre + str(nowDate) index_id = bot.conf.qq + '_' + gl[0].qq + '_' + str( int(round(time.time()))) + '_' + conMD5 # 将发送的信息存入es if not es.indices.exists(index=index_name): group_message_mappings(bot.session.qq, nowDate) es.index(index=index_name, doc_type=group_message_index_type, id=index_id, body=qq_item) bot.SendTo(gl[0], content) return 1 else: print 'you no own this group', group return 0
def parse_roomChat_msg(self, response, room_id): # DEBUG('Room: %s exit msg ids: %s'%(room_id, \ # '\t'.join(self.member_room_msg_ids[room_id]))) msgs = response["content"]["data"] msgs.reverse() for msg in msgs: message = '' extInfo = json.loads(msg["extInfo"]) msg_id = msg["msgidClient"] if msg_id in self.member_room_msg_ids[room_id]: continue DEBUG("小偶像的房间%s有新消息了!" % room_id) if len(self.member_room_msg_ids[room_id]) > 1: self.member_room_msg_ids[room_id].insert(0, msg_id) self.member_room_msg_ids[room_id].pop(-1) msg_object = extInfo["messageObject"] idol_name = extInfo["senderName"] msg_time = msg["msgTimeStr"] if msg['msgType'] == 0: #文字 if msg_object == "text": DEBUG("普通消息") message = ('【%s的口袋房间】[%s]\n %s:%s' % (idol_name, msg_time, idol_name, extInfo["text"])) + message elif msg_object == "faipaiText": DEBUG("翻牌消息") member_msg = extInfo['messageText'] gl_msg = extInfo['faipaiContent'] gl_name = extInfo['faipaiName'] message = ('【%s的口袋房间】[%s]\n gl(%s) : %s\n %s :%s' % (idol_name, msg_time, gl_name, gl_msg, idol_name, member_msg)) + message elif msg["msgType"] == 1: #图片 DEBUG("图片消息") if msg["bodys"] == "": DEBUG("skip pic") continue bodys = json.loads(msg["bodys"]) if "url" in bodys.keys(): url = bodys["url"] message = ('【%s的口袋房间】[%s]\n 小偶像发图片啦!:\n%s' % (idol_name, msg_time, url)) + message elif msg["msgType"] == 2: #语音 DEBUG("语音消息") if msg["bodys"] == "": DEBUG("skip voice") continue bodys = json.loads(msg["bodys"]) if "url" in bodys.keys(): url = bodys["url"] message = ('【%s的口袋房间】[%s]\n 小偶像发语音啦!:\n%s' % (idol_name, msg_time, url)) + message elif msg["msgType"] == 3: #小视频 DEBUG("小视频消息") if msg["bodys"] == "": DEBUG("skip video") continue bodys = json.loads(msg["bodys"]) if "url" in bodys.keys(): url = bodys["url"] message = ('【%s的口袋房间】[%s]\n 小偶像发小视频啦!:\n%s' % (idol_name, msg_time, url)) + message else: DEBUG("unknown msgType") continue # QQHandler.send_to_groups(group_id, message) bot.SendTo(bot.List('group', self.group_id)[0], message) time.sleep(2)
def senMsgToBuddy(msg, buddyList, bot): for buddy in buddyList: bg = bot.List('buddy', buddy) if bg is not None: bot.SendTo(bg[0], msg)
def sendMsgToGroup(msg, groupList, bot): for group in groupList: bg = bot.List('group', group) if bg is not None: bot.SendTo(bg[0], msg)