как вызвать REST API для действий в Google Assistant - PullRequest
0 голосов
/ 26 сентября 2018

Я видел некоторые ответы и до сих пор немного озадачен тем, как вызвать REST API для действий в google assistant.

Вот мой код:

'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-запроса он уже возвращает результат, не дожидаясь завершения запроса.

Я добавил 'return' в функции app.intent, но все еще не работает.

Есть предложения?

Спасибо!

1 Ответ

0 голосов
/ 27 сентября 2018
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);
});
...