Push-Benachrichtigungen (Dialogflow)

In Dialogflow ansehen

Klicken Sie auf Continue (Weiter), um unser Benachrichtigungsbeispiel in Dialogflow zu importieren. Folgen Sie dann den mit den folgenden Schritten zum Bereitstellen und Testen des Beispiels:

  1. Geben Sie einen Agent-Namen ein und erstellen Sie einen neuen Dialogflow-Agent für das Beispiel.
  2. Nachdem der Agent importiert wurde, klicken Sie auf Zum Agent.
  3. Klicken Sie im Hauptnavigationsmenü auf Fulfillment (Auftragsausführung).
  4. Aktivieren Sie den Inline-Editor und klicken Sie dann auf Bereitstellen. Der Editor enthält das Beispiel Code.
  5. Klicken Sie im Hauptnavigationsmenü auf Integrations (Integrationen) und dann auf Google Assistant
  6. Aktivieren Sie im angezeigten modalen Fenster die Option Automatische Vorschau der Änderungen und klicken Sie auf Testen. um den Actions-Simulator zu öffnen.
  7. Geben Sie im Simulator Talk to my test app ein, um das Beispiel zu testen.
<ph type="x-smartling-placeholder"></ph> Weiter

Deine Aktion kann dir bei Bedarf Benachrichtigungen an Nutzer senden, z. B. das Senden von Benachrichtigungen eine Erinnerung, wenn der Abgabetermin für eine Aufgabe näher rückt.

In diesem Leitfaden verwenden wir das Beispiel für Actions on Google-Tipps. als Referenz, um zu zeigen, wie du Push-Benachrichtigungen für deine Aktion einrichtest. Wenn Nutzer diese Aktion aufrufen, werden sie gefragt, ob sie einen Tipp hören möchten eigene Action zu entwickeln. Nutzer können eine bestimmte oder zufällig ausgewählte Kategorie für den Tipp auswählen oder den neuesten Tipp anzuhören.

Unterstützte Oberflächen

Push-Benachrichtigungen sind auf Android- und iOS-Geräten verfügbar (iOS-Geräte müssen die Assistant App installiert haben, um Push-Benachrichtigungen zu erhalten). Sie sind nicht derzeit auf Lautsprechern mit Sprachsteuerung, Smart Displays und anderen Oberflächen unterstützt.

Vorbereitung

Mindestens eine der Aktionen in Ihrem Actions-Projekt muss als Intents auslösen, die aufgerufen werden, wenn der Nutzer auf eine Benachrichtigung tippt, die er von Google Assistant.

Deine Aktionen können nicht so konfiguriert werden, dass der Standard-Begrüßungs-Intent über eine Push-Benachrichtigung ausgelöst wird.

Einrichtung der Konsole

So fügst du deiner Aktion Unterstützung für Push-Benachrichtigungen hinzu:

  1. Rufen Sie die Actions Console auf und gehen Sie auf Build > Aktionen:

  2. Klicken Sie auf die Aktion, die dem zusätzlichen auslösenden Intent entspricht, den Sie ausführen möchten Push-Benachrichtigungen zu aktivieren.

    Für das Beispiel für Actions on Google-Tipps würden Sie „tell_latest_tip“ auswählen.

  3. Scrollen Sie nach unten zum Abschnitt Nutzer-Engagement und aktivieren Sie die Option. Möchten Sie Push-Benachrichtigungen senden?

  4. Geben Sie einen Titel für den Inhalt ein.

    Für das Beispiel für Actions on Google-Tipps könnte der Titel „Neuer Tipp hinzugefügt“ lauten.

  5. Klicken Sie auf Speichern.

Importe

In den nächsten Abschnitten erfahren Sie, die folgenden Importe deklarieren:

<ph type="x-smartling-placeholder">
</ph> <ph type="x-smartling-placeholder">
</ph>
Dialogflow
const {
  dialogflow,
  UpdatePermission,
  Suggestions,
} = require('actions-on-google');
<ph type="x-smartling-placeholder">
</ph>
Actions SDK
const {
  actionssdk,
  UpdatePermission,
  Suggestions,
} = require('actions-on-google');

Opt-in-Nutzer

Bevor Sie Push-Benachrichtigungen an Nutzer senden können, müssen Sie sie um Zustimmung bitten. Zeigen Sie ihnen dazu einen Vorschlags-Chip, um sie um Erlaubnis zu bitten. Wenn sie die Berechtigung erteilen, erhalten Sie eine aktualisierte User-ID, die Sie Push-Benachrichtigungen an diesen Nutzer zu senden.

Infofelder mit Vorschlägen zum Aktivieren anzeigen

Damit Nutzer Push-Benachrichtigungen von deiner Aktion erhalten können, musst du ihnen eine Vorschlags-Chip, um sie dazu einzuladen, Push-Benachrichtigungen zu aktivieren.

Durch das folgende Code-Snippet erhält der Nutzer eine Benachrichtigung über neue Tipps. Vorschlag neben einer Textantwort angezeigt.

<ph type="x-smartling-placeholder">
</ph> <ph type="x-smartling-placeholder">
</ph>
Dialogflow Node.js
conv.ask('I can send you push notifications. Would you like that?');
conv.ask(new Suggestions('Send notifications'));
<ph type="x-smartling-placeholder">
</ph>
Actions SDK – Node.js
conv.ask(' I can send you push notifications. Would you like that?');
conv.ask(new Suggestions('Send notifications'));
<ph type="x-smartling-placeholder">
</ph>
Dialogflow Java
responseBuilder
    .add("I can send you push notifications. Would you like that?")
    .addSuggestions(new String[] {
        "Send notifications"
    });
<ph type="x-smartling-placeholder">
</ph>
Actions SDK – Java
responseBuilder
    .add("I can send you push notifications. Would you like that?")
    .addSuggestions(new String[] {
        "Send notifications"
    });
<ph type="x-smartling-placeholder">
</ph>
Dialogflow-JSON

Im folgenden JSON-Code wird eine Webhook-Antwort beschrieben.

{
  "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"
          }
        ]
      }
    }
  }
}
<ph type="x-smartling-placeholder">
</ph>
Actions SDK-JSON

Im folgenden JSON-Code wird eine Webhook-Antwort beschrieben.

{
  "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"
            }
          ]
        }
      }
    }
  ]
}

Nachdem sie auf den Chip getippt haben, müssen Sie die Berechtigung „UPDATE“ anfordern. Der folgende Code zeigt, wie das mit dem askForUpdatePermission geht. der Node.js-Clientbibliothek.

<ph type="x-smartling-placeholder">
</ph> <ph type="x-smartling-placeholder">
</ph>
Dialogflow Node.js
  1. Öffnen Sie den Agent in der Dialogflow-Konsole und wählen Sie den Intent aus, den Sie für Updates konfigurieren möchten.
  2. Scrollen Sie nach unten zu Antwort und öffnen Sie den Tab Google Assistant.
  3. Klicken Sie auf Nachrichteninhalt hinzufügen und wählen Sie Vorschläge für Chips aus.
  4. Geben Sie im Chip-Text einen Text ein, der den Nutzer zur Aktivierung einlädt. Im Actions on Google-Tipps haben wir den Chip auf Benachrichtigung über neue Tipps benachrichtigen gesetzt.
  5. Fügen Sie einen weiteren Dialogflow-Intent hinzu, z. B. setup_push, und Legen Sie eine entsprechende Aktion fest, zum Beispiel setup.push. Der Nutzerausdruck dieses Intents muss mit dem Text des Opt-in-Chips übereinstimmen. in unserem Beispiel Benachrichtigung über neue Tipps erhalten.
Das folgende Snippet zeigt, wie die Berechtigung über die Aktionen in der Google-Clientbibliothek für Node.js:
app.intent('Subscribe to Notifications', (conv) => {
  conv.ask(new UpdatePermission({
    intent: 'Notification',
  }));
});
<ph type="x-smartling-placeholder">
</ph>
Actions SDK – Node.js

Sie sollten Ihre NLU-Lösung so konfigurieren, dass eine Funktion ausgelöst wird, die den Berechtigung, wenn der Nutzerausdruck mit dem Wert der Push-Benachrichtigungen übereinstimmt Opt-in-Aufforderung. Hier ist ein sehr einfaches Beispiel, das auf einem String-Abgleich basiert:

conv.ask(new UpdatePermission({
  intent: 'Notification',
}));
<ph type="x-smartling-placeholder">
</ph>
Dialogflow Java
  1. Öffnen Sie den Agent in der Dialogflow-Konsole und wählen Sie den Intent aus, den Sie für Updates konfigurieren möchten.
  2. Scrollen Sie nach unten zu Antwort und öffnen Sie den Tab Google Assistant.
  3. Klicken Sie auf Nachrichteninhalt hinzufügen und wählen Sie Vorschläge für Chips aus.
  4. Geben Sie im Chip-Text einen Text ein, der den Nutzer zur Aktivierung einlädt. Im Actions on Google-Tipps haben wir den Chip auf Benachrichtigung über neue Tipps benachrichtigen gesetzt.
  5. Fügen Sie einen weiteren Dialogflow-Intent hinzu, z. B. setup_push, und Legen Sie eine entsprechende Aktion fest, zum Beispiel setup.push. Der Nutzerausdruck dieses Intents muss mit dem Text des Opt-in-Chips übereinstimmen. in unserem Beispiel Benachrichtigung über neue Tipps erhalten.
Das folgende Snippet zeigt, wie die Berechtigung über die Aktionen in der Google Java/Kotlin-Clientbibliothek:
@ForIntent("Subscribe to Notifications")
public ActionResponse subscribeToNotifications(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  responseBuilder.add(new UpdatePermission().setIntent("Notification"));
  return responseBuilder.build();
}
<ph type="x-smartling-placeholder">
</ph>
Actions SDK – Java

Sie sollten Ihre NLU-Lösung so konfigurieren, dass eine Funktion ausgelöst wird, die den Berechtigung, wenn der Nutzerausdruck mit dem Wert der Push-Benachrichtigungen übereinstimmt Opt-in-Aufforderung. Hier ist ein sehr einfaches Beispiel, das auf einem String-Abgleich basiert:

ResponseBuilder responseBuilder = getResponseBuilder(request);
responseBuilder.add(new UpdatePermission().setIntent("Notification"));
return responseBuilder.build();
<ph type="x-smartling-placeholder">
</ph>
Dialogflow-JSON

Im folgenden JSON-Code wird eine Webhook-Antwort mit Dialogflow beschrieben.

{
  "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"
          }
        }
      }
    }
  }
}
<ph type="x-smartling-placeholder">
</ph>
Actions SDK-JSON

Im folgenden JSON-Code wird eine Webhook-Antwort beschrieben, die das Actions SDK verwendet.

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

Abo abschließen

Um das Abo über den Node.js-Webhook abzuschließen, müssen Sie den die Benachrichtigungs-ID des Nutzers und den von ihm ausgewählten Intent. Beide werden als Argumente, wenn der Nutzer die Berechtigung erteilt.

Wenn Ihre Aktion mit Dialogflow erstellt wurde, müssen Sie Folgendes tun:

  • Fügen Sie einen Intent hinzu, der das actions_intent_PERMISSION verarbeitet.
  • Geben Sie als Aktionsnamen des Intents einen Namen an, den der Webhook verwenden kann. für später filtern.

Der folgende Code zeigt, wie ein Dialogflow-Intent mit einem Intent verarbeitet wird. mit dem Namen finish_push_setup und dem Aktionsnamen finish.push.setup:

<ph type="x-smartling-placeholder">
</ph> <ph type="x-smartling-placeholder">
</ph>
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.`);
  }
});
<ph type="x-smartling-placeholder">
</ph>
Actions SDK – 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.`);
  }
});
<ph type="x-smartling-placeholder">
</ph>
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();
}
<ph type="x-smartling-placeholder">
</ph>
Actions SDK – Java
@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();
}
<ph type="x-smartling-placeholder">
</ph>
Dialogflow-JSON

Im JSON-Format wird eine Anfrage an den Webhook beschrieben.

{
  "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"
}
<ph type="x-smartling-placeholder">
</ph>
Actions SDK-JSON

Im JSON-Format wird eine Anfrage an den Webhook beschrieben.

{
  "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"
        }
      ]
    }
  ]
}

Benachrichtigungen senden

Mit der Actions API können Sie Push-Benachrichtigungen an Nutzer senden. Um diese API zu verwenden, müssen Sie die API in Ihrem Google Cloud-Projekt aktivieren und eine JSON-Dienstkontoschlüssel. Weitere Informationen finden Sie in Schritt 8 der Anleitung in diesem Codebeispiel.

Sie können dann die Google OAuth2-Clientbibliothek verwenden, um den Dienstkontoschlüssel auszutauschen. um ein Zugriffstoken zu erhalten und das Token zur Authentifizierung Ihrer Anfragen an die Actions API zu verwenden.

Schlüssel für Dienstkonto abrufen

  1. Rufen Sie diese URL auf und ersetzen Sie „beispiel-projekt-1“ am Ende mit Ihrer Projekt-ID in der Actions Console: https://console.developers.google.com/apis/api/actions.googleapis.com/overview?project=example-project-1
  2. Wenn die Schaltfläche Aktivieren angezeigt wird, klicken Sie darauf. Fahren Sie andernfalls mit Schritt 3 fort.
  3. Rufen Sie diese URL auf und ersetzen Sie „beispiel-projekt-1“ am Ende mit Ihrer Projekt-ID in der Actions Console: https://console.developers.google.com/apis/credentials?project=example-project-1
  4. Klicken Sie auf Anmeldedaten erstellen > Dienstkontoschlüssel.
  5. Klicken Sie unter Dienstkonto auf das Feld Auswählen und dann auf Neuer Service. Konto.
  6. Geben Sie dem Dienstkonto einen Namen wie „Benachrichtigungen“ und die Rolle von Projektinhaber
  7. Wählen Sie den JSON-Schlüsseltyp aus und klicken Sie auf Erstellen. Ein JSON-Dienstkontoschlüssel auf Ihren lokalen Computer heruntergeladen.

Schlüssel gegen Zugriffstoken austauschen und Benachrichtigung senden

Wenn Sie eine Benachrichtigung über die Actions API senden möchten, müssen Sie Den Dienstkontoschlüssel für ein Zugriffstoken. Wir empfehlen die Verwendung eines Google API-Clients. für diese Bibliothek. In der folgenden Reihe von Code-Snippets verwenden wir den Parameter Google API-Clientbibliothek für Node.js

  1. Installieren Sie die Google API-Clientbibliothek und senden Sie folgende Anfrage: npm install googleapis request --save
  2. Verwenden Sie den folgenden Code, um ein Zugriffstoken aus dem Dienstkontoschlüssel abzurufen und senden Sie eine Push-Benachrichtigung:
<ph type="x-smartling-placeholder">
</ph> <ph type="x-smartling-placeholder">
</ph>
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}`);
    });
  }
});
<ph type="x-smartling-placeholder">
</ph>
Actions SDK – 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}`);
    });
  }
});
<ph type="x-smartling-placeholder">
</ph>
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);
}
<ph type="x-smartling-placeholder">
</ph>
Actions SDK – 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;

  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);
}