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(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 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 ready(app, itchat, current_user): init_result = itchat.web_init() wechat_init = Process_Wechat(db=db, app=app, itchat=itchat, current_user=current_user) wechat_init.process_web_init(init_result) # process_web_init(init_result,current_user.id,app) global chatroom_list chatroom_list = itchat.originInstance.storageClass.chatroomList wechat_init.process_chatroom(chatroom_list) wechat_init.process_wechatuser(chatroom_list) global welcome_list welcome_list = wechat_init.load_welcomeinfo() # 加载过滤条件 ad_notifs, ad_uncensor, ad_keywords = wechat_init.load_adv_rule() rule['ad_rule'].extend([ad_notifs, ad_uncensor, ad_keywords]) k_notifs, k_uncensor, k_keyword = wechat_init.load_keyword_rule() rule['keyword_rule'].extend([k_notifs, k_uncensor, k_keyword]) print('rule', rule) itchat.show_mobile_login() # itchat.get_contact(True) itchat.start_receiving() 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 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 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 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 login(self, exitCallback, uuid=None): 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 if uuid is None: statusFile = getProperty(self.configFile, 'wechat-status-file') itchat.auto_login(hotReload=True, statusStorageDir=statusFile) else: if not isLoginned(uuid): raise Exception('Failed to login with {}'.format(uuid)) userInfo = itchat.web_init() itchat.show_mobile_login() itchat.get_friends(True) itchat.start_receiving(exitCallback) self.me = itchat.search_friends() print self.me['NickName'], 'is working' self.watchFriends = list() names = getProperty(self.configFile, 'wechat-watch-friends').split(';') for name in names: friends = itchat.search_friends(name=name) self.watchFriends.extend(friends) self.watchGroups = list() names = getProperty(self.configFile, 'wechat-watch-groups').split(';') for name in names: groups = itchat.search_chatrooms(name=name) self.watchGroups.extend(groups) self.searchReplyPlate = getProperty(self.configFile, 'search-reply-plate') itchat.run(blockThread=False) # Run in a new thread self.run()
def run(self): itchat.auto_login() userInfo = itchat.web_init() self._signal_2.emit('成功登陆!账号:%s,可以关闭二维码了!' % userInfo['User']['NickName']) self.myUserName = userInfo['User']['UserName'] self.get_friendslist() self.get_chatroomslist() itchat.run()
def start(): @itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING,PICTURE, RECORDING, ATTACHMENT, VIDEO,FRIENDS]) def recive_contact_msg(msg): contact_name = get_contact_name(msg) try: wechatMain.recive_message(msg,contact_name) notify('TWchat',"new message from: "+contact_name) except AttributeError: pass @itchat.msg_register(TEXT, isGroupChat=True) def recive_group_msg(msg): group_name = get_group_name(msg) try: wechatMain.recive_message(msg,group_name) notify('TWchat',"new message from: "+group_name) except AttributeError: pass return def on_contact_item_click(button,info): wechatMain.chatListBox.addNewChat(info[0],info[1]) wechatMain.set_current_chat(info[0],info[1]) wechatMain.chatListBox.show_chat() return def on_chat_item_click(button,info): wechatMain.set_current_chat(info[0],info[1]) return palette = [ ('left', 'black', 'light gray'), ('right', 'black', 'dark cyan'), ('button', 'dark green','black'), ('mybg', 'black','dark cyan'), ('tobg', 'dark blue','light gray'), ('edit', 'dark cyan','black'), ('bg', 'dark green', 'black'),] print (''' _____ _ _ _____ _ _ ___ _____ |_ _|| | | |/ __ \| | | | / _ \ |_ _| | | | | | || / \/| |_| |/ /_\ \ | | | | | |/\| || | | _ || _ | | | | | \ /\ /| \__/\| | | || | | | | | \_/ \/ \/ \____/\_| |_/\_| |_/ \_/ ''') wechatMain = wegui.WechatMain(palette) itchat.auto_login(enableCmdQR=2,hotReload=True) itchat.run(blockThread=False) userInfo =itchat.web_init()['User'] owner_id = userInfo['UserName'] owner_name = userInfo['NickName'] contactlist= itchat.get_friends(update=True) chatlist = itchat.get_chatrooms() #contactlist = sorted(contactlist,key=lambda x:(x['RemarkPYInitial'],x['PYInitial'])) contactlist = sorted(contactlist,key=lambda x:(lazy_pinyin(get_name(x)))) wechatMain.initUserInfo(owner_id,owner_name,on_contact_item_click,on_chat_item_click,contactlist,chatlist) wechatMain.bind_itchat(itchat) wechatMain.createLoop()
def newWXInstance(): global friends global chatrooms userInfo = itchat.web_init() itchat.show_mobile_login() friends = itchat.get_friends(update=True) chatrooms = itchat.get_chatrooms(update=True) itchat.start_receiving() itchat.run() print('itchat end.')
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 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 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 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(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_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()
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() # 用当天的时间作为文件名.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']
# 2. Count。待显示的最近联系人数量。 # 3. ContactList。最近联系人信息。 # 4. SyncKey。同步口令。有数量count,还有信息id? # 5. User。登录者信息。 # 6. Chatset。聊天集? # 7. 'SKey': '@crypt_8dc3f7b8_e63df55a027c431016c33d3135f2d9fa' # 8. 'ClientVersion': 654314551, # 9. 'SystemTime': 1584465493, # 10. 'GrayScale': 1, # 11. 'InviteStartCount': 40, # 12. 'MPSubscribeMsgCount': 4, 待显示的公众号数量 # 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])
rec_msg = get_resp(msg.Text) itchat.send_msg(rec_msg, friend) print("\033[1;35m" + msg.User.NickName + "\033[0m" + " 发送文字消息:" + msg.Text) print("\033[1;35m自己回复:\033[0m" + rec_msg) elif msg.Type == 'Picture': print("\033[1;35m" + msg.User.NickName + "\033[0m" + " 发送图片消息") itchat.send_image('shuai.jpg', friend) elif msg.Type == 'Recording': # 下载MP3语音 msg.Text(msg.FileName) # 转换成wav wavName = msg.FileName.split('.')[0] + '.wav' get_wav(msg.FileName, wavName) # 语音识别 s = bai_api(wavName) # 调取机器人 rec_msg = get_resp(s['result'][0]) itchat.send_msg(rec_msg, friend) print("\033[1;35m" + msg.User.NickName + "\033[0m" + " 发送语音消息,识别出为:" + s['result'][0]) print("\033[1;35m自己回复:\033[0m" + rec_msg) os.remove(msg.FileName) os.remove(wavName) itchat.auto_login(hotReload=True) self_userName = itchat.web_init()["User"]["UserName"] # print(self_userName) itchat.run()
def loginCallback(): Zhu = itchat.search_friends(nickName='诸隆隆') codeClass.teacher = Zhu[0] print(Zhu[0]) initInfo = itchat.web_init() print(initInfo)
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()
def get(self, request, uuid): #未登录情况下,会报错,捕捉错误,返回首页扫二维码 try: status = itchat.check_login(uuid) if status == "200": Signature = [] userInfo = itchat.web_init() #初始化微信 # 使用一个字典统计好友男性和女性的数量 sex_dict = {'male': 0, 'female': 0, "unknown": 0} # 省份统计表 province_dict = { '北京': 0, '上海': 0, '天津': 0, '重庆': 0, '河北': 0, '山西': 0, '吉林': 0, '辽宁': 0, '黑龙江': 0, '陕西': 0, '甘肃': 0, '青海': 0, '山东': 0, '福建': 0, '浙江': 0, '台湾': 0, '河南': 0, '湖北': 0, '湖南': 0, '江西': 0, '江苏': 0, '安徽': 0, '广东': 0, '海南': 0, '四川': 0, '贵州': 0, '云南': 0, '内蒙古': 0, '新疆': 0, '宁夏': 0, '广西': 0, '西藏': 0, '香港': 0, '澳门': 0 } friends_list = itchat.get_friends(update=True)[1:] #获取好友列表 for friends in friends_list: # 统计性别 if friends["Sex"] == 1: sex_dict['male'] += 1 elif friends["Sex"] == 2: sex_dict['female'] += 1 else: sex_dict["unknown"] += 1 #省份统计 #判断省份是否在字典内 if friends["Province"] in province_dict.keys(): province_dict[friends["Province"]] += 1 else: province_dict[friends["Province"]] = 1 Signature.append(friends["Signature"]) #把好友个性签名连接 Signature_str = "".join(Signature) #去掉html标签 Signature_str = remove_tags(Signature_str) # 文本预处理 pattern = re.compile( u'\t|\n|\.|-|:|;|\)|\(|\?|"') # 定义正则表达式匹配模式 Signature_data = re.sub(pattern, '', Signature_str) # 将符合模式的字符去除 # 文本分词 seg_list_exact = jieba.cut(Signature_data, cut_all=False) # 精确模式分词 object_list = [] remove_words = [ u'的', u',', u'和', u'是', u'随着', u'对于', u'对', u'等', u'能', u'都', u'。', u' ', u'、', u'中', u'在', u'了', u'通常', u'️', u'✝', u'你' ] # 自定义去除词库 for word in seg_list_exact: # 循环读出每个分词 if word not in remove_words: # 如果不在去除词库中 object_list.append(word) # 分词追加到列表 # 词频统计 word_counts = collections.Counter(object_list) # 对分词做词频统计 word_counts_top20 = word_counts.most_common(60) # 获取前60最高频的词 all_word_counts_dict = {} for word_counts in word_counts_top20: all_word_counts_dict[word_counts[0]] = int(word_counts[1]) return render( request, "firends.html", { "male": sex_dict['male'], "female": sex_dict['female'], "unknown": sex_dict["unknown"], "all_province": province_dict, "all_word_counts_dict": all_word_counts_dict }) else: return redirect(reverse("wx")) except: return redirect(reverse("wx"))
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} })
def Log_in(self): self.userInfo = itchat.web_init() print('Welcom back!' + self.userInfo['User']['NickName'])
def init_username(self): """ 初始化微信所需数据 """ dic = itchat.web_init() print(dic) return dic['User']['NickName']
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
def run(self): itchat.auto_login() userInfo = itchat.web_init() self._signal_2.emit('成功登陆! 账号: %s' % userInfo['User']['NickName']) self._signal_2.emit('准备就绪,可以关闭二维码了!') itchat.run()
def run(self): userInfo = itchat.web_init() itchat.show_mobile_login() itchat.get_contact(True) print('Login successfully as %s' % userInfo['User']['NickName'])