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 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_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 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 readygo(self): init_result = self.itchat.web_init() self.itchat.dump_login_status('data/itchat{}.pk1'.format( self.current_user.get_id())) wechat_init = Process_Wechat(db=self.db, app=self.app, itchat=self.itchat, current_user=self.current_user) wechat_init.process_web_init(init_result) self.chatroomList = self.itchat.originInstance.storageClass.chatroomList wechat_init.process_chatroom(self.chatroomList) wechat_init.process_wechatuser(self.chatroomList) self.welcome_list = wechat_init.load_welcomeinfo() ad_notifs, ad_uncensor, ad_keywords = wechat_init.load_adv_rule() self.rule = {'ad_rule': [], 'keyword_rule': []} #清零 self.rule['ad_rule'].extend([ad_notifs, ad_uncensor, ad_keywords]) k_notifs, k_uncensor, k_keyword = wechat_init.load_keyword_rule() self.rule['keyword_rule'].extend([k_notifs, k_uncensor, k_keyword]) print('rule', self.rule) self.auto_replies = wechat_init.load_auto_reply() self.register() itchat.show_mobile_login() # itchat.get_contact(True) itchat.start_receiving() itchat.run()
def get_produce_information(self): url = 'http://192.168.9.164:88/realTimeMonitor/update' # IOT 本地网络入口 header = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36' } first_row = 'IOT assistant\n_____________________________\n机台|图号|数量|运行|停机|报警\n' text = '' response = requests.get(url, headers=header) data = response.json() IOT_informations = data.get('serverinformations') # 定义数据抓取规则 for x in IOT_informations: if x.get('states') == 3: # 红色警报 text = text + '{} {}#{}#{}^{} {} {}\n'.format(x.get('machineId'),x.get('productName').replace('N/A',''),x.get('producedParts'),\ x.get('totalRunTime')[:5],x.get('totalDownTime')[:5],x.get('alarmMsg'),x.get('idleMsg')) # 时间去除秒数[:5],图号N/A替换成空 elif x.get('states') == 1: # 绿色,正常生产 text = text + '{} {}#{}#{}^{}\n'.format(x.get('machineId'),x.get('productName').replace('N/A',''),\ x.get('producedParts'),x.get('totalRunTime')[:5],x.get('totalDownTime')[:5]) elif x.get('states') == 2: # 黄色警报 pass # 待补充 elif x.get('states') == 4: # 灰色警报,OffLine text = text + '{} {}#{}#{}^{} {}\n'.format(x.get('machineId'),x.get('productName').replace('N/A',''),x.get('producedParts'),\ x.get('totalRunTime')[:5],x.get('totalDownTime')[:5],'OffLine') if len(text) > 0: # 信息非空白,则发送至微信 msg = first_row + text + '_____________________________\n' + time.ctime( time.time()) # 末行添加当前日期时间 #user = itchat.search_friends(name='张总')[0]['UserName'] # name=备注名 #itchat.send(msg,toUserName=user) # filehelper:文件传输助手 itchat.send(msg, toUserName='******') itchat.show_mobile_login() else: pass
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 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): 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 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 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(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 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 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
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'] itchat.run()
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 run(self): userInfo = itchat.web_init() itchat.show_mobile_login() itchat.get_contact(True) print('Login successfully as %s' % userInfo['User']['NickName'])
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} })