How to Use Python to create WeChat chatbots and python chatbots

Source: Internet
Author: User

How to Use Python to create chatbots and python chatbots

I recently studied the API and found a very useful python Library: wxpy. Based on itchat, wxpy uses the Web communication protocol to implement functions such as logon, sending and receiving, searching for friends, and data statistics.

Here we will introduce this library and finally implement a chatbot.

Are you very excited? Are you looking forward to it?

Now, let's start our discussion.

Preparations

Easy to install. Download and install from official sources

pip install -U wxpy

Or install it from the Douban source.

pip install -U wxpy -i "https://pypi.doubanio.com/simple/"

Module

After the installation is complete, let's try several basic functions.

1. Scan the QR code to log on.

from wxpy import *bot = Bot()

Run the above program and a QR code will pop up. You can use your mobile phone to scan the QR code to log on.
However, the preceding program has one disadvantage: scan the QR code every time you run it. However, wxpy provides the following caching options:

bot = Bot(cache_path=True)

In this way, you do not need to scan the QR code every time after saving the logon information.

2. Send messages

bot.file_helper.send("hello")

Here, file_helper is the file transfer assistant. We send a message to the file transfer Assistant, which can receive the following message on the mobile phone end.

3. receive messages

We implement the function of automatically replying to a message.

@ Bot. register () def print_message (msg): print (msg. text) return msg. text # enter the Python command line to keep the program running embed ()

Go to your public account management platform and send a message to you at the backend. Then, you can receive the following message reply:

4. Search for friends and Groups

Let's implement a function to search for a company group, locate the boss, and forward the boss message.

From wxpy import * bot = Bot (cache_path = True) # locate the company group company_group = bot. groups (). search ('Company group') [0] # locate the 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') # clog the thread embed ()

This is a good news for those who like to shout in the group. In the future, there will be no need to worry about missing important information from the boss ~~

Data Statistics

Wxpy's friend statistics function is very easy to use, so that you can easily count the geographical distribution and gender distribution of friends.

In the following code, strong brother counts the distribution of his friends and prints out the 10 most popular areas.

From wxpy import * bot = Bot (cache_path = True) friends_stat = bot. friends (). stats () friend_loc = [] # each element is a binary list that stores region and number of people information for province, count in friends_stat ["province"]. iteritems (): if province! = "": Friend_loc.append ([province, count]) # Sort friend_loc.sort (key = lambda x: x [1], reverse = True) in reverse order) # for item in friend_loc [: 10]: print item [0], item [1]

The area distribution data is shown as follows:

Strong brother is in Shanghai, and most of his friends are also from Shanghai. The chart above reflects this situation.

The code for calculating gender distribution is as follows:

For sex, count in friends_stat ["sex"]. iteritems (): #1 stands for MALE, 2 stands for FEMALE if sex = 1: print "MALE % d" % count elif sex = 2: print "FEMALE % d" % count

Generate a chart showing gender distribution.

We can see that male accounts for the majority of friends. A lot of male friends, a lot of peace of mind, Ah ~~

CHATBOT

With the basic functions described above, we can implement a chatbot.

Chatbots are based on Turing robots. The Tuling robot can register an account with the highest intelligence in the Tuling robot-Chinese context and create a robot.

#-*-Coding: UTF-8-*-import jsonimport requestsfrom wxpy import * # Call the Turing robot API to send messages and obtain the robot's reply def auto_reply (text ): url = "http://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 (lele_qr = True, cache_path = True) @ bot. register (mp) def forward_message (msg): return auto_reply (msg. text) embed ()

Run the above program and send the message to yourself. You can see the following dialog:

The robot is so funny. I am about to get a red envelope and treat me as a boyfriend ~

Appendix

Wxpy documentation: http://wxpy.readthedocs.io/zh/latest/
Github address: https://github.com/youfou/wxpy/blob/master/docs/index.rst

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.