Python-微信聊天机器人

    xiaoxiao2025-02-15  16

    文章目录

    功能实现

    功能实现

    好友性别分析微信消息自动回复好友头像自动下载 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'] # print(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)) # print(friends) 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 = ['男', '女', '其他'] # explode = [0.1, 0, 0] plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False plt.axes(aspect='equal') plt.pie( x=rate, # explode=explode, 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'}, ) # friends_dic = json.loads(friends) # a = plt.title(friends['NickName'][0:0] + '的好友比例分布图') # print(type(a)) plt.show() def getHeadImg(): friends = itchat.get_friends()[0:] for j in friends: img = itchat.get_head_img(userName=j['UserName']) # path = 'C:\\Users\仁义\Desktop\好友头像\\' + j['NickName'] + '.jpg' 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" } } # print(data) # 将dic格式的data编码为UTF-8 data = json.dumps(data) # print(data) # requests的请求方式为post,并将请求结果转换为文本 re = requests.post(url=apiUil, data=data, ).text # 将请求结果str格式转换为dict格式 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-仁义 ##########') # itchat.auto_login(hotReload=True, ) a = input('是否分析好友性别比例(y/n):') if a == 'y': analysisFriends() b = input('是否开始机器人自动回复(y/n):') if b == 'y': # get_response('你好') # robot_reply() print('开启机器人自动回复......') itchat.run() c = input('是否下载好友头像(y/n):') if c == 'y': getHeadImg()

    最新回复(0)