DialogflowSDK中间件在解析承诺后返回



我目前正在玩actions-on-google节点 sdk,我正在努力弄清楚如何等待承诺在我的中间件中解析,然后再执行我的意图。我尝试使用async/await并从我的中间件函数返回promise,但这两种方法似乎都不起作用。我知道通常你不会像我在这里所做的那样覆盖意图,但这是为了测试正在发生的事情。

const {dialogflow} = require('actions-on-google');
const functions = require('firebase-functions');
const app = dialogflow({debug: true});
function promiseTest() {
return new Promise((resolve,reject) => {
setTimeout(() => {
resolve('Resolved');
}, 2000)
})
}
app.middleware(async (conv) => {
let r = await promiseTest();
conv.intent = r
})
app.fallback(conv => {
const intent = conv.intent;
conv.ask("hello, you're intent was " + intent );
});

看起来我至少应该能够返回promisehttps://actions-on-google.github.io/actions-on-google-nodejs/interfaces/dialogflow.dialogflowmiddleware.html

但我不熟悉打字稿,所以我不确定我是否正确阅读了这些文档。

有人能够建议如何正确执行此操作吗?例如,一个现实生活中的示例可能是我需要进行数据库调用并等待它在我的中间件中返回,然后再继续下一步。

我的函数在谷歌云函数中使用 NodeJS V8 测试版。

此代码的输出是实际意图的任何内容,例如默认的欢迎意图,而不是"已解决",但没有错误。因此,中间件会触发,但在承诺解决之前,它会转移到回退意图。例如,在设置conv.intent = r之前

异步的东西对 V2 API 来说真的很麻烦。对我来说,只能正确使用 NodeJS 8。原因是从 V2 开始,除非您返回 promise,否则操作将返回空,因为它在计算函数的其余部分之前已完成。要弄清楚还有很多工作要做,这是我的一些示例样板,应该可以让您继续:

'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {BasicCard, MediaObject, Card, Suggestion, Image, Button} = require('actions-on-google');
var http_request = require('request-promise-native');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
function handleMyIntent(agent) {
let conv = agent.conv();
let key = request.body.queryResult.parameters['MyParam'];
var myAgent = agent;
return new Promise((resolve, reject) => {
http_request('http://someurl.com').then(async function(apiData) {
if (key === 'Hey') {
conv.close('Howdy');
} else {
conv.close('Bye');
}
myAgent.add(conv);
return resolve();
}).catch(function(err) {
conv.close('  nUh, oh. There was an error, please try again later');
myAgent.add(conv);
return resolve();
})})
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('myCustomIntent', handleMyIntent);
agent.handleRequest(intentMap);
});

简要概述您的需求:

  • 您必须返回承诺决议。
  • 您必须对HTTP请求使用"request-promise-native"包
  • 您必须升级计划以允许出站 HTTP 请求 (https://firebase.google.com/pricing/(

所以事实证明,我的问题与谷歌 SDK 上的操作的过时版本有关。dialogflow firebase 示例使用的是 v2.0.0,在 package.json 中将其更改为 2.2.0 解决了该问题

最新更新