user5720052
user5720052

Reputation: 53

Mapping mulitiple intents to one function using actionMap for a DialogFlowApp

I am building an app using Dialogflow. The user answers some questions, and can review their answers later. My problem is with building the server to return the user's previous answers.

This is the code so far, where the intents are QUESTION_1 and QUESTION_2, and the parameters are GRATEFUL_1 and GRATEFUL_2:

'use strict';

process.env.DEBUG = 'actions-on-google:*';
const App = require('actions-on-google').DialogflowApp;
const functions = require('firebase-functions');

// a. the action names from the Dialogflow intents
const QUESTION_1 = 'Question-1';
const QUESTION_2 = 'Question-2';

// b. the parameters that are parsed from the intents
const GRATEFUL_1 = 'any-grateful-1';
const GRATEFUL_2 = 'any-grateful-2';

exports.JournalBot = functions.https.onRequest((request, response) => {
  const app = new App({request, response});
  console.log('Request headers: ' + JSON.stringify(request.headers));
  console.log('Request body: ' + JSON.stringify(request.body));

  // Return the last journal entry
  function reflect (app) {
    let grateful_1 = app.getArgument(GRATEFUL_1);
    app.tell('Here is your previous entry: ' + grateful_1);
  }

  // Build an action map, which maps intent names to functions
  let actionMap = new Map();
  actionMap.set(QUESTION_1, reflect);

  app.handleRequest(actionMap);
});

I want the 'reflect' function to be mapped to the GRATEFUL_2 response as well as GRATEFUL_1. I know how to do this, but how do I change this next bit to include both intents:

  actionMap.set(QUESTION_1, reflect);

Upvotes: 2

Views: 431

Answers (1)

Prisoner
Prisoner

Reputation: 50701

If you wanted the QUESTION_2 intent to also go to the reflect() function, you can simply add

actionMap.set(QUESTION_2, reflect);

But I don't think that is your problem. Inside reflect() you need to know which intent it was that got you there.

You can use app.getIntent() to get a string with the intent name and then match this to which response you want to give. So something like this might work:

function reflect( app ){
  let intent = app.getIntent();
  var grateful;
  switch( intent ){
    case QUESTION_1:
      grateful = GRATEFUL_1;
      break;
    case QUESTION_2:
      grateful = GRATEFUL_2;
      break;
  }
  var response = app.getArgument( grateful );
  app.tell( 'You previously said: '+response );
}

There are other variants, of course.

There is no requirement you actually use the actionMap and app.handleRequest() at all. If you have another way you want to determine which output you want to give based on the intent string, you're free to use it.

Upvotes: 2

Related Questions