How to play WeChat with Python

Source: Internet
Author: User
The code is here: Wzyonggege/python-wechat-itchat

Word clouds can be converted to small yellow people pictures

---------------------------------------------------------------------------------------------------

0. itchat

Recently studied some of the gameplay, we can through the web version of the Web version, scan code login to grab the packet crawl information, can also post to send information.

And then found itchat this open source project, the author is @littlecoder, has completed the interface, greatly facilitates our mining, the following functions are also through the itchat to achieve.

Install Itchat This library

Pip Install Itchat

First, a simple trial, the implementation of the login, run the following code will generate a two-dimensional code, scan code after the mobile phone to confirm login, will send a message to ' Filehelper ', this filehelper is the file transfer assistant.

Import itchat# Login Itchat.login () # Send Message itchat.send (U ' hello ', ' filehelper ')

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

1. Ratio of friends to men

Want to count their friends in the sex ratio, of course, is also very simple, first get friends List, statistics table gender count

Import itchat# First login itchat.login () # get friends List friends = Itchat.get_friends (update=true) [0:]# initialization counter, there are men and women, of course, some people are not filled male = female = other = 0# iterates through the list, the first of the lists is itself, so starting with "self" is calculated # 1 means male, 2 female for i in friends[1:]:sex = i["Sex"]if sex = = 1:male + = 1elif Sex = = 2:female + = 1else:other + # Total count, good calculation ratio ah ~total = Len (friends[1:]) # OK, print results printed U "male friends:%.2f%%"% (float (male)/To Tal * +) print U "female friend:%.2f%%"% (float (female)/total *) Print U "others:%.2f%%"% (float (other)/total * 100)

Well look at the results:

(Well, exposing the truth of my male friends more ~ ~)

Seems to be not intuitive enough, interested friends can add visual display, I use Python-based echarts here (have the opportunity to speak again)
First install the

Pip Install Echarts-python

Display scale general use percent round pie table bar

# Use Echarts, plus this paragraph from echarts import Echart, Legend, Piechart = Echart (U '%s's friend sex ratio '% (friends[0][' nickname ']), ' from Wecha T ') chart.use (' WeChat ',              [{' Value ': Male, ' name ': U ' male%.2f%% '% (float (male)/total *)},               {' value ': female  , ' name ': U ' female%.2f%% '% (float (female)/total * +)},               {' value ': Other, ' name ': U ' additional%.2f%% '% (float (other)/Total *)}],              radius=["50%", "70%"]) Chart.use (Legend (["Male", "female", "other"]) del chart.json["Xaxis"]del chart.json["YAxis"]chart.plot ()

Log In and login ~

2. Friends Personality Signature Word cloud

Get a friend list, the return of the JSON message also saw a personalized signature information, the brain hole open, everyone's personality signatures are caught, look at high-frequency words, also made a word cloud.

# Coding:utf-8import itchat# First Sign in Itchat.login () # Get a buddy list friends = Itchat.get_friends (update=true) [0:]for i in friends:# Get the personality signature Signature = i["Signature"]print Signature

Grab them all first.
After printing you will find that there are a lot of fields such as SPAN,CLASS,EMOJI,EMOJI1F3C3, because of the use of emoticons in the personality signature, these fields are to filter out, write a regular and replace method to filter out

For I in friends:# gets the personality signature Signature = i["Signature"].strip (). Replace ("span", ""). Replace ("Class", ""). Replace ("emoji", " # regular Match filters out emoji emoticons, such as EMOJI1F3C3 rep = Re.compile ("1f\d.+") signature = Rep.sub ("", signature) print signature

Next use Jieba participle, then make into Word cloud, first to install Jieba and Wordcloud Library

Pip Install Jiebapip 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 ("", ""). Replace ("" "," "") Re.compile ("1f\d.+") signature = Rep.sub ("", signature) Tlist.append (signature) # stitching string text = "". Join (TList) # Jieba Word 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 to choose the font storage path, here is the Mac, win the font 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 code

This.. Seems a little ugly, according to Wordcloud usage, I can find a picture to create a color scheme, I found a logo here

Modify the Code

# Wordcloud Word cloud import matplotlib.pyplot as Pltfrom wordcloud import Wordcloud, Imagecolorgeneratorimport osimport numpy as N Pimport 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 ')

Ah ~ seems to be OK, this is generated under the Mac, with a WIN10 generated under the

3. Auto-reply

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

The code is simple enough to see

#coding =utf8import itchat# Auto-Reply # packaged adorner, when the received message is text, i.e. text message @itchat.msg_register (' text ') def text_reply (msg): # When the message is not issued by itself if not msg[' fromusername ' = = myusername:# send a hint to the file assistant itchat.send_msg (U "[%s] received message from 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 ' [auto Reply] Hello, I am not in a moment, I will contact you again. \ n has received your message:%s\n '% (msg[' Text ']) if __name__ = = ' __main__ ': Itchat.auto_login () # get your own Usernamemyusername = itchat.get_ Friends (update=true) [0]["UserName"]itchat.run ()

After running will remain logged in, turn on auto-reply mode, on the phone to view:

Of course, in addition to text text information, you can also receive pictures (emoticons), voice, business cards, geographical location, sharing and type of note information (that is, someone prompts the class of messages, such as recall message), the adorner is written in the form below can be accepted, you can try

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


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.