2

我正在尝试使用 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()

有谁知道解决这个问题的方法?

4

2 回答 2

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
于 2017-01-11T15:14:43.817 回答
0

在 read() 之后使用 decode('utf-8')。

而且由于您刚开始,现在将您的代码移动到 Python 3.5 而不是 2.7 将是一个好主意......

apiai_request.getresponse().read().decode('utf-8'))

请注意,不幸的是,他们在示例中命名为“请求”,因为它与请求库、烧瓶请求等冲突……但这就是生活。

于 2016-10-10T13:47:52.100 回答