首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从运行nodejs的web钩子中得到正确的响应方式是什么?

从运行nodejs的web钩子中得到正确的响应方式是什么?
EN

Stack Overflow用户
提问于 2018-08-30 02:52:36
回答 2查看 1K关注 0票数 1

尝试实现运行nodejs的web钩子(使用V2对话框)。接收到的响应"MalformedResponse 'final_response‘必须设置。“下面是密码。到POST (app.post)结束时,代码块预期conv.close会发送SimpleResponse。但这是不可能的。需要帮助理解为什么会出现这个错误,以及解决这个错误的可能方向。

谢谢

代码语言:javascript
运行
复制
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()));
});
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-30 18:03:38

通常,"final_response" must be set错误是因为您没有发回任何东西。您的代码中有很多事情要做,虽然您在正确的轨道上,但是代码中有一些东西可能会导致这个错误。

首先,在代码中,您似乎对如何发送响应感到困惑。您既可以调用conv.close(),也可以调用注释掉的assistant.tell()conv.close()conv.ask()方法是使用库的这个版本发送回复的方法。以前的版本使用了tell()方法,不再支持该方法。

接下来,您的代码看起来只是在调用路由函数时才设置助理对象。虽然这是可以做到的,但这并不是通常的做法。通常,您将创建辅助对象并设置意图处理程序(使用assistant.intent())作为程序初始化的一部分。这是一个粗略的相当于设置快递应用程序和它的路线之前,请求本身进来。

设置助手并将其连接到一条路线的部分可能如下所示:

代码语言:javascript
运行
复制
const assistant = dialogflow();
app.post('/', assistant);

如果您真的想首先检查请求和响应对象,可以这样做

代码语言:javascript
运行
复制
const assistant = dialogflow();
app.post('/', function( req, res ){
  console.log(JSON.stringify(req.body,null,1));
  assistant( req, res );
});

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

但这导致了另一个问题。getPrice()函数调用request(),这是一个异步调用。异步调用是导致空响应的最大问题之一。如果使用异步调用,则必须返回承诺。在request()中使用承诺的最简单方法是使用请求-承诺-本地人包。

因此,该代码块可能看起来(非常粗略)如下:

代码语言:javascript
运行
复制
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()和意图处理程序都要注意的重要一点是,它们都返回了承诺。

最后,代码中有一些奇怪的方面。像res.status(500).send('Oppss... could not check the price');这样的行可能不会像你想的那样做。例如,它不会发出要说话的信息。相反,助理只会关闭连接,说出了一些问题。

票数 1
EN

Stack Overflow用户

发布于 2018-08-31 04:47:07

感谢“囚徒”。下面是基于上述评论的V2工作解决方案。在nodejs网络钩子(没有防火墙)上也验证了这一点。代码的V1版本是从https://glitch.com/~aog-template-1引用的

快乐编码!

代码语言:javascript
运行
复制
// 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()));
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52088600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档