【发布时间】:2021-09-29 18:40:05
【问题描述】:
我正在使用 Dialogflow 内联编辑器来调用 API。当我使用 console.log 从 API 记录一些数据时,它可以工作。但是,当我将 agent.add 与相同的变量一起使用时,它会出现错误。
我阅读了有关此问题的其他一些 stackoverflows,其中人们使用了 Promise 和 resolve 调用。我试图在我的代码中实现这一点。但是,我不确定我是否以正确的方式使用它。
这是我的代码:
'use strict';
const axios = require('axios');
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
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 randomHandler(agent){
const regio = agent.parameters.regio;
if (regio != "Alkmaar" && regio != "Schiphol"){
agent.add(`Deze regio bestaat helaas niet binnen NH nieuws, kies een andere regio of kies voor het nieuws uit heel Noord-Holland`);
} else {
return axios.get(`https://api.datamuse.com/words?rel_rhy=book`)
.then((result) => {
result.data.map (res => {
const dataArray = ""; // An array with the results. However we got it
const words = dataArray.map( entry => entry.word ); // Get just the "word" field from each entry in the dataArray
const wordsString = words.join(', '); // Put commas in between each word
agent.add( `The results are: ${wordsString}`);
});
});
}
}
// Run the proper function handler based on the matched Dialogflow intent name
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('random', randomHandler);
agent.handleRequest(intentMap);
});
这是我的 package.json:
{
"name": "dialogflowFirebaseFulfillment",
"description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": "10"
},
"scripts": {
"start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
"deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
},
"dependencies": {
"actions-on-google": "^2.2.0",
"firebase-admin": "^5.13.1",
"firebase-functions": "^2.0.2",
"dialogflow": "^0.6.0",
"dialogflow-fulfillment": "^0.5.0",
"axios" : "0.20.0"
}
}
【问题讨论】:
标签: node.js promise dialogflow-es webhooks actions-on-google