Recently studying wechat API, I found a very useful Python library: Wxpy. Based on ItChat, WXpy uses the communication protocol of wechat on the Web to realize functions such as wechat login, sending and receiving messages, searching friends, and data statistics.
Here we take a look at the library and finally implement a chatbot.
The preparatory work
The installation is very simple, download and install from the official source
pip install -U wxpy
Copy the code
Or install from douban source
pip install -U wxpy -i "https://pypi.doubanio.com/simple/"
Copy the code
Module, a preliminary study
With the installation complete, let’s try out a few basic features
1. Scan the code to log in to wechat
from wxpy import *
bot = Bot()
Copy the code
Run the above program, a QR code will pop up, and you can log in by scanning wechat on your phone.
But the above program has a disadvantage, each time it is run to scan the QR code. However, WXpy helpfully provides caching options, as follows
bot = Bot(cache_path=True)
Copy the code
Save your login information so you don’t have to scan the QR code every time.
2. Send the MESSAGE
bot.file_helper.send("hello")
Copy the code
File_helper is wechat’s file transfer assistant. We send a message to the file transfer assistant, and we can receive the following message on our mobile phone
3. Receive the news
We implement a function that automatically replies to received messages.
@bot.register() def print_message(MSG): print(msg.text) return msg.textCopy the code
Johnny opens his own public account management platform, sends a message to himself in the back end, and can receive the following message reply
4. Search your friends and wechat groups
Let’s implement a function to search for company groups, locate the boss, and forward boss messages
From wxpy import * bot = bot (cache_path=True) # company_group = bot.groups().search(' company_groups ')[0] # company_group = bot (cache_path=True) # company_group = bot.groups() @bot.register(company_group) def forward_boss_message(MSG): If msg.member == boss: msg.forward(bot.file_helper, prefix=' boss ') # embed()Copy the code
This is a good news for students whose boss likes to shout in the group. They don’t have to worry about missing out on important information from their boss
Data statistics
Wxpy’s friend statistics feature makes it easy to count your friends by location and gender.
In the code below, Johnny calculates the distribution of his friends and prints out the top 10 locations.
From wxpy import * bot = bot (cache_path=True) friends_stat = bot.friends().stats() friend_loc = [] # For province, count in friends_stat["province"]. Iteritems (): if province! Friend_loc.append ([type, count]) # sort(key=lambda x) X [1], reverse=True) # print item in friend_loc[:10]: print item[0], item[1]Copy the code
The resulting regional distribution data are graphed as follows
John is based in Shanghai, and most of his friends are from Shanghai, as the chart above shows.
The code for statistical sex distribution is as follows
For sex, count in friends_stat["sex"]. Iteritems (): # 1 MALE, 2 FEMALE if sex == 1: print "MALE %d" % count elif sex == 2: print "FEMALE %d" % countCopy the code
The data on the gender distribution are graphed as follows
You can see that the majority of friends are male. A lot of male friends, a lot of wife rest assured, HMM ~~
Chatbot
With that in mind, let’s implement a chatbot.
Chatbots are based on Turing robots. Turing Robot can register an account with the most intelligent robot brain in the Turing robot – Chinese context and create a robot. Note down the API key that will be used when calling the Turing API.
# -* -coding: UTF-8 -* -import json import requests from wxpy import * # Def auto_reply(text): Url = "http://www.tuling123.com/openapi/api" api_key = "your API key" content = {" key ": api_key," info ": text," userid ": "123456" } r = requests.post(url, data=json.dumps(payload)) result = json.loads(r.content) return "[tuling] " + result["text"] bot = Bot(console_qr=True, cache_path=True) @bot.register(mp) def forward_message(msg): return auto_reply(msg.text) embed()Copy the code
Run the program above, send a message to yourself, and you can see the following dialog
The robot was so funny that it asked for a red envelope and treated me as a boyfriend
This article has been updated with the public account of the same name
Welcome to wechat public account [Python and Data Analysis]
The appendix
Wxpy: Play wechat with Python
Github address: youfou/wxpy