def main(): # 微信登陆 itchat.auto_login(hotReload=True) # 获取微信好友信息 friends = itchat.get_friends(update=True) # 判断数据库是否存有数据,有则清空数据表 sql1 = 'SELECT COUNT(1) FROM wx_friend_list LIMIT 1;' row_count = readDb(sql1) # print(row_count[0]['count']) # sql_test = 'INSERT INTO wx_friend_list (Sex) values(1);' # print(sql_test) # writeDb(sql_test) if row_count[0]['count'] != 0: truncate_sql = 'TRUNCATE TABLE wx_friend_list;' writeDb(truncate_sql) if True: print('********************清空表成功.********************') print('********************开始写入数据库*****************') # 拼接insert Sql语句 i = 0 for friend in friends: del friend['MemberList'] cols = ','.join(friend.keys()) # qmarks = ','.join(['%s']*len(friend)) values = tuple(friend.values()) sql = 'INSERT INTO wx_friend_list({}) VALUES {};'.format(cols, values) # print(sql) writeDb(sql) # 写入数据库 if True: i += 1 print('已写入{}条数据'.format(i)) if friend == friends[-1]: print('********************数据写入完成********************')
def get_friend_status(friend): ownAccount = itchat.get_friends(update=True)[0] if friend['UserName'] == ownAccount['UserName']: return u'Own account' elif itchat.search_friends(userName=friend['UserName']) is None: return u'Not a friend' else: room = chatroom or get_chatroom() r = itchat.add_member_into_chatroom(room['UserName'], [friend]) # r = itchat.update_chatroom(chatroom) if r['BaseResponse']['ErrMsg'] == u'请求成功': if len(r['MemberList']) == 0: return u'No member in the chatroom' else: status = r['MemberList'][0]['MemberStatus'] itchat.delete_member_from_chatroom(room['UserName'], [friend]) return { 3: u'该好友已经将你加入黑名单。', 4: u'该好友已经将你删除。', }.get(status,u'该好友仍旧与你是好友关系。') # if status == 3: # return u'该好友已经将你加入黑名单。' # elif status == 4: # return u'该好友已经将你删除。' # else: # return get(status) + u'该好友仍旧与你是好友关系。' else: return r['BaseResponse']['ErrMsg'] + u'无法获取好友状态,预计已经达到接口调用限制'
def main(): #itchat.auto_login(hotReload=True, enableCmdQR=2, statusStorageDir='account.pkl') #通过命令行打印登入二维码 global robot_enabled, owner robot_enabled = len(sys.argv) > 1 and sys.argv[1] itchat.auto_login(hotReload=True) owner = itchat.get_friends()[0] itchat.run()
def demo(): # 可以保持一段时间登录状态,而不用每次运行代码都要扫码登录了 itchat.auto_login(hotReload=True) itchat.dump_login_status() #遍历好友列表 friends = itchat.get_friends(update=True)[:] for friend in friends: ''' 典型属性内容如下: {'MemberList': <ContactList: []>, 'VerifyFlag': 0, 'DisplayName': '', 'EncryChatRoomId': '', 'Alias': '', 'PYQuanPin': 'Evi1hui', 'PYInitial': 'EVI1HUI', 'RemarkName': '', 'AppAccountFlag': 0, 'City': '阳泉', 'ChatRoomId': 0, 'AttrStatus': 2147715109, 'UniFriend': 0, 'OwnerUin': 0, 'Statues': 0, 'StarFriend': 0, 'ContactFlag': 3, 'HeadImgUrl': '/cgi-bin/mmwebwx-bin/webwxgeticon?seq=654224580&username=@78606d673dcff895a468688273bb5e92862c15d9a0e8a574865785c8a0354660&skey=@crypt_cd4d9fd6_f8d94dff59afaff6b231f3f4b8aa1e15', 'Sex': 1, 'Uin': 0, 'HideInputBarFlag': 0, 'MemberCount': 0, 'Signature': '沉默的大多数', 'NickName': 'Evi1hui', 'RemarkPYQuanPin': '', 'UserName': '******', 'IsOwner': 0, 'RemarkPYInitial': '', 'KeyWord': 'wan', 'Province': '山西', 'SnsFlag': 177} ''' if friend['NickName'] == '兜哥的生活号': #print(friend['NickName']) print(friend) #发送的主键为UserName字段的值 itchat.send_msg('Nice to meet you!','@1df002b437271f75f1afd07b937801b3a7211aad221e24115fb153674ca044b7')
def sendall(msg): itchat.auto_login(hotReload=True) itchat.dump_login_status() # 遍历好友列表 friends = itchat.get_friends(update=True)[:] for friend in friends: ''' 典型属性内容如下: {'MemberList': <ContactList: []>, 'VerifyFlag': 0, 'DisplayName': '', 'EncryChatRoomId': '', 'Alias': '', 'PYQuanPin': 'Evi1hui', 'PYInitial': 'EVI1HUI', 'RemarkName': '', 'AppAccountFlag': 0, 'City': '阳泉', 'ChatRoomId': 0, 'AttrStatus': 2147715109, 'UniFriend': 0, 'OwnerUin': 0, 'Statues': 0, 'StarFriend': 0, 'ContactFlag': 3, 'HeadImgUrl': '/cgi-bin/mmwebwx-bin/webwxgeticon?seq=654224580&username=@78606d673dcff895a468688273bb5e92862c15d9a0e8a574865785c8a0354660&skey=@crypt_cd4d9fd6_f8d94dff59afaff6b231f3f4b8aa1e15', 'Sex': 1, 'Uin': 0, 'HideInputBarFlag': 0, 'MemberCount': 0, 'Signature': '沉默的大多数', 'NickName': 'Evi1hui', 'RemarkPYQuanPin': '', 'UserName': '******', 'IsOwner': 0, 'RemarkPYInitial': '', 'KeyWord': 'wan', 'Province': '山西', 'SnsFlag': 177} ''' UserName=friend['UserName'] NickName=friend['NickName'] City=friend['City'] #print("UserName:%s NickName:%s City:%s" % (UserName,NickName,City)) # 发送的主键为UserName字段的值 text="hi %s,%s" %(NickName,msg) # 休眠10秒 time.sleep(10) print(text) itchat.send_msg(text, UserName)
def push_wechat(name, real_price, real_percent, type): name='wwwei' itchat.auto_login(hotReload=True) account=itchat.get_friends(name) for i in account: if i['PYQuanPin']==name: toName=i['UserName'] content=name+' ' + str(real_price)+' '+ str(real_percent)+' percent '+ type itchat.send(content,toUserName=toName)
def getSignature(): itchat.login() friends = itchat.get_friends(update=True) file = open('sign.txt', 'a', encoding='utf-8') for f in friends: signature = f["Signature"].strip().replace("emoji", "").replace("span", "").replace("class", "") rec = re.compile("1f\d+\w*|[<>/=]") signature = rec.sub("", signature) file.write(signature + "\n")
def headImg(): itchat.login() friends = itchat.get_friends(update=True) # itchat.get_head_img() 获取到头像二进制,并写入文件,保存每张头像 for count, f in enumerate(friends): # 根据userName获取头像 img = itchat.get_head_img(userName=f["UserName"]) imgFile = open("img/" + str(count) + ".jpg", "wb") imgFile.write(img) imgFile.close()
def get_users(chatroomUserName=''): # chatroom = itchat.update_chatroom(chatroom['UserName']) # itchat.get_chatrooms(update=True) chatrooms = itchat.search_chatrooms(chatroomUserName); if chatrooms and chatroomUserName: return chatrooms[0]['MemberList'] # for friend in chatroom['MemberList']: # yield friend else: friend = itchat.get_friends(update=True) return friend
def get_chatroom(): global chatroom if chatroom is None: itchat.get_chatrooms(update=True) chatrooms = itchat.search_chatrooms(chatroomUserName); if chatrooms: return chatrooms[0] else: chatroom = itchat.create_chatroom(itchat.get_friends()[1:4], topic=chatroomUserName) if chatroom['BaseResponse']['ErrMsg'] == '': chatroom['UserName']=chatroomUserName return chatroom else: return chatroom
def get_chatroom(): global CHATROOM if CHATROOM is None: itchat.get_chatrooms(update=True) chatrooms = itchat.search_chatrooms(CHATROOM_NAME) if chatrooms: return chatrooms[0] else: r = itchat.create_chatroom(itchat.get_friends()[1:4], topic=CHATROOM_NAME) if r['BaseResponse']['ErrMsg'] == '': CHATROOM = {'UserName': r['ChatRoomName']} return CHATROOM else: return CHATROOM
def __init__(self, roomNicks): global wxRooms, myUid itchat.auto_login(hotReload=True, enableCmdQR=2, exitCallback=wechatExit) all_rooms = itchat.get_chatrooms(update=True) for r in all_rooms: if r['NickName'] in roomNicks: wxRooms[r['UserName']] = r['NickName'] wxRoomNicks[r['NickName']] = r['UserName'] logger.info('Room {} found.'.format(r["NickName"])) else: logger.info('{}: {}'.format(r['UserName'], r['NickName'])) friends = itchat.get_friends() myUid = friends[0]["UserName"]
def parse_signature(): itchat.login() siglist = [] friedns = itchat.get_friends(update=True)[1:] for i in friedns: signature = i["Signature"].strip().replace("span", "").replace("class", "").replace("emoji", "") rep = re.compile("1f\d+\w*|[<>/=]") signature = rep.sub("", signature) siglist.append(signature) text = "".join(siglist) with io.open('text.txt', 'a', encoding='utf-8') as f: wordlist = jieba.cut(text, cut_all=True) word_space_split = " ".join(wordlist) f.write(word_space_split) f.close()
def get_friends_status(friend): ownAccount = itchat.get_friends(update=True)[0] if friend['UserName'] == ownAccount['UserName']: return u'检测到本人账号。' elif itchat.search_friends(userName=friend['UserName']) is None: return u'该用户不在你的好友列表中。' else: chatroom = CHATROOM or get_chatroom() if chatroom is None: return CHATROOM_MSG r = itchat.add_member_into_chatroom(chatroom['UserName'], [friend]) if r['BaseResponse']['ErrMsg'] == '': status = r['MemberList'][0]['MemberStatus'] itchat.delete_member_from_chatroom(chatroom['UserName'],[friend]) return { 3: u'该好友已经将你加入黑名单。', 4: u'该好友已经将你删除。', }.get(status, u'该好友仍旧与你是好友关系。') else: return u'无法获取好友状态,预计已经达到接口调用限制。'
def get_prob(msg): reply = '' friend = itchat.search_friends(userName = msg['FromUserName']) ownAccount = itchat.get_friends(update=True)[0] if friend['UserName'] == ownAccount['UserName']: now = datetime.utcnow() now = time.mktime(now.timetuple()) df_future = pd.read_csv('data/btc_usd_full_next_quarter_future.csv','r',delimiter='\t', index_col=None) df_spot = pd.read_csv('data/btc_usd_full_spot.csv','r',delimiter='\t', index_col=None) price_f = get_price(now, df_future) price_s = get_price(now, df_spot) if msg['Text'] == u'diff': return str(price_f - price_s) if msg['Text'] == u'future': return str(price_f) if msg['Text'] == u'spot': return str(price_s)
def testcase1(): id='@5493580a22c9ba5db849ba33d0911d3d' content=datetime.datetime.now().strftime("%H:%M:%S") itchat.auto_login(hotReload=True) #itchat.auto_login() itchat.send(content,toUserName='******') account=itchat.get_friends(u'wwwei') print(account) print(type(account)) for i in account: #print(type(i)) #print(i) if i[u'PYQuanPin']==u'爱惟创意': print(i['UserName']) #print(i) #itchat.send(content, toUserName=id) print('done')
def getSex(): itchat.login() friends = itchat.get_friends(update=True) sex = dict() for f in friends: if f["Sex"] == 1: # 男 sex["man"] = sex.get("man", 0) + 1 elif f["Sex"] == 2: # 女 sex["women"] = sex.get("women", 0) + 1 else: # 未知 sex["unknown"] = sex.get("unknown", 0) + 1 # 柱状图展示 for i, key in enumerate(sex): plt.bar(key, sex[key]) plt.savefig("getsex.png") #保存图片 plt.ion() plt.pause(5) plt.close() #图片显示5s,之后关闭
def private_reply(msg): global flag global choose global friend_chatting global me if flag==0: choose = choose_check() #init your choose.can not change once it start the mode friendList = itchat.get_friends(update=True)[1:] #get all your friends for friend in friendList: if friend['UserName'] == msg['FromUserName']: if friend['NickName'] == 'Wendy':#change this to your nickname on wechat. me = friend['UserName'] break #save the key,use to do judgement(in order not to speak to myself) hint = 'match!' + (friend['NickName']) + (" is chating with u!") friend_chatting = friend['NickName']#current chatting with print '`'*len(hint) print hint print '`'*len(hint) if msg['FromUserName']!=me: print friend_chatting,"says: ",msg['Content'] if choose == 'n' and flag==1: itchat.send('come back later,I\'m busy right now.',toUserName = msg['FromUserName']) print 'have send autoreply.' elif choose=='y' and flag==1: text = raw_input( ">>>enter your message:(use enter to jump reply\n" ).decode(sys.stdin.encoding or locale.getpreferredencoding(True)) text.decode('utf-8') if not text=='\n':#three space enter in. itchat.send(text,toUserName=msg['FromUserName']) print 'reply have sent.' elif msg['FromUserName']==me: #in this circumstance,i chat on the phone at the same time.so no reply needed. print 'I do some talking on other client.',msg['Text']
def parse_friedns(): itchat.login() text = dict() friedns = itchat.get_friends(update=True)[0:] print(friedns) male = "male" female = "female" other = "other" for i in friedns[1:]: sex = i['Sex'] if sex == 1: text[male] = text.get(male, 0) + 1 elif sex == 2: text[female] = text.get(female, 0) + 1 else: text[other] = text.get(other, 0) + 1 total = len(friedns[1:]) print("男性好友: %.2f%%" % (float(text[male]) / total * 100) + "\n" + "女性好友: %.2f%%" % (float(text[female]) / total * 100) + "\n" + "不明性别好友: %.2f%%" % (float(text[other]) / total * 100)) draw(text)
def reply(msg): reply = '' friend = itchat.search_friends(userName = msg['FromUserName']) ownAccount = itchat.get_friends(update=True)[0] if friend['UserName'] == ownAccount['UserName']: if msg['Text'] == u'price': prices = u'' for product in products: price_info = get_price(product)[0] bids = price_info['bids'][0][0] asks = price_info['asks'][0][0] out = 'bids: '+ bids + ' asks: '+ asks + '\n' prices = prices + out return prices else: return u'good' #return u'Own account' #return u'你是那颗星星,我是你旁边的这颗星,我的整个轨迹是被你影响的,即使有一天这颗星星熄灭了,它变成了暗物质,它变成了看不见的东西,它依然在影响着我的轨迹,你的出现永远改变着我的星轨,无论你在哪里。' # 还是同样的雨天,还是相同的地点,在转角的咖啡馆,我又再一次遇到了那张我永远忘不掉的脸。四目相对,终于,她颤抖地问我,你还可以像以前一样牵着我过马路吗?我说:“奶奶,上次你走到马路中间就躺下了,讹了我几个月的工资啊 !”' elif friend is None: return u'Not a friend' elif friend.get('NickName') in [u'风早',u'Lemon']: reply = ' test autoreply ' return reply # or defaultReply
def testcase2(): itchat.auto_login(hotReload=True) print(itchat.get_friends())
# -*- coding: UTF-8 -*- import itchat import re itchat.login() user = itchat.get_friends() i = str(user[:1]) print(i) info = i[8:-2] print(info) name = str(re.findall(r"'NickName': '(.+?)'", info))[2:-2] sign = str(re.findall(r"'Signature': '(.+?)'", info))[2:-2] sex = str(re.findall(r"'Sex': (.+?),", info))[2:-2] uin = str(re.findall(r"'Uin': (.+?),", info))[2:-2] print(name) print(sign) print(sex) print(uin)
def reply(msg): reply = '' friend = itchat.search_friends(userName = msg['FromUserName']) ownAccount = itchat.get_friends(update=True)[0] if friend['UserName'] == ownAccount['UserName']:
download_dir = args.dir print("Logging in...") itchat.auto_login(hotReload=True) if args.list_chatroom: print("Getting chatrooms...") chatrooms = itchat.get_chatrooms(update=True) for chatroom in tqdm(chatrooms, desc="[Updating Groupchats]"): tqdm.write(chatroom['NickName']) exit() download_args = dict() if args.type == "self" or args.type == "all": print("Loading contact...") for mem in itchat.get_friends(update=True): download_args[mem['UserName']] = { "userName": mem['UserName'], "picDir": os.path.join( download_dir, slugify(f"{mem['NickName']}_{mem['RemarkName']}") + ".jpg") } if args.type == "groupchat" or args.type == "all": print("Getting groupchats...") chatrooms = itchat.get_chatrooms(update=True) # Nickname PYQuanPin RemarkPYQuanPin if not args.name: print(
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import itchat import time import os itchat.auto_login(hotReload = True, enableCmdQR=2) members = itchat.get_friends(update = True) f = open("friends.txt", "w") for m in members: f.write(str(m) + "\n") f.close() os.sys.exit(1) i = 0 ms = [] nickNames = ['何继中 智能焊接机器人', 'LHC', '三栖', '燕儿翩翩飞'] #ms.append(itchat.search_friends(nickName = 'LHC')) for member in members: if member['NickName'] in nickNames: friends = itchat.search_friends(userName = member['UserName'])
def save_receive_msg(msg): msg_receive_time = strftime("%Y-%m-%d %H:%M:%S", localtime()) if 'ActualNickName' in msg: msg_from_nickname = msg['ActualNickName'] msg_from = msg_from_nickname msg_from_username = msg['ActualUserName'] friends = itchat.get_friends(update=True) for friend in friends: if msg_from_username == friend['UserName']: if friend['RemarkName']: msg_from = friend['RemarkName'] else: msg_from = friend['NickName'] break """ groups = itchat.get_chatrooms(update=True) for group in groups: if msg['FromUserName'] == group['UserName']: group_name = group['NickName'] group_menber_count = group['MemberCount'] break if not group_name: group_name = '未命名群聊' group_name = group_name + '(%s人)' % str(group_menber_count) msg_from = group_name + '-->' + msg_from """ else: try: msg_from = itchat.search_friends( userName=msg['FromUserName'])['RemarkName'] if not msg_from: msg_from = itchat.search_friends( userName=msg['FromUserName'])['NickName'] except: msg_from = 'WeChat Official Accounts' msg_send_time = msg['CreateTime'] msg_id = msg['MsgId'] msg_content = None msg_link = None # 文本或者好友推荐 if msg['Type'] == 'Text' or msg['Type'] == 'Friends': msg_content = msg['Text'] print('[Text/Friends]: %s' % msg_content) # 附件/视屏/图片/语音 elif msg['Type'] == 'Attachment' or msg['Type'] == 'Video' or msg[ 'Type'] == 'Picture' or msg['Type'] == 'Recording': msg_content = msg['FileName'] msg['Text'](str(msg_content)) print('[Attachment/Video/Picture/Recording]: %s' % msg_content) # 位置信息 elif msg['Type'] == 'Map': x, y, location = re.search( "<location x=\"(.*?)\" y=\"(.*?)\".*label=\"(.*?)\".*", msg['OriContent']).group(1, 2, 3) if location is None: msg_content = r"纬度: " + x.__str__() + ", 经度: " + y.__str__() else: msg_content = r"" + location print('[Map]: %s' % msg_content) # 分享的音乐/文章 elif msg['Type'] == 'Sharing': msg_content = msg['Text'] msg_link = msg['Url'] print('[Sharing]: %s' % msg_content) FACEPACKAGE = msg_content MSGINFO.update({ msg_id: { "msg_from": msg_from, "msg_send_time": msg_send_time, "msg_receive_time": msg_receive_time, "msg_type": msg['Type'], "msg_content": msg_content, "msg_link": msg_link } })
def getFriends(self): lists = itchat.get_friends(update=True) return lists
def receive_msg(msg): global face_bug msg_time_rec = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) #接收消息的时间 if 'ActualNickName' in msg: from_user = msg['ActualUserName'] #群消息的发送者,用户的唯一标识 msg_from = msg['ActualNickName'] #发送者群内的昵称 friends = itchat.get_friends(update=True) #获取所有好友 for f in friends: if from_user == f['UserName']: #如果群消息是好友发的 if f['RemarkName']: # 优先使用好友的备注名称,没有则使用昵称 msg_from = f['RemarkName'] else: msg_from = f['NickName'] break groups = itchat.get_chatrooms(update=True) #获取所有的群 for g in groups: if msg['FromUserName'] == g['UserName']: #根据群消息的FromUserName匹配是哪个群 group_name = g['NickName'] group_menbers = g['MemberCount'] break group_name = group_name + "(" + str(group_menbers) + ")" gname = g['UserName'] else: if itchat.search_friends( userName=msg['FromUserName'])['RemarkName']: #优先使用备注名称 msg_from = itchat.search_friends( userName=msg['FromUserName'])['RemarkName'] else: msg_from = itchat.search_friends( userName=msg['FromUserName'])['NickName'] #在好友列表中查询发送信息的好友昵称 group_name = "" gname = "" msg_time = msg['CreateTime'] #信息发送的时间 msg_id = msg['MsgId'] #每条信息的id msg_content = None #储存信息的内容 msg_share_url = None #储存分享的链接,比如分享的文章和音乐 if msg['Type'] == 'Text' or msg['Type'] == 'Friends': #如果发送的消息是文本或者好友推荐 msg_content = msg['Text'] #如果发送的消息是附件、视频、图片、语音 elif msg['Type'] == "Attachment" or msg['Type'] == "Video" \ or msg['Type'] == 'Picture' \ or msg['Type'] == 'Recording': msg_content = msg['FileName'] #内容就是他们的文件名 msg['Text'](rev_tmp_dir + str(msg_content)) #下载文件 elif msg['Type'] == 'Map': #如果消息为分享的位置信息 x, y, location = re.search( "<location x=\"(.*?)\" y=\"(.*?)\".*label=\"(.*?)\".*", msg['OriContent']).group(1, 2, 3) if location is None: msg_content = r"纬度->" + x.__str__() + " 经度->" + y.__str__( ) #内容为详细的地址 else: msg_content = r"" + location elif msg['Type'] == 'Sharing': #如果消息为分享的音乐或者文章,详细的内容为文章的标题或者是分享的名字 msg_content = msg['Text'] msg_share_url = msg['Url'] #记录分享的url face_bug = msg_content #将信息存储在字典中,每一个msg_id对应一条信息 time.sleep(2) msg_information.update({ msg_id: { "msg_from": msg_from, "msg_time": msg_time, "msg_time_rec": msg_time_rec, "msg_type": msg["Type"], "msg_content": msg_content, "msg_share_url": msg_share_url, "group_name": group_name, "gname": gname } }) del_info = [] for k in msg_information: m_time = msg_information[k]['msg_time'] #取得消息时间 if int(time.time()) - m_time > 130: #如果消息时间是130秒甚至更久之前的,则删除。 del_info.append(k) if del_info: for i in del_info: msg_information.pop(i)
'Picture': 'img', 'Video': 'vid' }.get(msg['Type'], 'fil'), msg['FileName']) @itchat.msg_register(FRIENDS) def add_friend(msg): itchat.add_friend(**msg['Text']) # 该操作会自动将新好友的消息录入,不需要重载通讯录 itchat.send_msg('Nice to meet you!', msg['RecommendInfo']['UserName']) @itchat.msg_register(TEXT, isGroupChat=True) def text_reply(msg): if msg['isAt']: itchat.send( u'@%s\u2005I received: %s' % (msg['ActualNickName'], msg['Content']), msg['FromUserName']) itchat.auto_login(True) # 登陆的时候使用命令行显示二维码 itchat.run() # 获取自己的用户信息,返回自己的属性字典 itchat.get_friends() # 获取特定 UserName 的用户信息 itchat.get_friends(userName='******') # 获取任何一项等于 name 键值的用户 itchat.get_friends(name='littlecodersh') # 获取分别对应相应键值的用户 itchat.get_friends(wechatAccount='littlecodersh') # 三、四项功能可以一同使用 itchat.get_friends(name='LittleCoder 机器人', wechatAccount='littlecodersh')
#!/usr/local/bin/python # -*- coding: utf-8 -*- import itchat import pathlib import PIL.Image as Image import math import image itchat.auto_login(hotReload=True) friends = itchat.get_friends(update=True)[0:] # 核心:得到friends列表集,内含很多信息 # print("授权微信用户为:"+ user) # user = '******' user = pathlib.Path(user) if not user.exists(): user.mkdir() # 创建文件夹用于装载所有好友头像 num = 0 for i in friends: img = itchat.get_head_img(userName=i["UserName"]) with open(user / ("%d.jpg" % num), 'wb') as fileImage: fileImage.write(img) num += 1 print("所有好友头像数:%d" % num) eachsize = int(math.sqrt(640 * 640 / num)) # 先圈定每个正方形小头像的边长,如果嫌小可以加大 print("小正方形头像边长:%d" % eachsize) numrow = int(640 / eachsize) print("一行小头像数:%d" % numrow) numcol = int(math.ceil(num / numrow)) # 向上取整
import itchat itchat.auto_login(enableCmdQR=-1) accounts = itchat.get_friends() name_find = '失足' b = itchat.search_friends(nickname=name_find) user_num = b[0]['User']
def run(self): itchat.auto_login(hotReload=self.hotReload) self.friends = itchat.get_friends() self.current_name = self.friends[0].NickName os.chdir(self.base_path + '/' + self.current_name) itchat.new_instance().run()
import itchat # 统计好友性别 # 登录微信 # itchat.login() itchat.auto_login(hotReload=True) # 获取微信好友列表 friends = itchat.get_friends()[0:] male = 0 female = 0 other = 0 #print(friends) for i in friends[0:]: sex = i['Sex'] # print(sex) if sex == 1: male += 1 elif sex == 2: female += 1 else: other += 1 # 微信好友总数 total = len(friends[1:]) print("好友总数:%d" % total) print("男性好友:%.2f%%" % (float(male) / total * 100)) print("女性好友:%.2f%%" % (float(female) / total * 100))
@itchat.msg_register(itchat.content.TEXT) def print_content(msg): NickName = msg['User']['NickName'] user = itchat.search_friends(name=NickName)[0] text = msg['Text'] if text in message_dict.keys(): user.send(message_dict[text]) else: user.send(u"你好啊%s,我目前还不支持这个功能"%NickName) if __name__ == '__main__': itchat.auto_login() friends = itchat.get_friends(update=True)[0:]#获取好友信息 friends_list = [] for friend in friends: 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_list.append(item) #print(item) save_data(friends_list)
table = data.sheet_by_index(0) nrows = table.nrows print(nrows) names=[] for i in range(1,nrows): itmes = table.row_values(i) if(str(itmes[3])=='是'): names.append(str(itmes[1])) print(names) print(len(names)) itchat.auto_login(True) friendList=itchat.get_friends(update=True)[1:] sexDict={} nick_names=[] total=len(friendList) for friend in friendList: nick_names.append(friend['UserName']+' '+friend['NickName']+' '+friend['RemarkName']) print(nick_names) send_name=[] value="hi,这是定向消息,发自^(00)^ 。请填写问卷,请回复: 是 " for i in names:
import itchat Wchat = itchat.auto_login(hotReload=True) friends = itchat.get_friends()[1:] print(friends) friend_Uid = "" n = input("请输入好友的备注名称:") for i in friends: if i["RemarkName"] == n: print("已经找到了好友的UID哦...") friend_Uid = i["UserName"] break tex = input("send message:") itchat.send_msg(tex, friend_Uid) @itchat.msg_register(itchat.content.TEXT) def text_reply(msg): reply_text = msg['Text'] return reply_text t = text_reply() print(t) itchat.run()
def main(): itchat.auto_login() friends = itchat.get_friends(update=True)[0:] get_sex(friends) get_word(friends)
import itchat itchat.login() # itchat.send('hello', 'tony55199293') friends = itchat.get_friends(update=True)[0:] male = female = other = 0 for i in friends[1:]: sex = i["Sex"] if sex == 1: male += 1 elif sex == 2: female += 1 else: other += 1 print("male", male) print("female", female) print("other", other)
def get(): itchat.auto_login() friends = itchat.get_friends(update=True) return friends
def get_friend(msg): ownAccount = itchat.get_friends(update=True)[0] if msg['ToUserName'] != ownAccount['UserName']: return friendStatus = get_friend_status(msg['RecommendInfo']) itchat.send(friendStatus)
import itchat itchat.auto_login(hotReload=True) #自动登录 wxFriends = itchat.get_friends(update=True) #获取所有好友信息 sex = [] man = woman = sum = 0 for friend in wxFriends[0:]: sex = friend["Sex"] if sex == 1: man += 1 elif sex == 0: woman += 1 sum = man + woman print("微信中男性人数为:", man) print("微信中女性人数为:", woman) print("微信中的总人数为:", sum)
block = False for arg in args: block = block or (nickname == arg) # 根据昵称过滤需要屏蔽的对象 if block and not isGroup: print("自己人,别乱来: {} ---> {}".format(nickname, text)) return block if __name__ == '__main__': itchat.auto_login(hotReload=True) itchat.show_mobile_login() friends = itchat.get_friends() myself = itchat.get_friends()[0]["UserName"] # chat_rooms = itchat.get_chatrooms(update=True) # 存放接受消息的信息 msg_info = {} # 好友分析 + 词云图 toggle = wx.instance() if toggle.analysis.isAllEnabled: Analytics.wechat_friends_analysis(friends) Analytics.wechat_signature_words(friends) Analytics.file_classify("png", "PNG") Analytics.file_classify("html", "HTML")
def Revocation(msg): # 处理指令 itchat.get_friends(update=True) #print("Test",msg) if msg['ToUserName'] == "filehelper" and msg['Type'] == "Text": result = Execution.Execution(msg) if result[0] == 0: itchat.send(result[1] + r"文件:" + result[2] + r" 失败", toUserName="******") elif result[0] == 1: itchat.send(r"删除文件:" + result[2] + r" 成功", toUserName="******") else: pass return mytime = time.localtime() # 这儿获取的是本地时间 # 获取用于展示给用户看的时间 2017/03/03 13:23:53 msg_time_touser = mytime.tm_year.__str__() \ + "/" + mytime.tm_mon.__str__() \ + "/" + mytime.tm_mday.__str__() \ + " " + mytime.tm_hour.__str__() \ + ":" + mytime.tm_min.__str__() \ + ":" + mytime.tm_sec.__str__() msg_id = msg['MsgId'] # 消息ID msg_time = msg['CreateTime'] # 消息时间 if itchat.search_friends(userName=msg['FromUserName']): if itchat.search_friends(userName=msg['FromUserName'])['RemarkName']: msg_from = itchat.search_friends( userName=msg['FromUserName'])['RemarkName'] # 消息发送人备注 elif itchat.search_friends( userName=msg['FromUserName'])['NickName']: # 消息发送人昵称 msg_from = itchat.search_friends( userName=msg['FromUserName'])['NickName'] # 消息发送人昵称 else: msg_from = r"读取发送消息好友失败" else: msg_from = msg['ActualNickName'] msg_type = msg['Type'] # 消息类型 msg_content = None # 根据消息类型不同,消息内容不同 msg_url = None # 分享类消息有url # 图片 语音 附件 视频,可下载消息将内容下载暂存到当前目录 if msg['Type'] == 'Text': msg_content = msg['Text'] elif msg['Type'] == 'Picture': msg_content = msg['FileName'] msg['Text'](msg['FileName']) shutil.move(msg_content, r".\\Cache\\") elif msg['Type'] == 'Card': msg_content = msg['RecommendInfo']['NickName'] + r" 的名片" elif msg['Type'] == 'Map': x, y, location = re.search( "<location x=\"(.*?)\" y=\"(.*?)\".*label=\"(.*?)\".*", msg['OriContent']).group(1, 2, 3) if location is None: msg_content = r"纬度->" + x.__str__() + " 经度->" + y.__str__() else: msg_content = r"" + location elif msg['Type'] == 'Sharing': msg_content = msg['Text'] msg_url = msg['Url'] elif msg['Type'] == 'Recording': msg_content = msg['FileName'] msg['Text'](msg['FileName']) shutil.move(msg_content, r".\\Cache\\") elif msg['Type'] == 'Attachment': msg_content = msg['FileName'] msg['Text'](msg['FileName']) shutil.move(msg_content, r".\\Cache\\") elif msg['Type'] == 'Video': msg_content = msg['FileName'] msg['Text'](msg['FileName']) shutil.move(msg_content, r".\\Cache\\") elif msg['Type'] == 'Friends': msg_content = msg['Text'] # print(r"消息提取", # {"msg_from": msg_from, "msg_time": msg_time, "msg_time_touser": msg_time_touser, "msg_type": msg_type, # "msg_content": msg_content, "msg_url": msg_url}) print("消息提取", msg) # 更新字典 # {msg_id:(msg_from,msg_time,msg_time_touser,msg_type,msg_content,msg_url)} msg_store.update({ msg_id: { "msg_from": msg_from, "msg_time": msg_time, "msg_time_touser": msg_time_touser, "msg_type": msg_type, "msg_content": msg_content, "msg_url": msg_url } }) # 清理字典 ClearTimeOutMsg()
import itchat import matplotlib.pyplot as plt itchat.auto_login(hotReload=False) itchat.dump_login_status() we_friend = itchat.get_friends(update=True)[:] total = len(we_friend[1:]) man = woman = other = 0 for fri_info in we_friend[1:]: # print('fri_info:', fri_info) sex = fri_info['Sex'] # 如果sex=1 代表男性 sex=2代表女性 if sex == 1: man += 1 elif sex == 2: woman += 1 else: other += 1 man_ratio = int(man)/total * 100 # 用来正常显示中文标签plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号plt.figure(figsize=(5, 5)) # 绘制的图片为正圆sex_li = ['男', '女', '其他']radius = [0.01, 0.01, 0.01] # 设定各项距离圆心n个半径colors = ['red', 'yellowgreen', 'lightskyblue']proportion = [man_ratio, woman_ratio, other_ratio]plt.pie(proportion, explode=radius, labels=sex_li, colors=colors, autopct='%.2f%%') # 绘制饼图# 加入图例 loc = 'upper right' 位于右上角 bbox_to_anchor=[0.5, 0.5] # 外边距 上边 右边 borderaxespad = 0.3图例的内边距plt.legend(loc="upper right", fontsize=10, bbox_to_anchor=(1.1, 1.1), borderaxespad=0.3)# 绘制标题plt.title('微信好友性别比例') # 展示plt.show()100 woman_ratio = int(woman)/total * 100 other_ratio = int(other)/total * 100 plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号 plt.figure(figsize=(5, 5)) # 绘制的图片为正圆 sex_li = ['男', '女', '其他'] radius = [0.01, 0.01, 0.01] # 设定各项距离圆心n个半径 colors = ['red', 'yellowgreen', 'lightskyblue'] proportion = [man_ratio, woman_ratio, other_ratio]
#先加一个群里面的好友,然后把群中的人邀请加入另一个群 import itchat import time # 自动登录 itchat.auto_login(hotReload=True) print(itchat.get_friends()[0]) # 获取群聊列表 rooms = itchat.get_chatrooms() # 用户输入要转移到的群名称: # bRoomName = input('要转移到的群名称:') bRoomName = "测试B群" # 声明总用户的列表 allMemList = [] # 根据群名称得到群对象 bRoom = itchat.search_chatrooms(name=bRoomName) # 遍历所有的群 for room in rooms: # 获得每个群的群成员列表 memList = itchat.update_chatroom(room.UserName).MemberList # 将每个群成员加入总用户列表 allMemList.append(memList) # 遍历群成员列表 for mem in memList: # 获得每个成员的用户名(此处可扩展得到签名 备注 城市 性别等信息) userName = mem['UserName'] print(mem) ################正式启动 ############################### # 添加好友 if itchat.add_friend(userName=userName, status=2): print('添加成功') else:
arr2 = ['0'] * other #未知 arr.extend(arr1) arr.extend(arr2) plt.hist(arr) plt.show() msg = '好友总数:' + str(total) + '\n' +'男性比例:%2f%%' % (float(male) / total * 100) + '\n' +'女性比例:%2f%%' % (float(female) / total * 100) + '\n' +'未知性别:%2f%%' % (float(other) / total * 100) return msg if __name__ == '__main__': itchat.login() # itchat.send('Hello, filehelper', toUserName='******') #测试是否可以使用发送给文件助手消息 friends = itchat.get_friends(update=True) loginPer = friends[0]["NickName"] + ".txt" # print(friends) # 设置需要爬取的信息字段 result = [('RemarkName', '备注'), ('NickName', '微信昵称'), ('Sex', '性别'), ('City', '城市'), ('Province', '省份'), ('ContactFlag', '联系标识'), ('UserName', '用户名'), ('SnsFlag', '渠道标识'), ('Signature', '个性签名')] for user in friends: with open(loginPer, 'a', encoding='utf8') as fh: fh.write("-----------------------\n") for r in result: with open(loginPer, 'a', encoding='utf8') as fh: fh.write(r[1] + ":" + str(user.get(r[0])) + "\n") print("完成") msg = wechat(friends) itchat.send(msg,toUserName='******')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author :mabowen # @Time :2018/8/15 19:56 import itchat, time """ 检测微信单删 """ # 登陆 a = itchat.auto_login() print(a) # 获取好友列表 friendList = itchat.get_friends(update=True)[1:] num = [0, 1] def send(g, num): itchat.send('జ్ఞ ా', friendList[g + num]['UserName']) print( (friendList[g + num]['RemarkName'] or friendList[g + num]['NickName']), '已发送') itchat.send('正在开始测试', 'filehelper') # 预估时间 needtime = round(1 + int(len(friendList)) / 2 / 60, 2) itchat.send( '共' + str(len(friendList)) + '人' + '\n预计需要' + str(needtime) + 'min', 'filehelper') # 循环给各个好友发送信息,1s发两条 for g in range(0, len(friendList), 2):
elif msg['FromUserName'] == servername: message = json.loads(msg['Text']) if message['MessageType'] == 1: # the result of authetication # format: {'MessageType' : 1, 'ToUserName' : ToUserName, 'AutheticationResult' : Ture or False} if message['AuthenticationResult'] == True: send('绑定成功', message['ToUserName']) else: send('绑定失败,用户名或密码错误', message['ToUserName']) elif message['MessageType'] == 2: # General message to client or Required Schedulelist # format: {'MessageType' : 2, 'ToUserName' : ToUserName, 'Message' : Message} send(message['Message'], message['ToUserName']) else: # UserGuide send( '若要绑定用户,请以 用户+空格+你的用户名+空格+密码+空格+你的密码 的形式回复,例如:"用户 user 密码 123456"', msg['FromUserName']) except: print("Exception happen") pass itchat.auto_login(hotReload=True) a = itchat.get_friends() itchat.run() b = a
313000 儿歌类 314000 诗词类""" if code == 302000: return r["text"], r["list"] if code == 100000: return r["text"] if code == 200000: return r["text"], r["url"] if code == 313000: return r["text"], r["function"] if code == 314000: return r["text"], r["function"] if code == 308000: return r["text"], r["list"] # 自动回复 # 封装好的装饰器,当接收到的消息是Text,即文字消息 @itchat.msg_register('Text') def text_reply(msg): # 当消息不是由自己发出的时候 return u"[师傅不在,我是悟空]{}".format(tulin_robot(msg['Text'])) # 回复给好友 if __name__ == '__main__': itchat.auto_login(enableCmdQR=2) # 获取自己的UserName myUserName = itchat.get_friends(update=True)[0]["UserName"] itchat.run(debug=True)
logging.info(u"[" + msg["FromUserName"] + u"] - " + msg["Text"]) if msg["FromUserName"] == config["my_user_name"]: return ret = "" for period in config["period"]: if (is_in_period(period["start"], period["end"])): if is_first_access(msg): ret = u"{},{}。".format(period["reason"], period["reply"]) ret += u"\n(回复?查看更多功能)" else: ret = question_answer(msg) if ret == "": ret = direct_response(msg) if ret == "": ret = poem(msg) if ret == "": ret = tuling(msg) if ret != "": ret = u"[自动回复]\n" + ret msg.user.send(ret) logging.info(u"[此乃自动回复] - " + ret) break if __name__ == '__main__': itchat.auto_login(enableCmdQR=2, hotReload=True) config = json.loads(config) config["my_user_name"] = itchat.get_friends(update=True)[0]["UserName"] itchat.run()
#https://www.cnblogs.com/ouyangping/p/8453920.html #已经会使用登录登出,发文字文件图片信息,群发,获取朋友列表,公众号列表 import itchat as wx, time from itchat.content import * wx.auto_login(True) wx.login() wx.logout() #发送信息,这里toUserName参数是朋友的UserName, #类似于'@a62007da23b483439c6262894fdfd337e5858c3c68d8eea591608b6cd62a13e5' wx.send('123', toUserName='******') wx.send('123', toUserName=wx.get_friends()[3]['UserName']) #还有一种方法是 friend = wx.search_friends(name='柴小起')[0] friend.send('hello') #单纯发送信息 wx.send_msg('456', 'filehelper') #发图片 wx.send('@[email protected]', 'filehelper') #发文件 x.send('@[email protected]', 'filehelper') #返回完整的好友列表 fs = wx.get_friends() fs[0]['UserName']
if msg["FromUserName"] == config["my_user_name"]: return ret = "" for period in config["period"]: if (is_in_period(period["start"], period["end"])): if is_first_access(msg): ret = u"{},{}。".format(period["reason"], period["reply"]) ret += u"\n(回复?查看更多功能)" else: ret = question_answer(msg) if ret == "": ret = direct_response(msg) if ret == "": ret = poem(msg) if ret == "": ret = tuling(msg) if ret != "": ret = u"[自动回复]\n" + ret msg.user.send(ret) logging.info(u"[此乃自动回复] - " + ret) break if __name__ == '__main__': itchat.auto_login(enableCmdQR=2, hotReload=True) config = json.loads(config) config["my_user_name"] = itchat.get_friends(update=True)[0]["UserName"] itchat.run()
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 get_friend_list(): config.friends_nickname_list = [ i['NickName'] for i in itchat.get_friends() ] print(config.friends_nickname_list)
def getFriends(self): friends = itchat.get_friends(update=True)[0:] return friends
def text_reply(msg): auto_reply_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'auto_reply.json') friends=itchat.get_friends(update=True) time_now = int(time.time()) if any(word in msg['Text'] for word in ["开启自动回复", "关闭自动回复"]): for i in range(len(friends)): if((friends[i]['PYQuanPin'] == 'MasonPioneerYoung') and (msg['User']['PYQuanPin'] == 'MasonPioneerYoung')): if msg['Text'] == '开启自动回复': result = {'auto_reply': 1,'last_modify':time_now} with open(auto_reply_file, 'w') as out_file: json.dump(result, out_file) return '[已开启自动回复]' else: result = {'auto_reply': 0,'last_modify':time_now} with open(auto_reply_file, 'w') as out_file: json.dump(result, out_file) return '[已关闭自动回复]' try: with open(auto_reply_file, 'r') as in_file: auto_reply = json.load(in_file) except IOError: pass obj = infoparsing.textParsing(msg['Text'],friends,msg['User']['PYQuanPin']) res = obj.done() if time_now - auto_reply['last_modify'] > 1800: auto_reply['auto_reply'] = 1 result = {'auto_reply': 0,'last_modify':time_now} with open(auto_reply_file, 'w') as out_file: json.dump(result, out_file) if auto_reply['auto_reply'] == 1 and res == '': now = int(time.time()) time_now = datetime.datetime.now() current_date = time_now.strftime('%Y-%m-%d') work_st = current_date+' 09:00:00' work_ts = int(time.mktime(time.strptime(work_st, "%Y-%m-%d %H:%M:%S"))) work_et = current_date+' 19:00:00' work_te = int(time.mktime(time.strptime(work_et, "%Y-%m-%d %H:%M:%S"))) # fz_st = '2018-07-01 10:40:30' # fz_ts = int(time.mktime(time.strptime(fz_st, "%Y-%m-%d %H:%M:%S"))) # fz_et = '2018-07-16 12:00:00' # fz_te = int(time.mktime(time.strptime(fz_et, "%Y-%m-%d %H:%M:%S"))) # if((now>fz_ts)and(now<fz_te)): # st = current_date+' 20:00:00' # ts = int(time.mktime(time.strptime(st, "%Y-%m-%d %H:%M:%S"))) # et = current_date+' 23:59:59' # te = int(time.mktime(time.strptime(et, "%Y-%m-%d %H:%M:%S"))) # if((now>ts)and(now<te)): # return '在看世界杯,有事请留言' if((now>work_ts)and(now<work_te)): return '' else: return '现在有点忙,有事请留言' else: return res
def __init__(self): print('login...') itchat.auto_login(enableCmdQR=True, hotReload=True) self.friends = itchat.get_friends(update=True)
if count == 7: count = count + 1 return u'楠楠爱你哟, 玩的开心~~~' if count >7 and count != 10 and count != 11 and count != 12: count = count + 1 return u'嘻嘻嘻' if count == 10: count = count + 1 return u'你好无聊啊,后面都是嘻嘻嘻,别试啦' if count == 11: count = count + 1 return u'骗你的啦~~~' if count == 12: count = count + 1 return u'恭喜您已达成成就:无聊の人!' # count = count + 1 # return u'嘻嘻嘻' if __name__ == '__main__': itchat.auto_login() # itchat.send("Hello World Again 233 enter!", 'filehelper') myUserName = itchat.get_friends(update=True)[0]["UserName"] t1 = threading.Thread(target=itchat.run) t2 = threading.Thread(target=clockFunc) t2.start() t2.join() t1.start() t1.join()
try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() except: # 如果发生错误则回滚 db.rollback() memberlist = [] for member in weChat_id_list: if member != 0: memberlist.append(member) memberUsername = [] friendlist = itchat.get_friends()[1:] outfriendlist = [] nicknamelist = [] for friend in friendlist: if friend['NickName'] in memberlist: memberUsername.append(friend) for member in memberUsername: nicknamelist.append(member['NickName']) for nickname in memberlist: if nickname in nicknamelist: print(str(nickname) + " in group") else: print(str(nickname) + " not in group") outfriendlist.append(nickname)