def get_member_list(): python_chat_rooms = itchat.search_chatrooms(name='小猪的Python学习交流1群') if len(python_chat_rooms) > 0: group_username = python_chat_rooms[0]['UserName'] result = itchat.update_chatroom(group_username, detailedMember=True) member_python_list.clear() results = nickname_compile.findall(str(result)) for result in results: member_python_list.append(result) python_chat_rooms_2 = itchat.search_chatrooms(name='小猪的Python学习交流2群') if len(python_chat_rooms_2) > 0: group_username = python_chat_rooms_2[0]['UserName'] result = itchat.update_chatroom(group_username, detailedMember=True) member_python_list_2.clear() results = nickname_compile.findall(str(result)) for result in results: python_chat_rooms_2.append(result) android_chat_rooms = itchat.search_chatrooms(name='小猪的Android学习交流群') if len(android_chat_rooms) > 0: group_username = android_chat_rooms[0]['UserName'] result = itchat.update_chatroom(group_username, detailedMember=True) member_android_list.clear() results = nickname_compile.findall(str(result)) for result in results: member_android_list.append(result) speak_chat_rooms = itchat.search_chatrooms(name='技♂术交流🈲') if len(android_chat_rooms) > 0: group_username = speak_chat_rooms[0]['UserName'] result = itchat.update_chatroom(group_username, detailedMember=True) member_speak_list.clear() results = nickname_compile.findall(str(result)) for result in results: member_speak_list.append(result)
def getroom_message(): list = [] name = 'test' '''获取群的username,对群成员进行分析需要用到''' itchat.update_chatroom(FromUserName) RoomList = itchat.search_chatrooms(name=name) print(RoomList) if RoomList is None: print("%s group is not found!" % (name)) else: User_list = RoomList[0]['MemberList'] for User in User_list: UserName = User['UserName'] NickName = User['NickName'] display_name = User['DisplayName'] Updata_member(UserName, NickName, display_name) if display_name: Updata_invite_member(UserName, display_name) else: Updata_invite_member(UserName, NickName) dic = { 'member_num': UserName, 'member_name': NickName, 'group_num': FromUserName, 'group_name': name, 'display_name': display_name } IntoMysql_action(dic) list.append(UserName) return list
def get_names(msg): ''' 获取信息所属会话名称和信息属主昵称 ''' msg_user = msg['User'] if isinstance(msg_user, User): # 单人会话,会话名即用户昵称 nick_name = msg_user['NickName'] contact_name = nick_name return nick_name, contact_name # 多人会话,获取用户昵称 if 'ActualNickName' in msg and msg['ActualNickName']: nick_name = msg['ActualNickName'] else: msg_user = itchat.update_chatroom(msg_user['UserName']) from_user = msg_user.search_member(userName=msg['FromUserName']) nick_name = from_user['NickName'] # 多人会话,获取会话名 if 'NickName' in msg_user: contact_name = msg_user['NickName'] else: msg_user = itchat.update_chatroom(msg_user['UserName']) contact_name = msg_user['NickName'] return nick_name, contact_name
def delete_unchecked_member(memberList): if datetime.datetime.now().hour < 23: return '请在23时以后清理未签到成员!' itchat.get_chatrooms(update=True) chatroom = itchat.search_chatrooms('100days')[0] print(chatroom) itchat.update_chatroom(chatroom['UserName'], detailedMember=True) itchat.delete_member_from_chatroom(chatroom['UserName'], memberList) return '未签到成员清除完毕!'
def search_first_chatroom(chatroom_name): """根据群名称搜索群聊,并返回第一个""" rooms = itchat.search_chatrooms(chatroom_name) if not rooms: return None for one in rooms: if one['NickName'] == chatroom_name: room = one break else: room = rooms[0] itchat.update_chatroom(userName=room['UserName'], detailedMember=True) return itchat.search_chatrooms(userName=room['UserName'])
def get_waiting_list(): # get live chatroom list chatrooms = itchat.get_chatrooms() logger.debug( json.dumps([room['NickName'] for room in chatrooms], indent=2, ensure_ascii=False).encode('utf8')) lrsg_rooms = get_lrsg_rooms(chatrooms) # room member list could be empty, which needs to call update_chatroom need_refresh = False for room in lrsg_rooms: if len(room['MemberList']) == 0: logger.info( "room %s has empty MemberList, need to update_chatroom" % room['NickName']) need_refresh = True itchat.update_chatroom(room['UserName']) if need_refresh: logger.info("get_chatrooms again after update") chatrooms = itchat.get_chatrooms() lrsg_rooms = get_lrsg_rooms(chatrooms) # username is the reliable way to distinguish users r1_username_list = [ member['UserName'] for member in lrsg_rooms[0]['MemberList'] ] logger.debug("len(r1_username_list) = %s" % (len(r1_username_list))) # waiting list are the members that are in r2 and not in r1 waiting_list = [ member for member in lrsg_rooms[1]['MemberList'] if member['UserName'] not in r1_username_list ] logger.debug("len(waiting_list) = %s" % (len(waiting_list))) # write waiting list to a json file with open('waiting_list.json', 'w', encoding='utf-8') as f: json.dump([ "%s(%s)" % (member['NickName'], member['DisplayName']) for member in waiting_list ], f, ensure_ascii=False, indent=2) logger.info("waiting list is written to waiting_list.json")
def update_contacts(itchat): # This method SHOULD be executed after login friends = [{ 'username': f['UserName'], 'nickname': f['NickName'], 'remarkname': f['RemarkName'], 'sex': f['Sex'], 'city': f['City'] } for f in itchat.get_friends()] chatrooms = [{ 'encry_chatroom_id': r['EncryChatRoomId'], 'username': r['UserName'], 'nickname': r['NickName'], 'remarkname': r['RemarkName'], 'members': [{ 'nickname': m['NickName'] } for m in itchat.update_chatroom(r['UserName'])['MemberList']] } for r in itchat.get_chatrooms(update=True)] contacts = {'friends': friends, 'chatrooms': chatrooms} data = json.dumps(contacts, ensure_ascii=False) with open(config['contacts_storage_file'], 'w+', encoding='utf-8') as f: f.write(data)
def getName(chatroomName): itchat.get_chatrooms(update=True) cur_chatrooms = itchat.search_chatrooms(name=chatroomName) detailedChatroom = itchat.update_chatroom(cur_chatrooms[0]['UserName'], detailedMember=True) #print(json.dumps(cur_chatrooms)+"\n") return detailedChatroom["UserName"]
def group_pic(msg): group = itchat.get_chatrooms(update=True, ) from_user = '' for g in group: if g['NickName'] == '来123': #从群中找到指定的群聊 from_group = g['UserName'] ChatRoom = itchat.update_chatroom(from_group, detailedMember=True) for menb in ChatRoom['MemberList']: if menb['NickName'] == "柒年": #从群成员列表找到用户,只转发他的消息 from_user = menb['UserName'] for j in group: if j['NickName'] == '来': #把消息发到这个群 to_group = j['UserName'] if msg['ToUserName'] == from_group: if msg['FromUserName'] == from_user: msg['Text'](msg['FileName']) if msg['Type'] == "Picture": itchat.send_image( fileDir=msg['FileName'], toUserName=to_group) if msg['Type'] == "Recording": itchat.send_file( fileDir=msg['FileName'], toUserName=to_group) if msg['Type'] == "Attachment": itchat.send_file( fileDir=msg['FileName'], toUserName=to_group) if msg['Type'] == "Video": itchat.send_video( fileDir=msg['FileName'], toUserName=to_group)
def qun(): tongxuequn = '人文-信计B-2006级1班同学群' jinjiqun = '打开' memberList = itchat.update_chatroom(get_chatroom_username(jinjiqun), detailedMember=True) # print(len(memberList)) # print(memberList) sexy = {1: '男', 2: '女', 0: '其他'} gender = [] members = [] for x, y in memberList.items(): # 打印群内所有信息 print(x, y) n = 0 if x == 'MemberList': for z in y: # '''[z['UserName'],sexy[z['Sex']] ,z['Province'],z['City']]''' print(z['NickName'], z['DisplayName'], z['Province'], z['City']) itchat.send('@%s\u2005你好' % z['NickName'], toUserName=get_chatroom_username(jinjiqun)) time.sleep(0.5) n += 1 # 添加性别信息 # gender.append(sexy[z['Sex']]) # 打印出当前群内所有个人信息 for key, value in z.items(): print(key, value) print('--' * 10) print(n)
def getChatFriends(chatName): chatRoom = itchat.update_chatroom(getroom_message(chatName), detailedMember=True) list = chatRoom['MemberList'] print('群[%s]下载好友:%d 个' % (chatName, len(list))) return [(chatName, item['NickName'], item['RemarkName'], item['Province'], item['HeadImgUrl']) for item in list]
def update_chatroom(): try: data = json.loads(request.data) userName = data['userName'] return jsonify({'success': 1, 'data': itchat.update_chatroom(userName=userName)}) except Exception as e: return jsonify({'success': 0, 'msg': "Error {0}".format(str(e))})
def map(chatroomName): num = 0 chatrooms = itchat.get_chatrooms(update=True) for item in chatrooms: print (item["NickName"]) chatrooms = itchat.search_chatrooms(name=chatroomName) if chatrooms is None: print(u'没有找到群聊:' + chatroomName) else: if not os.path.exists("./" + chatroomName): os.mkdir("./" + chatroomName) chatroom = itchat.update_chatroom(chatrooms[0]['UserName']) counter = 0 for friend in chatroom['MemberList']: img = itchat.get_head_img(userName=friend["UserName"],chatroomUserName=chatrooms[0]['UserName']) fileImage = open("./" + chatroomName + "/" + str(counter) + ".jpg", 'wb') counter = counter + 1 try: fileImage.write(img) except: try: print (friend["NickName"] + " error.") except: print (friend["UserName"] + " error.") fileImage.close() num += 1
def wechatNotify(msg): # try: # 群信息 # print(msg.User) # 发消息人名称 print(msg.ActualNickName) # 发消息人id print(msg.ActualUserName) # print(msg.UserName) # 群名称 # print(msg.User.NickName) # 群id # print(msg.FromUserName) # 通过群id找到群中所有人 detailedChatroom = itchat.update_chatroom(msg.FromUserName, detailedMember=True) print(detailedChatroom) # 这里的userName是个info dict # 通过群聊来获得 userDict = {} for member in detailedChatroom.MemberList: # print(member) if msg.ActualUserName == member.UserName: userDict = member break # 用id或者info dict都无效 print(userDict) print(itchat.add_friend(userName=userDict, status=2))
def __init__(self, groupname): itchat.auto_login(True) itchat.run(blockThread=False) GroupName = groupname self.room = itchat.search_chatrooms('微信测试群')[0] self.room = itchat.update_chatroom(self.room['UserName'], detailedMember=True)
def send_special_wishes(chatroomName='微信群名'): itchat.get_chatrooms(update=True) chatrooms = itchat.search_chatrooms(name=chatroomName) if chatrooms is None: print(u'没有找到群聊:' + chatroomName) else: print('请输入要群发的信息,可以粘贴, 换行 # 结束') message = inputLine() chatroom = itchat.update_chatroom(chatrooms[0]['UserName']) for friend in chatroom['MemberList']: friend = itchat.search_friends(userName=friend['UserName']) # 如果不是演示目的,把下面的方法改为itchat.send即可 # RemarkName 你对好友的备注 NickName 好友自己的昵称 if friend: print(friend['RemarkName'] + ',' + message) time.sleep(.5) print('请检查信息是否有误,没有问题输入 s 发送') sendFlag = input() if sendFlag == 's': for friend in chatroom['MemberList']: friend = itchat.search_friends(userName=friend['UserName']) # 如果不是演示目的,把下面的方法改为itchat.send即可 # RemarkName 你对好友的备注 NickName 好友自己的昵称 if friend: itchat.send(friend['RemarkName'] + ',' + message, friend['UserName']) print(friend['RemarkName'] + '发送成功') time.sleep(.5) else: return
def recv_msg(msg): print(msg) if msg['Text'] == "100": ALREADY_SET = True itchat.send('输入群名,添加好友', toUserName='******') else: if msg['Text'] == "Test": itchat.send('输入200, 加好友', toUserName='******') else: chatroomName = "Test" print(chatroomName) itchat.get_chatrooms(update=True) chatrooms = itchat.search_chatrooms(name=chatroomName) if chatrooms is None: print(u'没有找到群聊:' + chatroomName) else: chatroom = itchat.update_chatroom(chatrooms[0]['UserName']) for friend in chatroom['MemberList']: friend = itchat.search_friends(userName=friend['UserName']) # 如果是演示目的,把下面的方法改为print即可 if friend != None: # print(friend) print(friend['UserName']) itchat.add_friend(userName=friend['UserName'], status=2) # itchat.add_member_into_chatroom('Test', [friend['UserName']]) # itchat.send_msg('Text message', toUserName=friend['UserName']) # print(REAL_SINCERE_WISH % (friend['DisplayName'] # or friend['NickName']), friend['UserName']) # itchat.send('hello', toUserName='******') itchat.send('欢迎使用本服务', toUserName=friend['UserName']) time.sleep(.5) else: print('no msg')
def analysis_chat_rooms(self): """获取群聊列表""" print("--->开始分析您的群聊数据") chat_rooms = itchat.get_chatrooms(update=True) for chat_room in chat_rooms[:-1]: chat_room_name = chat_room['NickName'] # 群聊名称 user_name = chat_room['UserName'] # 群聊id标志 room = itchat.update_chatroom(user_name, detailedMember=True) member_count = room['MemberCount'] # 群聊人数 # 群聊用户列表 for member in room['MemberList']: # avatar = 'https://wx.qq.com'.format(member['HeadImgUrl']) # 头像 self._count_sex(member['Sex']) self._count_province(member['Province']) print('群聊 %s 共有 %d 人 , 其中 %d 位男性 , %d 位女性 , %d 位性别未知' % (chat_room_name, member_count, self.male_num, self.female_num, self.unknown_gender)) # 省份数据处理(可选) self._handle_province(member_count) # 绘制性别柱图, 省份饼图(可选) self._plt_gender_bar(chat_room_name), self._plt_province_pie( chat_room_name) self._reset_data()
def CheckSex(): '''检测没有备注性别的用户''' ChatRoom = itchat.update_chatroom(getroom_message(), detailedMember=True) total = len(ChatRoom['MemberList']) for i in range(total): if ChatRoom['MemberList'][i]['Sex'] != 1 and ChatRoom['MemberList'][i][ 'Sex'] != 2: print("这位朋友性别不详:")
def get_room_from_name(itchat, name): ''' 根据房间名字,返回房间对象 ''' itchat.dump_login_status() rooms = itchat.search_chatrooms(name=name) if rooms is None: return None return itchat.update_chatroom(rooms[0]['UserName'], detailedMember=True)
def wellcome(msg): item = get_group_id(u'测试群') chatroom = itchat.update_chatroom(item) # print(chatroom['MemberList']) if '加入了群聊' in msg['Content']: itchat.send( "@" + chatroom['MemberList'][-1]['NickName'] + "\n欢迎新同学!大家关于社团或是学校有什么问题都可以在群上直接问哦!我们会尽力解答的。\n进群都改下备注哦~\n“年级_专业_姓名”\n例如:17_软件技术_谢心如 \n如果想报名我们社团,可以关注创软公众号回复“加入”", item)
def print_members(userName): try: members = itchat.update_chatroom(userName=userName)['MemberList'] except: return False for member in members: print(member['NickName']) print('{} members'.format(len(members))) return True
def get_group_members(): itchat.auto_login(hotReload=True) itchat.dump_login_status() room = itchat.search_chatrooms(name=u'xxxxxxx') gsq = itchat.update_chatroom(room[0]['UserName'], detailedMember=True) members = pd.DataFrame(gsq['MemberList']) members.to_csv('groupmembers.csv', index=False) print('Successfully saved group members information to csv file!')
def getName(chatroomName): cur_chatrooms = itchat.search_chatrooms(name=chatroomName) #print 'cur_chatrooms'+cur_chatrooms if (len(cur_chatrooms) == 0): return detailedChatroom = itchat.update_chatroom(cur_chatrooms[0]['UserName'], detailedMember=True) #print(json.dumps(cur_chatrooms)+"\n") return detailedChatroom["UserName"]
def update_members(chatroom): global room room = chatroom chatroom = itchat.search_chatrooms(name=room) room_id = chatroom[0]['UserName'] memberList = itchat.update_chatroom(room_id, detailedMember=True)['MemberList'] for member in memberList: update_display(member['NickName'], member['DisplayName'])
def get_member_list(): chat_rooms = itchat.search_chatrooms(name='小猪的Python学习交流群') if len(chat_rooms) > 0: global group_username group_username = chat_rooms[0]['UserName'] result = itchat.update_chatroom(group_username, detailedMember=True) member_list.clear() results = nickname_compile.findall(str(result)) for result in results: member_list.append(result)
def get_group_chat(): # 获取群聊信息 all=itchat.get_chatrooms() for a in all: print(a) # 获取特定群聊 s=itchat.search_chatrooms(name='LitterCoder') print(s) # 获取群聊用户列表 memberlist=itchat.update_chatroom('@abcdefg1234567') print(memberlist)
def init_info(): """ 初始化数据 """ global wechat_nick_name global IS_OPEN_EMAIL_NOTICE wechat_nick_name = itchat.search_friends()['NickName'] # 获取此微信号的昵称 set_note(u'微信号『{}』登录成功!'.format(wechat_nick_name)) try: if IS_OPEN_EMAIL_NOTICE: yag.login() print(u'邮件提醒功能已开启。') else: print(u'邮件提醒功能已关闭。') except Exception as exception: # print(str(exception)) print(u'邮件配置有错,已关闭邮件提醒功能。') IS_OPEN_EMAIL_NOTICE = False if IS_AUTO_ADD_FRIEND: print(u'自动同意添加好友已开启,同意关键词:{}。'.format(add_friend_keys)) else: print(u'自动同意添加好友已关闭。') if IS_OPEN_ADD_GROUP: # 已开启邀请功能 print(u'自动邀请群聊功能已开启,加群关键词:{}'.format(add_group_keys)) itchat.get_chatrooms(update=True) # 更新群聊数据。 for group_name in group_name_list: group_list = itchat.search_chatrooms( name=group_name) # 通过群聊名获取群聊信息 group_info = {} if group_list: group_uuid = group_list[0]['UserName'] group = itchat.update_chatroom(group_uuid, detailedMember=True) group_uuid = group['UserName'] group_info['group_name'] = group_name # 群聊名称 group_info['group_uuid'] = group_uuid # 群聊 uuid count = len(group['MemberList']) # 群聊人数 group_info['count'] = count member_uid_list = uid_list_compile.findall( str(group)) # 根据正则取出群组里所有用户的 uuid。 if member_uid_list: group_info['member_uid_list'] = member_uid_list group_infos_dict[group_uuid] = group_info print(u'群聊『{}』已注册,人数为:{}。'.format(group_name, count)) else: note = u'没有找到群聊「{}」 注意:必须要把需要的群聊保存到通讯录。'.format(group_name) set_note(note) break else: print(u'自动邀请群聊功能已关闭。') print(u'项目初始化已完成...开始正常工作。') print('-' * 50)
def auto_response(msg): # 群聊中发了文字,触发该函数,采用图灵机器人自动回复 group_name = itchat.search_chatrooms( userName=msg['FromUserName'])['NickName'] find_name = itchat.search_friends(userName=msg['FromUserName']) # ipdb.set_trace() if group_name not in args.shut_up_status: args.shut_up_status[group_name] = True memberdict = { m['UserName']: m for m in itchat.update_chatroom(msg['FromUserName'])['MemberList'] } args.memberlist[group_name] = memberdict if not find_name: find_name = args.memberlist[group_name][msg['ActualUserName']] input_text = msg['Text'] # 从好友发过来的消息 name = '主人' if find_name['NickName'] in args.root_names else find_name[ 'NickName'] if ('isAt' in msg and msg['isAt']) or ('IsAt' in msg and msg['IsAt']): if len(input_text.split()) == 1: if name == '主人': threshold = 10 nick = '' else: if np.random.randint(10) < 5: nick = '大佬' else: nick = '小哥哥' if find_name['Sex'] == 1 else '小姐姐' threshold = 4 ind = 0 if np.random.randint(10) < threshold else 1 num = np.random.randint(len(args.quick_res[ind])) itchat.send_msg('%s%s,%s' % (name, nick, args.quick_res[ind][num]), toUserName=msg['FromUserName']) args.shut_up_status[group_name] = False return if msg['Text'].split()[-1] in ['闭嘴', '别吵', '安静']: args.shut_up_status[group_name] = True itchat.send_msg('好的,%s' % name, toUserName=msg['FromUserName']) return if '出来' in msg['Text']: #.split()[-1] in ['出来', '说话']: args.shut_up_status[group_name] = False itchat.send_msg('好的,%s' % name, toUserName=msg['FromUserName']) return if not args.robot_shut_up and not args.shut_up_status[group_name]: if '6' == msg['Text'] or (msg['Text'].isdigit() and '6' in msg['Text']): itchat.send_msg('6' * np.random.randint(99), toUserName=msg['FromUserName']) else: get_response(msg, name) else: args.logger.write('%s: %s\n' % (name, msg['Text']))
def get_unchecked_member(): itchat.get_chatrooms(update=True) chatroom = itchat.search_chatrooms('100days')[0] #print(chatroom) itchat.update_chatroom(chatroom['UserName'], detailedMember=True) memberList = [] print(datetime.datetime.now().strftime("%Y-%m-%d")) unchecked_users = User.select().where( User.updated_date < datetime.datetime.now().strftime("%Y-%m-%d")) for user in unchecked_users: print(user.username) print([ m for m in chatroom['MemberList'] if m['UserName'] == user.openid ]) if [m for m in chatroom['MemberList'] if m['UserName'] == user.openid]: memberList.append([ m for m in chatroom['MemberList'] if m['UserName'] == user.openid ][0]) return memberList
def send_special_wishes(chatroomName='wishgroup'): itchat.get_chatrooms(update=True) chatrooms = itchat.search_chatrooms(name=chatroomName) if chatroomName is None: print(u'search result is none') else: chatroom = itchat.update_chatroom(chatroom[0]['UserName']) for friend in chatroom['MemberList']: friend = itchat.search_friends(userName=friend['UserName']) print(REAL_SINCERE_WISH % (friend['DisplayName'] or friend['NickName']), friend['UserName']) time.sleep(.5)
def get_newusers(chatroom): chatroom = itchat.update_chatroom(chatroom['UserName']) newusers = [] for friend in chatroom['MemberList']: #print("friend name is : %s " % (friend['DisplayName'] or friend['NickName'])) existfriend = itchat.search_friends(userName=friend['UserName']) if existfriend is not None: print('%s is in the friend list' % (friend['DisplayName'] or friend['NickName'])) pass else: newusers.append(friend) return newusers