功能实现
- 好友性别分析
- 微信消息自动回复
- 好友头像自动下载
import itchat
import requests
import json
import os
import matplotlib.pyplot as plt
import random
def analysisFriends():
friends = itchat.get_friends()
male = 0
female = 0
others = 0
for i in friends:
sex = i['Sex']
if sex == 1:
male += 1
elif sex == 2:
female += 1
else:
others += 1
total = len(friends[1:])
print('男性好友:%.2f%%' % (float(male) / total * 100))
print('女性好友:%.2f%%' % (float(female) / total * 100))
print('其他:%.2f%%' % (float(others) / total * 100))
man_rate = float(male) / total * 100
woman_rate = float(female) / total * 100
others_rate = float(others) / total * 100
rate = [man_rate, woman_rate, others_rate]
labels = ['男', '女', '其他']
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.axes(aspect='equal')
plt.pie(
x=rate,
labels=labels,
autopct='%.1f%%',
pctdistance=0.8,
labeldistance=1.2,
startangle=180,
radius=1.2,
wedgeprops={'linewidth': 1.5, 'edgecolor': 'pink'},
textprops={'fontsize': 15, 'color': 'black'},
)
plt.show()
def getHeadImg():
friends = itchat.get_friends()[0:]
for j in friends:
img = itchat.get_head_img(userName=j['UserName'])
dirname = '好友头像'
if not os.path.exists(dirname):
os.mkdir(dirname)
path = dirname + '/' + j['RemarkName'] + '.jpg'
try:
with open(path, 'wb') as f:
f.write(img)
except Exception as e:
print(repr(e))
print(j['RemarkName'] + '的头像已下载完成。')
def get_response(message):
apiUil = 'http://openapi.tuling123.com/openapi/api/v2'
keys = ['key1',
'key2',
'key3',
'key4',
'key5',
]
key = random.choice(keys)
data = {
"reqType": '',
"perception": {
"inputText": {
"text": message
},
"inputImage": {
"url": "imageUrl"
},
"selfInfo": {
"location": {
"city": "哈尔滨",
"province": "黑龙江省",
"street": "电碳路"
}
}
},
"userInfo": {
"apiKey": 'key',
"userId": "robot"
}
}
data = json.dumps(data)
re = requests.post(url=apiUil, data=data, ).text
re_dic = json.loads(re)
robotResponse = re_dic['results'][0]['values']['text']
return robotResponse
@itchat.msg_register(itchat.content.TEXT, isFriendChat=True)
def robot_reply(message):
defaultReply = '收到'
reply = get_response(message['Text'])
return reply or defaultReply
if __name__ == '__main__':
itchat.login()
print('########## 微信助手V1.0-仁义 ##########')
a = input('是否分析好友性别比例(y/n):')
if a == 'y':
analysisFriends()
b = input('是否开始机器人自动回复(y/n):')
if b == 'y':
print('开启机器人自动回复......')
itchat.run()
c = input('是否下载好友头像(y/n):')
if c == 'y':
getHeadImg()
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7466f7971a8c2f168775d4bc5ef5d36c.png)