# 0. itchat

Recently, we have studied some WeChat gameplay. We can use the web version of the WeChat WeChat web version , scan the code to log in, grab the packet to crawl information, and post to send information.

Then found itchat this open source project, the author is @LittleCoder , the micro-channel interface has been completed, greatly facilitated our mining micro letter, the following features are also realized by itchat.

Install the itchat library

`pip install itchat`

Let's start with a simple trial to realize WeChat login. Run the following code to generate a QR code. After scanning the code, the mobile phone will confirm the login, and a message will be sent to'filehelper'. This filehelper is the file transfer assistant on WeChat .

`import itchat# Login itchat.login()# Send message itchat.send(u'hello','filehelper')`

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

## 1. Male to female ratio of WeChat friends

If you want to count the gender ratio of your friends in WeChat, it is of course very simple. First get the friend list and count the gender counts in the list.

```import itchat# First login itchat.login()# Get friends list friends = itchat.get_friends(update=True)[0:]# Initialize the counter, there are male and female, of course, some people do not fill in male = female = other = 0# Traverse this list, the first in the list is self, so start counting from "self" # 1 means male, 2 female for i in friends[1:]:
sex = i["Sex"]
if sex == 1:
male += 1
elif sex == 2:
female += 1
else:
other += 1# The total number is counted, it is easy to calculate the ratio~ total = len(friends[1:])# Ok, print the result print u "Male friend: %.2f%%"% (float(male)/total * 100)print u"Female friend: %.2f%%"% (float(female)/total * 100)print u"Other: %.2f%%"% (float(other)/total * 100)```

Let's see the result:

(Well, it revealed the truth that I have more male friends~~)

It seems not intuitive enough, friends who are interested can add a visual display, I use Python-based Echarts here (if you have the opportunity to elaborate ), install it first

`pip install echarts-python`

The display ratio generally uses the percentage pie table.

```# Use echarts and add this paragraph from echarts import Echart, Legend, Piechart = Echart(u'%s' WeChat friend gender ratio'% (friends[0]['NickName']),'from WeChat')chart.use (Pie('WeChat',
[{'value': male,'name': u'male%.2f%%'% (float(male)/total * 100)},
{'value': female,'name': u'female%.2f%%'% (float(female)/total * 100)},
{'value': other,'name': u'other%.2f%%'% (float(other)/total * 100)}],
radius=["50%", "70%"]))chart.use(Legend(["male", "female", "other"]))del chart.json["xAxis"]del chart.json[ "yAxis"]chart.plot()```

Deng Deng Deng Deng~

## 2. Friend Personalized Signature Word Cloud

When getting the friend list, the returned json information also saw the information with personalized signatures. Once I opened my mind, I grabbed everyone's personalized signatures, looked at the high-frequency words, and made a word cloud.

```# coding:utf-8import itchat# First log in itchat.login()# Get friends list friends = itchat.get_friends(update=True)[0:]for i in friends:
# Get personalized signature
signature = i["Signature"]print signature```

After grabbing all of them and printing them, you will find that there are a lot of fields such as span, class, emoji, emoji1f3c3, etc. Because emojis are used in the personalized signature, these fields are to be filtered out, write a regular and replace method to filter Drop

```for i in friends:# Get personalized signature
signature = i["Signature"].strip().replace("span", "").replace("class", "").replace("emoji", "")# Regular matching filters out emoji expressions, For example emoji1f3c3 etc.
rep = re.compile("1f\d.+")
signature = rep.sub("", signature)
print signature```

Next, use jieba to segment words, and then make it into a word cloud, first install jieba and wordcloud library

```pip install jieba
pip install wordcloud```

Code

```# coding:utf-8import itchatimport reitchat.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("", signature)
tList.append(signature)# splicing string text = "".join(tList)# jieba participle import jiebawordlist_jieba = jieba.cut(text, cut_all=True)wl_space_split = "".join(wordlist_jieba)# wordcloud word cloud import matplotlib .pyplot as pltfrom wordcloud import WordCloudimport PIL.Image as Image# Here you need to choose the font storage path, here is Mac, the win font is in windows/Fonts 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()```

Run the code

This. . It seems a bit ugly. According to wordcloud usage, I can find a picture to generate the color scheme. I found a WeChat logo here.

Modify the code

```# wordcloud词云import matplotlib.pyplot as pltfrom wordcloud import WordCloud, ImageColorGeneratorimport osimport numpy as npimport PIL.Image as Imaged = 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 the picture and send it to the phone my_wordcloud.to_file(os.path.join(d, "wechat_cloud.png"))itchat.send_image("wechat_cloud.png",'filehelper ')```

Um~ It seems to be ok, this is generated under Mac, with one generated under win10

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

The code is very simple, let's take a look

```#coding=utf8import itchat# AUTO Reply# The encapsulated decorator, when the received message is Text, that is, the text message @itchat.msg_register('Text')def text_reply(msg):
# When the message is not sent by yourself
# Send a reminder to the file assistant
itchat.send_msg(u"[%s] received a message from my friend @%s: %s\n"%
(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(msg['CreateTime'])),
msg['User']['NickName'],
msg['Text']),'filehelper')
return u'[auto reply] Hello, I am away for business now, and I will contact you later./nYour message has been received: %s\n'% (msg['Text'])if __name__ =='__main__':

itchat.run()```

After running, it will remain logged in, turn on the automatic reply mode, and check on the phone:

Of course, in addition to text messages, you can also receive pictures (emoticons are counted as pictures), voices, business cards, geographic location, sharing and information of type Note (that is, messages that are prompted by someone, such as withdrawing messages), and write the decorator as follows The form is acceptable, everyone can try

`@itchat.msg_register(['Map','Card','Note','Sharing','Picture'])`

## 4. Finally

In addition to the above, you can also manage WeChat groups, automatically add friends, and you can also add a robot reply function, which will be added when you have time.

Thanks again to itchat author @LittleCoder

Reference: https://cloud.tencent.com/developer/article/1033477 The correct posture for playing WeChat with Python! -Cloud + Community-Tencent Cloud