0. itchat

Recently we studied some wechat play, we can through the webpage version of wechat wechat web version, scan code to log in to capture the packet to crawl information, but also can post to send information.

Then I found an open source project called ItChat, written by @Littlecoder, which has completed the interface of wechat, greatly facilitating the mining of wechat. The following functions are also implemented through Itchat.

Install the Itchat library

pip install itchat
Copy the code

Run the following code to generate a QR code. After scanning the code, the phone confirms the login and sends a message to ‘FileHelper’, which is the file transfer assistant on wechat.


Import itchat # login itchat.login() # send message itchat.send(u' hello ', 'filehelper')Copy the code

In addition to logging in and sending messages, we can also play this way, down ~


1. Ratio of male to female wechat friends

If you want to count the gender ratio of your friends in wechat, of course, it is also very simple to get the list of friends first and count the gender count in the list


Import itchat # import itchat.login() # get friends = itchat.get_friends(update=True)[0:] Male = female = other = 0 # select * from 'I' where # 1 = male, # 2 = female for friends[1:]: sex = i["Sex"] if sex == 1: male += 1 elif sex == 2: female += 1 else: Total = len(friends[1:]) = len(friends[1:]) %.2f%%" % (float(male)/total * 100) print u" %.2f%%" % (float(female)/total * 100) print u" %.2f%%" % (float(other) / total * 100)Copy the code

Let’s see the results:




(Ok, revealing the fact that I have more male friends ~ ~)

If you are interested, you can add a visual display. I will install Echarts based on Python

pip install echarts-python
Copy the code

Use a pie chart of percentages to show proportions


# Use echarts, From echarts import Echart, Legend, Pie chart = Echart(u'%s' (friends[0]['NickName']), 'the from WeChat') chart. Use (Pie (' WeChat '[{' value' : male, 'name' : u '. Men % 2 f % % % (float (male)/total * 100)}, {' value ': Female, 'name' : u '. Women % 2 f % % % (float (female)/total * 100)}, {' value ': the other,' name ': U '. Other % 2 f % % % (float (other)/total * 100)}], the radius = [" 50% ", "70%"])) chart. Use (Legend ([" male "and" female ", "other"])) del chart.json["xAxis"] del chart.json["yAxis"] chart.plot()Copy the code

Don, don, don, don



2. Personalized signature word cloud of friends

When we get the list of friends, we can also see the information with personality signature in the JSON information returned. When we open our imagination, we can catch everyone’s personality signature, look at the high frequency words, and make a word cloud.


# coding:utf-8 import itchat # login itchat.login() # get friends = itchat.get_friends(update=True)[0:] for I in Signature = I [" signature "] print signatureCopy the code

After all of them are captured and printed, you will find that there are a large number of fields such as SPAN, class, emoji, emoji1F3C3, etc. Since emojis are used in the personality signature, these fields need to be filtered out. Write a re and replace method to filter them out


for i in friends: Strip ().replace("span", "").replace("class", "").replace("emoji", "").replace("class", "").replace("emoji", Rep = re.compile("1f\d.+") signature = rep.sub("", signature) print signatureCopy the code

Jieba is jieba and wordCloud is jieba and WordCloud libraries are installed first


pip install jieba
pip install wordcloud
Copy the code

code


# coding:utf-8 import itchat import re itchat.login() friends = itchat.get_friends(update=True)[0:] tList = [] for i in friends: signature = i["Signature"].replace(" ", "").replace("span", "").replace("class", "").replace("emoji", "") rep = re.compile("1f\d.+") signature = rep.sub("", Join (tList) # jieba import jieba wordlist_jieba = jieba.cut(text, Cut_all =True) wl_space_split = "". Join (wordlist_jieba) # wordcloud import matplotlib.pyplot as PLT from wordcloud Import WordCloud import pil. Image as Image # My_wordcloud = WordCloud(background_color="white", max_words=2000, max_font_size=40, random_state=42, font_path='/Users/sebastian/Library/Fonts/Arial Unicode.ttf').generate(wl_space_split) plt.imshow(my_wordcloud) plt.axis("off") plt.show()Copy the code

Run the code


This.. It seems a little ugly. According to the use of WordCloud, I can find a picture to generate the color scheme. Here I find a wechat logo


Modify the code


Import matplotlib.pyplot as PLT from wordcloud import wordcloud, ImageColorGenerator import os import numpy as np import PIL.Image as Image d = os.path.dirname(__file__) alice_coloring = np.array(Image.open(os.path.join(d, "wechat.jpg"))) my_wordcloud = WordCloud(background_color="white", max_words=2000, mask=alice_coloring, max_font_size=40, random_state=42, font_path='/Users/sebastian/Library/Fonts/Arial Unicode.ttf')\ .generate(wl_space_split) image_colors = ImageColorGenerator(alice_coloring) plt.imshow(my_wordcloud.recolor(color_func=image_colors)) plt.imshow(my_wordcloud) Plt.axis ("off") plt.show() # save image and send it to mobile my_wordcloud.to_file(os.path.join(d, "wechat_cloud.png")) itchat.send_image("wechat_cloud.png", 'filehelper')Copy the code

Well, it seems to be ok, this is Mac generated, with a Win10 generated




3. Wechat automatically replies

Then to achieve a similar qq automatic reply, the principle is to receive the message, send the message back, at the same time send a file assistant, you can view the message in the file assistant.

The code is simple. Let’s see

@itchat.msg_register('Text') def text_reply(MSG): #coding=utf8 import itchat If not MSG ['FromUserName'] == myUserName: Send_msg (u"[%s] received a message from a friend @%s: %s\n" % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(msg['CreateTime'])), msg['User']['NickName'], msg['Text']), 'FileHelper ') # reply to a friend return u'[autoreply] Hello, I am away at the moment, I will contact you later. \ n has received your message: % s \ n '% (MSG) [' Text'] if __name__ = = "__main__ ': MyUserName = itchat.get_friends(update=True)[0]["UserName"] itchat.run()Copy the code

After running, it will keep the login state, enable the automatic reply mode, and view it on the mobile phone:

@itchat.msg_register(['Map', 'Card', 'Note', 'Sharing', 'Picture'])
Copy the code


4. The last

In addition to the above, you can also manage wechat groups, automatically add friends, and add the robot reply function, which will be made up when there is time.

Thanks again to Itchat writer @Littlecoder