当前位置:网站首页>Take you to use wxpy to create your own chat robot (plus wechat interface basic data visualization)
Take you to use wxpy to create your own chat robot (plus wechat interface basic data visualization)
2022-07-06 15:20:00 【Jane said Python】
Welcome to WeChat official account. : Jane said Python
account number :xksnh888
Follow the reply :1024, You can get selected e-books for programming learning .
Good articles in the past : Your wechat nickname , May be selling you out
Contents of this article
List of articles
- One 、wxpy Basic introduction and installation
- Two 、 True knowledge comes from practice
- 1. Send a message to your file transfer assistant
- 2. Send a message to a designated friend
- 3. Group-sent message ( I woke up this morning with a whim , Send everyone a good morning !)
- 4. Get the number of your wechat friends 、 Number of active wechat groups 、 WeChat official account
- 5. Construction of personal chat robot ( self-based )
- 6. Construction of personal chat robot ( Based on Turing robot )
- 7. Have some fun
- 3、 ... and 、 an account of happenings after the event being told
Preface
This article is about X Sir, I have a brief look these days Python Insidewxpy
After module , collocationmatplotlib
A module written bywxpy
Basic usage , Mainly usedwxpy
Carry out a series of automatic operations on wechat , Such as the use ofwxpy
Login WeChat 、 Send message to wechat file assistant 、 Send a message to a single wechat friend 、 Wechat message group sending ( Use caution [/ Evil smile ]) And the construction and use process of wechat chat machine , Do you thinkwxpy
Only such ?No, Last X Sir, take advantage ofwxpy
Got the number of my wechat friends 、 Gender 、 Nickname and personal signature , WeChat official account 、 Official account information , collocationmatplotlib
A series of data visualization is carried out , Mixed in the middle X Mr. Zhang's analysis of some staggering words , From these ,,, I read out a real me ( Positive solution at the end of the paper ).
One 、wxpy Basic introduction and installation
1.wxpy Basic introduction
wxpy be based on itchat, Used Web Wechat communication protocol , Through a large number of interface optimization to improve the ease of use of the module , And expand the functions . Wechat login is realized 、 Send and receive messages 、 Search for friends 、 Data statistics 、 WeChat official account 、 WeChat friends 、 Wechat group basic information acquisition and other functions .
It can be used to realize the automatic operation of various wechat personal numbers .
2.wxpy install
Method 1 : Direct installation
pip install wxpy
Method 2 : Douban source installation ( recommend )
pip install -i https://pypi.douban.com/simple/ wxpy
Two 、 True knowledge comes from practice
1. Send a message to your file transfer assistant
from wxpy import *
# Initialize a robot object
bot = Bot(cache_path=True)
# Send message to file transfer assistant
bot.file_helper.send("hello,I'm XksA!")
Bot
Introduction to basic parameters of class :
cache_path –
Sets the cache path for the current session , And enable the cache function ; by None ( Default ) The cache function is not enabled .
After the cache is enabled, repeated code scanning can be avoided in a short time , When the cache fails, the login will be required again .
Set to True when , Use default cache path ‘wxpy.pkl’.
qr_path – Path to save QR code
console_qr – Display login QR code in terminal
A QR code picture will pop up after running , Just log in with wechat scanning code , Come back and see the mobile phone news .
* Special reminder :* The wechat account used cannot be a newly registered account , Otherwise, it will report a mistake KeyError: 'pass_ticket'
.
2. Send a message to a designated friend
# Initialize a robot object
# cache_path Cache path , The given value is the cache file path generated by the first login
bot = Bot(cache_path="H:\PyCoding\Wxpy_test\wxpy.pkl")
# Find friends " The minimalist XksA"
my_friend = bot.friends().search(' The minimalist XksA')[0]
# Send a message
my_friend.send('hello The minimalist XksA!')
''' In addition, you can send the following content , Try it yourself Send pictures my_friend.send_image('hello.png') Send video my_friend.send_video('hello.mp4') Send a file my_friend.send_file('hello.rar') '''
Running results :
3. Group-sent message ( I woke up this morning with a whim , Send everyone a good morning !)
import time
# Initialize a robot object
# cache_path Cache path for login status , The given value is the cache file path generated by the first login
bot = Bot(cache_path="H:\PyCoding\Wxpy_test\wxpy.pkl")
# Group-sent message ( Use caution , Ha ha ha )
my_friends = bot.friends(update=False)
my_friends.pop(0) # Remove the first element of the list ( own )
for i in range(120):
friend = my_friends[i]
friend.send('Good morning,the early bird catches the worm!( Good morning , The early bird catches the worm !)')
time.sleep(2)
friend.send(' Don't reply , Refueling together in life !')
Running effect :
4. Get the number of your wechat friends 、 Number of active wechat groups 、 WeChat official account
# Get all your friends [ Return list contains Chats object ( All your friends , Including myself )]
t0 = bot.friends(update=False)
# View your friends ( Get rid of yourself )
print(" Number of my friends :"+str(len(t0)-1))
# Get all wechat groups [ Return list contains Groups object ]
t1 = bot.groups(update=False)
# View the number of wechat groups ( Active )
print(" My wechat group chat :"+str(len(t1)))
# WeChat official account for all concerns [ Return list contains Chats object ]
t2 = bot.mps(update=False)
# WeChat's official account of concern
print(" My official account of WeChat public :"+str(len(t2)))
Running results :
# notes : If you just take t0、t1、t2 Print out the corresponding name ( Different types of , You can try it yourself )
Number of my friends :242
My wechat group chat :6
My official account of WeChat public :125
5. Construction of personal chat robot ( self-based )
#####(1) Own chat robot
# Find chat objects
my_friend = bot.friends().search(' The minimalist XksA')[0]
my_friend.send('hello The minimalist XksA!')
# Automatic recovery
# If you want to reply to all your friends, set the parameters my_friend Change to chats = [Friend]
@bot.register(my_friend)
def my_friednd_message(msg):
print('[ receive ]' + str(msg))
if msg.type != 'Text': # Message reply content other than text
ret = ' What did you show me ![ please ]'
elif " Where are you from? " in str(msg): # Answer specific questions
ret = " I come from minimalism XksA"
else: # Text message auto answer
ret = ' I love you! '
print('[ send out ]' + str(ret))
return ret
# Enter interactive Python Command line interface , And block the current thread
embed()
#####(2) Chat renderings
6. Construction of personal chat robot ( Based on Turing robot )
#####(1) preparation
Click here Sign up for a Turing robot account , Then create a robot , You can get your Turing robot api.
#####(2) Create your own chat robot
- Method 1 : Use
Tuling
class , Simple implementation
# Login cache path , Set to... For the first time True
# Generate cache file wxpy.pkl after , Is the path to the file
bot = Bot(cache_path="H:\PyCoding\Wxpy_test\wxpy.pkl")
tuling = Tuling(api_key=' Your Turing interface api')
print(' The minimalist robot has started ')
# My trumpet , Caution in testing
my_friednd = bot.friends().search(' The minimalist XksA')[0]
# If you want to reply to all your friends, set the parameters my_friend Change to chats = [Friend]
# Use Turing robot to automatically chat with designated friends
@bot.register(my_friend)
def reply_my_friend(msg):
tuling.do_reply(msg)
# Enter interactive Python Command line interface , And block the current thread
embed()
- Method 2 : Send it manually
post
request , A little trouble hahaha ~
def auto_ai(text):
url = "http://www.tuling123.com/openapi/api"
api_key = " Your Turing interface api"
payload = {
"key": api_key,
"info": text,
"userid": " cousin "
}
r = requests.post(url, data=json.dumps(payload))
result = json.loads(r.content)
return "[ Minimalist robot ] " + result["text"]
bot = Bot(cache_path="H:\PyCoding\Wxpy_test\wxpy.pkl")
print(' The minimalist robot has started ')
# My trumpet , Caution in testing
my_friednd = bot.friends().search(' The minimalist XksA')[0]
# If you want to reply to all your friends, set the parameters my_friend Change to chats = [Friend]
@bot.register(my_friednd)
def my_friednd_message(msg):
print('[ receive ]' + str(msg))
if msg.type != 'Text':
ret = ' What did you show me ![ please ]'
else:
ret = auto_ai(msg.text)
print('[ send out ]' + str(ret))
return ret
# Enter interactive Python Command line interface , And block the current thread
embed()
#####(3) Chat renderings
Basic test , Turing robot can query the weather 、 ticket 、 translate 、 Basic chat and other functions , Than we wrote ourselves , strong ,,, Ha ha ha .
7. Have some fun
(1) Get wechat friend gender 、 Location distribution data
''' author : The minimalist XksA data : 2018.8.26 goal : Get wechat friend gender 、 Distribution 、 Wechat nickname , Visual analysis '''
from wxpy import *
# Initialize a robot object
# cache_path Cache path , The given value is the cache file path generated by the first login
bot = Bot(cache_path="H:\PyCoding\Wxpy_test\wxpy.pkl")
# Get a list of friends ( Including myself )
my_friends = bot.friends(update=False)
''' stats_text function : Help us simply count the basic information of wechat friends Text of simple statistical results :param total: The total number :param sex: Gender distribution :param top_provinces: Province Distribution :param top_cities: City Distribution :return: Statistical result text '''
print(my_friends.stats_text())
Running results :
cousin share 245 Four wechat friends
men : 140 (57.1%)
women : 79 (32.2%)
TOP 10 Province
hubei : 88 (35.92%)
guangdong : 16 (6.53%)
Beijing : 12 (4.90%)
hunan : 5 (2.04%)
Shanghai : 5 (2.04%)
Zhejiang : 4 (1.63%)
Henan : 4 (1.63%)
anhui : 3 (1.22%)
Shandong : 3 (1.22%)
fujian : 3 (1.22%)
TOP 10 City
jingzhou : 25 (10.20%)
wuhan : 22 (8.98%)
Yellowstone : 21 (8.57%)
haidian : 5 (2.04%)
Guangzhou : 5 (2.04%)
Shenzhen : 4 (1.63%)
huanggang : 4 (1.63%)
Hangzhou : 3 (1.22%)
Changsha : 3 (1.22%)
Changping : 3 (1.22%)
(2) utilize Matplotlib Data visualization
1) Gender pie chart
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']
# The above two lines of code solve the problem matplotlib The drawing cannot display Chinese
import matplotlib.pyplot as plt
labels = [' men ', ' women ', ' other ']
sizes = [57.1, 32.2, 10.7]
explode = (0, 0.1, 0)
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
# Vertical and horizontal equality , Draw a circle
ax1.axis('equal')
plt.legend()
plt.show()
design sketch :
My god ( owner-draw ), My wechat friends are actually mostly men , Hey , It's normal , I never flirt , Of course, there are not too few girls hey , Including family, friends and some social people Hey .
2) Urban distribution bar chart
import numpy as np
import matplotlib.pyplot as plt
n_groups = 10
# Urban distribution quantity weight
city_weight = (10.2,8.98,8.57,2.04,2.04,1.63,1.63,1.22,1.22,1.22)
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.4
error_config = {
'ecolor': '0.3'}
rects1 = ax.bar(index, city_weight, bar_width,alpha=opacity, color='b', error_kw=error_config,label=' City ')
ax.set_xlabel(' The city name ')
ax.set_ylabel(' Data share (%)')
ax.set_title(' Friend City Top10')
ax.set_xticks(index + bar_width / 2)
ax.set_xticklabels((' jingzhou ', ' wuhan ', ' Yellowstone ', ' haidian ', ' Guangzhou ',' Shenzhen ', ' huanggang ', ' Hangzhou ', ' Changsha ', ' Changping '))
ax.legend()
fig.tight_layout()
plt.show()
design sketch :
It is easy to see from the figure X Sir, many friends are in Jingzhou , Guess what X Where are you from, sir ? you 're right , It's from Jingzhou hey , Are you also home to the most people among your friends ?( Suddenly homesick !)
3) Distribution map of friend provinces
from pyecharts import Map
# matplotlib The method is troublesome , It doesn't show up yet pyecharts good , Just used it. pyecharts
value = [359.2, 65.3, 49.0, 20.4, 20.4, 16.3, 16.3, 12.2, 12.2,12.2]
attr = [
" hubei ", " guangdong ", " Beijing ", " hunan ", " Shanghai ", " Zhejiang ", " Henan ", " anhui ", " Shandong "," fujian "
]
map = Map(" Friends distribution Province Top10", width=600, height=400)
map.add(
"",
attr,
value,
maptype="china",
is_visualmap=True,
visual_text_color="#000",
)
map.render()
design sketch :
Is it very straightforward , My friends are basically in central and southern China , Do you know the distribution of your friends ? I'm in the middle and lower reaches of the Yangtze River , There are water and mountains here , There are flowers and grass , There is a paradise .
4) Get friends' wechat nicknames and personal signatures , Word cloud analysis
bot = Bot(cache_path="H:\PyCoding\Wxpy_test\wxpy.pkl")
# Get a list of friends ( Including myself )
my_friends = bot.friends(update=False)
# Wechat nickname
nick_name = ''
# Wechat personal signature
wx_signature = ''
for friend in my_friends:
# Wechat nickname :NickName
nick_name = nick_name + friend.raw['NickName']
# Individuality signature :Signature
wx_signature = wx_signature + friend.raw['Signature']
nick_name = jiebaclearText(nick_name)
wx_signature = jiebaclearText(wx_signature)
make_wordcloud(nick_name,1)
make_wordcloud(wx_signature,2)
design sketch :
My wechat friend nickname , It's a little complicated. , Taobao , Hao Hao , stone , And Entrepreneurship , Of course, the most striking is the teacher , They say the teacher is a gardener , Thank you for raising us ( Sudden sense ).
I found that they can practice into a paragraph : All our lives , Is the greatest ordinary self , Meet a beautiful self , Life is more than life , come on. ...
5) Get attention to the name and basic introduction of WeChat official account , Word cloud analysis
# Get the name of WeChat official account
wx_public_name = ''
# Brief introduction of official account
wx_pn_signature = ''
# Get WeChat official account list
my_wx_pn = bot.mps(update=False)
for wx_pn in my_wx_pn:
wx_public_name = wx_public_name + wx_pn.raw['NickName']
wx_pn_signature = wx_pn_signature + wx_pn.raw['Signature']
wx_public_name = jiebaclearText(wx_public_name)
make_wordcloud(wx_public_name,3)
wx_pn_signature = jiebaclearText(wx_pn_signature)
make_wordcloud(wx_pn_signature,4)
design sketch :
See anything strange ? You ask me how much I love you , You look at Python I know. Ha ha !
It can be seen that I pay attention to the positive , Excellent , The official account of technology people should be public. ( The minimalist XksA[ To laugh ]), Hey ,Java,Python, English , data , Reptiles …
3、 ... and 、 an account of happenings after the event being told
summary
Visualize the results from the data above , I speculated that I :X sir , Wechat nickname old watch , Gender male , Coordinate address: Jingzhou, Hubei , Most of the friends are men , It shows that you are ambitious , There are also many women , It shows that women are also good , Wechat friend's personal signature is basically positive , Yeslife
, Yesstruggle
, Yeslike
, WeChat official account is most technical related. , Focus onPython
, Sometimes I play half heartedlyJava
, It should be a college student , Also concerned about the official account of universities. ... Ha ha ha ( The above is pure X Mr. bragging , Seems to make sense hey !)
Writing this article is purely the author's interest , Hey , Welcome to exchange and study !
X Sir, main research Python Data analysis and visualization , Official account number : The minimalist XksA, Long term sharing of learning notes and learning resources , First, a new learning exchange group was established , Welcome to study and communicate with others .
This article refers to the documentation :
1.wxpy Official profile
2.matplotlib Official profile
All the source code of this article has been uploaded to the code cloud :wxpy_matplotlib_learning
边栏推荐
- JDBC introduction
- Global and Chinese market of barrier thin film flexible electronics 2022-2028: Research Report on technology, participants, trends, market size and share
- MySQL数据库(五)视 图 、 存 储 过 程 和 触 发 器
- Practical cases, hand-in-hand teaching you to build e-commerce user portraits | with code
- Nest and merge new videos, and preset new video titles
- Opencv recognition of face in image
- ucore lab6 调度器 实验报告
- CSAPP家庭作業答案7 8 9章
- How to become a good software tester? A secret that most people don't know
- Automated testing problems you must understand, boutique summary
猜你喜欢
UCORE lab1 system software startup process experimental report
UCORE lab7 synchronous mutual exclusion experiment report
Mysql database (I)
UCORE LaB6 scheduler experiment report
ucore lab6 调度器 实验报告
软件测试Bug报告怎么写?
ucore Lab 1 系统软件启动过程
软件测试行业的未来趋势及规划
C language do while loop classic Level 2 questions
What are the commonly used SQL statements in software testing?
随机推荐
Thinking about three cups of tea
UCORE lab1 system software startup process experimental report
Threads et pools de threads
What are the software testing methods? Show you something different
How to solve the poor sound quality of Vos?
UCORE LaB6 scheduler experiment report
Which version of MySQL does php7 work best with?
MySQL数据库(一)
UCORE lab8 file system experiment report
What are the commonly used SQL statements in software testing?
Global and Chinese markets of MPV ACC ECU 2022-2028: Research Report on technology, participants, trends, market size and share
Pedestrian re identification (Reid) - Overview
ucore lab7
STC-B学习板蜂鸣器播放音乐
JDBC介绍
ucore lab2 物理内存管理 实验报告
C4D quick start tutorial - Introduction to software interface
[pytorch] simple use of interpolate
Oracle foundation and system table
In Oracle, start with connect by prior recursive query is used to query multi-level subordinate employees.