def monitor_login(itchat, current_user, app): global isLoggedIn while 1: waiting_time = 0 while not isLoggedIn: status = itchat.check_login() waiting_time += 1 print(status) 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 Exception if isLoggedIn: print("已经确认登陆了") break print("==== here status is ", status) itchat.check_login() ready(app, itchat, current_user)
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 login(): '登录微信网页版' uuid = open_QR() 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 userInfo = itchat.web_init() friends = itchat.get_friends(True) chatrooms = itchat.get_chatrooms() mps = itchat.get_mps() # 测试的时候用 with open('1.pk', 'wb') as f: pickle.dump([friends, chatrooms, mps], f) return friends, chatrooms, mps
def getqrimg(request): ul = {} print('Getting oepnqr') uuid = open_QR() waitForConfirm = False while 1: status = itchat.check_login(uuid) if status == '200': break elif status == '201': if waitForConfirm: print('Please press confirm') waitForConfirm = True elif status == '408': print('Reloading QR Code') uuid = open_QR() waitForConfirm = False time.sleep(3) userInfo = itchat.web_init() print("ui", userInfo) # itchat.show_mobile_login() # itchat.get_contract() # print('Login successfully as %s' % userInfo['NickName']) itchat.start_receiving() return JsonResponse(ul)
def main(): global timer uuid = open_QR() waitForConfirm = False while 1: status = itchat.check_login(uuid) if status == '200': print(status) break elif status == '201': print(status) if waitForConfirm: output_info('Please press confirm') waitForConfirm = True elif status == '408': print(status) output_info('Reloading QR code') uuid = open_QR() waitForConfirm = False userInfo = itchat.web_init() itchat.show_mobile_login() itchat.get_friends() output_info('login successfully with %s' % userInfo['User']['NickName']) itchat.start_receiving() @itchat.msg_register(TEXT) def simple_reply(msg): if msg['Type'] == 'Text': print('I received: %s' % msg.text) timer_fun() # time.sleep(20 * 5) # timer.cancel() itchat.run()
def login_wechat(self): try: uuid = self.open_qr() self.outputWritten("请扫描二维码\n") waitForConfirm = False while 1: status = itchat.check_login(uuid) if status == '200': break elif status == '201': if waitForConfirm: self.outputWritten('请进行确认\n') waitForConfirm = True elif status == '408': self.outputWritten('重新加载二维码\n') time.sleep(3) uuid = self.open_qr() waitForConfirm = False userInfo = itchat.web_init() itchat.show_mobile_login() itchat.get_friends(True) self.outputWritten('登陆成功!账号为:%s\n' % userInfo['User']['NickName']) itchat.start_receiving() self.refresh_button.setText("已登录:{}".format(userInfo['User']['NickName'])) self.exit_button.setEnabled(True) except Exception as e: print("登录出错:",e) self.outputWritten('登陆出错:{}\n'.format(e)) try: # 获取群聊列表 chatrooms = itchat.get_chatrooms() print(type(chatrooms)) return chatrooms except Exception as e: self.outputWritten("获取群聊列表出错:{}\n".format(e))
def login_wechat(self): try: uuid = self.open_qr() self.outputWritten("请扫描二维码 ") waitForConfirm = False while 1: status = itchat.check_login(uuid) if status == '200': break elif status == '201': if waitForConfirm: self.outputWritten('请进行确认 ') waitForConfirm = True elif status == '408': self.outputWritten('重新加载二维码 ') time.sleep(3) uuid = self.open_qr() waitForConfirm = False userInfo = itchat.web_init() itchat.show_mobile_login() print('itchat.show_mobile_login() 执行完成!') itchat.get_friends() print('itchat.get_friends(update=True)[0:] 执行完成!') self.outputWritten('登陆成功!账号为:%s ' % userInfo['User']['NickName']) itchat.start_receiving() print('itchat.start_receiving() 执行完成!') self.refresh_button.setText("已登录:{}".format( userInfo['User']['NickName'])) self.exit_button.setEnabled(True) except Exception as e: print("登录出错:", e) self.outputWritten('登陆出错:{} '.format(e)) try: chatrooms = itchat.get_chatrooms() print('chatrooms = itchat.get_chatrooms() 执行完成!') print(type(chatrooms)) except Exception as e: self.outputWritten("获取群聊列表出错:{} ".format(e)) try: friends = itchat.get_friends() print('friends = itchat.get_friends() 执行完成!') print(type(friends)) except Exception as e: self.outputWritten("获取群聊列表出错:{} ".format(e)) try: mps = itchat.get_mps() print('mps = itchat.get_mps() 执行完成!') print(type(mps)) except Exception as e: self.outputWritten("获取群聊列表出错:{} ".format(e)) if chatrooms and friends and mps: return [chatrooms, friends, mps] def run(self): try: self.refresh_button.setEnabled(False) self.exit_button.setEnabled(True) self.finished_signal.emit(self.login_wechat()) except Exception as e: self.outputWritten("运行登录线程出错:{} ".format(e))
def post(self, request): uuid = request.POST.get("uuid") status = itchat.check_login(uuid) if status == "200": return HttpResponse("success") else: return HttpResponse("fail")
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 self_detect(): global uuid print('we are testing...') robot_status = itchat.check_login(uuid) if robot_status != '200': itchat.auto_login(hotReload=True) itchat.run() # Rebuild the timer timer = threading.Timer(1, main) timer.start()
def read_status(): global count, timer, uuid count += 1 print('timer runs every 1 second, and this is the %s' % count + ' time') status = itchat.check_login(uuid) print('The present status for # robot service is: %s' % status) # rebuild timer timer = threading.Timer(5, read_status) timer.start()
def WXConfirmQR(): itchat.logout() print "itchat.logout" status = itchat.check_login(login_uuid) print 'status = ' + str(status) + '\tuuid = ' + str(login_uuid) if status == '200': thread.start_new_thread(newWXInstance, ()) print "itchat login succeed" return "succeed" else: print "itchat login fail" return "fail"
def run(self): # 线程相关代码 while not self.loginflag: status = itchat.check_login() file_str = status self.sleep(1) #登录成功 if status == '200': self.loginflag = True self.sinOut.emit(file_str) else: self.loginflag = False self.sinOut.emit(file_str)
def keepliverun(): # 为了让实验过程更加方便(修改程序不用多次扫码),我们使用热启动 status4login = itchat.check_login() log.critical(f"微信登录状态为:\t{status4login}") if status4login == '200': log.info(f'已处于成功登录状态') return itchat.auto_login(hotReload=True, loginCallback=after_login, exitCallback=after_logout) # itchat.auto_login(hotReload=True) # 设定获取信息时重试的次数,默认是5,设定为50,不知道是否能够起作用 itchat.originInstance.receivingRetryCount = 50 init_info = itchat.web_init() # showmsgexpanddictetc(init_info) if init_info['BaseResponse']['Ret'] == 0: logstr = "微信初始化信息成功返回,获取登录用户信息" log.info(logstr) host_nickname = init_info['User']['NickName'] host_username = init_info['User']['UserName'] log.critical(f"函数《{sys._getframe().f_code.co_name}》中用户变量为:\t{(host_nickname, host_username)}") if (host_username is not None) and (len(host_username) > 0): setcfpoptionvalue('everwebchat', get_host_uuid(), 'host_nickname', host_nickname) setcfpoptionvalue('everwebchat', get_host_uuid(), 'host_username', host_username) else: log.critical("username is None") elif (itchat.originInstance.loginInfo): log.info("从itchat.originInstance.loginInfo中获取登录用户信息") host_nickname = dict(itchat.originInstance.loginInfo['User'])['NickName'] host_username = dict(itchat.originInstance.loginInfo['User'])['UserName'] log.critical(f"函数《{sys._getframe().f_code.co_name}》中用户变量为:\t{(host_nickname, host_username)}") if (host_username is not None) and (len(host_username) > 0): setcfpoptionvalue('everwebchat', get_host_uuid, 'host_nickname', host_username) setcfpoptionvalue('everwebchat', get_host_uuid, 'host_username', host_username) else: log.critical("username is None") else: log.critical(f"函数《{sys._getframe().f_code.co_name}》中用户变量为:\t{(host_nickname, host_username)}") # notechat = newchatnote() # listchatrooms() # listfriends() itchat.run()
def isLoginned(uuid): for count in range(10): status = int(itchat.check_login(uuid)) if status is 200: return True if status is 201: print 'Wait for confirm in mobile #', count randomSleep(1, 2) continue print 'Error status:', status return False return False
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 auto_login(uuid): uuid = open_QR() 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 userInfo = itchat.web_init() print userInfo itchat.show_mobile_login() itchat.get_friends(True) output_info('Login successfully as %s' % userInfo['NickName']) itchat.start_receiving()
def Login(uuid): waitForConfirm = False while True: status = itchat.check_login(uuid) if status=='200': break elif status=='201': if waitForConfirm: LogCat("Plase press confrim ....") waitForConfirm=True elif status == '408': LogCat("Reloading QR code....") uuid = getUUID() print uuid getQR(uuid) waitForConfirm = False itchat.web_init() itchat.show_mobile_login() itchat.get_contract() contract = itchat.get_contractTest() itchat.start_receiving()#key print contract return contract
def login(self, uuid): '''Login wechat for send message''' # uuid = self.open_QR() waitForConfirm = False while 1: status = itchat.check_login(uuid) if status == '200': break elif status == '201': if waitForConfirm: log.info('Please press confirm') waitForConfirm = True elif status == '408': log.info('Reloading QR Code') waitForConfirm = False userInfo = itchat.web_init() itchat.show_mobile_login() log.info('Start get contacts, this may take sometime') itchat.get_friends(True) log.info('Login successfully as %s' % userInfo['User']['NickName']) itchat.start_receiving()
def login(id): while True: #检查登录状态 status = itchat.check_login(id) print(config.uuid, status) #如果登录状态符合要求,就等待10s再重新检查状态 if status in ['200', '201']: print('Already login') time.sleep(10) #如果状态检查不符合要求,则进行登录,登录成功则获取uuid,并获取朋友,聊天室,公众号列表 elif status in ['400', '408', '0']: print('Need to login') try: itchat.auto_login(hotReload=True) itchat.send_msg('login successfully!', toUserName='******') config.uuid = itchat.get_QRuuid() get_friend_list() get_chart_room_list() get_mp_list() itchat.run() except: #如果失败,重试 time.sleep(10)
def bot_reply_controller(request): global uuid print('██wechat_bot_reply_server') waitForConfirm = False while 1: print(uuid) status = itchat.check_login(uuid) print(status) if status == '200': break elif status == '201': if waitForConfirm: print('[INFO] Please press confirm') waitForConfirm = True elif status == '408': print('[INFO] Reloading QR Code') uuid = auto_reply_service.open_QR() waitForConfirm = False itchat.web_init() itchat.show_mobile_login() itchat.get_friends(True) print('[INFO] Login successfully') itchat.start_receiving() if status == '200': @itchat.msg_register(TEXT) def simple_reply(msg): auto_reply_service.auto_reply(msg) itchat.run(debug=True) itchat.dump_login_status() else: itchat.auto_login() itchat.dump_login_status() print('Config stored, so exit.') return
def login_process(self): uuid = self.open_QR() waitForConfirm = False while 1: status = itchat.check_login(uuid) if status == '200': break elif status == '201': if waitForConfirm: self.output_info('Please press confirm') waitForConfirm = True elif status == '408': self.output_info('Reloading QR Code') uuid = self.open_QR() waitForConfirm = False userInfo = itchat.web_init() ProgramStatus.my_own_username = userInfo['User']['UserName'] itchat.show_mobile_login() itchat.start_receiving() itchat.get_friends(True) ProgramStatus.is_login = True print('Login successfully as %s' % userInfo['User']['NickName']) self.check_names_exist() self.programSignal.login_success_signal.emit()
def get_pic(friends_info): mkpath("/img") i = 1 for friend_info in friends_info: save_head(friend_info['UserName'], i) i += 1 os.chdir("..") def get_info(friend_list): sex_dict = {} sex_dict['0'] = "其他" sex_dict['1'] = "男" sex_dict['2'] = "女" friends_info = [] for friend in friend_list: item = {} item['NickName'] = friend['NickName'] item['HeadImgUrl'] = friend['HeadImgUrl'] item['Sex'] = sex_dict[str(friend['Sex'])] item['Province'] = friend['Province'] item['Signature'] = friend['Signature'] item['UserName'] = friend['UserName'] friends_info.append(item) save_info(friends_info) get_pic(friends_info) if itchat.check_login() != 200: itchat.auto_login(hotReload=True) get_info(itchat.get_friends(update=True))
def wechat_check_login(): return itchat.check_login()
def analysis(com_queue=None): global all_friend_list, friends_in_chatrooms, duplicate, has_return_qr,\ base_path, result_path, title_path, summary_path, shixoong_qr_path,\ user_header, user_nickname, \ friends_num, remarked_friends, star_friends # 扫码登录微信 init() if itchat.check_login(): itchat.logout() # 登录微信,需要扫面下方输出结果的二维码 # 网页版 # itchat.auto_login(enableCmdQR=True, qrCallback=qrcode_handle) # PC版 uuid = open_qr(com_queue=com_queue) waitForConfirm = False while 1: status = itchat.check_login(uuid) if status == '200': if com_queue: com_queue.put({"mode": 6}) break elif status == '201': if not waitForConfirm: print ('Please press confirm') # TODO 提示手机确认 if com_queue: com_queue.put({"mode":2}) waitForConfirm = True elif status == '408': print ('Reloading QR Code') uuid = open_qr(com_queue=com_queue) waitForConfirm = False itchat.web_init() itchat.show_mobile_login() # ------------------------------------------------------------------ """ 获取数据并去重 联系人列表 已保存到通讯录中群聊的人员 """ # 获取当前好友列表 _friends_list = itchat.get_friends(update=True) # 获取头像并保存本地待用 user = _friends_list[0] user.get_head_image(user_header) # 获取昵称 user_nickname = user.NickName # todo 回调登录成功 if com_queue: com_queue.put({"mode":3}) # 好友个数 friends_num = len(_friends_list[1:]) # 将好友列表加入最终朋友列表,去除自己 for one in _friends_list[1:]: remark = 0 star = 0 # 备注 if one.RemarkName and one.RemarkName is not "": remark = 1 remarked_friends += 1 # 星标 if one.StarFriend and one.StarFriend == 1: star = 1 star_friends += 1 friend = Friend(one.UserName, one.Sex, one.Province, one.City, remark, star) all_friend_list.append(friend) # 获取当前所有群聊列表 chat_room_list = itchat.get_chatrooms(update=True) # 获取微信群聊中的所有成员 if chat_room_list is None: print("你连一个群聊都没有找到~") else: print u"共找到群聊:%d个\n" % len(chat_room_list) #for room in tqdm(chat_room_list): for index, room in enumerate(chat_room_list): room_updated = itchat.update_chatroom(room.UserName, detailedMember=True) # print "正在处理:%d/%d,请稍后" % ((index + 1), len(chat_room_list)), '\r', # 获取一个群聊中,所有群成员的公开信息 # print "memberlist = %d/%d" % (len(room_updated.MemberList),len(chat_room_list)), '\r', for member in room_updated.MemberList: friend = Friend(member.UserName, member.Sex, member.Province, member.City) if friend not in all_friend_list: all_friend_list.append(friend) friends_in_chatrooms += 1 else: duplicate += 1 # break # for test progress = int((index+1) / float(len(chat_room_list)) * 100) # todo 更新进度条 if com_queue: com_queue.put({"mode":4, "progress": progress}) print u"\n连接了%d人, 群聊人数%d, 好友人数%d." % (len(all_friend_list), friends_in_chatrooms, friends_num) # ------------------------------------------------------------------ # 绘制数据 # 初始化表格元组数据 data_json = json.dumps(all_friend_list, cls=FriendEncoder) df = pd.read_json(data_json, orient="records") # 获取性别数据 male_number = len(df[df['sex'] == 1]) female_number = len(df[df['sex'] == 2]) unknown_sex_number = len(df[df['sex'] == 0]) sex_data = [male_number, female_number, unknown_sex_number] # 统计省份数据 # 省份名称集合 provinces = [] # 各省份人数 provinces_people = [] # 饼图中哪个突出 provinces_explode = [0.1] # 获得省份数据副本,已按数量排序 province_df = df['province'].value_counts().copy() # 丢弃其中省份为空的好友数据 # 统计前6省份 for p in province_df.keys(): if len(provinces) >= 6: break if not p: continue # 转为拼音 provinces.append("".join(lazy_pinyin(p)).title()) provinces_people.append(province_df[p]) provinces_explode.append(0) # 删除多余的一个0 provinces_explode.pop() # 进行城市数据显示 # 城市 cities = [] # 各城市对应人数 city_people = [] city_df = df['city'].value_counts().copy() # 丢弃其中城市为空的好友数据城 for c in city_df.keys(): if len(cities) >= 5: break if not c: continue # 转为拼音 # 优化城市字符显示 name_formatted = lazy_pinyin(c) name_formatted[0] = name_formatted[0].title() name_final = '' MAX_NAME_LENGTH = 8 for index, word in enumerate(name_formatted): if '\n' in name_final: last_newline = name_final.rindex('\n') str_temp = name_final[last_newline + 1:] else: str_temp = name_final str_temp += word if len(str_temp) > MAX_NAME_LENGTH: word = '\n' + word name_final += word cities.append(name_final) city_people.append(city_df[c]) # todo 注意由于plt在子线程中使用会出现问题,此处将plt生成图片部分转到主线程中执行。 if com_queue: com_queue.put({"mode": 10, "sex_data": sex_data, "provinces_data": {"provinces_people": provinces_people, "provinces": provinces, "provinces_explode": provinces_explode}, "city_data": {"cities": cities, "city_people": city_people} })
while uuid is None: uuid = itchat.get_QRuuid() time.sleep(1) output_info('Getting QR Code') if itchat.get_QR(uuid): break elif get_count >= 9: output_info('Failed to get QR Code, please restart the program') sys.exit() output_info('Please scan the QR Code') return uuid uuid = open_QR() 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 userInfo = itchat.web_init() itchat.show_mobile_login() itchat.get_friends(True) output_info('Login successfully as') itchat.start_receiving()
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
uuid = itchat.get_QRuuid() time.sleep(10) output_info('Getting QR Code') if itchat.get_QR(uuid): break elif get_count >= num: output_info('获取二维码出错,请重启程序') sys.exit() output_info('请重新扫二维码') return uuid #得到微信的UID1 uuid = open_QR() #已扫描二维码uuid ->'201' waitForConfirm = False while 1: 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()
def login_c(): itchat.check_login() return r()
def check_wx_login(): login_result = itchat.check_login() if '200' is not login_result: _logger.error('wx login fail') sys.exit(-2) return True
def check_login(): return itchat.check_login(qruuid)