Powiadomienia push (Dialogflow)

Przeglądaj w Dialogflow

Kliknij Continue (Dalej), aby zaimportować nasze przykładowe powiadomienia w Dialogflow. Następnie postępuj zgodnie z poniższe czynności, aby wdrożyć i przetestować przykład:

  1. Wpisz nazwę agenta i utwórz nowego agenta Dialogflow dla przykładu.
  2. Gdy agent zakończy importowanie, kliknij Przejdź do agenta.
  3. W głównym menu nawigacyjnym kliknij Fulfillment (Realizacja).
  4. Włącz edytor wbudowany, a następnie kliknij Wdróż. Edytor zawiera próbkę w kodzie.
  5. W głównym menu nawigacyjnym kliknij Integrations (Integracje), a następnie kliknij Google (Google). .
  6. W wyświetlonym oknie modalnym włącz Automatyczny podgląd zmian i kliknij Przetestuj aby otworzyć Symulator działań.
  7. W symulatorze wpisz Talk to my test app, aby przetestować próbkę.
Dalej

Akcja może przekazywać użytkownikom powiadomienia w razie potrzeby. Może to być na przykład wysłanie powiadomienia o zbliżającym się terminie wykonania zadania.

W tym przewodniku stosujemy przykładowe wskazówki dotyczące Actions on Google jak skonfigurować powiadomienia push dotyczące akcji. Gdy użytkownik wywoła to działanie, pojawi się pytanie, czy chce usłyszeć wskazówkę dotyczące tworzenia własnej akcji. Użytkownicy mogą wybrać konkretną lub losowo wybraną kategorię. aby usłyszeć najnowszą wskazówkę.

Obsługiwane platformy

Powiadomienia push są dostępne na urządzeniach z Androidem i iOS (urządzenia z iOS muszą musisz mieć zainstalowaną aplikację Asystent, żeby otrzymywać powiadomienia push). Nie obecnie obsługiwane na głośnikach aktywowanych głosem, inteligentnych ekranach i innych platformach.

Wymagania wstępne

Co najmniej jedno z działań w projekcie Actions musi być skonfigurowane jako intencję wyzwalającą, która będzie wywoływana, gdy użytkownik kliknie powiadomienie otrzymane z Asystenta.

Akcji nie można skonfigurować tak, aby uruchamiały domyślną intencję powitalną z powiadomienia push.

Konfiguracja konsoli

Aby dodać obsługę powiadomień push do akcji:

  1. Otwórz Konsolę działań i wybierz do Kompilacja > Działania.

  2. Kliknij działanie pasujące do dodatkowej intencji aktywującej, którą chcesz uruchomić. włącz powiadomienia push dla:

    W przypadku przykładowych wskazówek w Actions on Google należy wybrać „tell_latest_tip”.

  3. Przewiń w dół do sekcji Zaangażowanie użytkowników i włącz tę opcję. Czy chcesz wysyłać powiadomienia push?

  4. Wypełnij pole Tytuł treści.

    Przykładowe wskazówki dotyczące Actions on Google mogą brzmieć „Dodano nową wskazówkę”.

  5. Kliknij Zapisz.

Importy

W kolejnych sekcjach w kodzie realizacji muszą zadeklarować następujący import:

Dialogflow
const {
  dialogflow,
  UpdatePermission,
  Suggestions,
} = require('actions-on-google');
Pakiet SDK Actions
const {
  actionssdk,
  UpdatePermission,
  Suggestions,
} = require('actions-on-google');

Użytkownicy, którzy wyrazili zgodę

Zanim zaczniesz wysyłać użytkownikom powiadomienia push, musisz ich poprosić o zgodę na udostępnianie. Możesz to zrobić, wyświetlając element z sugestią, aby poprosić o zgodę. Gdy przyznają uprawnienia, otrzymasz zaktualizowany identyfikator użytkownika do wysłania powiadomienia push.

Pokazuj elementy z sugestią dotyczącą wyrażenia zgody

Aby użytkownicy mogli otrzymywać powiadomienia push z akcji, musisz im pokazać: z sugestią, aby zachęcić ich do wyrażenia zgody na powiadomienia push.

Ten fragment kodu wysyła do użytkownika komunikat „Ostrzegaj mnie o nowych wskazówkach”. sugestia obok odpowiedzi tekstowej.

Dialogflow Node.js
conv.ask('I can send you push notifications. Would you like that?');
conv.ask(new Suggestions('Send notifications'));
Pakiet SDK Actions w Node.js
conv.ask(' I can send you push notifications. Would you like that?');
conv.ask(new Suggestions('Send notifications'));
Dialogflow Java
responseBuilder
    .add("I can send you push notifications. Would you like that?")
    .addSuggestions(new String[] {
        "Send notifications"
    });
Pakiet SDK Actions w Javie
responseBuilder
    .add("I can send you push notifications. Would you like that?")
    .addSuggestions(new String[] {
        "Send notifications"
    });
Plik JSON Dialogflow

Pamiętaj, że poniższy kod JSON opisuje odpowiedź webhooka.

{
  "payload": {
    "google": {
      "expectUserResponse": true,
      "richResponse": {
        "items": [
          {
            "simpleResponse": {
              "textToSpeech": "Hi! Welcome to Push Notifications!"
            }
          },
          {
            "simpleResponse": {
              "textToSpeech": "I can send you push notifications. Would you like that?"
            }
          }
        ],
        "suggestions": [
          {
            "title": "Send notifications"
          }
        ]
      }
    }
  }
}
Plik JSON z pakietu SDK Actions

Pamiętaj, że poniższy kod JSON opisuje odpowiedź webhooka.

{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "possibleIntents": [
        {
          "intent": "actions.intent.TEXT"
        }
      ],
      "inputPrompt": {
        "richInitialPrompt": {
          "items": [
            {
              "simpleResponse": {
                "textToSpeech": "Hi! Welcome to Push Notifications!"
              }
            },
            {
              "simpleResponse": {
                "textToSpeech": " I can send you push notifications. Would you like that?"
              }
            }
          ],
          "suggestions": [
            {
              "title": "Send notifications"
            }
          ]
        }
      }
    }
  ]
}

Po kliknięciu elementu musisz poprosić o przyznanie uprawnień UPDATE. Poniższy kod pokazuje, jak to zrobić za pomocą askForUpdatePermission w bibliotece klienta Node.js.

Dialogflow Node.js
  1. Otwórz agenta w konsoli Dialogflow i wybierz intencję, którą konfigurujesz dla aktualizacji.
  2. Przewiń w dół do sekcji Odpowiedź i otwórz kartę Asystent Google.
  3. Kliknij Dodaj treść wiadomości i wybierz Elementy sugestii.
  4. Ustaw tekst elementu, który zachęca użytkownika do wyrażenia zgody. W Przykładowe wskazówki dotyczące Actions on Google ustawiliśmy element na Ostrzegaj mnie o nowych poradach.
  5. dodać kolejną intencję Dialogflow, nazywaną na przykład setup_push, ustaw odpowiednie działanie, na przykład setup.push. wyrażenie użytkownika dotyczące tej intencji musi odpowiadać tekstowi elementu wymagającego zgody, w naszym przykładzie Ostrzegaj mnie o nowych wskazówek.
. Ten fragment kodu pokazuje, jak poprosić o przyznanie uprawnień za pomocą polecenia Działania w bibliotece klienta Google dla Node.js:
app.intent('Subscribe to Notifications', (conv) => {
  conv.ask(new UpdatePermission({
    intent: 'Notification',
  }));
});
Pakiet SDK Actions w Node.js

Skonfiguruj swoje rozwiązanie NLU tak, aby aktywowało funkcję, która prosi o pozwolenie na uprawnienia, jeśli wyrażenie użytkownika pasuje do wartości powiadomień push. z prośbą o zgodę na udział w ankiecie. Oto bardzo podstawowy przykład oparty na dopasowywaniu ciągów znaków:

conv.ask(new UpdatePermission({
  intent: 'Notification',
}));
Dialogflow Java
  1. Otwórz agenta w konsoli Dialogflow i wybierz intencję, którą konfigurujesz dla aktualizacji.
  2. Przewiń w dół do sekcji Odpowiedź i otwórz kartę Asystent Google.
  3. Kliknij Dodaj treść wiadomości i wybierz Elementy sugestii.
  4. Ustaw tekst elementu, który zachęca użytkownika do wyrażenia zgody. W Przykładowe wskazówki dotyczące Actions on Google ustawiliśmy element na Ostrzegaj mnie o nowych poradach.
  5. dodać kolejną intencję Dialogflow, nazywaną na przykład setup_push, ustaw odpowiednie działanie, na przykład setup.push. wyrażenie użytkownika dotyczące tej intencji musi odpowiadać tekstowi elementu wymagającego zgody, w naszym przykładzie Ostrzegaj mnie o nowych wskazówek.
. Ten fragment kodu pokazuje, jak poprosić o przyznanie uprawnień za pomocą polecenia Działania w bibliotece klienta Google Java/Kotlin:
@ForIntent("Subscribe to Notifications")
public ActionResponse subscribeToNotifications(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  responseBuilder.add(new UpdatePermission().setIntent("Notification"));
  return responseBuilder.build();
}
Pakiet SDK Actions w Javie

Skonfiguruj swoje rozwiązanie NLU tak, aby aktywowało funkcję, która prosi o pozwolenie na uprawnienia, jeśli wyrażenie użytkownika pasuje do wartości powiadomień push. z prośbą o zgodę na udział w ankiecie. Oto bardzo podstawowy przykład oparty na dopasowywaniu ciągów znaków:

ResponseBuilder responseBuilder = getResponseBuilder(request);
responseBuilder.add(new UpdatePermission().setIntent("Notification"));
return responseBuilder.build();
Plik JSON Dialogflow

Zwróć uwagę, że poniższy kod JSON opisuje odpowiedź webhooka za pomocą Dialogflow.

{
  "payload": {
    "google": {
      "expectUserResponse": true,
      "systemIntent": {
        "intent": "actions.intent.PERMISSION",
        "data": {
          "@type": "type.googleapis.com/google.actions.v2.PermissionValueSpec",
          "permissions": [
            "UPDATE"
          ],
          "updatePermissionValueSpec": {
            "intent": "tell_latest_tip"
          }
        }
      }
    }
  }
}
Plik JSON z pakietu SDK Actions

Pamiętaj, że poniższy plik JSON opisuje odpowiedź webhooka za pomocą pakietu Actions SDK.

{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "possibleIntents": [
        {
          "intent": "actions.intent.PERMISSION",
          "inputValueData": {
            "@type": "type.googleapis.com/google.actions.v2.PermissionValueSpec",
            "permissions": [
              "UPDATE"
            ],
            "updatePermissionValueSpec": {
              "intent": "tell_latest_tip"
            }
          }
        }
      ]
    }
  ]
}

Dokończ subskrypcję

Aby sfinalizować subskrypcję z webhooka Node.js, musisz zapisać komponent identyfikator powiadomień użytkownika i wybraną przez niego intencję. Oba są przekazywane jako jeśli użytkownik przyznał Ci uprawnienia.

Jeśli akcja została utworzona za pomocą Dialogflow, musisz wykonać te czynności:

  • Dodaj intencję, która obsługuje: actions_intent_PERMISSION.
  • Określ nazwę Action intencji na taką, którą webhook może mieć filtr na później.

Ten kod pokazuje, jak obsługiwać intencję Dialogflow z intencją o nazwie finish_push_setup, a nazwa działania finish.push.setup:

Dialogflow Node.js
app.intent('Confirm Notifications Subscription', (conv) => {
  if (conv.arguments.get('PERMISSION')) {
    const updatesUserId = conv.arguments.get('UPDATES_USER_ID');
    // Store user ID in database for later use
    conv.close(`Ok, I'll start alerting you.`);
  } else {
    conv.close(`Ok, I won't alert you.`);
  }
});
Pakiet SDK Actions w Node.js
app.intent('actions.intent.PERMISSION', (conv) => {
  if (conv.arguments.get('PERMISSION')) {
    const updatesUserId = conv.arguments.get('UPDATES_USER_ID');
    // Store user ID in database for later use
    conv.close(`Ok, I'll start alerting you.`);
  } else {
    conv.close(`Ok, I won't alert you.`);
  }
});
Dialogflow Java
@ForIntent("Confirm Notifications Subscription")
public ActionResponse confirmNotificationsSubscription(ActionRequest request) {
  // Verify the user has subscribed for push notifications
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  if (request.isPermissionGranted()) {
    Argument userId = request.getArgument(ConstantsKt.ARG_UPDATES_USER_ID);
    if (userId != null) {
      // Store the user's ID in the database
    }
    responseBuilder.add("Ok, I'll start alerting you.");
  } else {
    responseBuilder.add("Ok, I won't alert you.");
  }
  responseBuilder.endConversation();
  return responseBuilder.build();
}
Pakiet SDK Actions w Javie
@ForIntent("actions.intent.PERMISSION")
public ActionResponse confirmNotificationsSubscription(ActionRequest request) {
  // Verify the user has subscribed for push notifications
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  if (request.isPermissionGranted()) {
    Argument userId = request.getArgument(ConstantsKt.ARG_UPDATES_USER_ID);
    if (userId != null) {
      // Store the user's ID in the database
    }
    responseBuilder.add("Ok, I'll start alerting you.");
  } else {
    responseBuilder.add("Ok, I won't alert you.");
  }
  responseBuilder.endConversation();
  return responseBuilder.build();
}
Plik JSON Dialogflow

Zwróć uwagę, że poniższy kod JSON opisuje żądanie do webhooka.

{
  "responseId": "ee9e7ed5-fa1a-48c6-aac7-f9fbe94f1f58-712767ed",
  "queryResult": {
    "queryText": "actions_intent_PERMISSION",
    "action": "confirm.subscription",
    "parameters": {},
    "allRequiredParamsPresent": true,
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            ""
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/PROJECT_ID/agent/sessions/ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k/contexts/actions_capability_screen_output"
      },
      {
        "name": "projects/PROJECT_ID/agent/sessions/ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k/contexts/actions_capability_account_linking"
      },
      {
        "name": "projects/PROJECT_ID/agent/sessions/ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k/contexts/actions_capability_media_response_audio"
      },
      {
        "name": "projects/PROJECT_ID/agent/sessions/ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k/contexts/actions_capability_audio_output"
      },
      {
        "name": "projects/PROJECT_ID/agent/sessions/ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k/contexts/actions_capability_web_browser"
      },
      {
        "name": "projects/PROJECT_ID/agent/sessions/ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k/contexts/google_assistant_input_type_keyboard"
      },
      {
        "name": "projects/PROJECT_ID/agent/sessions/ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k/contexts/actions_intent_permission",
        "parameters": {
          "PERMISSION": true,
          "text": "yes",
          "UPDATES_USER_ID": "ABwppHHssyPbvEBF1mgN7Ddwb7mkhiVohW9PZ--I_svqy7zFElA4DHkf9pn04UBd5gwZo26_RfXCQ8otcztyIfe6MCQ"
        }
      }
    ],
    "intent": {
      "name": "projects/PROJECT_ID/agent/intents/c7f7b30b-5b88-4bb5-b0b8-1cd0862d1dd2",
      "displayName": "Confirm Notifications Subscription"
    },
    "intentDetectionConfidence": 1,
    "languageCode": "en"
  },
  "originalDetectIntentRequest": {
    "source": "google",
    "version": "2",
    "payload": {
      "user": {
        "permissions": [
          "UPDATE"
        ],
        "locale": "en-US",
        "userVerificationStatus": "VERIFIED"
      },
      "conversation": {
        "conversationId": "ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k",
        "type": "ACTIVE",
        "conversationToken": "[]"
      },
      "inputs": [
        {
          "intent": "actions.intent.PERMISSION",
          "rawInputs": [
            {
              "inputType": "KEYBOARD",
              "query": "yes"
            }
          ],
          "arguments": [
            {
              "name": "PERMISSION",
              "boolValue": true,
              "textValue": "true"
            },
            {
              "name": "text",
              "rawText": "yes",
              "textValue": "yes"
            },
            {
              "name": "UPDATES_USER_ID",
              "textValue": "ABwppHHssyPbvEBF1mgN7Ddwb7mkhiVohW9PZ--I_svqy7zFElA4DHkf9pn04UBd5gwZo26_RfXCQ8otcztyIfe6MCQ"
            }
          ]
        }
      ],
      "surface": {
        "capabilities": [
          {
            "name": "actions.capability.SCREEN_OUTPUT"
          },
          {
            "name": "actions.capability.ACCOUNT_LINKING"
          },
          {
            "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
          },
          {
            "name": "actions.capability.AUDIO_OUTPUT"
          },
          {
            "name": "actions.capability.WEB_BROWSER"
          }
        ]
      },
      "availableSurfaces": [
        {
          "capabilities": [
            {
              "name": "actions.capability.AUDIO_OUTPUT"
            },
            {
              "name": "actions.capability.SCREEN_OUTPUT"
            },
            {
              "name": "actions.capability.WEB_BROWSER"
            }
          ]
        }
      ]
    }
  },
  "session": "projects/PROJECT_ID/agent/sessions/ABwppHGIgmmU3zBcYMF_vWoHaM4JUo3wniYBHdbUF25l63G7EQWjRnlne8Ar7AOcRHWn1lrEKGy8qdP0UXLcWDBq93k"
}
Plik JSON z pakietu SDK Actions

Zwróć uwagę, że poniższy kod JSON opisuje żądanie do webhooka.

{
  "user": {
    "permissions": [
      "UPDATE"
    ],
    "locale": "en-US",
    "userVerificationStatus": "VERIFIED"
  },
  "conversation": {
    "conversationId": "ABwppHEP6OAFZHkSGEiZ5HYM9qrlk8YtIH1DQmJ52cxXELSPvM-kSc_tMJ_5O6ITbgVJlY9i2FIsKWjE_HXLke48",
    "type": "NEW"
  },
  "inputs": [
    {
      "intent": "actions.intent.PERMISSION",
      "rawInputs": [
        {
          "inputType": "KEYBOARD",
          "query": "yes"
        }
      ],
      "arguments": [
        {
          "name": "PERMISSION",
          "boolValue": true,
          "textValue": "true"
        },
        {
          "name": "text",
          "rawText": "yes",
          "textValue": "yes"
        },
        {
          "name": "UPDATES_USER_ID",
          "textValue": "ABwppHFvBKC-tMYUsUjJkm3YECgZvd6A3sOc7KuQvO4ZdQX3bGLmyoQ41dh4Zmtlzv_kaOKBt1Sf6eRpNbayynrl"
        }
      ]
    }
  ],
  "surface": {
    "capabilities": [
      {
        "name": "actions.capability.AUDIO_OUTPUT"
      },
      {
        "name": "actions.capability.WEB_BROWSER"
      },
      {
        "name": "actions.capability.SCREEN_OUTPUT"
      },
      {
        "name": "actions.capability.ACCOUNT_LINKING"
      },
      {
        "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
      }
    ]
  },
  "availableSurfaces": [
    {
      "capabilities": [
        {
          "name": "actions.capability.AUDIO_OUTPUT"
        },
        {
          "name": "actions.capability.SCREEN_OUTPUT"
        },
        {
          "name": "actions.capability.WEB_BROWSER"
        }
      ]
    }
  ]
}

Wyślij powiadomienia

Możesz wysyłać powiadomienia push do użytkowników za pomocą interfejsu Actions API. Aby użyć tego interfejsu API, musisz aktywować interfejs API w projekcie Google Cloud, a następnie skonfigurować i pobrać Klucz konta usługi JSON. Patrz krok 8 w instrukcjach w przykładowym kodzie tutaj.

Następnie możesz użyć biblioteki klienta Google OAuth2 do wymiany klucza konta usługi dla tokena dostępu i wykorzystać go do uwierzytelniania żądań wysyłanych do interfejsu Actions API.

Uzyskiwanie klucza konta usługi

  1. Przejdź pod ten adres URL, zastępując fragment „przykładowy-projekt-1” na końcu identyfikatorem projektu w Konsoli Actions: https://console.developers.google.com/apis/api/actions.googleapis.com/overview?project=example-project-1
  2. Jeśli zobaczysz przycisk Włącz, kliknij go. W przeciwnym razie przejdź do kroku 3.
  3. Przejdź pod ten adres URL, zastępując fragment „przykładowy-projekt-1” na końcu identyfikatorem projektu w Konsoli Actions: https://console.developers.google.com/apis/credentials?project=example-project-1
  4. Kliknij Utwórz dane logowania > Klucz konta usługi.
  5. Kliknij pole Wybierz w sekcji Konto usługi, a następnie Nowa usługa. Konto.
  6. Nadaj kontu usługi nazwę, na przykład „powiadomienia”. oraz roli Właściciel projektu.
  7. Wybierz typ klucza JSON i kliknij Utwórz. Klucz konta usługi JSON to pobrane na komputer lokalny.

Wymień klucz na token dostępu i wyślij powiadomienie

Aby wysłać powiadomienie za pomocą interfejsu Actions API, musisz wymienić klucz konta usługi odpowiadający tokenowi dostępu. Zalecamy użycie klienta interfejsu API Google . W serii fragmentów kodu używamy funkcji Biblioteka klienta interfejsu API Google w Node.js.

  1. Zainstaluj bibliotekę klienta interfejsów API Google i poproś o wykonanie tych czynności: npm install googleapis request --save
  2. Aby uzyskać token dostępu z klucza konta usługi, użyj tego kodu i wyślij powiadomienie push:
.
Dialogflow Node.js
const {google} = require('googleapis');
const request = require('request');

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

jwtClient.authorize((err, tokens) => {
  if (!err) {
    request.post('https://actions.googleapis.com/v2/conversations:send', {
      auth: {
        bearer: tokens.access_token,
      },
      json: true,
      body: {
        customPushMessage: {
          userNotification: {
            title: 'Push Notification Title',
          },
          target: {
            userId: '<UPDATES_USER_ID>',
            intent: 'Notification Intent',
          },
        },
        isInSandbox: true,
      },
    }, (err, httpResponse, body) => {
      console.log(`${httpResponse.statusCode}: ${httpResponse.statusMessage}`);
    });
  }
});
Pakiet SDK Actions w Node.js
const {google} = require('googleapis');
const request = require('request');

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

jwtClient.authorize((err, tokens) => {
  if (!err) {
    request.post('https://actions.googleapis.com/v2/conversations:send', {
      auth: {
        bearer: tokens.access_token,
      },
      json: true,
      body: {
        customPushMessage: {
          userNotification: {
            title: 'Push Notification Title',
          },
          target: {
            userId: '<UPDATES_ORDER_ID>',
            intent: 'Notification Intent',
          },
        },
        isInSandbox: true,
      },
    }, (err, httpResponse, body) => {
      console.log(`${httpResponse.statusCode}: ${httpResponse.statusMessage}`);
    });
  }
});
Dialogflow Java
final class Notification {

  private final String title;

  Notification(String title) {
    this.title = title;
  }

  String getTitle() {
    return title;
  }
}

final class Target {

  private final String userId;
  private final String intent;
  private final String locale;

  Target(String userId, String intent, String locale) {
    this.userId = userId;
    this.intent = intent;
    this.locale = locale;
  }

  String getUserId() {
    return userId;
  }

  String getIntent() {
    return intent;
  }

  String getLocale() {
    return locale;
  }
}

final class PushMessage {

  private final Notification userNotification;
  private final Target target;

  PushMessage(Notification userNotification, Target target) {
    this.userNotification = userNotification;
    this.target = target;
  }

  Notification getUserNotification() {
    return userNotification;
  }

  Target getTarget() {
    return target;
  }
}

final class PushNotification {

  private final PushMessage customPushMessage;
  private boolean isInSandbox;

  PushNotification(PushMessage customPushMessage, boolean isInSandbox) {
    this.customPushMessage = customPushMessage;
    this.isInSandbox = isInSandbox;
  }

  PushMessage getCustomPushMessage() {
    return customPushMessage;
  }

  boolean getIsInSandbox() {
    return isInSandbox;
  }
}

private PushNotification createNotification(String title, String userId, String intent, String locale) {
  Notification notification = new Notification(title);
  Target target = new Target(userId, intent, locale);
  PushMessage message = new PushMessage(notification, target);
  boolean isInSandbox = true;
  return new PushNotification(message, isInSandbox);
}

private ServiceAccountCredentials loadCredentials() throws IOException {
  String actionsApiServiceAccountFile =
      this.getClass().getClassLoader().getResource("service-account.json").getFile();
  InputStream actionsApiServiceAccount = new FileInputStream(actionsApiServiceAccountFile);
  ServiceAccountCredentials serviceAccountCredentials =
      ServiceAccountCredentials.fromStream(actionsApiServiceAccount);
  return (ServiceAccountCredentials)
      serviceAccountCredentials.createScoped(
          Collections.singleton(
              "https://www.googleapis.com/auth/actions.fulfillment.conversation"));
}

private String getAccessToken() throws IOException {
  AccessToken token = loadCredentials().refreshAccessToken();
  return token.getTokenValue();
}

public void sendNotification(String title, String userId, String intent, String locale) throws IOException {
  Preconditions.checkNotNull(title, "title cannot be null.");
  Preconditions.checkNotNull(userId, "userId cannot be null.");
  Preconditions.checkNotNull(intent, "intent cannot be null.");
  Preconditions.checkNotNull(locale, "locale cannot be null");
  PushNotification notification = createNotification(title, userId, intent, locale);

  HttpPost request = new HttpPost("https://actions.googleapis.com/v2/conversations:send");

  String token = getAccessToken();

  request.setHeader("Content-type", "application/json");
  request.setHeader("Authorization", "Bearer " + token);

  StringEntity entity = new StringEntity(new Gson().toJson(notification));
  entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
  request.setEntity(entity);
  HttpClient httpClient = HttpClientBuilder.create().build();
  httpClient.execute(request);
}
Pakiet SDK Actions w Javie
final class Notification {

  private final String title;

  Notification(String title) {
    this.title = title;
  }

  String getTitle() {
    return title;
  }
}

final class Target {

  private final String userId;
  private final String intent;

  Target(String userId, String intent) {
    this.userId = userId;
    this.intent = intent;
  }

  String getUserId() {
    return userId;
  }

  String getIntent() {
    return intent;
  }
}

final class PushMessage {

  private final Notification userNotification;
  private final Target target;

  PushMessage(Notification userNotification, Target target) {
    this.userNotification = userNotification;
    this.target = target;
  }

  Notification getUserNotification() {
    return userNotification;
  }

  Target getTarget() {
    return target;
  }
}

final class PushNotification {

  private final PushMessage customPushMessage;
  private boolean isInSandbox;

  PushNotification(PushMessage customPushMessage, boolean isInSandbox) {
    this.customPushMessage = customPushMessage;
    this.isInSandbox = isInSandbox;
  }

  PushMessage getCustomPushMessage() {
    return customPushMessage;
  }

  boolean getIsInSandbox() {
    return isInSandbox;
  }
}

private PushNotification createNotification(String title, String userId, String intent) {
  Notification notification = new Notification(title);
  Target target = new Target(userId, intent);
  PushMessage message = new PushMessage(notification, target);
  boolean isInSandbox = true;
  return new PushNotification(message, isInSandbox);
}

private ServiceAccountCredentials loadCredentials() throws IOException {
  String actionsApiServiceAccountFile =
      this.getClass().getClassLoader().getResource("service-account.json").getFile();
  InputStream actionsApiServiceAccount = new FileInputStream(actionsApiServiceAccountFile);
  ServiceAccountCredentials serviceAccountCredentials =
      ServiceAccountCredentials.fromStream(actionsApiServiceAccount);
  return (ServiceAccountCredentials)
      serviceAccountCredentials.createScoped(
          Collections.singleton(
              "https://www.googleapis.com/auth/actions.fulfillment.conversation"));
}

private String getAccessToken() throws IOException {
  AccessToken token = loadCredentials().refreshAccessToken();
  return token.getTokenValue();
}

public void sendNotification(String title, String userId, String intent) throws IOException {
  Preconditions.checkNotNull(title, "title cannot be null.");
  Preconditions.checkNotNull(userId, "userId cannot be null.");
  Preconditions.checkNotNull(intent, "intent cannot be null.");
  PushNotification notification = createNotification(title, userId, intent);

  HttpPost request = new HttpPost("https://actions.googleapis.com/v2/conversations:send");

  String token = getAccessToken();

  request.setHeader("Content-type", "application/json");
  request.setHeader("Authorization", "Bearer " + token);

  StringEntity entity = new StringEntity(new Gson().toJson(notification));
  entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
  request.setEntity(entity);
  HttpClient httpClient = HttpClientBuilder.create().build();
  httpClient.execute(request);
}