def sendall(msg): itchat.auto_login(hotReload=True) itchat.dump_login_status() # 遍历好友列表 friends = itchat.get_friends(update=True)[:] for friend in friends: ''' 典型属性内容如下: {'MemberList': <ContactList: []>, 'VerifyFlag': 0, 'DisplayName': '', 'EncryChatRoomId': '', 'Alias': '', 'PYQuanPin': 'Evi1hui', 'PYInitial': 'EVI1HUI', 'RemarkName': '', 'AppAccountFlag': 0, 'City': '阳泉', 'ChatRoomId': 0, 'AttrStatus': 2147715109, 'UniFriend': 0, 'OwnerUin': 0, 'Statues': 0, 'StarFriend': 0, 'ContactFlag': 3, 'HeadImgUrl': '/cgi-bin/mmwebwx-bin/webwxgeticon?seq=654224580&username=@78606d673dcff895a468688273bb5e92862c15d9a0e8a574865785c8a0354660&skey=@crypt_cd4d9fd6_f8d94dff59afaff6b231f3f4b8aa1e15', 'Sex': 1, 'Uin': 0, 'HideInputBarFlag': 0, 'MemberCount': 0, 'Signature': '沉默的大多数', 'NickName': 'Evi1hui', 'RemarkPYQuanPin': '', 'UserName': '******', 'IsOwner': 0, 'RemarkPYInitial': '', 'KeyWord': 'wan', 'Province': '山西', 'SnsFlag': 177} ''' UserName=friend['UserName'] NickName=friend['NickName'] City=friend['City'] #print("UserName:%s NickName:%s City:%s" % (UserName,NickName,City)) # 发送的主键为UserName字段的值 text="hi %s,%s" %(NickName,msg) # 休眠10秒 time.sleep(10) print(text) itchat.send_msg(text, UserName)
def information(msg): #这里如果这里的msg['Content']中包含消息撤回和id,就执行下面的语句 if '撤回了一条消息' in msg['Content']: old_msg_id = re.search(r"\<msgid\>(.*?)\<\/msgid\>", msg['Content']).group(1) #在返回的content查找撤回的消息的id old_msg = msg_information.get(old_msg_id) #得到消息 #print (old_msg) if len(old_msg_id)<11: #如果发送的是表情包 itchat.send_file(face_bug,toUserName='******') else: #发送撤回的提示给文件助手 msg_body = "告诉你一个秘密~" + "\n" \ + old_msg.get('msg_from') + " 撤回了 " + old_msg.get("msg_type") + " 消息" + "\n" \ + old_msg.get('msg_time_rec') + "\n" \ + "撤回了什么 ⇣" + "\n" \ + r"" + old_msg.get('msg_content') #如果是分享的文件被撤回了,那么就将分享的url加在msg_body中发送给文件助手 if old_msg['msg_type'] == "Sharing": msg_body += "\n就是这个链接➣ " + old_msg.get('msg_share_url') # 将撤回消息发送到文件助手 itchat.send_msg(msg_body, toUserName='******') # 有文件的话也要将文件发送回去 if old_msg["msg_type"] == "Picture" \ or old_msg["msg_type"] == "Recording" \ or old_msg["msg_type"] == "Video" \ or old_msg["msg_type"] == "Attachment": file = '@fil@%s' % (old_msg['msg_content']) itchat.send(msg=file, toUserName='******') os.remove(old_msg['msg_content']) # 删除字典旧消息 msg_information.pop(old_msg_id)
def demo(): # 可以保持一段时间登录状态,而不用每次运行代码都要扫码登录了 itchat.auto_login(hotReload=True) itchat.dump_login_status() #遍历好友列表 friends = itchat.get_friends(update=True)[:] for friend in friends: ''' 典型属性内容如下: {'MemberList': <ContactList: []>, 'VerifyFlag': 0, 'DisplayName': '', 'EncryChatRoomId': '', 'Alias': '', 'PYQuanPin': 'Evi1hui', 'PYInitial': 'EVI1HUI', 'RemarkName': '', 'AppAccountFlag': 0, 'City': '阳泉', 'ChatRoomId': 0, 'AttrStatus': 2147715109, 'UniFriend': 0, 'OwnerUin': 0, 'Statues': 0, 'StarFriend': 0, 'ContactFlag': 3, 'HeadImgUrl': '/cgi-bin/mmwebwx-bin/webwxgeticon?seq=654224580&username=@78606d673dcff895a468688273bb5e92862c15d9a0e8a574865785c8a0354660&skey=@crypt_cd4d9fd6_f8d94dff59afaff6b231f3f4b8aa1e15', 'Sex': 1, 'Uin': 0, 'HideInputBarFlag': 0, 'MemberCount': 0, 'Signature': '沉默的大多数', 'NickName': 'Evi1hui', 'RemarkPYQuanPin': '', 'UserName': '******', 'IsOwner': 0, 'RemarkPYInitial': '', 'KeyWord': 'wan', 'Province': '山西', 'SnsFlag': 177} ''' if friend['NickName'] == '兜哥的生活号': #print(friend['NickName']) print(friend) #发送的主键为UserName字段的值 itchat.send_msg('Nice to meet you!','@1df002b437271f75f1afd07b937801b3a7211aad221e24115fb153674ca044b7')
def deal_with_msg(msg): text = msg['Content'] if text == u'加群': time.sleep(random.randint(1, 3)) itchat.add_member_into_chatroom(get_group_id("小猪的Python学习交流群"), [{'UserName': msg['FromUserName']}], useInvitation=True) elif text == u'博客': time.sleep(random.randint(1, 3)) return 'coder-pig的个人主页-掘金:https://juejin.im/user/570afb741ea493005de84da3' elif text == u'Github': time.sleep(random.randint(1, 3)) return 'https://github.com/coder-pig' elif text == u'公众号': time.sleep(random.randint(1, 3)) itchat.send_image('gzh.jpg', msg['FromUserName']) elif text == u'打赏': time.sleep(random.randint(1, 3)) itchat.send_image('ds.gif', msg['FromUserName']) time.sleep(random.randint(1, 3)) itchat.send_msg('您的打赏,会让小猪更有动力肝出\n更Interesting的文章,谢谢支持~', msg['FromUserName']) time.sleep(random.randint(1, 3)) itchat.send_image('wxpay.png', msg['FromUserName']) else: time.sleep(random.randint(1, 3)) itchat.send_image('hrwh.png', msg['FromUserName'])
def itchat_send(): sms = get_hyper_links_rmrb() sms_text = "\n".join(sms) itchat.auto_login() name = itchat.search_friends(name = 'Mao') Mao = name[0]["UserName"] itchat.send_msg(sms_text, toUserName = Mao)
def deal_with_friend(msg): if add_friend_compile.search(msg['Content']) is not None: itchat.add_friend(**msg['Text']) # 自动将新好友的消息录入,不需要重载通讯录 time.sleep(random.randint(1, 3)) itchat.send_msg('嘤嘤嘤,我是智障机器人小Pig,\n很高兴认识你,回复关键字:\n\n 加群,博客,Github,公众号,打赏 \n\n 来继续我们的摔跤♂故事!', msg['RecommendInfo']['UserName']) time.sleep(random.randint(1, 3)) itchat.send_image('welcome.png', msg['RecommendInfo']['UserName'])
def setmsg(msg): rooms = itchat.get_chatrooms(update=True) if rooms is not None: for i in rooms: uname = i['UserName'] nname = i['NickName'] itchat.send_msg(msg, uname) print("已发送成功到群:%s!" % nname) else: print("没有任何群!")
def sendmsg_onegroup(): gname = input("请输入你想发送的的群的名字:") msg = input("请输入你想发送的话:") room = itchat.search_chatrooms(gname) if room is not None: username = room[0]['UserName'] itchat.send_msg(msg, username) print("发送成功!") else: print("未找到该群!")
def text_reply(msg): # 当消息不是由自己发出的时候 if not msg['FromUserName'] == myUserName: # 发送一条提示给文件助手 itchat.send_msg(u"[%s]收到好友@%s 的信息:%s\n" % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(msg['CreateTime'])), msg['User']['NickName'], msg['Text']), 'filehelper') # 回复给好友 return u'[自动回复]您好,我现在有事不在,一会再和您联系。\n已经收到您的的信息:%s\n' % (msg['Text'])
def sendmsg_allgroup(): msg = input("请输入你想发送的话:") rooms = itchat.get_chatrooms(update=True) if rooms is not None: for i in rooms: uname = i['UserName'] nname = i['NickName'] itchat.send_msg(msg, uname) print("已发送成功到群:%s!" % nname) else: print("没有任何群!")
def report_weather(): """Send Weather """ weather = requests.get( "http://www.sojson.com/open/api/weather/json.shtml?city=北京").json() if weather.get('status', 0) == 200: try: weather_strs = weather['data']['forecast'][0] weather_str = '日期:{date}\n天气:{type}\n'\ '气温:{low}-{high}\n'\ '风向:{fengxiang} {fengli} \n'.format(**weather_strs) except KeyError: return itchat.send_msg(weather_str, 'filehelper')
def text_reply(msg): if not msg['FromUserName'] == myUserName: print (msg['FromUserName'], '======================', msg['User']['RemarkName']) itchat.send_msg(u"[%s]收到好友@%s 的信息:%s\n" % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(msg['CreateTime'])),msg['User']['NickName'],msg['Text']), 'filehelper') if msg['User']['RemarkName'] == u'杨雨婷': global count print('yes', count) if count == 0: count = count + 1 return u'嘻嘻嘻,亲爱的,早上好哟!' if count == 1: count = count + 1 return u'希望这次不要失败了' if count == 2: count = count + 1 return u'是不是surprise?(←—___←——— ||| 看来失败了)' if count == 3: count = count + 1 return u'就是想大洋彼岸的你早晨醒来时能看到我的问好' if count == 4: count = count + 1 return u'这样看其实我也成功啦!!!撒花!!!' if count == 5: count = count + 1 return u'好啦,好啦,今天我也要放假了呢!就看你玩的那么爽!!!' if count == 6: count = count + 1 return u'但是要多发图知不知道!小猫小狗小花小草草泥马都可以,当然最终要的是有小仙女(单压X1)' if count == 7: count = count + 1 return u'楠楠爱你哟, 玩的开心~~~' if count >7 and count != 10 and count != 11 and count != 12: count = count + 1 return u'嘻嘻嘻' if count == 10: count = count + 1 return u'你好无聊啊,后面都是嘻嘻嘻,别试啦' if count == 11: count = count + 1 return u'骗你的啦~~~' if count == 12: count = count + 1 return u'恭喜您已达成成就:无聊の人!'
def send_msg(post_detail, msg_push_config): files = [] msg = post_detail.format_msg(True) logging.info('PostDetail -> %s' % str(post_detail)) if not config.ENABLE_PUSH_MSG: logging.info('推送开关已关闭,消息未推送 -> \n%s' % msg) return logging.info('准备推送 -> \n%s' % msg) for chatroom in msg_push_config: if not chatroom.enable_chatroom_push(post_detail.source): logging.info(chatroom.nick_name + ':已关闭【' + post_detail.source + '】推送消息!') continue if not chatroom.enable_push(post_detail): logging.info('当前【%s】不推送此消息!' % (chatroom.nick_name)) continue if chatroom.user_name == '': logging.info('【%s】无法推送,找不到标志符,请保存群聊到通讯录后重新登录!' % (chatroom.nick_name)) continue itchat.send_msg(msg, toUserName=chatroom.user_name) # 发送图片 if chatroom.pic_enable and len(post_detail.images) != 0: # 保证图片只下载一次 if len(files) == 0: if len(post_detail.images) > config.ALLOW_MAX_IMAGE_COUNT: files.append(post_detail.merge_image(config.BASE_TMP_DIR)) else: files = post_detail.download_image(config.BASE_TMP_DIR) for path in files: itchat.send_image(path, toUserName=chatroom.user_name) time.sleep(2) time.sleep(random.randint(2, 5)) # 删除临时文件 for path in files: if os.path.exists(path): os.remove(path)
def add_friend(msg): print(u'[ Terminal Info ] New Friend Request 新朋友的请求,自动通过验证添加加好友 From: %s' % msg['RecommendInfo']['UserName']) itchat.add_friend(**msg['Text']) # 该操作会自动将新好友的消息录入,不需要重载通讯录 itchat.send_image( '/Users/suser/Desktop/store_file/ricky.jpg', msg['RecommendInfo']['UserName']) itchat.send_image( '/Users/suser/Desktop/Desktop/store_file/fred.jpg', msg['RecommendInfo']['UserName']) itchat.send_image( '/Users/suser/Desktop/store_file/introduction.jpg', msg['RecommendInfo']['UserName']) itchat.send_image( '/Users/suser/Desktop/store_file/space.jpg',msg['RecommendInfo']['UserName']) itchat.send_msg( u'[Bot]The documents below are for you if you are a client' , msg['RecommendInfo']['UserName']) reply = itchat.send_file( '/Users/suser/Desktop/store_file/Coderbunker collaboration model with clients.pdf', msg['RecommendInfo']['UserName']) reply = itchat.send_file( '/Users/suser/Desktop/store_file/Coderbunker Contract template - Agora Space.pdf', msg['RecommendInfo']['UserName']) itchat.send_msg(u'[Bot]Thank you for adding CoderBunker! Will you please tell us if you are here for freelancer, client, or other purposes? \n #freelancer for freelancer #client for client and #other for other 😊' ,msg['RecommendInfo']['UserName'])
def reply(self, babyWords): ''' 回复该被关心的人的消息 ''' reply_words = '' if self.is_talk_with_zhao: if babyWords != '好啦,我不无聊啦': reply_words = self.get_zhao_words(babyWords) else: self.is_talk_with_zhao = False reply_words = '好叽,那下次聊啦!' else: if babyWords == '有点无聊': self.is_talk_with_zhao = True reply_words = '那小Z陪你聊会天啦,你说“好啦,我不无聊啦”,小Z的陪聊就结束啦!' elif babyWords == '不玩了': self.is_using = False reply_words = '好叽,下次来玩!' itchat.send_msg(reply_words, toUserName=self.name_uuid) elif babyWords == '在干什么': reply_words = BabyCareAbouter.what_i_am_doing elif babyWords == '七月份的尾巴你是狮子座': self.is_using = True reply_words = ('暗号对接成功!进入隐藏功能页面!\n ' '1.语音或者文字发送“在干什么”,我会告诉你我正在忙什么啦!\n' '2.语音或者文字发送“有点无聊”,性感小Z,在线陪聊!\n' '3.语音或者文字发送“不玩了”,隐藏功能页面就关闭啦!\n') elif self.is_using: reply_words = ('正在隐藏功能页面!\n' '1.语音或者文字发送“在干什么”,我会告诉你我正在忙什么啦!\n' '2.语音或者文字发送“有点无聊”,性感小Z,在线陪聊!\n' '3.语音或者文字发送“不玩了”,隐藏功能页面就关闭啦!\n') if not self.is_using: return #延时1s后发送 time.sleep(1) itchat.send_msg(reply_words, toUserName=self.name_uuid)
def findWeather(msg): weather = 'http://www.weather.com.cn/' heb = 'http://www.weather.com.cn/weather/101050101.shtml' helper = SpiderHelper(base=weather).init() bs = helper.getBs(url=heb) temper = bs.find(id='7d').ul.find_all('li') tianqi = temper[0].text.replace('\n', ' ') itchat.send_msg('哈尔滨天气:'+tianqi, msg['FromUserName']) lis = bs.find('div', class_='hide show').ul.find_all('li') j = 0 for i in lis: # if i['class']=='li1': if j == 0: # 紫外线 j += 1 itchat.send_msg(i.em.text+':'+i.span.text+'\n'+i.p.text, msg['FromUserName']) continue if j == 1: # 减肥 j += 1 # print('减肥') continue if j == 2: # 健康 j += 1 # print(i.em.text) # print(i.span.text) # print(i.p.text) continue if j == 3: # 穿衣指数 j += 1 itchat.send_msg(i.em.text+':'+i.span.text+'\n'+i.p.text, msg['FromUserName']) continue if j == 4: # 洗车指数 j += 1 # print(i.em.text) # print(i.span.text) # print(i.p.text) continue if j == 5: # 空气污染 j += 1 itchat.send_msg(i.em.text+':'+i.span.text+'\n'+i.p.text, msg['FromUserName']) continue
def receive_msg(self, msg): if 'UserName' not in msg['User']: # 可能是公众号发的消息 return my_info = itchat.search_friends() reply_content = msg['Content'].encode('utf8') my_reply = my_info['UserName'] == msg[ 'FromUserName'] #msg['User']['UserName'] 不管对方或是我发的,都是对方的信息 lastReplyInfo = self.obj_db_helper.get_last_reply_time(msg['User']) if my_reply is True: self.obj_db_helper.update_last_reply_time(msg['ToUserName']) for call in config.robot_calls: #自动回复 if call in reply_content: self.robot_reply(msg['ToUserName'], reply_content.replace(call, '')) break else: for call in config.robot_calls: # 自动回复 if call in reply_content: self.robot_reply(msg['FromUserName'], reply_content.replace(call, '')) return if time.time() - lastReplyInfo[0] > config.robot_time: if lastReplyInfo[1] > 0: if config.robot_auto_reply is True: self.robot_reply(msg['FromUserName'], reply_content) else: if msg['User']['RemarkName'] in config.girl_friend_name: itchat.send_msg(u"小主人快来呀,你的女朋友找你来了", msg['FromUserName']) self.obj_db_helper.set_robot_replying( msg['FromUserName'], '1') else: itchat.send_msg(u"小主人现在不在线哦,稍后会给你回消息,急事请电话联系!", msg['FromUserName'])
def run(self): autoreply = False while True: try: # 获取信息 msgs = wc.get_msg() if msgs: # 按次序提取信息 for msg in msgs[0]: time.sleep(0.2) try: # 找到自己的发言,‘开始你的表演’,‘停止你的表演’ 作为开始和结束的指令 if msg['MsgType'] == 1: if msg['FromUserName'] == wc.originInstance.storageClass.userName: if '开始你的表演' in msg['Content']: autoreply = True logging.info('表演开始咯') wc.send_msg('表演开始', self.xb) if '停止你的表演' in msg['Content']: autoreply = False logging.info('表演谢幕了') wc.send_msg('表演谢幕', self.xb) elif '@@' not in msg['FromUserName'] and '@' in msg['FromUserName'] : # 获取不是小冰的信息 if autoreply: if msg['FromUserName'] != self.xb: # 添加到接收列表 self.mi.append(copy.deepcopy(msg)) # 小冰的信息 else: # 添加到回复列表 self.mo.append(copy.deepcopy(msg)) except IndexError: pass except: logging.warning('Getting module face a problem') pass
def information(msg): # 这里如果这里的msg['Content']中包含消息撤回和id,就执行下面的语句 if '撤回了一条消息' in msg['Content']: # 在返回的content查找撤回的消息的id old_msg_id = re.search("\<msgid\>(.*?)\<\/msgid\>", msg['Content']).group(1) # 得到消息 old_msg = msg_information.get(old_msg_id) print(old_msg) if len(old_msg_id) < 11: # 如果发送的是表情包 itchat.send_file(face_bug, toUserName='******') else: # 发送撤回的提示给文件助手 msg_body = "【" \ + old_msg.get('msg_from') + " 撤回了 】\n" \ + old_msg.get("msg_type") + " 消息:" + "\n" \ + old_msg.get('msg_time_rec') + "\n" \ + r"" + old_msg.get('msg_content') # 如果是分享的文件被撤回了,那么就将分享的url加在msg_body中发送给文件助手 if old_msg['msg_type'] == "Sharing": msg_body += "\n就是这个链接➣ " + old_msg.get('msg_share_url') fw.write(msg_body + '\n') fw.flush() # 将撤回消息发送到文件助手 itchat.send_msg(msg_body, toUserName='******') # 有文件的话也要将文件发送回去 if old_msg["msg_type"] == "Picture" \ or old_msg["msg_type"] == "Recording" \ or old_msg["msg_type"] == "Video" \ or old_msg["msg_type"] == "Attachment": file = '@fil@%s' % (old_msg['msg_content']) itchat.send(msg=file, toUserName='******') os.remove(old_msg['msg_content']) # 删除字典旧消息 msg_information.pop(old_msg_id) # 在好友列表中查询发送信息的好友昵称 msg_from = itchat.search_friends(userName=msg['FromUserName'])['NickName']
def monitor_msg(msg): if '撤回了一条信息' in msg['Content']: recall_msg_id = re.search("\<msgid\>(.*?)\<\/msgid\>", msg['Content']).group(1) recall_msg = MSGINFO.get(recall_msg_id) print('[Recall]: %s' % recall_msg) if len(recall_msg_id) < 11: itchat.send_file(FACEPACKAGE, toUserName='******') else: prompt = '+++' + recall_msg.get('msg_from') + '撤回了一条消息+++\n' \ '--消息类型: ' + recall_msg.get('msg_type') + '\n' \ '--接收时间: ' + recall_msg.get('msg_receive_time') + '\n' \ '--消息内容: ' + recall_msg.get('msg_content') if recall_msg['msg_type'] == 'Sharing': prompt += '\n链接: ' + recall_msg.get('msg_link') itchat.send_msg(prompt, toUserName='******') if recall_msg['msg_type'] == 'Attachment' or recall_msg[ 'msg_type'] == 'Video' or recall_msg[ 'msg_type'] == 'Picture' or recall_msg[ 'msg_type'] == 'Recording': file = '@fil@%s' % (recall_msg['msg_content']) itchat.send(msg=file, toUserName='******') os.remove(recall_msg['msg_content']) MSGINFO.pop(recall_msg_id)
def ending(winner): global user global weuser global role global userlist global groupchatlangren global groupchatmain itchat.send_msg('游戏结束。获胜者:%s\n请自行删除并退出。' % winner, toUserName=groupchatmain) itchat.send_msg('游戏结束。获胜者:%s\n请自行删除并退出。' % winner, toUserName=groupchatlangren) userDict = [] #初始化 global idnow global roles global ifgame global langrenamout global cunminamout global yuyanjia global cunmin global langren global nvwu idnow = 0 ifgame = False user = {} weuser = {} role = {} userlist = [] ifchosen = False groupchatmain = '' groupchatlangren = '' langren = [] cunmin = [] nvwu = '' yuyanjia = '' roles = ['langren', 'nvwu', 'yuyanjia', 'cunmin']
def wechat_service(msg): recall_message_handle(msg, is_group=False) print("接收到了MAP, CARD, NOTE, SHARING类的信息") # print(msg) if msg.type == "Map": print("接收到了MAP消息") itchat.send_msg("识别到了地图类型消息,正在自动提取地址", toUserName=msg.fromUserName) result = WeChatAction.map_analysis(msg) itchat.send_msg(result, toUserName=msg.fromUserName) elif msg.type == "Note": if msg["MsgType"] == 10000 and "红包" in msg["Content"]: itchat.send_msg("谢谢老板的红包[玫瑰]", toUserName=msg.fromUserName) if msg["MsgType"] == 10000 and "拍了拍" in msg["Content"]: itchat.send_msg("小心的拍,拍伤了要赔钱的[旺柴]", toUserName=msg.fromUserName)
def search(FromData): searchCount = 0 #登陆微信,记住登陆状态 itchat.auto_login(hotReload=True) # 获取微信名 users = itchat.search_friends('Admin') wxname = (users[0]['UserName']) proxys = proxyCheck() headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0' } # requests.adapters.DEFAULT_RETRIES = 5 while (True): r = requests.post('https://search.damai.cn/searchajax.html', data=FromData, headers=headers, proxies=random.choice(proxys)) print(r) result = r.text result = eval(result) # 把str类型,转换为字典类型 # print(result) pageData = result['pageData'] if pageData.__contains__('resultData') & pageData['totalResults'] > 0: print(pageData['resultData']) itchat.send('有新票务更新!!!', toUserName=wxname) itchat.send_msg(str(pageData['resultData']), toUserName=wxname) break else: searchCount += 1 print(searchCount, time.asctime(time.localtime(time.time()))) time.sleep(30)
def text_reply(msg): global auto_reply, rebort_apply, apikey # The command signal of "[自动回复]" if msg['FromUserName'] == myUserName and msg['Content'] == u"开启自动回复": auto_reply = True itchat.send_msg(u"[自动回复]已经打开。\n", msg['FromUserName']) elif msg['FromUserName'] == myUserName and msg['Content'] == u"关闭自动回复": auto_reply = False itchat.send_msg(u"[自动回复]已经关闭。\n", msg['FromUserName']) elif msg['FromUserName'] == myUserName and msg['Content'] == u"开启图灵机器人": rebort_apply = True itchat.send_msg(u"[图灵机器人]已经打开。\n", msg['FromUserName']) print('[图灵机器人]已经打开。') elif msg['FromUserName'] == myUserName and msg['Content'] == u"关闭图灵机器人": rebort_apply = False itchat.send_msg(u"[图灵机器人]已经关闭。\n", msg['FromUserName']) else: if auto_reply == True: itchat.send_msg(u"[自动回复]您好,我现在有事不在,一会再和您联系。\n", msg['FromUserName']) else: # Sleep 1 second is not necessary. Just cheat human. # time.sleep(1) if rebort_apply == True: cont = requests.get( 'http://www.tuling123.com/openapi/api?key=%s&info=%s' % (apikey, msg['Content'])).content m = json.loads(cont) itchat.send(m['text'], msg['FromUserName']) if m['code'] == 200000: itchat.send(m['url'], msg['FromUserName']) if m['code'] == 302000: itchat.send(m['list'], msg['FromUserName']) if m['code'] == 308000: itchat.send(m['list'], msg['FromUserName']) return
def msg_handler(self, msg): txt = msg['Text'] if txt == '/q': itchat.send_msg("Quitting...", self.user) self.send_separator(self.user) self.finished = True return True Tuling.num_of_reqs += 1 response = self.post_data(txt) code = response["code"] if code == 100000: itchat.send_msg(response["text"], self.user) elif code == 200000: itchat.send_msg("\n".join([response["text"], response["url"]]), self.user) else: itchat.send_msg(response["text"], self.user)
def text_reply(msg): msg_re = msg['Text'] global status # 自动回复状态 if msg_re == '查询好友': itchat.send_msg('输入要查询的好友名称', toUserName=self_user) listen_serach() elif msg_re == '骑车' and msg['FromUserName'] == self_user: status = '骑车' + reply itchat.send(reply_status + status, self_user) elif msg_re == '休息' and msg['FromUserName'] == self_user: status = '休息' + reply itchat.send(reply_status + status, self_user) elif msg_re == '睡觉' and msg['FromUserName'] == self_user: status = '睡觉' + reply itchat.send(reply_status + status, self_user) elif msg_re == '结束' and msg['FromUserName'] == self_user: status = '' itchat.send('自动回复已关闭') elif msg_re == '菜单' and msg['FromUserName'] == self_user: menu() elif msg_re == '分享' and msg['FromUserName'] == self_user: itchat.send_msg('输入要分享给的好友名称') if msg['FromUserName'] != self_user: itchat.send(status, toUserName=msg['FromUserName'])
def text_reply(msg): """text""" try: if msg['User']['NickName'] == 'Kay' and msg['Content'].find( '我们#') == 0: send_text = u'%s,%s' friend_list = itchat.get_friends(update=True)[1:] for friend in friend_list: if (friend.get('NickName', '') and friend.get('NickName', '') != '朋友推荐消息'): itchat.send( send_text % (get_right_str(friend['DisplayName']) or get_right_str( friend['NickName']), msg['Content'][3:]), friend['UserName']) time.sleep(uniform(1, 2)) itchat.send_msg(msg='done', toUserName=msg['FromUserName']) else: time.sleep(uniform(1, 3)) itchat.send_msg(msg='欢迎您,%s!\n%s'%(get_right_str(msg['User']['NickName']), TEXT_REPLY),\ toUserName=msg['FromUserName']) LOG.info(msg) except Exception: LOG.record_except()
def command(s): try: if s['Text'] == '关闭自动回复': swit.break_myswitch() itchat.send_msg('自动回复功能已关闭', toUserName='******') elif s['Text'] == '开启自动回复': swit.open_myswitch() itchat.send_msg('自动回复功能已开启', toUserName='******') elif s['Text'] == '关闭程序': itchat.logout() sys.exit('收到远程命令,退出程序') elif s['Text'] == '关机': os.system('shutdown -h now') else: itchat.send_msg('识别不了的命令.', toUserName='******') except Exception as e: itchat.send_msg('执行命令时发生了错误', toUserName='******')
def simple_reply(msg): #设置为nolocal global groups print("simple_reply begin msg") for group in groups: if msg['FromUserName'] == group._group_id: src_group = group target_groups = get_target_groups(src_group, tuple(groups)) # 筛选出已激活的 active_target_groups = [ group for group in target_groups if group._group_id ] forward_message(msg, src_group, active_target_groups) if not group._group_id: print(group._group_id) #None # 不存在的时候 #如果找到群id就不找,否则每条消息来都找一下,维护一个群列表,全局 group_instance = itchat.search_chatrooms( name=group._group_name) #本地测试群 if group_instance: group.set_id(group_instance[0]['UserName']) #没有设置成功? print("{}激活,group_id:{}".format(group._group_name, group._group_id)) itchat.send_msg('机器人已激活: )', group._group_id)
def change_function(): global paperweeklyGroupId #data_list = pubsub.listen() #for item in data_list: # The last for section will block,使用多线程,处理阻塞问题 message = pubsub.get_message() #每次只获取一条 if message and paperweeklyGroupId: # 全局变量paperweeklyGroupId ,初始化为None # message是json,data值为序列化后的json数据,需要做反序列化,可以参考test文件 print("paperweeklyGroupId:", paperweeklyGroupId) itchat.send_msg(str(message), paperweeklyGroupId) #完成主动推送 print('主动推送:', message) @itchat.msg_register(TEXT, isGroupChat=True) # 群聊,TEXT , 可视为已经完成的filter def simple_reply(msg): # 需要判断是否处理消息,只处理目标群消息 global paperweeklyGroupId if msg['FromUserName'] == paperweeklyGroupId: print('处理群gtest消息') # 业务逻辑 , 回调handle response = handle_group_msg(msg) # type print response if response['type'] == 'q': #谈论帖子 to_wechat_msg = '帖子发送成功 \n 帖子id:{} \n 使用 /bot/t/(id) 可回复'.format( response['response']['id']) itchat.send_msg(to_wechat_msg, paperweeklyGroupId) if response['type'] == 't': #谈论帖子 to_wechat_msg = '帖子回复成功 :)' itchat.send_msg(to_wechat_msg, paperweeklyGroupId) # 做个日志记录 if not paperweeklyGroupId: #如果找到群id就不找,否则每条消息来都找一下,维护一个群列表,全局 gtest = itchat.search_chatrooms(name=paperweeklyGroupName) #本地测试群 if gtest: paperweeklyGroupId = gtest[0]['UserName'] itchat.send_msg('找到群id:', paperweeklyGroupId)
def information(msg): # 这里如果这里的msg['Content']中包含消息撤回和id,就执行下面的语句 if '撤回了一条消息' in msg['Content']: # 在返回的content查找撤回的消息的id old_msg_id = re.search("\<msgid\>(.*?)\<\/msgid\>", msg['Content']).group(1) old_msg = msg_information.get(old_msg_id) # 得到消息 # print old_msg logger.info("***********注意,上面有消息已被撤回**********") print u"***********注意,上面有消息已被撤回**********" if len(old_msg_id) < 11: # 如果发送的是表情包 itchat.send_file(face_bug, toUserName='******') else: # 发送撤回的提示给文件助手 msg_body = "【"\ + old_msg.get('msg_from') + " 群消息撤回提醒】\n"\ + " 撤回了 " + old_msg.get("msg_type") + " 消息:" + "\n" \ + old_msg.get('msg_time_rec') + "\n" \ + r"" + old_msg.get('msg_content') # 如果是分享的文件被撤回了,那么就将分享的url加在msg_body中发送给文件助手 if old_msg['msg_type'] == "Sharing": msg_body += "\n就是这个链接➣ " + old_msg.get('msg_share_url') # 将撤回消息发送到文件助手 itchat.send_msg(msg_body, toUserName='******') # 有文件的话也要将文件发送回去 if old_msg["msg_type"] == "Picture" \ or old_msg["msg_type"] == "Recording" \ or old_msg["msg_type"] == "Video" \ or old_msg["msg_type"] == "Attachment": file = '@fil@%s' % (old_msg['msg_content']) itchat.send(msg=file, toUserName='******') os.remove(old_msg['msg_content']) # 删除字典旧消息 msg_information.pop(old_msg_id)
def monitorMsg(msg): if 'withdrawed a message' in msg['Content']: recall_msg_id = re.search("\<msgid\>(.*?)\<\/msgid\>", msg['Content']).group(1) recall_msg = MSGINFO.get(recall_msg_id) print('[Recall]: %s' % recall_msg) if len(recall_msg_id) < 11: itchat.send_file(FACEPACKAGE, toUserName='******') else: prompt = '+++' + recall_msg.get('msg_from') + 'withdrawed a message+++\n' \ '--Message type:' + recall_msg.get('msg_type') + '\n' \ '--Received time:' + recall_msg.get('msg_receive_time') + '\n' \ '--Message content:' + recall_msg.get('msg_content') if recall_msg['msg_type'] == 'Sharing': prompt += '\nlink:' + recall_msg.get('msg_link') itchat.send_msg(prompt, toUserName='******') if recall_msg['msg_type'] == 'Attachment' or recall_msg[ 'msg_type'] == "Video" or recall_msg[ 'msg_type'] == 'Picture' or recall_msg[ 'msg_type'] == 'Recording': file = '@fil@%s' % (recall_msg['msg_content']) itchat.send(msg=file, toUserName='******') os.remove(recall_msg['msg_content']) MSGINFO.pop(recall_msg_id)
def event_welcome(user_name, new_member_names, chatroom_id): """ 群新成员欢迎 :param user_name: 机器人绑定的用户id @。。。。。 :param sender_id: 群新成员id @。。。。。 :param chatroom_id: 群id @@。。。。。 :return: none """ group_table = users.UserInfo().db[settings.groups_table] welcome_info = list( group_table.find( { 'user_name': user_name, 'group_id': chatroom_id, 'switch': 'on' }, { 'welcome_words': 1, 'frequence': 1 })) if not welcome_info: return welcome_info = welcome_info[0] welcome_words = welcome_info['welcome_words'] welcome_frequence = int(welcome_info['frequence']) * 60 # 换算为秒 conn_redis = redis.Redis(host=settings.redis_host, password=settings.redis_pwd, db=13) is_exists = conn_redis.exists(chatroom_id) if is_exists: return else: print(welcome_words) itchat.send_msg('@' + new_member_names + '\n' + welcome_words, chatroom_id) conn_redis.set(chatroom_id, 'send', ex=welcome_frequence)
def send_photo(): itchat.auto_login(hotReload=True) while True: import redis r = redis.Redis(host='localhost', port=6379, decode_responses=True) itchat_status = r.get('itchat_status') if itchat_status == '0': for nicheng in nichengs: users = itchat.search_friends(name=nicheng) userName = users[0]['UserName'] itchat.send_image(screen_path, toUserName=userName) itchat.send('test message:send photo success to person!', toUserName=userName) for roomname in rooms: iRoom = itchat.search_chatrooms(roomname) for room in iRoom: if room['NickName'] == roomname: userName = room['UserName'] break itchat.send_msg('test message:send photo success to room!', userName) itchat.send_image(screen_path, userName) r.set('itchat_status', '1') r.connection_pool.disconnect()
def send_msg(list, is_send): global name_index global remark_index global special_index global max_delayed blessing_dic = get_blessing() for i in range(1, len(list)): friend = list[i] if friend[special_index]: username = friend[special_index] elif friend[remark_index]: username = friend[remark_index] else: username = friend[name_index] if len(friend[group_index]) > 1: if friend[group_index] in blessing_dic.keys(): blessings = blessing_dic[friend[group_index]] else: if friend[sex_index] == 2: blessings = blessing_dic["女生祝福语"] else: blessings = blessing_dic["男生祝福语"] blessing = random.choice(blessings) msg = blessing.replace("name", username) if is_send: time.sleep(random.randint(2, max_delayed)) itchat.send_msg(msg, toUserName=friend[id_index]) print("发送: %s" % msg) else: print("打印: %s" % msg)
def handle_xiaobing_reply(msg): global current_asker_id_name, last_xiaobing_response_ts, is_xiaobing_busy if not current_asker_id_name: debug_print('Xiaobing replied but has no one to contact') return last_xiaobing_response_ts = now() is_xiaobing_busy = False asker = itchat.search_friends(userName=current_asker_id_name) if msg['Type'] == 'Picture': debug_print(u'Xiaobing replied a picture. Relaying to {}'.format( get_user_display_name(asker))) send_img(msg, current_asker_id_name) elif msg['Type'] == 'Text': debug_print(u'Xiaobing replied {}. Relaying to {}'.format( msg['Text'], get_user_display_name(asker))) itchat.send_msg(u'小冰: {}'.format(msg['Text']), current_asker_id_name) else: # gracefully handle unsupported formats with generic reply debug_print( u'Xiaobing replied a {}, which is not yet supported'.format( msg['Type'])) itchat.send_msg(u'小冰: 嘤嘤嘤', current_asker_id_name)
def inform_process(self): if Settings.is_inform_brothers: for bro_name in ProgramStatus.brother_username: itchat.send_msg(Settings.send_to_brother_message, bro_name) time.sleep(0.5) if Settings.is_sent_to_file_receiver: itchat.send_msg('你女朋友把你从黑名单里拔出来了!你快去哄她!', toUserName='******') time.sleep(0.5) itchat.send_msg('你快去哄她!', toUserName='******') time.sleep(0.5)
def send_msg(): # itchat.send_msg('Hello, filehelper呀这是接口发送', toUserName='******') try: data = json.loads(request.data.decode('utf-8')) msg = data['msg'] userName = data['UserName'] if len(itchat.get_friends()) != 0: result = itchat.send_msg(msg, toUserName=userName) # <ItchatReturnValue: {'BaseResponse': {'Ret': 0, 'ErrMsg': '请求成功', 'RawMsg': '请求成功'}, 'MsgID': '1034229085747027697', 'LocalID': '14887975733746'}> print(result) Ret = result['BaseResponse']['Ret'] return jsonify({'success': 1, 'msg': '成功发送', 'Ret': Ret}) else: return jsonify({'success': 0, 'msg': '尚未登陆'}) except Exception as e: return jsonify({'success': 0, 'msg': "Error {0}".format(str(e))})
def text_reply(msg): if is_at_me(msg.ToUserName): if users[msg.FromUserName] == FriendStatus.UNKNOWN: if check_trigger_words(msg.Content): users[msg.FromUserName] = FriendStatus.SELF_INTRO itchat.send_msg(msg=FIRST_REPLY % (msg.User.NickName, GROUP_NAME), toUserName=msg.FromUserName) elif users[msg.FromUserName] == FriendStatus.SELF_INTRO: if check_self_intro(msg.Content): users[msg.FromUserName] = FriendStatus.INVITE_SENT send_group_invitation(msg) intro_upcomming_member(msg.User.NickName, msg.Content) itchat.send_msg(msg=GOODBYE % (msg.User.NickName, GROUP_NAME), toUserName=msg.FromUserName) else: itchat.send_msg(msg=INTRO_FAILED, toUserName=msg.FromUserName) elif users[msg.FromUserName] == FriendStatus.INVITE_SENT and check_trigger_words(msg.Content): # the user sent trigger words again but the invitation already sent send_group_invitation(msg) itchat.send_msg(msg=GOODBYE % (msg.User.NickName, GROUP_NAME), toUserName=msg.FromUserName)
def text_reply(msg): global private_users, private_groups, admin_users get_config_users() # 发送者的昵称 sender_name = msg['User']['NickName'] if 'NickName' in msg['User'] else 'filehelper' # 发送消息的内容 content = str(msg['Text']) logger.logger.info('[text_reply] Message from {}:{}'.format(sender_name, content)) if not sender_name == 'filehelper': try: post_server(get_long_timestamp(), sender_name, content, config_parser.get('prod_server_url'), 'recieve') except: print('post error!!!') for user in private_users: if user in sender_name: for admin in admin_users: itchat.send_msg(sender_name + ': ' + content, admin_users[admin]) if sender_name in admin_users and '_' in content: message = content.split('_')[1] receiver = content.split('_')[0] if receiver == 'group': for group_name in private_groups: itchat.send_msg(message, private_groups[group_name]) logger.logger.info('[text_reply] Send message to {}:{}'.format(group_name, message)) else: if receiver in private_users: if len(message) == 17 and message[-4] == '.' and message[6] == '-': if os.path.isfile('./filecache/' + message): itchat.send_file('./filecache/' + message, private_users[receiver]) logger.logger.info('[text_reply] Forward message to {}:{}' .format(receiver, './filecache/' + message)) else: for admin in admin_users: itchat.send_msg('[text_reply] Forward message failed! Warning to {}: {} not exists!' .format(admin, './filecache/' + message), admin_users[admin]) logger.logger.info('[text_reply] Forward message failed! Warning to {}: {} not exists!' .format(admin, './filecache/' + message)) else: itchat.send_msg(message, private_users[receiver]) logger.logger.info('[text_reply] Forward message to {}:{}'.format(receiver, message)) return_msg = gate_helper.get_return_msg(content) if return_msg != 'ERROR': logger.logger.info('[text_reply] Return message:{}'.format(return_msg)) return return_msg
def send_msgs(): with sqlite3.connect('events.db') as db: cur = db.cursor() cur.execute('select msgid,content from push_msgs') res = cur.fetchall() for msgid, content in res: if itchat.send_msg(content, toUserName=group_name): cur = db.cursor() cur.execute('delete from push_msgs where msgid=?', [msgid]) db.commit() print(' -> sent msg:', content) else: if msgid not in logged_errors: print('!!! send failed:', content) log('error', '微信消息发送失败(#%d):%s' % (msgid, content)) logged_errors.add(msgid) time.sleep(.5)
def send_msgs(): with sqlite3.connect('events.db') as db: cur=db.cursor() cur.execute('select msgid,content from push_msgs') res=cur.fetchall() for msgid,content in res: if itchat.send_msg(content,toUserName=group_name): cur=db.cursor() cur.execute('delete from push_msgs where msgid=?',[msgid]) db.commit() print(' -> sent msg:',content) else: if msgid not in logged_errors: print('!!! send failed:',content) log('error','微信消息发送失败(#%d):%s'%(msgid,content)) logged_errors.add(msgid) time.sleep(.5)
def new_year(msg): if msg['ToUserName'] == 'filehelper': groupUserName = itchat.search_chatrooms('uuuu')[0]['UserName'] if '发送人' in msg['Content'][0:3]: # 要发送的消息 # 所有好友 users = itchat.get_friends(update=True) for user in users[1:]: # 好友备注 userRemarkName = user['RemarkName'] if '-' in userRemarkName: # 昵称 petName = userRemarkName[userRemarkName.rindex('-') + 1:] ''' 发送信息格式大致为: start: 昵称: 祝福语 end; ''' sendMsg = petName + ':\n' + text_br_index( msg['Content'][3:]) # 发送消息 itchat.send_msg(sendMsg, user['UserName']) else: not_send.append(userRemarkName) print('所有用户数量: ' + str(len(users))) elif '发送群' in msg['Content'][0:3]: # 要发送的消息 sendMsg = text_br_index(msg['Content'][3:]) # 所有群 groups = itchat.get_chatrooms() for group in groups: groupName = group['NickName'] if '快乐一家人' == groupName or '幸福大家庭' == groupName: # 不做处理 continue else: # 对群内发送消息 toUserName = group['UserName'] itchat.send_msg(sendMsg, toUserName) print('所有群数量: ' + str(len(groups))) elif '非好友' == msg['Content']: # 获取非好友对象 print(not_friends()) elif '清空' == msg['Content']: # 获取非好友对象 print(clean_not_friends()) elif '未发送' == msg['Content']: itchat.send_msg('未发送\n' + str(not_send), groupUserName) else: # 如果是接收到好友发送的消息, 则进行备份, 用户 backup(msg)
def add_friend(msg): # 该操作会自动将新好友的消息录入,不需要重载通讯录 itchat.add_friend(**msg['Text']) # 加完好友后,给好友打个招呼 itchat.send_msg('[愉快]你好,我是网购优惠券、返利机器人,\n发送【帮助】查看使用机器人流程。', msg['RecommendInfo']['UserName'])
def custom_push(msg): cmd,_,content=msg['Content'].partition(' ') if cmd.lower()=='send': return '成功' if itchat.send_msg(content,toUserName=group_name) else '失败'
def on_batch_end(self, batch, logs=None): if batch % 100 == 0: itchat.send_msg('[batch] ' + str(batch) + ' ' + str(logs), toUserName='******')
def on_epoch_end(self, epoch, logs=None): itchat.send_msg('[epoch] ' + str(epoch) + ' ' + str(logs), toUserName='******')
import itchat itchat.auto_login() itchat.send_msg("hello")
def add_friend(msg): itchat.add_friend(**msg['Text']) itchat.send_msg(u'项目主页:github.com/littlecodersh/ItChat\n' + u'源代码 :回复源代码\n' + u'图片获取:回复获取图片\n' + u'欢迎Star我的项目关注更新!', msg['RecommendInfo']['UserName'])
def add_friend(msg): itchat.add_friend(**msg['Text']) itchat.get_contract() itchat.send_msg('Nice to meet you!', msg['RecommendInfo']['UserName'])