python-微信自动回复(附源码)

版权声明:禁止转载至其它平台,转载至博客需带上此文链接。 https://blog.csdn.net/qq_41841569/article/details/85339028

今天发现一个好玩的项目,用python实现微信自动回复。

来源:https://mp.weixin.qq.com/s/3q5l14c1BvJUtEmEkOA_Rw

用起来记得把参数改改。

源代码:

python-微信自动回复(附源码)

import itchat
import requests
import re
# 抓取网页
def getHtmlText(url):
 try:
 r = requests.get(url,timeout=30)
 r.raise_for_status()
 r.encoding = r.apparent_encoding
 return r.text
 except:
 return ""
# 自动回复
# 封装好的装饰器,当接收到的消息是Text,即文字消息
@itchat.msg_register(['Text','Map', 'Card', 'Note', 'Sharing', 'Picture'])
def text_reply(msg):
 # 当消息不是由自己发出的时候
 if not msg['FromUserName'] == Name["pikachu"]:
 # 回复给好友
 url = "http://www.tuling123.com/openapi/api?key=apikey&info="
 url = url + msg['Text']
 html = getHtmlText(url)
 message = re.findall(r'"text":".*?"',html)
 reply = eval(message[0].split(':')[1])
 return reply
if __name__ == '__main__':
 itchat.auto_login()
 # 获取自己的UserName
 friends = itchat.get_friends(update=True)[0:]
 Name = {}
 Nic = []
 User = []
 for i in range(len(friends)):
 Nic.append(friends[i]["NickName"])
 User.append(friends[i]["UserName"])
 for i in range(len(friends)):
 Name[Nic[i]] = User[i]
 itchat.run()

原理:

这个就是自动登录网页版微信(这是itchat库的功能),把联系人发送的消息输入图灵机器人,然后把URL页面上的消息抓下来,返回给联系人。

这个功能还挺有用的,可以接入自己的数据库,就可以查询想要的数据啦。

作者的效果图:

python-微信自动回复(附源码)

猜你喜欢

转载自blog.csdn.net/qq_41841569/article/details/85339028