Google V2 webhook 外部 api 访问的操作

Actions on Google V2 webhook external api acces

在 Google V1 上的操作中,我可以使用 Webhook api 轻松解析信息,

但 V2 有不同的方法,它跳过了 request() 函数,只处理 conv.tell/conv.ask.

V1代码:

function helpIntent (app) {                                   
        request(API_URL, { json: true }, function (error, response, body) {
              console.log("nameIntent Response: " + JSON.stringify(response) + " | Body: " + body + " | Error: " + error);
              var msg = body.response;
              app.tell(msg);
        });                                                                  
}

V2代码:

app.intent('help', (conv) => {
      request(API_URL, { json: true }, function (error, response, body) {
           console.log("nameIntent Response: " + JSON.stringify(response) + " | Body: " + body + " | Error: " + error);
           var msg = body.response;
           conv.close(msg);
      })                                                                   
});

那么如何使 conv.close(msg)V2 code 中被正确调用?

问题是 request 是一个异步操作。使用最新版本的 actions-on-google 库,如果您的处理程序中有一个异步调用,您 必须 return 一个 Promise。否则,当处理程序结束时,异步函数仍将挂起,触发处理程序的代码不知道这一点,因此它会立即return 响应。

最简单的方法是使用 request-promise-native 包而不是 request 包。这可能会使您的代码看起来像这样:

app.intent('help', (conv) => {
  var rp = require('request-promise-native');

  var options = {
    uri: API_URL,
    json: true // Automatically parses the JSON string in the response
  };

  return rp(options)
    .then( response => {
      // The response will be a JSON object already. Do whatever with it.
      console.log( 'response:', JSON.stringify(response,null,1) );
      var value = response.msg;
      return conv.close( value );
    });
};