Получение нулевого контекста при передаче контекста от одного намерения к другому, когда я пытаюсь использовать помощник Google

Я пытаюсь изучить интеграцию Google Assistant с помощью DialogFlow, я написал следующий код, который работает как шарм, когда я тестирую в dialogFlow, но терпит неудачу, когда я тестирую то же самое в Google Assistant (т.е. контекст, переданный из Intent getBillingInfo, становится нулевым при доступе в намерении payBill ). Пожалуйста, помогите мне понять, в чем я ошибаюсь.

Код:

var https = require ('https');
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?`);
  }

      // // below to get this function to be run when a Dialogflow intent is matched
  function getBillingInfoHandler(agent) {
    const parameters = request.body.queryResult.parameters;
    var phoneNumber = parameters['phone-number'];
    console.log("Phone Number: "+ phoneNumber);
    let url = "https://testapi.io/api/shwej//getBillingInfo";
    return new Promise((resolve, reject) => {       
    https.get(url, (res) => {
            let body = ''; // var to store the response chunks
            res.on('data', (chunk) => {body += chunk; });
            res.on('end', () => {
                // After all the data has been received, parse the JSON for desired data
                let response = JSON.parse(body);
                let output = response.billing_amount;
                // Resolve the promise with the output text
                console.log(body);
                agent.add("Your bill for " + phoneNumber + " is " + output + " ₹ ");
                agent.add(new Suggestion(`Click to Pay`));

                //agent.setContext('billing_context');
                //const context = {'phoneNumber': phoneNumber, 'billAmount': output};
                //agent.setContext(context);
                agent.setContext({
                'name':'billing-context',
                'lifespan': 50,
                'parameters':{
                    'phoneNumber': phoneNumber, 
                    'billAmount': output
                }
                });
                resolve();
            });
            res.on('error', (error) => {
                agent.add("Error occurred while calling API.");
                console.log(`Error calling the API: ${error}`);
                reject();
            });
    });
    });

  }

 function payBillHandler(agent) {
     let billingContext = agent.getContext('billing-context');

     if (typeof billingContext === 'undefined' || billingContext === null){
         agent.add("Some error with passing context!!!");
     }else{
        agent.add("Your payment is successful! ");
        agent.add(" Phone Number : " + billingContext.parameters.phoneNumber);
        agent.add(" Amount paid : " + billingContext.parameters.billAmount + " ₹ ");
     }
   }

  // 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('getBillingInfo', getBillingInfoHandler);
  intentMap.set('payBill', payBillHandler);
  agent.handleRequest(intentMap);
});

person Jefry C    schedule 08.05.2019    source источник


Ответы (1)


Не похоже, что вы импортируете клиентскую библиотеку Actions on Google. Попробуйте заменить первые несколько строк своего исполнения на:

// Import the Dialogflow module and response creation dependencies
// from the Actions on Google client library.

const {
  dialogflow,
  BasicCard,
  Permission,
  Suggestions,
} = require('actions-on-google');

// Import the firebase-functions package for deployment.
const functions = require('firebase-functions');

// Instantiate the Dialogflow client.
const app = dialogflow({debug: true});

Вы также можете попробовать Действия в Google codelabs (уровень 1 , уровень 2) или просмотрите Действия в репозиториях github Google.

person Max Wiederholt    schedule 16.05.2019