【Python3.6】將個人微信改造成機器人自動對話
阿新 • • 發佈:2018-12-25
原始碼:http://download.csdn.net/download/weixin_37637399/9983454
python版本:Python3.6
前期準備:註冊一個圖靈機器人:http://www.tuling123.com,得到一個APIkey,如下圖。
思路:使用itchat庫呼叫微信介面,將圖靈機器人API作為微信機器人的自動對話。
import requests
import itchat
#填寫自己剛才註冊的圖靈機器人的APIkey
KEY = '自己的圖靈機器人的APIkey'
#根據圖靈機器人API的規定傳送資料
def tuling_reponse (msg):
url = 'http://www.tuling123.com/openapi/api'
data = {
'key' : KEY,
'info' : msg,
'userid' : 'xsl' #這個隨便填,作為機器人識別的標誌,因為一個機器人可以供多個使用者使用
}
#rep返回的資料格式大概是這樣{'code': 100000, 'text': '你好'}
rep = requests.post(url,data).json()
return rep.get('text')
#定義訊息處理函式
#itchat.content.TEXT代表只處理文字資訊,圖片、語音都可以處理,自己百度一下就好
@itchat.msg_register(itchat.content.TEXT)
def get_reponse(msg):
reponse=tuling_reponse(msg['Text'])
return reponse
itchat.auto_login(hotReload=True)
itchat.run()