安装
安装python3环境,请找度娘。
pip install itchat
pip install requests
抓取网页
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["自己微信号"]:
# 或者指定微信好友
if msg['FromUserName'] == Name["好友微信昵称"]:
# 回复给好友
tulingkey = "***********" #注册图灵官网申请自己的机器人
url = "http://www.tuling123.com/openapi/api?key=%s&info=" % (tulingkey)
url = url + msg['Text']
html = getHtmlText(url)
message = re.findall(r'\"text\"\:\".*?\"',html)
reply = eval(message[0].split(':')[1])
return reply
完整代码
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 ""
# 自动回复
@itchat.msg_register(['Text','Map', 'Card', 'Note', 'Sharing', 'Picture'])
def text_reply(msg):
# 当消息不是由自己发出的时候 if not msg['FromUserName'] == Name["自己微信号"]:
# 或者指定微信好友
if msg['FromUserName'] == Name["好友微信昵称"]:
# 回复给好友
tulingkey = "***********" #注册图灵官网,申请自己的机器人
url = "http://www.tuling123.com/openapi/api?key=%s&info=" % (tulingkey)
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(hotReload=True)
# 获取自己的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()
网友评论