Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何访问JSON以鹦鹉学舌地回复用户响应?_Python_Json_Flask_Google Assistant Sdk - Fatal编程技术网

Python 如何访问JSON以鹦鹉学舌地回复用户响应?

Python 如何访问JSON以鹦鹉学舌地回复用户响应?,python,json,flask,google-assistant-sdk,Python,Json,Flask,Google Assistant Sdk,我正在尝试制作一个谷歌家庭助理,只要用户对它说什么,它就会鹦鹉学舌地回复。基本上,我需要捕获用户所说的内容,然后将其反馈到响应中 我找到了一些拼图 一个是初始化API以执行查询: api = ApiAi(os.environ['DEV_ACCESS_TOKEN'], os.environ['CLIENT_ACCESS_TOKEN']) 另一种是回退意图,旨在捕获用户所说的任何内容,并将其重复: @assist.action('fallback', is_fallback=True) def s

我正在尝试制作一个谷歌家庭助理,只要用户对它说什么,它就会鹦鹉学舌地回复。基本上,我需要捕获用户所说的内容,然后将其反馈到响应中

我找到了一些拼图

一个是初始化API以执行查询:

api = ApiAi(os.environ['DEV_ACCESS_TOKEN'], os.environ['CLIENT_ACCESS_TOKEN'])
另一种是回退意图,旨在捕获用户所说的任何内容,并将其重复:

@assist.action('fallback', is_fallback=True)
def say_response():
    """ Setting the fallback to act as a looper """
    speech = "test this" # <-- this should be whatever the user just said
    return ask(speech)
我初始化的模块如下所示:

{
  "id": "XXXX",
  "timestamp": "2017-07-20T14:10:06.149Z",
  "lang": "en",
  "result": {
    "source": "agent",
    "resolvedQuery": "ok then",
    "action": "say_response",
    "actionIncomplete": false,
    "parameters": {},
    "contexts": [],
    "metadata": {
      "intentId": "a452b371-f583-46c6-8efd-16ad9cde24e4",
      "webhookUsed": "true",
      "webhookForSlotFillingUsed": "true",
      "webhookResponseTime": 112,
      "intentName": "fallback"
    },
    "fulfillment": {
      "speech": "test this",
      "source": "webhook",
      "messages": [
        {
          "speech": "test this",
          "type": 0
        }
      ],
      "data": {
        "google": {
          "expect_user_response": true,
          "is_ssml": true
        }
      }
    },
    "score": 1
  },
  "status": {
    "code": 200,
    "errorType": "success"
  },
  "sessionId": "XXXX"
}
完整程序如下所示:

import os
from flask import Flask, current_app, jsonify
from flask_assistant import Assistant, ask, tell, event, context_manager, request
from flask_assistant import ApiAi

app = Flask(__name__)
assist = Assistant(app, '/')

api = ApiAi(os.environ['DEV_ACCESS_TOKEN'], os.environ['CLIENT_ACCESS_TOKEN'])
# api.post_query(query, None)

@assist.action('fallback', is_fallback=True)
def say_response():
    """ Setting the fallback to act as a looper """
    speech = "test this" # <-- this should be whatever the user just said
    return ask(speech)

@assist.action('help')
def help():
    speech = "I just parrot things back!"
    ## a timeout and event trigger would be nice here? 
    return ask(speech)

@assist.action('quit')
def quit():
    speech = "Leaving program"
    return tell(speech)

if __name__ == '__main__':
    app.run(debug=False, use_reloader=False)
导入操作系统
从烧瓶导入烧瓶,当前应用程序,jsonify
来自flask_assistant导入助手、询问、告知、事件、上下文管理器、请求
来自美国助理进口ApiAi
app=烧瓶(名称)
辅助=助手(应用程序“/”)
api=ApiAi(os.environ['DEV\u ACCESS\u TOKEN'],os.environ['CLIENT\u ACCESS\u TOKEN']))
#api.post_查询(查询,无)
@assist.action('fallback',is_fallback=True)
def say_response():
“”“将回退设置为充当循环器”“”

speech=“testthis”#flask\u助手库很好地将请求解析为
dict
对象

您可以通过以下方式获得
resolvedQuery

speech = request['result']['resolvedQuery']
只需使用sys.any创建一个新的intent(不管名称如何)和一个模板;之后,在服务器上使用类似于以下代码的代码

userInput = req.get(‘result’).get(‘parameters’).get(‘YOUR_SYS_ANY_PARAMETER_NAME’)
然后将userInput作为语音响应发送回

下面是获取初始JSON数据的方式:

@app.route(’/google_webhook’, methods=[‘POST’])
def google_webhook():
# Get JSON request
jsonRequest = request.get_json(silent=True, force=True, cache=False)

print("Google Request:")
print(json.dumps(jsonRequest, indent=4))

# Get result 
appResult = google_process_request(jsonRequest)
appResult = json.dumps(appResult, indent=4)

print("Google Request finished")

# Make a JSON response 
jsonResponse = make_response(appResult)
jsonResponse.headers['Content-Type'] = 'application/json'
return jsonResponse

这就是我需要的。非常感谢。