Constructor

DialogflowApp

new DialogflowApp(options)

Parameters

Name Description

options

Object

JSON configuration.

Example

const DialogflowApp = require('actions-on-google').DialogflowApp;
const app = new DialogflowApp({request: request, response: response,
  sessionStarted:sessionStarted});

Methods

ask

ask(inputPrompt, noInputs) returns Object

Asks to collect the user's input.

NOTE: Due to a bug, if you specify the no-input prompts, the mic is closed after the 3rd prompt, so you should use the 3rd prompt for a bye message until the bug is fixed.

Parameters

Name Description

inputPrompt

(string, SimpleResponse, or RichResponse)

The input prompt response.

noInputs

Optional

Array of string

Array of re-prompts when the user does not respond (max 3).

Returns

Object HTTP response.

Example

const app = new DialogflowApp({request: request, response: response});
const WELCOME_INTENT = 'input.welcome';
const NUMBER_INTENT = 'input.number';

function welcomeIntent (app) {
  app.ask('Welcome to action snippets! Say a number.',
    ['Say any number', 'Pick a number', 'We can stop here. See you soon.']);
}

function numberIntent (app) {
  const number = app.getArgument(NUMBER_ARGUMENT);
  app.tell('You said ' + number);
}

const actionMap = new Map();
actionMap.set(WELCOME_INTENT, welcomeIntent);
actionMap.set(NUMBER_INTENT, numberIntent);
app.handleRequest(actionMap);

askForDeliveryAddress

askForDeliveryAddress(reason) returns Object

Asks user for delivery address.

Parameter

Name Description

reason

string

Reason given to user for asking delivery address.

Returns

Object HTTP response.

Example

const app = new DialogflowApp({request: request, response: response});
const WELCOME_INTENT = 'input.welcome';
const DELIVERY_INTENT = 'delivery.address';

function welcomeIntent (app) {
  app.askForDeliveryAddress('To make sure I can deliver to you');
}

function addressIntent (app) {
  const postalCode = app.getDeliveryAddress().postalAddress.postalCode;
  if (isInDeliveryZone(postalCode)) {
    app.tell('Great looks like you\'re in our delivery area!');
  } else {
    app.tell('I\'m sorry it looks like we can\'t deliver to you.');
  }
}

const actionMap = new Map();
actionMap.set(WELCOME_INTENT, welcomeIntent);
actionMap.set(DELIVERY_INTENT, addressIntent);
app.handleRequest(actionMap);

askWithCarousel

askWithCarousel(inputPrompt, carousel) returns Object

Asks to collect the user's input with a carousel.

Parameters

Name Description

inputPrompt

(string, RichResponse, or SimpleResponse)

The input prompt response.

carousel

Carousel

Carousel built with buildCarousel.

Returns

Object HTTP response.

Example

const app = new DialogflowApp({request, response});
const WELCOME_INTENT = 'input.welcome';
const OPTION_INTENT = 'option.select';

function welcomeIntent (app) {
  app.askWithCarousel('Which of these looks good?',
    app.buildCarousel()
     .addItems([
       app.buildOptionItem(SELECTION_KEY_ONE,
         ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2'])
         .setTitle('Number one'),
       app.buildOptionItem(SELECTION_KEY_TWO,
         ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2'])
         .setTitle('Number two'),
     ]));
}

function optionIntent (app) {
  if (app.getSelectedOption() === SELECTION_KEY_ONE) {
    app.tell('Number one is a great choice!');
  } else {
    app.tell('Number two is a great choice!');
  }
}

const actionMap = new Map();
actionMap.set(WELCOME_INTENT, welcomeIntent);
actionMap.set(OPTION_INTENT, optionIntent);
app.handleRequest(actionMap);

askWithList

askWithList(inputPrompt, list) returns Object

Asks to collect the user's input with a list.

Parameters

Name Description

inputPrompt

(string, RichResponse, or SimpleResponse)

The input prompt response.

list

List

List built with buildList.

Returns

Object HTTP response.

Example

const app = new DialogflowApp({request, response});
const WELCOME_INTENT = 'input.welcome';
const OPTION_INTENT = 'option.select';

function welcomeIntent (app) {
  app.askWithList('Which of these looks good?',
    app.buildList('List title')
     .addItems([
       app.buildOptionItem(SELECTION_KEY_ONE,
         ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2'])
         .setTitle('Title of First List Item'),
       app.buildOptionItem(SELECTION_KEY_TWO,
         ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2'])
         .setTitle('Title of Second List Item'),
     ]));
}

function optionIntent (app) {
  if (app.getSelectedOption() === SELECTION_KEY_ONE) {
    app.tell('Number one is a great choice!');
  } else {
    app.tell('Number two is a great choice!');
  }
}

const actionMap = new Map();
actionMap.set(WELCOME_INTENT, welcomeIntent);
actionMap.set(OPTION_INTENT, optionIntent);
app.handleRequest(actionMap);

getArgument

getArgument(argName) returns Object

Get the argument value by name from the current intent. If the argument is included in originalRequest, and is not a text argument, the entire argument object is returned.

Note: If incoming request is using an API version under 2 (e.g. 'v1'), the argument object will be in Proto2 format (snake_case, etc).

Parameter

Name Description

argName

string

Name of the argument.

Returns

Object Argument value matching argName or null if no matching argument.

Example

const app = new DialogflowApp({request: request, response: response});
const WELCOME_INTENT = 'input.welcome';
const NUMBER_INTENT = 'input.number';

function welcomeIntent (app) {
  app.ask('Welcome to action snippets! Say a number.');
}

function numberIntent (app) {
  const number = app.getArgument(NUMBER_ARGUMENT);
  app.tell('You said ' + number);
}

const actionMap = new Map();
actionMap.set(WELCOME_INTENT, welcomeIntent);
actionMap.set(NUMBER_INTENT, numberIntent);
app.handleRequest(actionMap);

getContext

getContext() returns Object

Returns the incoming context by name for this intent.

Returns

Object Context value matching name or null if no matching context.

Example

const app = new DialogflowApp({request: request, response: response});
const CONTEXT_NUMBER = 'number';
const NUMBER_ARGUMENT = 'myNumber';

function welcomeIntent (app) {
  app.setContext(CONTEXT_NUMBER);
  app.ask('Welcome to action snippets! Say a number.');
}

function numberIntent (app) {
  let context = app.getContext(CONTEXT_NUMBER);
  // context === {
  //   name: 'number',
  //   lifespan: 0,
  //   parameters: {
  //     myNumber: '23',
  //     myNumber.original: '23'
  //   }
  // }
  const number = app.getArgument(NUMBER_ARGUMENT);
  app.tell('You said ' + number);
}

const actionMap = new Map();
actionMap.set(WELCOME_INTENT, welcomeIntent);
actionMap.set(NUMBER_INTENT, numberIntent);
app.handleRequest(actionMap);

getContextArgument

getContextArgument(contextName, argName) returns Object

Get the context argument value by name from the current intent. Context arguments include parameters collected in previous intents during the lifespan of the given context. If the context argument has an original value, usually representing the underlying entity value, that will be given as part of the return object.

Parameters

Name Description

contextName

string

Name of the context.

argName

string

Name of the argument.

Returns

Object Object containing value property and optional original property matching context argument. Null if no matching argument.

Example

const app = new DialogflowApp({request: request, response: response});
const WELCOME_INTENT = 'input.welcome';
const NUMBER_INTENT = 'input.number';
const OUT_CONTEXT = 'output_context';
const NUMBER_ARG = 'myNumberArg';

function welcomeIntent (app) {
  const parameters = {};
  parameters[NUMBER_ARG] = '42';
  app.setContext(OUT_CONTEXT, 1, parameters);
  app.ask('Welcome to action snippets! Ask me for your number.');
}

function numberIntent (app) {
  const number = app.getContextArgument(OUT_CONTEXT, NUMBER_ARG);
  // number === { value: 42 }
  app.tell('Your number is  ' + number.value);
}

const actionMap = new Map();
actionMap.set(WELCOME_INTENT, welcomeIntent);
actionMap.set(NUMBER_INTENT, numberIntent);
app.handleRequest(actionMap);

getContexts

getContexts() returns Array of Context

Returns the incoming contexts for this intent.

Returns

Array of Context Empty if no active contexts.

Example

const app = new DialogflowApp({request: request, response: response});
const CONTEXT_NUMBER = 'number';
const NUMBER_ARGUMENT = 'myNumber';

function welcomeIntent (app) {
  app.setContext(CONTEXT_NUMBER);
  app.ask('Welcome to action snippets! Say a number.');
}

function numberIntent (app) {
  let contexts = app.getContexts();
  // contexts === [{
  //   name: 'number',
  //   lifespan: 0,
  //   parameters: {
  //     myNumber: '23',
  //     myNumber.original: '23'
  //   }
  // }]
  const number = app.getArgument(NUMBER_ARGUMENT);
  app.tell('You said ' + number);
}

const actionMap = new Map();
actionMap.set(WELCOME_INTENT, welcomeIntent);
actionMap.set(NUMBER_INTENT, numberIntent);
app.handleRequest(actionMap);

getDateTime

getDateTime() returns DateTime

Gets user provided date and time. Use after askForDateTime.

Returns

DateTime Date and time given by the user. Null if no user date and time given.

getDeliveryAddress

getDeliveryAddress() returns DeliveryAddress

Gets order delivery address. Only use after calling askForDeliveryAddress.

Returns

DeliveryAddress Delivery address information. Null if user denies permission, or no address given.

getDeviceLocation

getDeviceLocation() returns DeviceLocation

If granted permission to device's location in previous intent, returns device's location (see askForPermissions). If device info is unavailable, returns null.

Returns

DeviceLocation Null if location permission is not granted.

Example

const app = new DialogflowApp({request: req, response: res});
app.askForPermission("To get you a ride",
  app.SupportedPermissions.DEVICE_PRECISE_LOCATION);
// ...
// In response handler for permissions fallback intent:
if (app.isPermissionGranted()) {
  sendCarTo(app.getDeviceLocation().coordinates);
}

getIncomingCarousel

getIncomingCarousel() returns Carousel

Returns the Carousel constructed in API.AI response builder.

Returns

Carousel Carousel created in API.AI. If no Carousel was created, an empty Carousel is returned.

Example

const app = new App({request: req, response: res});

function pickOption (app) {
if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
    app.askWithCarousel('Which of these looks good?',
      app.getIncomingCarousel().addItems(
        app.buildOptionItem('another_choice', ['Another choice']).
        setTitle('Another choice').setDescription('Choose me!')));
  } else {
    app.ask('What would you like?');
  }
}

const actionMap = new Map();
actionMap.set('pick.option', pickOption);

app.handleRequest(actionMap);

getIncomingList

getIncomingList() returns List

Returns the List constructed in API.AI response builder.

Returns

List List created in API.AI. If no List was created, an empty List is returned.

Example

const app = new App({request: req, response: res});

function pickOption (app) {
if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
    app.askWithList('Which of these looks good?',
      app.getIncomingList().addItems(
        app.buildOptionItem('another_choice', ['Another choice']).
        setTitle('Another choice')));
  } else {
    app.ask('What would you like?');
  }
}

const actionMap = new Map();
actionMap.set('pick.option', pickOption);

app.handleRequest(actionMap);

getIncomingRichResponse

getIncomingRichResponse() returns RichResponse

Returns the RichResponse constructed in API.AI response builder.

Returns

RichResponse RichResponse created in API.AI. If no RichResponse was created, an empty RichResponse is returned.

Example

const app = new App({request: req, response: res});

function tellFact (app) {
  let fact = 'Google was founded in 1998';

  if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
    app.ask(app.getIncomingRichResponse().addSimpleResponse('Here\'s a ' +
      'fact for you. ' + fact + ' Which one do you want to hear about ' +
      'next, Google\'s history or headquarters?'));
  } else {
    app.ask('Here\'s a fact for you. ' + fact + ' Which one ' +
      'do you want to hear about next, Google\'s history or headquarters?');
  }
}

const actionMap = new Map();
actionMap.set('tell.fact', tellFact);

app.handleRequest(actionMap);

getInputType

getInputType() returns number

Gets type of input used for this request.

Returns

number One of DialogflowApp.InputTypes. Null if no input type given.

getIntent

getIntent() returns string

Get the current intent. Alternatively, using a handler Map with handleRequest, the client library will automatically handle the incoming intents.

Returns

string Intent id or null if no value.

Example

const app = new DialogflowApp({request: request, response: response});

function responseHandler (app) {
  const intent = app.getIntent();
  switch (intent) {
    case WELCOME_INTENT:
      app.ask('Welcome to action snippets! Say a number.');
      break;

    case NUMBER_INTENT:
      const number = app.getArgument(NUMBER_ARGUMENT);
      app.tell('You said ' + number);
      break;
  }
}

app.handleRequest(responseHandler);

getRawInput

getRawInput() returns string

Gets the user's raw input query.

Returns

string User's raw query or null if no value.

Example

const app = new DialogflowApp({request: request, response: response});
app.tell('You said ' + app.getRawInput());

getSelectedOption

getSelectedOption() returns string

Returns the option key user chose from options response.

Returns

string Option key of selected item. Null if no option selected or if current intent is not OPTION intent.

Example

const app = new App({request: req, response: res});

function pickOption (app) {
  if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
    app.askWithCarousel('Which of these looks good?',
      app.getIncomingCarousel().addItems(
        app.buildOptionItem('another_choice', ['Another choice']).
        setTitle('Another choice').setDescription('Choose me!')));
  } else {
    app.ask('What would you like?');
  }
}

function optionPicked (app) {
  assistant.ask('You picked ' + app.getSelectedOption());
}

const actionMap = new Map();
actionMap.set('pick.option', pickOption);
actionMap.set('option.picked', optionPicked);

app.handleRequest(actionMap);

getSignInStatus

getSignInStatus() returns string

Gets status of user sign in request.

Returns

string Result of user sign in request. One of DialogflowApp.SignInStatus. Null if no sign in status.

getSurfaceCapabilities

getSurfaceCapabilities() returns Array of string

Gets surface capabilities of user device.

Returns

Array of string Supported surface capabilities, as defined in AssistantApp.SurfaceCapabilities.

getTransactionDecision

getTransactionDecision() returns TransactionDecision

Gets transaction decision information. Only use after calling askForTransactionDecision.

Returns

TransactionDecision Transaction decision data. Returns object with userDecision only if user declines. userDecision will be one of Transactions.ConfirmationDecision. Null if no decision given.

getTransactionRequirementsResult

getTransactionRequirementsResult() returns string

Gets transactability of user. Only use after calling askForTransactionRequirements. Null if no result given.

Returns

string One of Transactions.ResultType.

getUser

getUser() returns User

Gets the User object. The user object contains information about the user, including a string identifier and personal information (requires requesting permissions, see askForPermissions).

Returns

User Null if no value.

Example

const app = new DialogflowApp({request: request, response: response});
const userId = app.getUser().userId;

getUserConfirmation

getUserConfirmation() returns boolean

Gets confirmation decision. Use after askForConfirmation.

Returns

boolean True if the user replied with affirmative response. False if user replied with negative response. Null if no user confirmation decision given.

isInSandbox

isInSandbox() returns boolean

Returns true if the app is being tested in sandbox mode. Enable sandbox mode in the (Actions console)[console.actions.google.com] to test transactions.

Returns

boolean True if app is being used in Sandbox mode.

isPermissionGranted

isPermissionGranted() returns boolean

Returns true if the request follows a previous request asking for permission from the user and the user granted the permission(s). Otherwise, false. Use with askForPermissions.

Returns

boolean True if permissions granted.

Example

const app = new DialogflowApp({request: request, response: response});
app.askForPermissions("To get you a ride", [
  app.SupportedPermissions.NAME,
  app.SupportedPermissions.DEVICE_PRECISE_LOCATION
]);
// ...
// In response handler for permissions fallback intent:
if (app.isPermissionGranted()) {
 // Use the requested permission(s) to get the user a ride
}

isRequestFromApiAi

isRequestFromApiAi(key, value) returns boolean

Verifies whether the request comes from API.AI.

Parameters

Name Description

key

string

The header key specified by the developer in the API.AI Fulfillment settings of the app.

value

string

The private value specified by the developer inside the fulfillment header.

Returns

boolean True if the request comes from API.AI.

setContext

setContext(name, lifespan, parameters)

Set a new context for the current intent.

Parameters

Name Description

name

string

Name of the context. API.AI converts to lowercase.

lifespan

Optional

int

Context lifespan.

parameters

Optional

Object

Context JSON parameters.

Example

const app = new DialogflowApp({request: request, response: response});
const CONTEXT_NUMBER = 'number';
const NUMBER_ARGUMENT = 'myNumber';

function welcomeIntent (app) {
  app.setContext(CONTEXT_NUMBER);
  app.ask('Welcome to action snippets! Say a number.');
}

function numberIntent (app) {
  const number = app.getArgument(NUMBER_ARGUMENT);
  app.tell('You said ' + number);
}

const actionMap = new Map();
actionMap.set(WELCOME_INTENT, welcomeIntent);
actionMap.set(NUMBER_INTENT, numberIntent);
app.handleRequest(actionMap);

tell

tell(textToSpeech)

Tells the Assistant to render the speech response and close the mic.

Parameter

Name Description

textToSpeech

(string, SimpleResponse, or RichResponse)

Final response. Spoken response can be SSML.

Returns

The response that is sent back to Assistant.

Example

const app = new DialogflowApp({request: request, response: response});
const WELCOME_INTENT = 'input.welcome';
const NUMBER_INTENT = 'input.number';

function welcomeIntent (app) {
  app.ask('Welcome to action snippets! Say a number.');
}

function numberIntent (app) {
  const number = app.getArgument(NUMBER_ARGUMENT);
  app.tell('You said ' + number);
}

const actionMap = new Map();
actionMap.set(WELCOME_INTENT, welcomeIntent);
actionMap.set(NUMBER_INTENT, numberIntent);
app.handleRequest(actionMap);