Push notifications

Your Action can send push notifications to users whenever relevant, such as sending a reminder when the due date for a task is near.

In this guide, we use the Actions on Google tips sample as a reference to show you how to set up push notifications for your Action. When users invoke this Action, it asks whether they want to hear a tip about developing their own Action. Users can choose either a specific or randomly selected category for the tip, or they can choose to hear the most recent tip.

Prerequisites

At least one of the Actions in your Actions project must be configured as a triggering intent which will be invoked when the user taps a notification received from the Assistant.

Console setup

To add support for push notifications to your Action:

  1. Go to the Actions console and navigate to Build > Actions.

  2. Click the Action that matches the additional triggering intent you want to enable push notifications for.

    For the Actions on Google tips sample, you would select "tell_latest_tip".

  3. Scroll down to the User engagement section and turn on Would you like to send push notifications.

  4. Enter a Content title.

    For the Actions on Google tips sample, the title could be "New tip added".

  5. Click Save.

Opt-in users

Before you can send push notifications to users, you must ask for them to opt-in. You can do this by showing them a suggestion chip to ask for their permission. When they grant permission, you need to save their userID and the app intent for which they want to receive the notifications.

Show suggestion chips for opt-in

Before users can receive push notifications from your Action, you must show them a suggestion chip to invite them to opt-in for push notifications.

After they tap the chip, you must ask for the UPDATE permission. The following code shows you how to do this with the askForUpdatePermission function of the Node.js client library.

Dialogflow
  1. Open your agent in the Dialogflow console and select the intent you're configuring for updates.
  2. Scroll down to Response and open the Google Assistant tab.
  3. Click Add message content and select Suggestion chips.
  4. Set the chip text to something that invites the user to opt-in. In the Actions on Google tips sample we set the chip to Alert me of new tips.
  5. Add another Dialogflow intent, called for example setup_push, and set a corresponding action, for example setup.push. The user expression of this intent must match the text of the opt-in chip, in our example Alert me of new tips.
The following snippet shows how to request the permission using the Actions on Google client library for Node.js:
app.intent('setup_push', (conv) => {
  conv.ask(new UpdatePermission({intent: 'tell_latest_tip'}));
});
  
Actions SDK

You should configure your NLU solution to trigger a function that asks the permission if the user expression matches the value of the push notifications opt-in prompt. Here's a very basic example based on string matching:

const userInput = conv.input.raw;
if (userInput === 'Alert me of new tips') {
  app.intent('setup_push', (conv) => {
    conv.ask(new UpdatePermission({intent: 'tell_latest_tip'}));
  });
}

Finalize the subscription

To finalize the subscription from your Node.js webhook, you need to save the User ID for the user and the intent they selected. Both are passed as arguments if the user grants the permission.

If your Action is built with Dialogflow, you need to:

  • Add an intent that handles the actions_intent_PERMISSION.
  • Specify the intent's Action name to something that your webhook can filter for later.

The following code shows how to handle a Dialogflow intent with an intent named finish_push_setup with an Action name of finish.push.setup:

app.intent('finish_push_setup', (conv) => {
  if (conv.arguments.get('PERMISSION')) {
    const userID = conv.arguments.get('UPDATES_USER_ID');
    // code to save intent and userID in your db
    conv.close(`Ok, I'll start alerting you.`);
  } else {
    conv.close(`Ok, I won't alert you.`);
  }
});

Send notifications

You can send push notifications to users using the Actions API. To use this API, you need to activate the API in your Google Cloud project and setup and download a JSON service account key.

You can then use the Google OAuth2 client library to exchange the service account key for an access token and use the token to authenticate your requests to the Actions API.

Get a service account key

  1. Go to this URL, replacing "example-project-1" at the end with your project ID in the Actions Console: https://console.developers.google.com/apis/api/actions.googleapis.com/overview?project=example-project-1
  2. If you see an Enable button, click it. Otherwise, proceed to step 3.
  3. Go to this URL, replacing "example-project-1" at the end with your project ID in the Actions Console: https://console.developers.google.com/apis/credentials?project=example-project-1
  4. Click Create credentials > Service Account Key.
  5. Click the Select box under Service Account and click New Service Account.
  6. Give the Service Account a name like "notifications" and the Role of Project Owner.
  7. Select the JSON key type and click Create. A JSON service account key is downloaded to your local machine.

Exchange the key for an access token and send a notification

When you want to send a notification through the Actions API, you need to exchange the service account key for an access token. We recommend using a Google API client library for this. In the series of code snippets that follow, we are using the Google API Node.js client library.

  1. Install the Google API client library and request: npm install googleapis request --save
  2. Use the following code to get an access token from the service account key and send a push notification:
const google = require('googleapis');
const key = require(PATH_TO_KEY);

let jwtClient = new google.auth.JWT(
  key.client_email, null, key.private_key,
  ['https://www.googleapis.com/auth/actions.fulfillment.conversation'],
  null
);

jwtClient.authorize((err, tokens) => {
  // code to retrieve target userId and intent
  let notif = {
    userNotification: {
      title: '<NOTIFICATION_TITLE>',
    },
    target: {
      userId: '<USER_ID>',
      intent: '<INTENT>',
      // Expects a IETF BCP-47 language code (i.e. en-US)
      locale: '<LOCALE>'
    },
  };

  request.post('https://actions.googleapis.com/v2/conversations:send', {
    'auth': {
      'bearer': tokens.access_token,
     },
    'json': true,
    'body': {'customPushMessage': notif},
  }, (err, httpResponse, body) => {
     console.log(httpResponse.statusCode + ': ' + httpResponse.statusMessage);
  });
});

Test push notifications

If you want to test push notifications but don't have your own Action, you can deploy your test version of the Actions on Google tips sample by following the instructions to set up and run the sample.