尝试实现运行Node.js的Web挂钩(使用V2对话流)。收到的响应“必须设置格式错误的响应'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()));
});
答案 0 :(得分: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 );
});
与此相关,这似乎是您尝试在路由处理程序中执行代码,然后尝试调用意图处理程序。同样,这可能是可行的,但不是建议的使用库的方法。 (而且我还没有尝试调试您的代码,以查看您的代码执行方式是否存在问题,以查看您是否有效地执行了该代码。)更典型的做法是从调用getPrice()
,而不是尝试从路由处理程序内部调用它。
但这会导致另一个问题。 getPrice()
函数调用request()
,这是一个异步调用。异步调用是导致响应为空的最大问题之一。如果您使用的是异步通话,则必须返回承诺。与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');
之类的行可能不会执行您认为会做的事情。例如,它不会发送要说的信息。相反,助手将只是关闭连接并说出问题了。
答案 1 :(得分:0)
非常感谢@Prisoner。以下是基于以上注释的V2工作解决方案。已经在nodejs webhook上验证了相同的内容(没有firebase)。从https://glitch.com/~aog-template-1
引用了V1版本的代码祝您编码愉快!!
// 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()));
});