如何直接在 Dialogflow 上获取文本响应?

How to get text response directly on Dialogflow?

我正在尝试从 dialogflow 获得直接的文本响应。我确实从 github 上的示例代码中得到了答案,但那根本不是用户友好的。如何获得 "Speech-Only" 响应?

import os.path
import sys

try:
    import apiai
except ImportError:
    sys.path.append(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)
    )
    import apiai

CLIENT_ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN'


def main():
    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)

    request = ai.text_request()

    request.lang = 'de'  # optional, default value equal 'en'

    request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"

    request.query = "Hello"

    response = request.getresponse()

    print (response.read())


if __name__ == '__main__':
    main()

我只希望得到一个简单的结果。一个简单的问候语。

我得到的=b'{\n "id": "306fd06a-d9e6-4c2e-8c05-98ff7fc0ecd5",\n "timestamp": "2017-12-05T22:18:15.563Z",\n "lang": "en",\n "result": {\n "source": "agent",\n "resolvedQuery": "hi",\n "action": "input.welcome",\n "actionIncomplete": false,\n "parameters": {},\n "contexts": [],\n "metadata": {\n "intentId": "8406ea3a-a0c9-4470-829f-aba0ce2da2e5",\n "webhookUsed": "false",\n "webhookForSlotFillingUsed": "false",\n "intentName": "Default Welcome Intent"\n },\n "fulfillment": {\n "speech": "Hi there!",\n "messages": [\n {\n "type": 0,\n "speech": "Hi there!"\n }\n ]\n },\n "score": 1.0\n },\n "alternateResult": {\n "source": "domains",\n "resolvedQuery": "hi",\n "action": "smalltalk.greetings.hello",\n "actionIncomplete": false,\n "parameters": {},\n "contexts": [],\n "metadata": {},\n "fulfillment": {\n "speech": "Hey!",\n "source": "agent"\n },\n "score": 1.0\n },\n "status": {\n "code": 200,\n "errorType": "success",\n "webhookTimedOut": false\n },\n "sessionId": "mr.9000"\n}'

像这样尝试获取消息:

response = json.loads(request.getresponse().read().decode('utf-8'))
message = response['result']['fulfillment']['speech']
print (message)

别忘了加

import json

开头。如果您还没有安装它,请安装它。如果你想在 python 中处理 json,你将不得不这样做。 告诉我它是否有效

您似乎在使用 Dialogflow's query API. The format of the response is documented here。您必须解析 JSON。最常见的方法是...

  1. 使用您需要导入的 json 模块(即文件顶部的 import json)。
  2. 接下来,您需要加载使用加载方法收到的 JSON 字符串(即在定义 response 后添加一行:response_dict = json.loads(response.read())
  3. 最后,您需要从 response_dict 对象中检索正确的字符串:print(response_dict.['result']['resolvedQuery'])