Dialogflow fulfillment parameter type error can't read property of undefined

64 views Asked by At

I was trying to test a code to see if i can take parameters out of intent and read them back to the user, but for some reason this isn't working and I dont know why, this is the code:

// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';

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 cal_credit(agent){
   var number=0;
   const test = agent.parameter.number; 

    agent.add(`The number of credits remaining is ${test}`);
  }

  // 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('remaining_credit', cal_credit);

  // intentMap.set('your intent name here', yourFunctionHandler);
  // intentMap.set('your intent name here', googleAssistantHandler);
  agent.handleRequest(intentMap);
});

and here is the error:

TypeError: Cannot read property 'number' of undefined
    at cal_credit (/workspace/index.js:26:33)
    at WebhookClient.handleRequest (/workspace/node_modules/dialogflow-fulfillment/src/dialogflow-fulfillment.js:303:44)
    at exports.dialogflowFirebaseFulfillment.functions.https.onRequest (/workspace/index.js:67:9)
    at cloudFunction (/workspace/node_modules/firebase-functions/lib/providers/https.js:57:9)
    at process.nextTick (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/function_wrappers.js:98:17)
    at process._tickCallback (internal/process/next_tick.js:61:11)
1

There are 1 answers

2
Tetrapod 3 Dev On

Parameters are only passed when it is correctly matched in intent configuration "Action and parameters". It's not always guaranteed that this parameter will have a value. You might consider the following approaches:

  1. Check if number is in agent.parameters:

    function cal_credit(agent){
    
        if (!agent?.parameters?.number) return;
    
        // ... existing code ...
    }
    
  2. cal_credit function only with those intents where number is a relevant and expected parameter.