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. Are you excited? Are you looking forward to it? All right, let’s get started.

The preparatory work

The installation is very simple, download and install from the official source

pip install -U wxpy

Or install from douban source

pip install -U wxpy -i “pypi.doubanio.com/simple/”

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()

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)

Save your login information so you don’t have to scan the QR code every time.

Qun: 850973621, There are free video tutorials, development tools,

Electronic books, project source code sharing. Exchange and learn together, make progress together!

2. Send the MESSAGE

bot.file_helper.send(“hello”)

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.text

Go to the Python command line and keep the program running

embed()

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)

Locating company groups

Company_groups = bot.groups().search(‘ company_groups ‘)[0]

Locate the boss

Boss = company_group.search(‘ boss name ‘)[0]

Forward the boss’s message to the file Transfer assistant

@bot.register(company_group)

def forward_boss_message(msg):

if msg.member == boss:

MSG. Forward (bot.file_helper, prefix=’ boss ‘)

Plug thread

embed()

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 = [] # Each element is a binary list that stores location and number of people

for province, count in friends_stat[“province”].iteritems():

if province ! = “” :

friend_loc.append([province, count])

Sort the number of people in reverse order

friend_loc.sort(key=lambda x: x[1], reverse=True)

The 10 regions with the highest number of printers

for item in friend_loc[:10]:

print item[0], item[1]

The resulting regional distribution data are graphed as follows

My friend is from Shanghai, and the chart above reflects the situation as it really is. The code for statistical sex distribution is as follows

for sex, count in friends_stat[“sex”].iteritems():

1 represents MALE and 2 represents FEMALE

if sex == 1:

print “MALE %d” % count

elif sex == 2:

print “FEMALE %d” % count

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.

– coding: utf-8 –

import json

import requests

from wxpy import *

Call the Turing robot API, send a message and get a reply from the robot

def auto_reply(text):

url = “www.tuling123.com/openapi/api”

Api_key = “Your API key”

payload = {

“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()

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