安裝
安裝python3環(huán)境,請(qǐng)找度娘。
pip install itchat
pip install requests
抓取網(wǎng)頁(yè)
def getHtmlText(url):
try:
r = requests.get(url,timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
當(dāng)接收到的消息是Text時(shí)自動(dòng)回復(fù)
@itchat.msg_register(['Text','Map', 'Card', 'Note', 'Sharing', 'Picture'])
def text_reply(msg):
# 當(dāng)消息不是由自己發(fā)出的時(shí)候 if not msg['FromUserName'] == Name["自己微信號(hào)"]:
# 或者指定微信好友
if msg['FromUserName'] == Name["好友微信昵稱"]:
# 回復(fù)給好友
tulingkey = "***********" #注冊(cè)圖靈官網(wǎng)申請(qǐng)自己的機(jī)器人
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
# 抓取網(wǎng)頁(yè)
def getHtmlText(url):
try:
r = requests.get(url,timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
# 自動(dòng)回復(fù)
@itchat.msg_register(['Text','Map', 'Card', 'Note', 'Sharing', 'Picture'])
def text_reply(msg):
# 當(dāng)消息不是由自己發(fā)出的時(shí)候 if not msg['FromUserName'] == Name["自己微信號(hào)"]:
# 或者指定微信好友
if msg['FromUserName'] == Name["好友微信昵稱"]:
# 回復(fù)給好友
tulingkey = "***********" #注冊(cè)圖靈官網(wǎng),申請(qǐng)自己的機(jī)器人
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()