从运行nodejs的webhook响应的正确方法是什么?

问题描述 投票:1回答:2

尝试实现运行nodejs的web-hook(使用V2 dialogflow)。收到回复“必须设置MalformedResponse'final_response'。”下面是代码。在POST(app.post)代码块结束时,期望conv.close将发送SimpleResponse。但那并没有发生。需要帮助理解为什么会出现这个错误以及解决它的可能方向。

谢谢

const express = require('express');
const {
  dialogflow,
  Image,
  SimpleResponse,
} = require('actions-on-google')

const bodyParser = require('body-parser');
const request = require('request');
const https = require("https");
const app = express();
const Map = require('es6-map');

// Pretty JSON output for logs
const prettyjson = require('prettyjson');
const toSentence = require('underscore.string/toSentence');

app.use(bodyParser.json({type: 'application/json'}));

// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));

// http://expressjs.com/en/starter/basic-routing.html
app.get("/", function (request, response) {
  console.log("Received GET request..!!");
  //response.sendFile(__dirname + '/views/index.html');
  response.end("Response from my server..!!");
});

// Handle webhook requests
app.post('/', function(req, res, next) {
  console.log("Received POST request..!!");
  // Log the request headers and body, to aide in debugging. You'll be able to view the
  // webhook requests coming from API.AI by clicking the Logs button the sidebar.
  console.log('======Req HEADERS================================================');    
  logObject('Request headers: ', req.headers);
  console.log('======Req BODY================================================');    
  logObject('Request body: ', req.body);
  console.log('======Req END================================================');    

  // Instantiate a new API.AI assistant object.
  const assistant = dialogflow({request: req, response: res});

  // Declare constants for your action and parameter names
  //const PRICE_ACTION = 'price';  // The action name from the API.AI intent
  const PRICE_ACTION = 'revenue';  // The action name from the API.AI intent
  var price = 0.0

  // Create functions to handle intents here
  function getPrice(assistant) {
    console.log('** Handling action: ' + PRICE_ACTION);
    let requestURL = 'https://blockchain.info/q/24hrprice';
    request(requestURL, function(error, response) {
      if(error) {
        console.log("got an error: " + error);
        next(error);
      } else {        
        price = response.body;
        logObject('the current bitcoin price: ' , price);
        // Respond to the user with the current temperature.
        //assistant.tell("The demo price is " + price);
      }
    });
  }

  getPrice(assistant); 

  var reponseText = 'The demo price is ' + price;

  // Leave conversation with SimpleResponse 
  assistant.intent(PRICE_ACTION, conv => {
    conv.close(new SimpleResponse({
     speech: responseText,
     displayText: responseText,
    })); 
  });

}); //End of app.post

// Handle errors.
app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Oppss... could not check the price');
})

// Pretty print objects for logging.
function logObject(message, object, options) {
  console.log(message);
  console.log(prettyjson.render(object, options));
}

// Listen for requests.
let server = app.listen(process.env.PORT || 3000, function () {
  console.log('Your app is listening on ' + JSON.stringify(server.address()));
});
actions-on-google
2个回答
1
投票

一般来说,"final_response" must be set错误是因为你没有发回任何东西。您的代码中有很多内容,当您处于正确的轨道上时,代码中有一些可能导致此错误的内容。

首先 - 在代码中,您似乎对如何发送响应感到困惑。你既可以打电话给conv.close(),也可以打电话给assistant.tell()conv.close()conv.ask()方法是使用此版本的库发送回复的方式。 tell()方法由以前的版本使用,不再受支持。

接下来,您的代码看起来只是在调用路由功能时才设置助手对象。虽然可以这样做,但这不是通常的做法。通常,您将创建助手对象并设置Intent处理程序(使用assistant.intent())作为程序初始化的一部分。这相当于在请求本身进入之前设置快速应用程序及其路由。

设置“助手”然后将其挂钩到路线中的部分可能如下所示:

const assistant = dialogflow();
app.post('/', assistant);

如果你真的想先检查请求和响应对象,你可能会这样做

const assistant = dialogflow();
app.post('/', function( req, res ){
  console.log(JSON.stringify(req.body,null,1));
  assistant( req, res );
});

与此相关似乎是您尝试在路由处理程序中执行代码,然后尝试调用intent处理程序。同样,这可能是可能的,但不是建议的使用库的方法。 (而且我还没有尝试调试你的代码,看你是否有问题,看看你是否有效地做了它。)更典型的是从Intent处理程序内部调用getPrice()而不是尝试从路由处理程序内部调用它。

但这导致了另一个问题。 getPrice()函数调用request(),这是一个异步调用。异步调用是导致空响应的最大问题之一。如果您使用的是异步调用,则必须返回Promise。使用request()的Promise的最简单方法是使用request-promise-native包。

所以代码块可能看起来像(非常粗略)像这样:

const rp = require('request-promise-native');

function getPrice(){
  return rp.get(url)
    .then( body => {
      // In this case, the body is the value we want, so we'll just return it.
      // But normally we have to get some part of the body returned
      return body;
    });
}

assistant.intent(PRICE_ACTION, conv => {
  return getPrice()
    .then( price => {
      let msg = `The price is ${price}`;
      conv.close( new SimpleResponse({
        speech: msg,
        displayText: msg
      });
    });
});

关于getPrice()和意图处理程序的重要注意事项是它们都返回一个Promise。

最后,您的代码中有一些奇怪的方面。像res.status(500).send('Oppss... could not check the price');这样的线路可能不会做你认为他们会做的事情。例如,它不会发送要讲的消息。相反,助手只会关闭连接并说出错了。


0
投票

非常感谢@Prisoner。以下是基于以上评论的V2工作解决方案。已经在nodejs webhook上验证了相同内容(没有firebase)。 V1版本的代码是从https://glitch.com/~aog-template-1引用的

快乐的编码.. !!

// init project pkgs
const express = require('express');
const rp = require('request-promise-native');
const {
  dialogflow,
  Image,
  SimpleResponse,
} = require('actions-on-google')

const bodyParser = require('body-parser');
const request = require('request');
const app = express().use(bodyParser.json());

// Instantiate a new API.AI assistant object.
const assistant = dialogflow();

// Handle webhook requests
app.post('/', function(req, res, next) {
  console.log("Received POST request..!!");
  console.log('======Req HEADERS============================================');    
  console.log('Request headers: ', req.headers);
  console.log('======Req BODY===============================================');    
  console.log('Request body: ', req.body);
  console.log('======Req END================================================');    

  assistant(req, res);

});

// Declare constants for your action and parameter names
const PRICE_ACTION = 'revenue';  // The action name from the API.AI intent
var price = 0.0

// Invoke http request to obtain blockchain price
function getPrice(){
  console.log('getPrice is invoked');
  var url = 'https://blockchain.info/q/24hrprice';
  return rp.get(url)
    .then( body => {
      // In this case, the body is the value we want, so we'll just return it.
      // But normally we have to get some part of the body returned
      console.log('The demo price is ' + body);
      return body;
    });
}

// Handle AoG assistant intent
assistant.intent(PRICE_ACTION, conv => {
  console.log('intent is triggered');
  return getPrice()
    .then(price => {
      let msg = 'The demo price is ' + price;
      conv.close( new SimpleResponse({
        speech: msg,
      }));
   });
});

// Listen for requests.
let server = app.listen(process.env.PORT || 3000, function () {
  console.log('Your app is listening on ' + JSON.stringify(server.address()));
});
© www.soinside.com 2019 - 2024. All rights reserved.