Home > Article > Backend Development > How to play with WeChat using Python
The code is placed here: wzyonggege/python-wechat-itchat
The word cloud can be replaced with a minion picture
---- -------------------------------------------------- ----------------------------------------
Recently I have studied some ways to play WeChat. We can use the web version of WeChat to log in by scanning the QR code to capture packets and crawl information, and we can also post to send information.
Then I discovered the open source project itchat. The author is @LittleCoder. It has completed the WeChat interface, which greatly facilitates our exploration of WeChat. The following functions are also provided through itchat. accomplish.
Install the itchat library
pip install itchat
Let’s do a simple trial first to log in to WeChat. Running the following code will generate a QR code. Scan the code on the mobile phone After confirming the login, a message will be sent to 'filehelper'. This filehelper is the file transfer assistant on WeChat.
import itchat# 登录itchat.login()# 发送消息itchat.send(u'你好', 'filehelper')
In addition to logging in and sending messages, we can also play like this, go down~
Want to count Of course, it is very simple to determine the gender ratio of your friends in WeChat. First get the friend list and count the genders in the list
import itchat# 先登录itchat.login()# 获取好友列表friends = itchat.get_friends(update=True)[0:]# 初始化计数器,有男有女,当然,有些人是不填的male = female = other = 0# 遍历这个列表,列表里第一位是自己,所以从"自己"之后开始计算# 1表示男性,2女性for i in friends[1:]:sex = i["Sex"]if sex == 1:male += 1elif sex == 2:female += 1else:other += 1# 总数算上,好计算比例啊~total = len(friends[1:])# 好了,打印结果print u"男性好友:%.2f%%" % (float(male) / total * 100)print u"女性好友:%.2f%%" % (float(female) / total * 100)print u"其他:%.2f%%" % (float(other) / total * 100)
Let’s take a look at the result:
(Okay, it exposed the truth that I have more male friends~~)
It seems not intuitive enough. Friends who are interested can add a visual display. I use Echarts based on python here ( I’ll talk about it in detail when I have a chance)
Install it first
pip install echarts-python
Generally use the percentage round cake table to display the proportion
# 使用echarts,加上这段from echarts import Echart, Legend, Piechart = Echart(u'%s的微信好友性别比例' % (friends[0]['NickName']), 'from WeChat')chart.use(Pie('WeChat', [{'value': male, 'name': u'男性 %.2f%%' % (float(male) / total * 100)}, {'value': female, 'name': u'女性 %.2f%%' % (float(female) / total * 100)}, {'value': other, 'name': u'其他 %.2f%%' % (float(other) / total * 100)}], radius=["50%", "70%"]))chart.use(Legend(["male", "female", "other"]))del chart.json["xAxis"]del chart.json["yAxis"]chart.plot()
dingdendenden Log in~
When getting the friend list, you can also see personalized signature information in the returned json information. With my imagination running wild, I grabbed everyone's signatures, looked at the high-frequency words, and made a word cloud.
# coding:utf-8import itchat# 先登录itchat.login()# 获取好友列表friends = itchat.get_friends(update=True)[0:]for i in friends:# 获取个性签名signature = i["Signature"]print signature
First grab them all
After printing, you will find that there are a large number of span, class, emoji, emoji1f3c3, etc. fields, because emoticons are used in the personalized signature. These fields need to be filtered out. Write a regular and replace method to filter out
for i in friends:# 获取个性签名signature = i["Signature"].strip().replace("span", "").replace("class", "").replace("emoji", "")# 正则匹配过滤掉emoji表情,例如emoji1f3c3等rep = re.compile("1f\d.+")signature = rep.sub("", signature)print signature
. Next, use jieba to segment words and then create word clouds. First, install jieba and wordcloud libraries.
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)# 拼接字符串text = "".join(tList)# jieba分词import jiebawordlist_jieba = jieba.cut(text, cut_all=True)wl_space_split = " ".join(wordlist_jieba)# wordcloud词云import matplotlib.pyplot as pltfrom wordcloud import WordCloudimport PIL.Image as Image# 这里要选择字体存放路径,这里是Mac的,win的字体在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 code
This. . It seems a bit ugly. According to wordcloud usage, I can find a picture to generate a color scheme. Here I found a picture of WeChat’s logo
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()# 保存图片 并发送到手机my_wordcloud.to_file(os.path.join(d, "wechat_cloud.png"))itchat.send_image("wechat_cloud.png", 'filehelper')
Hmm~ It seems ok, this is generated under Mac, attached is one generated under win10
Then we will implement an automatic reply similar to that on QQ. The principle is to send the message back after receiving the message, and at the same time send one to the file assistant. View messages together in File Assistant.
The code is very simple, let’s take a look
#coding=utf8import itchat# 自动回复# 封装好的装饰器,当接收到的消息是Text,即文字消息@itchat.msg_register('Text')def text_reply(msg):# 当消息不是由自己发出的时候if not msg['FromUserName'] == myUserName:# 发送一条提示给文件助手itchat.send_msg(u"[%s]收到好友@%s 的信息:%s\n" %(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(msg['CreateTime'])), msg['User']['NickName'], msg['Text']), 'filehelper')# 回复给好友return u'[自动回复]您好,我现在有事不在,一会再和您联系。\n已经收到您的的信息:%s\n' % (msg['Text'])if __name__ == '__main__':itchat.auto_login()# 获取自己的UserNamemyUserName = itchat.get_friends(update=True)[0]["UserName"]itchat.run()
After running, it will stay logged in, turn on the automatic reply mode, and view it on your mobile phone:
Of course, in addition to text information, you can also receive pictures (emoticons are considered pictures), voice, business cards, geographical location, sharing and information of type Note (that is, messages that are prompted by someone, such as withdrawing messages). The decorator written in the following form is acceptable. You can try
<code class="language-text">@itchat.msg_register(['Map', 'Card', 'Note', 'Sharing', 'Picture'])</code><br><br><br>
The above is the detailed content of How to play with WeChat using Python. For more information, please follow other related articles on the PHP Chinese website!