Home  >  Article  >  Backend Development  >  Teach you how to create a WeChat chatbot using Python

Teach you how to create a WeChat chatbot using Python

不言
不言Original
2018-06-02 15:24:283738browse

This article mainly teaches you how to use Python to create a WeChat chat robot. It has certain reference value. Interested friends can refer to it.

Recently researched the WeChat API and found a very easy-to-use python Library: wxpy. Based on itchat, wxpy uses the Web WeChat communication protocol to implement WeChat login, send and receive messages, search for friends, data statistics and other functions.

Here we will introduce this library and implement a chatbot at the end.

Are you excited? Are you looking forward to it?

Okay, next, let’s start our main topic.

Preparation

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 "https://pypi.doubanio.com/simple/"

Initial exploration of the module

After the installation is completed, let’s try a few basic functions

1. Scan the QR code to log in to WeChat

from wxpy import *
bot = Bot()

Run the above program, and a QR code will pop up. Scan it with your mobile phone's WeChat to log in.
But the above program has a shortcoming, you need to scan the QR code every time you run it. However, wxpy very considerately provides caching options, as shown below

bot = Bot(cache_path=True)

This way you can save the login information, so you don’t have to scan the QR code every time.

2. Send a message

bot.file_helper.send("hello")

The file_helper here is the file transfer assistant of WeChat. We send a message to the file transfer assistant and you can receive the following message on the mobile phone

3. Accept messages

We implement a function to automatically reply to messages.

@bot.register()
def print_message(msg): 
 print(msg.text) 
 return msg.text

# 进入Python命令行,让程序保持运行
embed()

Brother Qiang opens his own official account management platform and sends a message to himself on the backend, and he will receive the following message reply

4. Search friends and WeChat groups

Let’s implement a function to search company groups, locate bosses and forward boss messages

from wxpy import *

bot = Bot(cache_path=True)

# 定位公司群
company_group = bot.groups().search('公司微信群')[0]

# 定位老板

boss = company_group.search('老板大名')[0]

# 将老板的消息转发到文件传输助手
@bot.register(company_group)
def forward_boss_message(msg): 
 if msg.member == boss:  
 msg.forward(bot.file_helper, prefix='老板发言')

# 堵塞线程
embed()

This is good news for students whose bosses like to shout in the group , you no longer have to worry about missing important information from your boss~~

Data Statistics

wxpy’s friend statistics function is very easy to use and can be easily used Statistics of geographical location distribution and gender distribution of friends.

In the code below, Brother Qiang counts the distribution of his friends and prints out the 10 areas with the largest number of people.

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([province, count])

# 对人数倒序排序
friend_loc.sort(key=lambda x: x[1], reverse=True)

# 打印人数最多的10个地区
for item in friend_loc[:10]:
 print item[0], item[1]

The statistical regional distribution data is drawn into a chart as follows

Brother Qiang is in Shanghai, and most of his friends are also from Shanghai. The chart above is also reflects the situation truthfully.

The code for statistical gender 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" % count

Generate the chart of gender distribution data as follows

You can see that among the friends, men account for most. If you have many male friends, your wife will feel at ease. Well~~

Chatbot

With the foundation of the above function introduction, let’s implement a chatbot.

The chatbot is based on Turing robot. Turing Robot can register an account and create a robot on Turing Robot - the most intelligent robot brain in the Chinese context.

# -*- coding: utf-8 -*-
import json
import requests
from wxpy import *

# 调用图灵机器人API,发送消息并获得机器人的回复
def auto_reply(text): 
 url = "http://www.tuling123.com/openapi/api"
 api_key = "你的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 above program and send a message to yourself. You can see the following dialogue

The robot is so funny. It asks for red envelopes when it comes up. I’m a boyfriend~

#

The above is the detailed content of Teach you how to create a WeChat chatbot using Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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