我正在尝试从dialogflow获取直接文本响应。我从github上的示例代码中得到答案,但这根本不是用户友好的。如何才能获得“仅限语音”的回复?
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}'
答案 0 :(得分:3)
尝试这样来获取消息:
response = json.loads(request.getresponse().read().decode('utf-8'))
message = response['result']['fulfillment']['speech']
print (message)
别忘了添加
import json
一开始。如果尚未安装,请安装它。如果你想在python中处理json,你将不得不这样做。 告诉我它是否有效
答案 1 :(得分:0)
您似乎正在使用Dialogflow's query API。记录的响应格式为here。您必须解析JSON。最常见的方法是......
json
模块(例如文件顶部的import json
)。 response
后添加一行:response_dict = json.loads(response.read())
response_dict
对象中检索正确的字符串:print(response_dict.['result']['resolvedQuery'])