Table of Contents
0. itchat
1. The ratio of male to female friends on WeChat
#2. Friend personalized signature word cloud
3. WeChat automatic reply
Home Backend Development Python Tutorial How to play with WeChat using Python

How to play with WeChat using Python

Jun 21, 2017 pm 04:26 PM
python detailed

The code is placed here: wzyonggege/python-wechat-itchat

The word cloud can be replaced with a minion picture

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

0. itchat

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
Copy after login

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')
Copy after login

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

1. The ratio of male to female friends on WeChat

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)
Copy after login

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
Copy after login

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()
Copy after login

dingdendenden Log in~

#2. Friend personalized signature word cloud

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
Copy after login

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
Copy after login

. Next, use jieba to segment words and then create word clouds. First, install jieba and wordcloud libraries.

pip install jieba
pip install wordcloud
Copy after login

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()
Copy after login

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')
Copy after login

Hmm~ It seems ok, this is generated under Mac, attached is one generated under win10

3. WeChat automatic reply

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()
Copy after login

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="text">@itchat.msg_register(['Map', 'Card', 'Note', 'Sharing', 'Picture'])</code><br><br><br>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

How to use mysql after installation How to use mysql after installation Apr 08, 2025 am 11:48 AM

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

MySQL download file is damaged and cannot be installed. Repair solution MySQL download file is damaged and cannot be installed. Repair solution Apr 08, 2025 am 11:21 AM

MySQL download file is corrupt, what should I do? Alas, if you download MySQL, you can encounter file corruption. It’s really not easy these days! This article will talk about how to solve this problem so that everyone can avoid detours. After reading it, you can not only repair the damaged MySQL installation package, but also have a deeper understanding of the download and installation process to avoid getting stuck in the future. Let’s first talk about why downloading files is damaged. There are many reasons for this. Network problems are the culprit. Interruption in the download process and instability in the network may lead to file corruption. There is also the problem with the download source itself. The server file itself is broken, and of course it is also broken when you download it. In addition, excessive "passionate" scanning of some antivirus software may also cause file corruption. Diagnostic problem: Determine if the file is really corrupt

MySQL can't be installed after downloading MySQL can't be installed after downloading Apr 08, 2025 am 11:24 AM

The main reasons for MySQL installation failure are: 1. Permission issues, you need to run as an administrator or use the sudo command; 2. Dependencies are missing, and you need to install relevant development packages; 3. Port conflicts, you need to close the program that occupies port 3306 or modify the configuration file; 4. The installation package is corrupt, you need to download and verify the integrity; 5. The environment variable is incorrectly configured, and the environment variables must be correctly configured according to the operating system. Solve these problems and carefully check each step to successfully install MySQL.

Solutions to the service that cannot be started after MySQL installation Solutions to the service that cannot be started after MySQL installation Apr 08, 2025 am 11:18 AM

MySQL refused to start? Don’t panic, let’s check it out! Many friends found that the service could not be started after installing MySQL, and they were so anxious! Don’t worry, this article will take you to deal with it calmly and find out the mastermind behind it! After reading it, you can not only solve this problem, but also improve your understanding of MySQL services and your ideas for troubleshooting problems, and become a more powerful database administrator! The MySQL service failed to start, and there are many reasons, ranging from simple configuration errors to complex system problems. Let’s start with the most common aspects. Basic knowledge: A brief description of the service startup process MySQL service startup. Simply put, the operating system loads MySQL-related files and then starts the MySQL daemon. This involves configuration

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

How to optimize database performance after mysql installation How to optimize database performance after mysql installation Apr 08, 2025 am 11:36 AM

MySQL performance optimization needs to start from three aspects: installation configuration, indexing and query optimization, monitoring and tuning. 1. After installation, you need to adjust the my.cnf file according to the server configuration, such as the innodb_buffer_pool_size parameter, and close query_cache_size; 2. Create a suitable index to avoid excessive indexes, and optimize query statements, such as using the EXPLAIN command to analyze the execution plan; 3. Use MySQL's own monitoring tool (SHOWPROCESSLIST, SHOWSTATUS) to monitor the database health, and regularly back up and organize the database. Only by continuously optimizing these steps can the performance of MySQL database be improved.

Does mysql need the internet Does mysql need the internet Apr 08, 2025 pm 02:18 PM

MySQL can run without network connections for basic data storage and management. However, network connection is required for interaction with other systems, remote access, or using advanced features such as replication and clustering. Additionally, security measures (such as firewalls), performance optimization (choose the right network connection), and data backup are critical to connecting to the Internet.

See all articles