[英]how to call a REST API for Actions on Google Assistant
我已經看到了一些答案,但對於如何在Google助手上調用REST API for Actions仍然有些困惑。
這是我的代碼:
'use strict';
// Import the Dialogflow module from the Actions on Google client library.
const {dialogflow} = require('actions-on-google');
// Import the firebase-functions package for deployment.
const functions = require('firebase-functions');
const http = require('https');
// Instantiate the Dialogflow client.
const app = dialogflow({debug: true});
// Handle the Dialogflow intent named 'favorite color'.
// The intent collects a parameter named 'color'.
app.intent('favorite color', (conv, {any}) => {
//const luckyNumber = any.length;
// Respond with the user's lucky number and end the conversation.
//conv.close('Your lucky number is ' + luckyNumber);
return callApi(any).then((output) => {
console.log(output);
conv.close(`I found ${output.length} items!!`);
}).catch(() => {
conv.close('Error occurred while trying to get vehicles. Please try again later.');
});
});
function callApi (any){
return new Promise((resolve, reject) => {
// Create the path for the HTTP request to get the vehicle
//Make the HTTP request to get the vehicle
http.get({host: 'hawking.sv.cmu.edu', port: 9023, path: '/dataset/temporary'}, (res) => {
let body = ''; // var to store the response chunks
res.on('data', (d) => { body += d; }); // store each response chunk
res.on('end', () => {
// After all the data has been received parse the JSON for desired data
let response = JSON.parse(body);
let output = {};
//
// //copy required response attributes to output here
//
console.log(response.length.toString());
resolve(output);
// callback(output);
});
res.on('error', (error) => {
console.log(`Error calling the API: ${error}`)
reject();
});
}); //http.get
// let output = {};
// resolve(output);
}); //promise
}
// Set the DialogflowApp object to handle the HTTPS POST request.
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);
它始終表明:
必須設置MalformedResponse'final_response'。
看來http.get是異步的,並且在發出http請求之前,它已經返回了結果,而無需等待完成請求。
我在app.intent函數中添加了“ return”,但仍然無法正常工作。
有什么建議么?
謝謝!
app.intent('demo14mata', (conv, {any}) => {
var html = ""
http.get(url,(res)=>{
res.on("data",(data)=>{
html+=data
})
res.on("end",()=>{
console.log(html)
conv.close('return info is' + html);
})
}).on("error",(e)=>{
console.log('something wrong')
conv.close('no info return');
})
conv.close('no info return is(outside)' + html);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.