我正在尝试使用api.ai创建自己的聊天机器人。
它第一次变好但第二次出现此错误:
Traceback (most recent call last):
File "/root/Documents/Projects/Darlene/core/api.py", line 34, in <module>
main()
File "/root/Documents/Projects/Darlene/core/api.py", line 28, in main
speech, action = b.handle(cmd)
File "/root/Documents/Projects/Darlene/core/api.py", line 15, in handle
response = self.request.getresponse().read()
File "/usr/local/lib/python2.7/dist-packages/apiai/requests/request.py", line 133, in getresponse
return self._connection.getresponse()
File "/usr/lib/python2.7/httplib.py", line 1123, in getresponse
raise ResponseNotReady()
httplib.ResponseNotReady
看起来api有问题。但我不确定。 这是我的代码:
import apiai
import json
class Bot(object):
def __init__(self, client_token='<clientToken>'):
self.AI = apiai.ApiAI(client_token)
self.request = self.AI.text_request()
self.request.lang = 'en'
def handle(self, text):
self.request.query = text
response = self.request.getresponse().read()
speech = str(json.loads(response)['result']['fulfillment']['speech'])
action = str(json.loads(response)['result']['action'])
if action is not '':
return speech, action
else:
return speech, None
def main():
b = Bot()
while True:
cmd = raw_input('me; ')
speech, action = b.handle(cmd)
print speech
if action is not None:
print 'action'
if __name__ == '__main__':
main()
有没有人知道解决这个问题的方法?
答案 0 :(得分:2)
请不要重复使用请求。只为每个阶段创建新请求。同样如下:
def handle(self, text):
self.request = self.AI.text_request()
self.request.lang = 'en'
self.request.query = text
response = self.request.getresponse().read()
speech = str(json.loads(response)['result']['fulfillment']['speech'])
action = str(json.loads(response)['result']['action'])
if action is not '':
return speech, action
else:
return speech, None
答案 1 :(得分:0)
而且,由于您刚开始将代码移至Python 3.5而不是2.7 ...
。apiai_request.getresponse()读取()进行解码(&#39; UTF-8&#39;))
请注意,不幸的是,他们在他们的例子中命名了#34;请求&#34;因为它与请求库,烧瓶请求等冲突......但这就是生命。