【python 應用】50行實現微信聊天機器人

開發工具

python3.7html

itchatpython

 

原理講解

作一個可以與人交流的機器人有不少種方法,最簡單的莫過於使用他人提供的接口。web

咱們這裏以圖靈機器人爲例,演示這一功能。json

圖靈機器人簡單而言就是以必定的規則給圖靈的服務器發送數據包(包含你對他說的話)api

圖靈的服務器會以必定的規則給你返回數據包(包含他回覆你的話),圖靈機器人的Tyling Key的獲取的幫助文檔http://www.tuling123.com/help/h_cent_webapi.jhtml服務器

你須要一個Tuling Key來告訴圖靈服務器你有權和他對話,我這裏免費提供一些:app

8edce3ce905a4c1dbb965e6b35c3834d
eb720a8970964f3f855d863d24406576
1107d5601866433dba9599fac1bc0083
71f28bf79c820df10d39b4074345ef8c

下面我作一個配置圖靈機器人的簡單介紹工具

請求方式post

HTTP POST開發工具

請求參數

請求參數格式爲 json

 

發送的規則簡而言之是這樣的:

{
	"reqType":0, "perception": { "inputText": { "text": msg, } }, "userInfo": { "apiKey": KEY, "userId": uid, } } 

其中userId是用戶的標誌,讓機器人知道你是你。(也就是一個Tuling Key能夠有多個用戶)

而返回的內容基本是這樣的:

{
'intent': {'code': xxx}, 'results': [{'groupType': 0, 'resultType': 'text', 'values': {'text': 'xxx'}}] }

咱們須要的內容就在values鍵的text鍵裏面。

這裏咱們使用requests包完成整個操做(已經包含在itchat包的安裝中了)。

最後值得一提的就是這是一個post請求,那麼直接上代碼應該比我絮絮不休的說要直觀不少。

# -*- coding: utf-8 -*- import json import time import requests import itchat #Turling_key KEY = '54d7869f48ff4f1f8d856d52d3c7cdf2' def get_response(msg):     '''     發送數據包給圖靈服務器     '''     apiUrl = 'http://openapi.tuling123.com/openapi/api/v2'     #動態生成userid     uid = 'rrh'     #字典轉json     data ={     "reqType":0,     "perception": {         "inputText": {             "text": msg,         }     },     "userInfo": {         "apiKey": KEY,         "userId": uid,     } }          try:         data_json = json.dumps(data)         response = requests.post(apiUrl,data=data_json).json()         print(response)         return response['results'][0]['values']['text']     except:         return #處理消息並自動回覆 @itchat.msg_register(itchat.content.TEXT) def tuling_reply(msg):     #默認回覆     defaultReply = '【{}】,這句話俺聽不懂啦'.format(msg['Text'])     FromUserName = msg['FromUserName']     reply = get_response(msg['Text'])     if reply:         itchat.send(reply,toUserName=FromUserName)     else:         itchat.send(defaultReply,toUserName=FromUserName) if __name__ == '__main__':     itchat.auto_login(hotReload=True)     itchat.run()
相關文章
相關標籤/搜索