def monitor_login(itchat): isLoggedIn = False while 1: waiting_time = 0 while not isLoggedIn: status = itchat.check_login() waiting_time += 1 print(waiting_time) if status == '200': print("status is 200!") isLoggedIn = True elif status == '201': print("status is 201!") if isLoggedIn is not None: print('Please press confirm on your phone.') isLoggedIn = None elif status != '408': break elif waiting_time == 5: raise if isLoggedIn: print("已经确认登陆了") break print("==== here status is ", status) itchat.check_login() itchat.web_init() itchat.show_mobile_login() itchat.get_contact(True) # you can do your business here # itchat.start_receiving() # add heartbeat itchat.run()
def register_reply(msg): if(msg['Text']=="打印名单"): student = '' source = msg['FromUserName'] for i in range(len(itchat.get_contact())): if(itchat.get_contact()[i]['UserName']==source): user_group = itchat.get_contact()[i]['MemberList'] for j in range(len(user_group)): student += user_group[j]['NickName'] + '\n' itchat.send(student, source)
def login(self): status = itchat.check_login() print(status) if status == '200': print('logged in') itchat.web_init() itchat.show_mobile_login() itchat.get_contact(True) self.is_logging = False itchat.start_receiving() return status
def check_login(): uuid = request.args.get('uuid', None) # print(f'34{uuid}') status = itchat.check_login(uuid) if status == '200': web_init = itchat.web_init() itchat.get_contact(True) return redirect(url_for('weixin.show')) elif status == '201': return render_template('weixin/login.html', uuid=uuid, qr='weixin', note='请在手机上确认登陆!') else: return render_template('weixin/login.html', uuid=uuid, qr='weixin', note='请使用微信扫描二维码进行登陆!')
def groupMsgHelper(msg): if msg.type == 'Text' and msg.text == '群发': friends = itchat.get_friends() contacts = itchat.get_contact() for friend in friends: print(friend) # friend.send("%s , 儿童节快乐!!!,保持一个不老的心哦。" % friend.RemarkName) for contact in contacts: print(contact)
def get_friends_info(): try: itchat.auto_login(hotReload=True) except: itchat.auto_login(hotReload=True, enableCmdQR=True) friends_info = itchat.get_friends() mps_info = itchat.get_mps() # 公众号信息 chartrooms_info = itchat.get_chatrooms() # 群信息 head_img_info = itchat.get_head_img() # 头像信息 msg_info = itchat.get_msg() contact_info = itchat.get_contact() for info in chartrooms_info: print(info) with open('test.jpg', 'wb') as img: img.write(head_img_info) img.flush() img.close() with open('wechat_info.txt', 'w', encoding='utf-8') as file: for friend in friends_info: file.write(str(friend)) file.write('\n\n\n')
def wxBot_Msg(msg): msg_type = msg['Type'] if msg_type == TEXT: contact = itchat.get_contact() print "通讯录:\n" print contact print msg['FromUserName'] print "\n\n\n获取微信朋友:get_friends:\n" print itchat.get_friends() print itchat.search_friends("朱姝") cmdMsgList = msg[TEXT].split(' ') if cmdMsgList[0] == 'autoreply' or cmdMsgList[0] == 'ar': autoReplyFriends(cmdMsgList) else: wxBot_reply(msg) elif msg_type == 'NOTE': print '通知消息' else: print '消息异常'
def friendlist(self): qun, users = itchat.get_contact(update=True) return qun, users
# coding=utf8 import itchat, time itchat.auto_login(True) SINCERE_WISH = u'祝%s新年快乐!' a = itchat.get_friends(update=True) itchat.get_chatrooms(update=True) itchat.get_contact(update=True) itchat.get_mps(update=True) itchat.get_msg() friendList = itchat.get_friends(update=True)[1:] for friend in friendList: # 如果是演示目的,把下面的方法改为print即可 # itchat.send(SINCERE_WISH % (friend['DisplayName'] # or friend['NickName']), friend['UserName']) print("%s , %s" % (friend['DisplayName'] or friend['NickName'], friend['UserName'])) # time.sleep(.5)
#coding=utf-8 import itchat from itchat.storage.templates import Chatroom from itchat.storage.templates import User from itchat.storage.templates import MassivePlatform itchat.auto_login() list_contact = itchat.get_contact() list_chatrooms = itchat.get_chatrooms() list_friends = itchat.get_friends() list_mps = itchat.get_mps() print(list_contact[0].keys()) print(list_chatrooms[0].keys()) print(list_friends[0].keys()) print(list_mps[0].keys())
import itchat def loginSuccess(): print("登录成功") def exitSuccess(): print("退出登录") # def getAllFriends(): # return # def getAllFriends(): if __name__ == '__main__': itchat.auto_login(hotReload=True, loginCallback=loginSuccess, exitCallback=exitSuccess) # print(itchat.get_friends()) all_friends = itchat.get_friends() for chatroom in itchat.get_contact(): print(chatroom) # itchat.send_file() for friend in all_friends: # print(friend) print(friend['NickName']) # itchat.send("Hello,chenhao", toUserName='******') # itchat.send_file("itchat.pkl")
def login(): uuid = open_QR() print('-------get qrcode') waitForConfirm = False while 1: status = itchat.check_login(uuid) if status == '200': break elif status == '201': if waitForConfirm: output_info('Please press confirm') waitForConfirm = True elif status == '408': output_info('Reloading QR Code') uuid = open_QR() waitForConfirm = False print('-------get login success') itchat.login() # 保存登陆状态 itchat.dump_login_status(fileDir=login_status_dir) # 获取登陆人信息 userInfo = itchat.web_init() print('Login successfully as %s' % userInfo['User']['NickName']) # 手机web微信登陆状态显示 itchat.show_mobile_login() print('-------show mobile login') # 获取最新近聊列表 itchat.get_contact(update=True) print('-------get contact complete') # 获取最新好友列表 itchat.get_friends(update=True) print('-------get friends complete') # 获取最新群聊列表 chatrooms = itchat.get_chatrooms(update=True) print('-------get chatrooms complete') # 更新群聊详细信息(人员列表) for chatroom in chatrooms: # print(json.dumps(chatroom)) itchat.update_chatroom(userName=chatroom['UserName']) print('-------update chatrooms members complete') # 启动心跳连接 itchat.start_receiving() print('-------start receiving,itchat class:' + str(itchat)) # 消息注册 好友消息 @itchat.msg_register(TEXT) def text_reply(msg): # print(json.dumps(msg)) fromuser = itchat.search_friends( userName=msg['FromUserName'])['NickName'] print(itchat.search_friends(userName=msg['ToUserName'])) touser = itchat.search_friends(userName=msg['ToUserName'])['NickName'] msgtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(msg.createTime)) msgtext = msg['Text'] print('time:%s from:%s to: %s content:%s' % (msgtime, fromuser, touser, msgtext)) # 消息注册 群聊消息 @itchat.msg_register(TEXT, isGroupChat=True) def text_reply(msg): print(json.dumps(msg)) # chatgroupname = msg['User']['NickName'] print(itchat.search_chatrooms(userName=msg['ToUserName'])) chatgroupname = itchat.search_chatrooms( userName=msg['ToUserName'])['NickName'] chatusername = msg['ActualNickName'] msgtext = msg['Text'] msgtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(msg.createTime)) print('time:%s from:%s group:%s content:%s' % (msgtime, chatusername, chatgroupname, msgtext)) @itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO]) def download_files(msg): file = msg.download( os.path.join(BASE_DIR, 'static\wx_files', msg.fileName)) typeSymbol = { PICTURE: 'img', VIDEO: 'vid', }.get(msg.type, 'fil') return '@%s@%s' % (typeSymbol, msg.fileName) # itchat.run(blockThread=False) itchat.run()
if msg['FileName'][-4:] == '.gif': return # 下载图片等文件 msg['Text'](msg['FileName']) # 转发至其他需要同步消息的群聊 itchat.send('@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 'fil'), msg['FileName']), name) # 扫二维码登录 itchat.auto_login(enableCmdQR=True) # 获取所有通讯录中的群聊 # 需要在微信中将需要同步的群聊都保存至通讯录 chatrooms = itchat.get_chatrooms(update=True, contactOnly=True) #chatrooms = chatrooms[1] chatroom_ids = [c['UserName'] for c in chatrooms] #chatroom_ids = chatrooms['UserName'] print('正在监测的群聊:'+str(len(chatrooms))+ '个') print(' '.join([item['NickName'] for item in chatrooms])) #搜索发送的好友 #friends_list = itchat.get_friends(update=True) #name = itchat.search_friends(name=u'李鹏辉')[0]["UserName"] #搜索发送的群聊 group = itchat.get_contact() for i in range(len(group)): if group[i]['NickName'] == 'test': name = group[i]['UserName'] # 开始监测 itchat.run()
def login(): if load_login(): global if_login if_login = True logger.info('loan login status success') return '200' logger.info('begin to login ...') status = itchat.check_login(qruuid) logger.info('check login status' + status) if status == '200': if_login = True logger.info('check login, status success') elif status == '201': logger.info('check login, need confirm') return status elif status == '408': logger.info('check login, qrCode timeout') get_qr() return status # 获取登陆人信息 user_info = itchat.web_init() logger.info('Login successfully as %s' % user_info['User']['NickName']) # 手机web微信登陆状态显示 itchat.show_mobile_login() logger.info('show mobile login') # 获取最新近聊列表 itchat.get_contact(update=True) logger.info('get contact complete') # 获取最新好友列表 itchat.get_friends(update=True) logger.info('get friends complete') # 获取最新群聊列表 chat_rooms = itchat.get_chatrooms(update=True) logger.info('get chatRooms complete') # 更新群聊详细信息(人员列表) for chat_room in chat_rooms: logger.debug(json.dumps(chat_room)) itchat.update_chatroom(userName=chat_room['UserName']) logger.info('update chatRooms members complete') # 保存登陆状态 itchat.dump_login_status(fileDir=login_status_dir) logger.info('save the login success to %s' % login_status_dir) # 启动心跳连接 itchat.start_receiving() logger.info('start receiving and heartbeat') class WebMessage(object): def __init__(self, _msg): self._msg = _msg def get_msg(self): return self._msg # 消息注册,好友文本消息 @itchat.msg_register(TEXT) def text_reply(msg): logger.debug(json.dumps(msg)) # q_msg = WebMessage('text', msg) # q.put(q_msg) msg_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(msg.createTime)) msg_from = itchat.search_friends( userName=msg['FromUserName'])['NickName'] msg_to = itchat.search_friends(userName=msg['ToUserName'])['NickName'] msg_text = msg['Text'] wx_record = WxRecord(is_group='0', msg_type=msg.type, msg_time=msg_time, msg_from=msg_from, msg_to=msg_to, msg_text=msg_text) wx_record.save() q.put( WebMessage({ 'is_group': '0', 'msg_type': msg.type, 'msg_time': msg_time, 'msg_from': msg_from, 'msg_to': msg_to, 'msg_text': msg_text })) logger.debug( "save to db type:%s time:%s from:%-15s to: %-15s content:%s" % (msg.type, msg_time, msg_from, msg_to, msg_text)) # 消息注册,好友图片/音频/视频/文件消息 @itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO]) def download_files(msg): msg.download(os.path.join(wx_files_dir, msg.fileName)) msg_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(msg.createTime)) msg_from = itchat.search_friends( userName=msg['FromUserName'])['NickName'] msg_to = itchat.search_friends(userName=msg['ToUserName'])['NickName'] msg_text = os.path.join(wx_files_dir, msg.fileName) wx_record = WxRecord(is_group='0', msg_type=msg.type, msg_time=msg_time, msg_from=msg_from, msg_to=msg_to, msg_text=msg_text) wx_record.save() q.put( WebMessage({ 'is_group': '0', 'msg_type': msg.type, 'msg_time': msg_time, 'msg_from': msg_from, 'msg_to': msg_to, 'msg_text': msg_text })) logger.debug( "save to db type:%s time:%s from:%-15s to: %-15s content:%s" % (msg.type, msg_time, msg_from, msg_to, msg_text)) # 消息注册,群文本消息 @itchat.msg_register(TEXT, isGroupChat=True) def text_reply(msg): logger.debug(json.dumps(msg)) msg_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(msg.createTime)) msg_from = msg['ActualNickName'] msg_to = msg['User']['NickName'] msg_text = msg['Text'] wx_record = WxRecord(is_group='1', msg_type=msg.type, msg_time=msg_time, msg_from=msg_from, msg_to=msg_to, msg_text=msg_text) wx_record.save() q.put( WebMessage({ 'is_group': '1', 'msg_type': msg.type, 'msg_time': msg_time, 'msg_from': msg_from, 'msg_to': msg_to, 'msg_text': msg_text })) logger.debug( "save to db type:%s time:%s from:%-15s to: %-15s content:%s" % ('2', msg_time, msg_from, msg_to, msg_text)) # 消息注册,群图片/音频/视频/文件消息 @itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO], isGroupChat=True) def download_files(msg): msg.download(os.path.join(wx_files_dir, msg.fileName)) msg_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(msg.createTime)) msg_from = itchat.search_friends( userName=msg['FromUserName'])['NickName'] msg_to = itchat.search_friends(userName=msg['ToUserName'])['NickName'] msg_text = os.path.join(wx_files_dir, msg.fileName) wx_record = WxRecord(is_group='1', msg_type=msg.type, msg_time=msg_time, msg_from=msg_from, msg_to=msg_to, msg_text=msg_text) wx_record.save() q.put( WebMessage({ 'is_group': '1', 'msg_type': msg.type, 'msg_time': msg_time, 'msg_from': msg_from, 'msg_to': msg_to, 'msg_text': msg_text })) logger.debug( "save to db type:%s time:%s from:%-15s to: %-15s content:%s" % (msg.type, msg_time, msg_from, msg_to, msg_text)) # 新建线程跑任务 def new_thread(): itchat.run() threading.Thread(target=new_thread).start() logger.info("聊天记录同步中 ... ") return status
# 13. 'MPSubscribeMsgList': 公众号信息列表 # 14. 'ClickReportInterval': 600000 # %% itchat.web_init() # %% [markdown] # ##### `itchat.get_contact()` # %% [markdown] # 群列表。好像是所有群,就是不知道是按照什么顺序排列的,还是随意排?! # # dict中有IsOwner属性,是否群主 # %% ctlst = itchat.get_contact(update=True) len(ctlst) # [ct for ct in ctlst if ct['NickName'] == '白晔峰'] # 列出群名,还可以区别是否群主的群 '\t'.join([qun['NickName'] for qun in ctlst if qun['IsOwner'] == 0]) # %% [markdown] # ##### `itchat.originInstance.HotReloadDir` # %% [markdown] # 热启动的pkg文件地址。 # %% itchat.originInstance.hotReloadDir # %%
def get_friends(self): self._init_login() for friend in itchat.get_friends(): print(itchat.get_contact())
import itchat itchat.auto_login(hotReload=True) contact_list = itchat.get_contact() print(contact_list) friends_list = itchat.get_friends() # print(friends_list)
#coding=utf-8 import itchat from itchat.storage.templates import ContactList itchat.auto_login() print(itchat.get_contact()) print(itchat.get_chatrooms()) print(itchat.get_friends()) print(itchat.get_mps()) print(type(itchat.get_contact())) print(type(itchat.get_chatrooms())) print(type(itchat.get_friends())) print(type(itchat.get_mps()))
) def loginCallback(): print("***登录成功***") def exitCallback(): print("***已退出***") itchat.auto_login(hotReload=True, enableCmdQR=2, loginCallback=loginCallback, exitCallback=exitCallback) roomslist = itchat.get_contact(update=True) print(roomslist) #发送内容 context = """ Hello,world! """ SR_info = [] #A类交易所信息 exchange_a = [] #B类交易所信息 exchange_b = [] #钱包信息 wallet = []
status = itchat.check_login(uuid) #返回值:登陆成功->'200',已扫描二维码->'201',二维码失效->'408',未获取到信息->'0' if status == '200': break elif status == '201': if waitForConfirm: output_info('Please press confirm') waitForConfirm = True elif status == '408': output_info('Reloading QR Code') uuid = open_QR() waitForConfirm = False userInfo = itchat.web_init() itchat.show_mobile_login() itchat.get_contact() # 用当天的时间作为文件名.txt,记录点名的学生信息 filename = time.strftime("%Y-%m-%d", time.localtime(time.time())) + ".txt" if not os.path.exists(filename): os.system(r"touch{}".format(filename)) with open(filename, "a", encoding="utf-8") as f: f.write(userInfo['User']['NickName'] + "同学于" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + "上课签到" + "\n") output_info('Login successfully as %s' % userInfo['User']['NickName']) itchat.start_receiving() # Start auto-replying @itchat.msg_register(itchat.content.TEXT) def simple_reply(msg): if msg['Type'] == 'Text': return 'I received: %s' % msg['Content'] itchat.run()
def add_friend(msg): itchat.add_friend(**msg['Text']) itchat.get_contact() itchat.send_msg(msg['RecommendInfo']['UserName'], 'Nice to meet you!')
def get_groups(self): self.groups_info = itchat.get_contact()
def run(self): userInfo = itchat.web_init() itchat.show_mobile_login() itchat.get_contact(True) print('Login successfully as %s' % userInfo['User']['NickName'])