10分鐘用Python告訴你兩個機器人聊天能聊出什麼火花

欲直接下載代碼文件,關注咱們的公衆號哦!查看歷史消息便可!php

如今不是講各類各樣的人工智能嘛,AI下棋,AI客服,AI玩家……其實我一直很好奇,兩個AI碰上會怎樣,好比一塊兒下棋,一塊兒打遊戲……python

今天作個簡單的小實驗,看看兩個AI一塊兒聊天會是什麼樣子的。爲了讓實驗效果更好,咱們兩個機器人選取了不一樣網站的機器人(圖靈和茉莉)。api

01 準備

1) pip下載安裝python的requests模塊,這個調用接口發送消息要用到。函數

2) 去圖靈機器人官網(http://www.turingapi.com/)申請帳號->進入機器人設置->得到apikey。以下:post

記得不要把密鑰那裏點開,否則後面要加密傳輸搞得很麻煩。測試

3) 茉莉機器人官網(http://www.itpk.cn/)申請帳號->我的中心->得到Api key and Api Secret:網站

記得:人工智能

茉莉API地址:http://i.itpk.cn/api.php
圖靈API地址:http://www.tuling123.com/openapi/api加密

待會搞事要用到。url

02 開始搞事

好了,如今一切準備就緒,咱們開始搞事情。

先調一下圖靈機器人,測試一下:

1import requests
 2
 3tuling_data = {
 4    "key": "5da047a95db8450ea6e710dd065d4be4",
 5    "info": '今天武漢天氣怎樣?',      #發送的數據
 6    "userid": "272872"
 7}
 8tuling_api_url = 'http://www.tuling123.com/openapi/api'
 9t = requests.post(tuling_api_url, data=tuling_data)         #post請求
10print(t.text)

運行結果以下:

大功告成,不過返回的是數據包,待會咱們用函數處理一下,提取所需的信息便可。

一樣能夠調用茉莉機器人:

1import requests
 2
 3moli_data = {
 4    "question":'今天武漢天氣如何?',    #問題
 5    "api_key": "ac00db995a4a8f2a3f3623c82f3cc9d9",
 6    "api_secret": "anaoutswrz1y"
 7}
 8moli_api_url = 'http://i.itpk.cn/api.php'
 9m = requests.post(moli_api_url, data = moli_data)
10print(m.text)

返回結果:

03 機器人之間的對話

而後就是整合兩個機器人,讓他們在一塊兒聊聊天看看會發生什麼了。

最簡單的思路,先給一個導火線,而後死循環讓他倆對話就行。。。

1from time import sleep
 2import requests
 3
 4question = input("輸入導火線:")
 5TULING = '圖靈'
 6MOLI = '茉莉'
 7print(TULING+':'+question)          #導火索  哈哈
 8while True:
 9    #圖靈
10    tuling_data = {
11        "key": "5da047a95db8450ea6e710dd065d4be4",
12        "info": question,
13        "userid": "272872"
14    }
15    tuling_api_url = 'http://www.tuling123.com/openapi/api'
16    t = requests.post(tuling_api_url, data=tuling_data) #post請求
17
18    print(TULING+':'+eval(t.text)["text"]) #用eval函數處理一下圖靈返回的消息
19    question = eval(t.text)["text"]     #重置question —>讓茉莉回答
20
21    #茉莉
22    moli_data = {
23        "question": question,
24        "api_key": "ac00db995a4a8f2a3f3623c82f3cc9d9",
25        "api_secret": "anaoutswrz1y"
26    }
27    moli_api_url = 'http://i.itpk.cn/api.php'       #api地址
28    m = requests.post(moli_api_url, data = moli_data)
29    print(MOLI+':'+m.text)
30    sleep(1)        #設置循環延遲

不過這聊天確實有點尷尬啊:

相關文章
相關標籤/搜索