環境:Python 3.7.0b3
平臺:Windows
編譯工具:PyCharm
所需模塊Module:itchat、 requests(pip install)
準備:獲取圖靈機器人的api key(先在http://www.tuling123.com/openapi/api註冊,然後創建機器人)
發送post請求:將一json串傳給requests.post()的json參數
(注意中英文符號!!!)
代碼如下(key部分自做修改,註釋部分可調出單獨調試):
'''
Created on 2018年11月26日
@author: 狗賣萌
'''
#coding=utf8
import requests
import itchat
#itchat是一個開源的微信個人號接口,爲python調用微信
#itchat不是微信官方提供的庫,有風險;注意!!!消息發送不過於頻繁及過多重複信息,以免被封
#二維碼登陸網頁版微信
itchat.auto_login(hotReload=True)
#itchat.auto_login(hotReload=True)參數爲True,退出程序以後暫存登錄狀態
#保持熱登錄狀態,但有時限。登錄信息保存在同目錄下itchat.pkl文件中,下次登陸再次調用此方法登入
listfriends = itchat.get_friends()[0:]#獲取好友列表
# [0:] 切片,slice表示一般是start:end:step
# a[start:] >>> items start through the rest of the array
#print(listfriend[0:])此處可獲取好友列表
#exit()
#API調用
apiUrl = 'http://www.tuling123.com/openapi/api'
def get_response(message):
#發給服務器的數據
data = {
'key':'Input Your apiUrlKey',#yes,do as you see
'info': message,
'userid' : '狗賣萌',
}
try:
r = requests.post(apiUrl, data=data).json()
#捕捉異常,post發送方式到apiUrl,在沒有'text'的值的時候返回None
print('狗賣萌 :%s'% r["text"])#機器人回覆的消息
return r.get('text')
except:
#返回None
return
#get_response('狗賣萌呀?')
@itchat.msg_register(itchat.content.TEXT)
def auto_reply(msg):#通過run調用
#name = input('清輸入要自動回覆的微信好友')
defaultReply = 'I received: ' + msg['Text']
#realFriends = itchat.search_friends('DUDUDU')
#獲取微信好友姓名name='DUDUDU'(示例)
#注意後面的if與else
realFriendsName = realFriends[0]['UserName']
#nickName,微信編碼後的名稱
#print(realFriendsName)
print('User:%s' % msg['Text']) # 獲取機器人回覆的消息
reply = get_response(msg['Text'])
'''
if msg['FromUserName'] == realFriendsName:#加if與else
itchat.send(reply,toUserName=realFriendsName)
else:
itchat.send(reply,toUserName=realFriendsName)
#給指定人發消息>>>if
'''
return reply or defaultReply
#如果return有內容,那麼返回return,否則返回defaultReply
itchat.run()
好像是有點生硬來着,也可以改人物設置的,只是嘛要錢錢
若需要機器人持久在線,可以把腳本掛到服務器上,全天運行
(新微信號暫時無法網頁登陸)
若需快速退出的話可以調用itchat.logout()註銷登錄狀態
注意:新微信號暫時無法登入網頁版微信