這兩一直在玩聊天機器人,現在分享給大家。
一、獲取機器人
首先去圖靈機器人官網注冊一個賬號并新建一個其它類機器人。新建完成后在“我的機器人》機器人詳情》接入”頁面即可看到每一個機器人的API KEY,如下圖所示:

二、測試機器人
上面我們已經有了機器人并拿到了key現在新建一個程序測試下
import requests
import json
from datetime import datetime
key = '***' #替換成你的key
while True:
data = str(input('請輸入:'))
data = {"key":key,"info":data}
postdata = json.dumps(data)
r = requests.post('http://www.tuling123.com/openapi/api',data=postdata)
rend_data = r.text
updata = json.loads(rend_data)
rend_data = ''
#根距接收的數據類型選擇 say 方式
if updata['code'] == 100000:
print( updata['text'])
if updata['code'] == 200000:
print( updata['text'])
print( updata['url'])
if updata['code'] == 308000:
temp = (updata['list'])
for i in range(0,len(temp)):
client_data = dict(temp[i])
print(client_data['icon'])
print(client_data['name'])
print(client_data['info'])
print(client_data['detailurl'])
if updata['code'] == 302000:
temp = (updata['list'])
for i in range(0,len(temp)):
client_data = dict(temp[i])
print(client_data['article'])
print(client_data['icon'])
print(client_data['source'])
print(client_data['detailurl'])
測試效果如下:

三、接入貝殼
1、新建一個文件并保存為config.py 用來保存配置。代碼如下:
#!/uer/bin/python3
# -*- coding:utf-8 -*-
#===================
# bitiot.net 配置
#===================
class bigiot:
host = 'www.eqytg.org'
port = 8181
deviceid = '***' #設備ID
apikey = '***' #key
iputid1 = '***' #數據接口,備用
checkin = {
"M":"checkin",
"ID":deviceid,
"K":apikey
}
#===========================
# 圖靈機器人配置
# http://www.tuling123.com/
#===========================
class tulin:
key = '***' #機器人key
host = 'http://www.tuling123.com/openapi/api'
2、新建一個文件并保存為function.py 用來存放函數。代碼如下:
#!/uer/bin/python3
# -*- coding:utf-8 -*-
import requests
import socket
import time
import json
from config import bigiot as big
from config import tulin as t
from datetime import datetime
address =(big.host, big.port)
checkin = json.dumps(big.checkin)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#=============================
# bigiot
# 2016/12/21
#=============================
class bigiot:
def big_line(self): #連接貝殼平臺
while True:
try:
s.connect(address)
print(address)
time.sleep(2)
except:
print('連接失敗!嘗試重新連接...')
time.sleep(2)
else:
s.sendall(checkin.encode('utf-8'))
s.sendall(b'\n')
print(checkin)
break
def keep_online(self,t): #在線狀態檢察
if time.time() - t > 40: #每40S'{"M":"status"}'一次
s.sendall(b'{\"M":\"status\"}\n')
print('[{0}]-->check status'.format(datetime.now()))
return time.time()
else:
return t
def say(self,id,coutent): #發送指令(say方式)
__coutent = {"M":"say","ID":id, "C":coutent}
__coutent = json.dumps(__coutent)
s.sendall(__coutent.encode('utf-8'))
s.sendall(b'\n')
def process(self,b_data): #解析平臺數據
global msg
msg = b_data
print('[{0}]-->{1}'.format(datetime.now(),msg))
if msg['M'] == 'connected':
s.sendall(checkin.encode('utf-8'))
s.sendall(b'\n')
if msg['M'] == 'say':
bigiot.chitchat(msg['C']) #調用機器人函數
if msg['M'] == 'login':
bigiot.say(msg['ID'], '你好!我是小冰,請問有什么可以幫你!')
msg.clear()
def chitchat(self,data): #機器人
__data = {"key":t.key,"info":data}
__postdata = json.dumps(__data)
r = requests.post(t.host,data=__postdata)
__rend_data = r.text
__updata = json.loads(__rend_data)
__rend_data = ''
print('[{0}]-->{1}'.format(datetime.now(),__updata['code']))
#根距接收的數據類型選擇 say 方式
if __updata['code'] == 100000:
bigiot.say(msg['ID'], __updata['text'])
if __updata['code'] == 200000:
bigiot.say(msg['ID'], __updata['text'])
bigiot.say(msg['ID'], __updata['url'])
if __updata['code'] == 308000:
__temp = (__updata['list'])
for i in range(0,len(__temp)):
__client_data = dict(__temp[i])
bigiot.say(msg['ID'], __client_data['detailurl'])
bigiot.say(msg['ID'], __client_data['info'])
bigiot.say(msg['ID'], __client_data['name'])
bigiot.say(msg['ID'], __client_data['icon'])
if __updata['code'] == 302000:
__temp = (__updata['list'])
for i in range(0,len(__temp)):
__client_data = dict(__temp[i])
bigiot.say(msg['ID'], __client_data['detailurl'])
bigiot.say(msg['ID'], __client_data['source'])
bigiot.say(msg['ID'], __client_data['icon'])
bigiot.say(msg['ID'], __client_data['article'])
__updata = ''
bigiot = bigiot()
3、新建一個文件并保存為tcp_client.py 代碼如下:
#!/uer/bin/python3
# -*- coding:utf-8 -*-
import function
import time
fs = function.s
bigiot = function.bigiot
bigiot.big_line() #調用big_line()連接bigiot.net
fs.settimeout(0)
t1 = t2 =time.time()
while True:
try:
temp = fs.recv(1024)
t1 = time.time()
except:
time.sleep(2)
t1 = bigiot.keep_online(t1)
pass
else:
try:
msg = eval(str(temp,encoding = 'utf-8'))
t2 = time.time()
except:
'''
如果90s內沒有收到平臺返回的數據,
則認定為掉線,并重新調用big_line()
函數
'''
if time.time() - t2 > 90:
bigiot.big_line()
else:
bigiot.process(msg)
msg.clear()
把上面三個方件放在一個方件夾內,然后啟動tcp_client.py
現在你的機器人也上線了^-^
四、一些問題
1、這套代碼在PC的運行正常,樹莓派上也沒問題;但在樹莓派上運行時機器人回答的比較慢,我的是大概5秒才收到返回信息而PC是秒回。至于是什么原因造成不太清楚還望大神指點。
2、在function.py中的process()函數中加入了對{"M":"login"}的返回,如果你現在有兩個設備在相互say將有可能陷入無限循環,當然你也可以去掉對{"M":"login"}的處理。
3、由于本人是剛學python所以代碼中對錯誤的處理都比較‘暴力’,當遇到錯誤時只會跳過并不會輸出錯誤信息;如你要調試代碼請用python IDLE 調試或自行更改錯誤處理方式。這種錯誤處 理方式極不推薦可其它的我還沒學會-_-!
4、不要問我為什么把非要用類,上面說過了,我現在剛學python的類,拿來練手的。