python 实现微信机器人自动回复
程序员文章站
2022-03-28 15:34:59
1.python 实现微信机器人自动回复# 源代码如下:import jsonimport itchatimport requestsimport re# 机器人接口调用def getHtmlText(url): try: r = requests.get(url, timeout=30) r.raise_for_status() r.encoding = r.apparent_encoding return r...
1.python 实现微信机器人自动回复
# 源代码如下:
import json
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):
# 当消息不是由自己发出的时候
print(msg)
if msg['FromUserName'] != Name["自己的微信昵称"]:
# 回复给好友
url = "http://api.qingyunke.com/api.php?key=free&appid=0&msg="
url = url + msg['Text']
html = getHtmlText(url)
object = json.loads(html)
re = object['content']
print("auto message--->" + re)
return re
else:
print("no auto send--->")
if __name__ == '__main__':
itchat.auto_login()
qr = itchat.get_QR;
# 获取自己的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()
2.启动后看到如下,表示启动成功,会弹出一张二维码图
3.扫码成功后登录成功!看到Start auto replying 即成功啦!
4.完成机器人聊天啦!
本文地址:https://blog.csdn.net/qq_36472252/article/details/109030287