Intent helper (Dialogflow)

Esplora in Dialogflow

Fai clic su Continua per importare il nostro esempio di assistenti in Dialogflow. Quindi, segui questi passaggi per eseguire il deployment e testare l'esempio:

  1. Inserisci il nome di un agente e crea un nuovo agente Dialogflow per l'esempio.
  2. Al termine dell'importazione dell'agente, fai clic su Vai all'agente.
  3. Nel menu di navigazione principale, vai ad Fulfillment.
  4. Attiva l'editor incorporato, quindi fai clic su Esegui il deployment. L'editor contiene il codice di esempio.
  5. Nel menu di navigazione principale, vai a Integrazioni, quindi fai clic su Assistente Google.
  6. Nella finestra modale visualizzata, attiva Anteprima automatica delle modifiche e fai clic su Test per aprire il simulatore di azioni.
  7. Nel simulatore, inserisci Talk to my test app per testare il campione.
Continua

Gli assistenti dicono all'assistente di assumere temporaneamente il controllo della conversazione per ottenere dati comuni come il nome completo dell'utente, una data e un'ora o un indirizzo di consegna. Quando richiedi un aiutante, l'assistente presenta agli utenti un'interfaccia utente standard e coerente per ottenere queste informazioni, così non devi progettarne una personalizzata.

Panoramica dell'utilizzo

La procedura generale per utilizzare un helper con Dialogflow e l'SDK Actions è descritta di seguito per Dialogflow e l'SDK Actions. Per ulteriori informazioni su ciascun helper, consulta le sezioni specifiche della Guida.

Dialogflow

Node.js

  1. Chiama conv.ask() con l'oggetto helper appropriato. Quando chiami una funzione helper, la libreria client invia una risposta all'assistente contenente l'intent helper corrispondente. In base all'intent, l'assistente sa di dover eseguire la finestra di dialogo per l'helper corrispondente.
  2. Dichiara un intent Dialogflow che specifica un evento che corrisponde a uno degli intent helper. Per un elenco degli eventi supportati, consulta la sezione degli intent helper. Questo intent non deve necessariamente avere frasi L'utente dice, perché viene sempre attivato quando l'evento viene attivato (quando l'assistente ha finito di eseguire l'assistente).
  3. Quando l'assistente restituisce il risultato dell'helper nella richiesta successiva al fulfillment, viene attivato l'intent Dialogflow corrispondente che potrai gestire normalmente.

JSON

  1. Specifica l'intent dell'helper nell'oggetto possibleIntents quando rispondi all'assistente. Quando l'assistente riceve la risposta, sa che deve eseguire la finestra di dialogo per l'assistente. Consulta gli intent help per informazioni sugli intent che puoi richiedere di soddisfare.
  2. Dichiara un intent Dialogflow che specifica un evento che corrisponde a uno degli intent helper. Per un elenco degli eventi supportati, consulta la sezione degli intent helper. Questo intent non deve necessariamente avere frasi L'utente dice, perché viene sempre attivato quando viene attivato l'evento.
  3. Quando l'assistente restituisce il risultato dell'assistente nella richiesta successiva al fulfillment, analizza la richiesta e i dati necessari.

SDK Actions

Node.js

  1. Richiama ask con i parametri appropriati. Una funzione helper chiede all'assistente di soddisfare uno degli intent descritti negli intent helper. Quando chiami una funzione helper, la libreria client invia una risposta all'assistente che contiene uno di questi intent. In base all'intent, l'assistente sa di dover eseguire la finestra di dialogo per l'helper corrispondente.
  2. Quando l'assistente restituisce il risultato dell'assistente nella richiesta successiva al fulfillment, ricevi l'intent corrispondente nella richiesta. In questo modo puoi rilevare che un helper ha restituito un risultato. Utilizza la funzione getter corrispondente per l'helper per ottenere i dati necessari.

JSON

  1. Specifica l'intent dell'helper nell'oggetto possibleIntents quando rispondi all'assistente. Quando l'assistente riceve la risposta, sa che deve eseguire la finestra di dialogo per l'assistente. Consulta gli intent help per informazioni sugli intent che puoi richiedere di soddisfare.
  2. Quando l'assistente restituisce il risultato dell'assistente nella richiesta successiva al fulfillment, analizza la richiesta e i dati necessari.

Intent helper

La tabella seguente descrive gli intent supportati che puoi richiedere all'assistente di soddisfare. Se utilizzi Dialogflow, devi anche creare un intent Dialogflow che specifichi l'evento corrispondente per l'intent helper.

Nome intent Nome evento Dialogflow Utilizzo
actions.intent.PERMISSION actions_intent_PERMISSION Ottieni il nome completo, la posizione approssimativa o la posizione esatta dell'utente oppure tutte e tre le informazioni.
actions.intent.OPTION actions_intent_OPTION Ricevi l'elemento selezionato da un elenco o dall'interfaccia utente di un carosello. In alternativa, se l'utente non effettua una selezione dall'elenco o dall'interfaccia utente del carosello, riceverà un input vocale o di testo corrispondente alla chiave nell'interfaccia utente del carosello o dell'elenco.
actions.intent.DATETIME actions_intent_DATETIME Ottieni dall'utente una data e un orario inseriti.
actions.intent.SIGN_IN actions_intent_SIGN_IN Richiede una procedura di collegamento degli account per collegare l'account di un utente.
actions.intent.PLACE actions_intent_PLACE Ottieni un indirizzo o una posizione salvata dall'utente.
actions.intent.CONFIRMATION actions_intent_CONFIRMATION Ottenere una conferma dall'utente (ad esempio, una risposta a una domanda sì o no).

Le seguenti sezioni descrivono gli helper disponibili e l'intent associato che devi richiedere per utilizzare l'helper.

Informazioni utente

Con questo helper puoi ottenere le seguenti informazioni sull'utente:

  • Nome visualizzato
  • Nome
  • Cognome
  • Posizione approssimativa del dispositivo (codice postale e città)
  • Posizione esatta del dispositivo (coordinate e via)

Chiamata a chi cerca aiuto

Il seguente esempio di codice mostra come chiamare l'helper utilizzando la libreria client. Gli snippet JSON mostrano la risposta webhook corrispondente.

Node.js

app.intent('Permission', (conv) => {
  const permissions = ['NAME'];
  let context = 'To address you by name';
  // Location permissions only work for verified users
  // https://developers.google.com/actions/assistant/guest-users
  if (conv.user.verification === 'VERIFIED') {
    // Could use DEVICE_COARSE_LOCATION instead for city, zip code
    permissions.push('DEVICE_PRECISE_LOCATION');
    context += ' and know your location';
  }
  const options = {
    context,
    permissions,
  };
  conv.ask(new Permission(options));
});

Java

@ForIntent("Permission")
public ActionResponse getPermission(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  String[] permissions = new String[] {ConstantsKt.PERMISSION_NAME};
  String context = "To address you by name";
  // Location permissions only work for verified users
  // https://developers.google.com/actions/assistant/guest-users
  if (request.getUser().getUserVerificationStatus().equals("VERIFIED")) {
    // Could use PERMISSION_DEVICE_COARSE_LOCATION instead for city, zip code
    permissions =
        new String[] {
          ConstantsKt.PERMISSION_NAME, ConstantsKt.PERMISSION_DEVICE_PRECISE_LOCATION
        };
  }
  responseBuilder
      .add("PLACEHOLDER")
      .add(new Permission().setPermissions(permissions).setContext(context));

  return responseBuilder.build();
}

Node.js

const permissions = ['NAME'];
let context = 'To address you by name';
// Location permissions only work for verified users
// https://developers.google.com/actions/assistant/guest-users
if (conv.user.verification === 'VERIFIED') {
  // Could use DEVICE_COARSE_LOCATION instead for city, zip code
  permissions.push('DEVICE_PRECISE_LOCATION');
  context += ' and know your location';
}
const options = {
  context,
  permissions,
};
conv.ask(new Permission(options));

Java

ResponseBuilder responseBuilder = getResponseBuilder(request);
String[] permissions = new String[] {ConstantsKt.PERMISSION_NAME};
String context = "To address you by name";
// Location permissions only work for verified users
// https://developers.google.com/actions/assistant/guest-users
if (request.getUser().getUserVerificationStatus().equals("VERIFIED")) {
  // Could use PERMISSION_DEVICE_COARSE_LOCATION instead for city, zip code
  permissions =
      new String[] {
        ConstantsKt.PERMISSION_NAME, ConstantsKt.PERMISSION_DEVICE_PRECISE_LOCATION
      };
}
responseBuilder
    .add("PLACEHOLDER")
    .add(new Permission().setPermissions(permissions).setContext(context));

return responseBuilder.build();

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "payload": {
    "google": {
      "expectUserResponse": true,
      "systemIntent": {
        "intent": "actions.intent.PERMISSION",
        "data": {
          "@type": "type.googleapis.com/google.actions.v2.PermissionValueSpec",
          "optContext": "To address you by name and know your location",
          "permissions": [
            "NAME",
            "DEVICE_PRECISE_LOCATION"
          ]
        }
      }
    }
  }
}

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "possibleIntents": [
        {
          "intent": "actions.intent.PERMISSION",
          "inputValueData": {
            "@type": "type.googleapis.com/google.actions.v2.PermissionValueSpec",
            "optContext": "To address you by name and know your location",
            "permissions": [
              "NAME",
              "DEVICE_PRECISE_LOCATION"
            ]
          }
        }
      ]
    }
  ]
}

Recupero dei risultati dell'helper in corso...

Il seguente esempio di codice mostra come accedere al risultato dell'helper utilizzando la libreria client. Gli snippet JSON rappresentano la richiesta e contengono il risultato dell'helper che riceverà il fulfillment.

Node.js

app.intent('Permission Handler', (conv, params, confirmationGranted) => {
  // Also, can access latitude and longitude
  // const { latitude, longitude } = location.coordinates;
  const {location} = conv.device;
  const {name} = conv.user;
  if (confirmationGranted && name && location) {
    conv.ask(`Okay ${name.display}, I see you're at ` +
      `${location.formattedAddress}`);
  } else {
    conv.ask(`Looks like I can't get your information.`);
  }
  conv.ask(`Would you like to try another helper?`);
  conv.ask(new Suggestions([
    'Confirmation',
    'DateTime',
    'Place',
  ]));
});

Java

@ForIntent("Permission Handler")
public ActionResponse handlePermission(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  Location location = request.getDevice().getLocation();
  String name = request.getUser().getProfile().getDisplayName();

  if (request.isPermissionGranted()) {
    responseBuilder.add("Okay " + name + ", I see you're at " + location.getFormattedAddress());
  } else {
    responseBuilder.add("Looks like I can't get your information");
  }
  responseBuilder
      .add("Would you like to try another helper?")
      .addSuggestions(new String[] {"Confirmation", "DateTime", "Place"});

  return responseBuilder.build();
}

Node.js

app.intent('actions.intent.PERMISSION', (conv, confirmationGranted) => {
  // Also, can access latitude and longitude
  // const { latitude, longitude } = location.coordinates;
  const {location} = conv.device;
  const {name} = conv.user;
  if (confirmationGranted && name && location) {
    conv.ask(`Okay ${name.display}, I see you're at ` +
      `${location.formattedAddress}`);
  } else {
    conv.ask(`Looks like I can't get your information.`);
  }
  conv.ask(`Would you like to try another helper?`);
  conv.ask(new Suggestions([
    'Confirmation',
    'DateTime',
    'Place',
  ]));
});

Java

@ForIntent("actions.intent.PERMISSION")
public ActionResponse handlePermission(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  Location location = request.getDevice().getLocation();
  String name = request.getUser().getProfile().getDisplayName();

  if (request.isPermissionGranted()) {
    responseBuilder.add("Okay " + name + ", I see you're at " + location.getFormattedAddress());
  } else {
    responseBuilder.add("Looks like I can't get your information");
  }
  responseBuilder
      .add("Would you like to try another helper?")
      .addSuggestions(new String[] {"Confirmation", "DateTime", "Place"});

  return responseBuilder.build();
}

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "responseId": "f26883c9-0283-4827-85bf-533f4442b4f9-712767ed",
  "queryResult": {
    "queryText": "actions_intent_PERMISSION",
    "parameters": {},
    "allRequiredParamsPresent": true,
    "fulfillmentText": "Webhook failed for intent: Permission Handler",
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            "Webhook failed for intent: Permission Handler"
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHGu7m_m6bTsKuLb6noyG_o-9BMSf8J9cfY8dpJIPN_hHT79qfqRrZPtyx515K-sl9SU8Jy3auH6pLmy99Y/contexts/actions_capability_account_linking"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHGu7m_m6bTsKuLb6noyG_o-9BMSf8J9cfY8dpJIPN_hHT79qfqRrZPtyx515K-sl9SU8Jy3auH6pLmy99Y/contexts/actions_capability_screen_output"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHGu7m_m6bTsKuLb6noyG_o-9BMSf8J9cfY8dpJIPN_hHT79qfqRrZPtyx515K-sl9SU8Jy3auH6pLmy99Y/contexts/actions_capability_web_browser"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHGu7m_m6bTsKuLb6noyG_o-9BMSf8J9cfY8dpJIPN_hHT79qfqRrZPtyx515K-sl9SU8Jy3auH6pLmy99Y/contexts/actions_capability_audio_output"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHGu7m_m6bTsKuLb6noyG_o-9BMSf8J9cfY8dpJIPN_hHT79qfqRrZPtyx515K-sl9SU8Jy3auH6pLmy99Y/contexts/actions_capability_media_response_audio"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHGu7m_m6bTsKuLb6noyG_o-9BMSf8J9cfY8dpJIPN_hHT79qfqRrZPtyx515K-sl9SU8Jy3auH6pLmy99Y/contexts/google_assistant_input_type_keyboard"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHGu7m_m6bTsKuLb6noyG_o-9BMSf8J9cfY8dpJIPN_hHT79qfqRrZPtyx515K-sl9SU8Jy3auH6pLmy99Y/contexts/actions_intent_permission",
        "parameters": {
          "PERMISSION": true,
          "text": "yes"
        }
      }
    ],
    "intent": {
      "name": "projects/df-helpers-kohler/agent/intents/6475b0ef-dd52-4afa-a1b9-7a19e7e93a80",
      "displayName": "Permission Handler"
    },
    "intentDetectionConfidence": 1,
    "languageCode": "en"
  },
  "originalDetectIntentRequest": {
    "source": "google",
    "version": "2",
    "payload": {
      "user": {
        "profile": {
          "displayName": "Sachit Mishra",
          "givenName": "Sachit",
          "familyName": "Mishra"
        },
        "permissions": [
          "NAME",
          "DEVICE_PRECISE_LOCATION"
        ],
        "locale": "en-US",
        "userVerificationStatus": "VERIFIED"
      },
      "conversation": {
        "conversationId": "ABwppHGu7m_m6bTsKuLb6noyG_o-9BMSf8J9cfY8dpJIPN_hHT79qfqRrZPtyx515K-sl9SU8Jy3auH6pLmy99Y",
        "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"
            }
          ]
        }
      ],
      "surface": {
        "capabilities": [
          {
            "name": "actions.capability.ACCOUNT_LINKING"
          },
          {
            "name": "actions.capability.SCREEN_OUTPUT"
          },
          {
            "name": "actions.capability.WEB_BROWSER"
          },
          {
            "name": "actions.capability.AUDIO_OUTPUT"
          },
          {
            "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
          }
        ]
      },
      "device": {
        "location": {
          "coordinates": {
            "latitude": 37.42241550000001,
            "longitude": -122.0840805
          },
          "formattedAddress": "Google Building 40 1600 Amphitheatre Parkway, Mountain View, California 94043",
          "zipCode": "94043",
          "city": "Mountain View"
        }
      },
      "availableSurfaces": [
        {
          "capabilities": [
            {
              "name": "actions.capability.WEB_BROWSER"
            },
            {
              "name": "actions.capability.SCREEN_OUTPUT"
            },
            {
              "name": "actions.capability.AUDIO_OUTPUT"
            }
          ]
        }
      ]
    }
  },
  "session": "projects/df-helpers-kohler/agent/sessions/ABwppHGu7m_m6bTsKuLb6noyG_o-9BMSf8J9cfY8dpJIPN_hHT79qfqRrZPtyx515K-sl9SU8Jy3auH6pLmy99Y"
}

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "user": {
    "profile": {
      "displayName": "Sachit Mishra",
      "givenName": "Sachit",
      "familyName": "Mishra"
    },
    "permissions": [
      "DEVICE_PRECISE_LOCATION",
      "NAME"
    ],
    "locale": "en-US",
    "userVerificationStatus": "VERIFIED"
  },
  "conversation": {
    "conversationId": "ABwppHEcidO2jguO4hS8maDeMVx8aasSCcBWZHrF3EmOMIaWRP9qF0BcACistiIoeyiSNTW6KD_tqN_U-xAIOXhPvA",
    "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"
        }
      ]
    }
  ],
  "surface": {
    "capabilities": [
      {
        "name": "actions.capability.AUDIO_OUTPUT"
      },
      {
        "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
      },
      {
        "name": "actions.capability.ACCOUNT_LINKING"
      },
      {
        "name": "actions.capability.SCREEN_OUTPUT"
      },
      {
        "name": "actions.capability.WEB_BROWSER"
      }
    ]
  },
  "device": {
    "location": {
      "coordinates": {
        "latitude": 37.4197238,
        "longitude": -122.08212759999999
      },
      "formattedAddress": "Google Building 45 1585 Charleston Road, Mountain View, California 94043",
      "zipCode": "94043",
      "city": "Mountain View"
    }
  },
  "availableSurfaces": [
    {
      "capabilities": [
        {
          "name": "actions.capability.SCREEN_OUTPUT"
        },
        {
          "name": "actions.capability.WEB_BROWSER"
        },
        {
          "name": "actions.capability.AUDIO_OUTPUT"
        }
      ]
    }
  ]
}

Lo snippet riportato sopra mostra come verificare se l'utente ti ha concesso le informazioni e poi accedere ai dati.

Una volta ottenute le informazioni sull'utente, ti consigliamo di conservarle in modo permanente per non dover ripetere la domanda. Puoi utilizzare lo spazio di archiviazione dell'utente per archiviare le informazioni degli utenti in tutte le conversazioni. Dai un'occhiata al nostro esempio di Name Psychic in Node.js e Java per vedere UserStorage in azione.

Chiamata a chi cerca aiuto

Il seguente esempio di codice mostra come chiamare l'helper utilizzando la libreria client. Gli snippet JSON mostrano la risposta webhook corrispondente.

Node.js

app.intent('List', (conv) => {
  if (!conv.screen) {
    conv.ask('Sorry, try this on a screen device or select the ' +
      'phone surface in the simulator.');
    return;
  }

  conv.ask('This is a list example.');
  // Create a list
  conv.ask(new List({
    title: 'List Title',
    items: {
      // Add the first item to the list
      'SELECTION_KEY_ONE': {
        synonyms: [
          'synonym 1',
          'synonym 2',
          'synonym 3',
        ],
        title: 'Title of First List Item',
        description: 'This is a description of a list item.',
        image: new Image({
          url: 'https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png',
          alt: 'Image alternate text',
        }),
      },
      // Add the second item to the list
      'SELECTION_KEY_GOOGLE_HOME': {
        synonyms: [
          'Google Home Assistant',
          'Assistant on the Google Home',
      ],
        title: 'Google Home',
        description: 'Google Home is a voice-activated speaker powered by ' +
          'the Google Assistant.',
        image: new Image({
          url: 'https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png',
          alt: 'Google Home',
        }),
      },
      // Add the third item to the list
      'SELECTION_KEY_GOOGLE_PIXEL': {
        synonyms: [
          'Google Pixel XL',
          'Pixel',
          'Pixel XL',
        ],
        title: 'Google Pixel',
        description: 'Pixel. Phone by Google.',
        image: new Image({
          url: 'https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png',
          alt: 'Google Pixel',
        }),
      },
    },
  }));
});

Java

@ForIntent("List")
public ActionResponse list(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  if (!request.hasCapability(Capability.SCREEN_OUTPUT.getValue())) {
    return responseBuilder
        .add("Sorry, try ths on a screen device or select the phone surface in the simulator.")
        .add("Which response would you like to see next?")
        .build();
  }

  responseBuilder
      .add("This is a list example.")
      .add(
          new SelectionList()
              .setTitle("List Title")
              .setItems(
                  Arrays.asList(
                      new ListSelectListItem()
                          .setTitle("Title of First List Item")
                          .setDescription("This is a description of a list item.")
                          .setImage(
                              new Image()
                                  .setUrl(
                                      "https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png")
                                  .setAccessibilityText("Image alternate text"))
                          .setOptionInfo(
                              new OptionInfo()
                                  .setSynonyms(
                                      Arrays.asList("synonym 1", "synonym 2", "synonym 3"))
                                  .setKey("SELECTION_KEY_ONE")),
                      new ListSelectListItem()
                          .setTitle("Google Home")
                          .setDescription(
                              "Google Home is a voice-activated speaker powered by the Google Assistant.")
                          .setImage(
                              new Image()
                                  .setUrl(
                                      "https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png")
                                  .setAccessibilityText("Google Home"))
                          .setOptionInfo(
                              new OptionInfo()
                                  .setSynonyms(
                                      Arrays.asList(
                                          "Google Home Assistant",
                                          "Assistant on the Google Home"))
                                  .setKey("SELECTION_KEY_GOOGLE_HOME")),
                      new ListSelectListItem()
                          .setTitle("Google Pixel")
                          .setDescription("Pixel. Phone by Google.")
                          .setImage(
                              new Image()
                                  .setUrl(
                                      "https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png")
                                  .setAccessibilityText("Google Pixel"))
                          .setOptionInfo(
                              new OptionInfo()
                                  .setSynonyms(
                                      Arrays.asList("Google Pixel XL", "Pixel", "Pixel XL"))
                                  .setKey("SELECTION_KEY_GOOGLE_PIXEL")))));
  return responseBuilder.build();
}

Node.js

if (!conv.screen) {
  conv.ask('Sorry, try this on a screen device or select the ' +
    'phone surface in the simulator.');
  return;
}

conv.ask('This is a list example.');
// Create a list
conv.ask(new List({
  title: 'List Title',
  items: {
    // Add the first item to the list
    'SELECTION_KEY_ONE': {
      synonyms: [
        'synonym 1',
        'synonym 2',
        'synonym 3',
      ],
      title: 'Title of First List Item',
      description: 'This is a description of a list item.',
      image: new Image({
        url: 'https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png',
        alt: 'Image alternate text',
      }),
    },
    // Add the second item to the list
    'SELECTION_KEY_GOOGLE_HOME': {
      synonyms: [
        'Google Home Assistant',
        'Assistant on the Google Home',
    ],
      title: 'Google Home',
      description: 'Google Home is a voice-activated speaker powered by ' +
        'the Google Assistant.',
      image: new Image({
        url: 'https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png',
        alt: 'Google Home',
      }),
    },
    // Add the third item to the list
    'SELECTION_KEY_GOOGLE_PIXEL': {
      synonyms: [
        'Google Pixel XL',
        'Pixel',
        'Pixel XL',
      ],
      title: 'Google Pixel',
      description: 'Pixel. Phone by Google.',
      image: new Image({
        url: 'https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png',
        alt: 'Google Pixel',
      }),
    },
  },
}));

Java

ResponseBuilder responseBuilder = getResponseBuilder(request);
if (!request.hasCapability(Capability.SCREEN_OUTPUT.getValue())) {
  return responseBuilder
      .add("Sorry, try ths on a screen device or select the phone surface in the simulator.")
      .add("Which response would you like to see next?")
      .build();
}

responseBuilder
    .add("This is a list example.")
    .add(
        new SelectionList()
            .setTitle("List Title")
            .setItems(
                Arrays.asList(
                    new ListSelectListItem()
                        .setTitle("Title of First List Item")
                        .setDescription("This is a description of a list item.")
                        .setImage(
                            new Image()
                                .setUrl(
                                    "https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png")
                                .setAccessibilityText("Image alternate text"))
                        .setOptionInfo(
                            new OptionInfo()
                                .setSynonyms(
                                    Arrays.asList("synonym 1", "synonym 2", "synonym 3"))
                                .setKey("SELECTION_KEY_ONE")),
                    new ListSelectListItem()
                        .setTitle("Google Home")
                        .setDescription(
                            "Google Home is a voice-activated speaker powered by the Google Assistant.")
                        .setImage(
                            new Image()
                                .setUrl(
                                    "https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png")
                                .setAccessibilityText("Google Home"))
                        .setOptionInfo(
                            new OptionInfo()
                                .setSynonyms(
                                    Arrays.asList(
                                        "Google Home Assistant",
                                        "Assistant on the Google Home"))
                                .setKey("SELECTION_KEY_GOOGLE_HOME")),
                    new ListSelectListItem()
                        .setTitle("Google Pixel")
                        .setDescription("Pixel. Phone by Google.")
                        .setImage(
                            new Image()
                                .setUrl(
                                    "https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png")
                                .setAccessibilityText("Google Pixel"))
                        .setOptionInfo(
                            new OptionInfo()
                                .setSynonyms(
                                    Arrays.asList("Google Pixel XL", "Pixel", "Pixel XL"))
                                .setKey("SELECTION_KEY_GOOGLE_PIXEL")))));
return responseBuilder.build();

JSON

Tieni presente che il JSON di seguito descrive una risposta webhook.

{
  "payload": {
    "google": {
      "expectUserResponse": true,
      "systemIntent": {
        "intent": "actions.intent.OPTION",
        "data": {
          "@type": "type.googleapis.com/google.actions.v2.OptionValueSpec",
          "listSelect": {
            "title": "List Title",
            "items": [
              {
                "optionInfo": {
                  "key": "SELECTION_KEY_ONE",
                  "synonyms": [
                    "synonym 1",
                    "synonym 2",
                    "synonym 3"
                  ]
                },
                "description": "This is a description of a list item.",
                "image": {
                  "url": "https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png",
                  "accessibilityText": "Image alternate text"
                },
                "title": "Title of First List Item"
              },
              {
                "optionInfo": {
                  "key": "SELECTION_KEY_GOOGLE_HOME",
                  "synonyms": [
                    "Google Home Assistant",
                    "Assistant on the Google Home"
                  ]
                },
                "description": "Google Home is a voice-activated speaker powered by the Google Assistant.",
                "image": {
                  "url": "https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png",
                  "accessibilityText": "Google Home"
                },
                "title": "Google Home"
              },
              {
                "optionInfo": {
                  "key": "SELECTION_KEY_GOOGLE_PIXEL",
                  "synonyms": [
                    "Google Pixel XL",
                    "Pixel",
                    "Pixel XL"
                  ]
                },
                "description": "Pixel. Phone by Google.",
                "image": {
                  "url": "https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png",
                  "accessibilityText": "Google Pixel"
                },
                "title": "Google Pixel"
              }
            ]
          }
        }
      },
      "richResponse": {
        "items": [
          {
            "simpleResponse": {
              "textToSpeech": "This is a list example."
            }
          }
        ]
      }
    }
  }
}

JSON

Tieni presente che il JSON di seguito descrive una risposta webhook.

{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "possibleIntents": [
        {
          "intent": "actions.intent.OPTION",
          "inputValueData": {
            "@type": "type.googleapis.com/google.actions.v2.OptionValueSpec",
            "listSelect": {
              "title": "List Title",
              "items": [
                {
                  "optionInfo": {
                    "key": "SELECTION_KEY_ONE",
                    "synonyms": [
                      "synonym 1",
                      "synonym 2",
                      "synonym 3"
                    ]
                  },
                  "description": "This is a description of a list item.",
                  "image": {
                    "url": "https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png",
                    "accessibilityText": "Image alternate text"
                  },
                  "title": "Title of First List Item"
                },
                {
                  "optionInfo": {
                    "key": "SELECTION_KEY_GOOGLE_HOME",
                    "synonyms": [
                      "Google Home Assistant",
                      "Assistant on the Google Home"
                    ]
                  },
                  "description": "Google Home is a voice-activated speaker powered by the Google Assistant.",
                  "image": {
                    "url": "https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png",
                    "accessibilityText": "Google Home"
                  },
                  "title": "Google Home"
                },
                {
                  "optionInfo": {
                    "key": "SELECTION_KEY_GOOGLE_PIXEL",
                    "synonyms": [
                      "Google Pixel XL",
                      "Pixel",
                      "Pixel XL"
                    ]
                  },
                  "description": "Pixel. Phone by Google.",
                  "image": {
                    "url": "https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png",
                    "accessibilityText": "Google Pixel"
                  },
                  "title": "Google Pixel"
                }
              ]
            }
          }
        }
      ],
      "inputPrompt": {
        "richInitialPrompt": {
          "items": [
            {
              "simpleResponse": {
                "textToSpeech": "This is a list example."
              }
            }
          ]
        }
      }
    }
  ]
}

Puoi visualizzare una UI con elenco o carosello e ottenere l'opzione selezionata dall'utente con l'intent actions.intent.OPTION.

Recupero dei risultati dell'helper in corso...

I seguenti esempi di codice mostrano come accedere al risultato dell'helper utilizzando la libreria client. Gli snippet JSON rappresentano la richiesta e contengono il risultato dell'helper che riceverà il fulfillment.

I seguenti snippet mostrano come verificare quale opzione ha selezionato l'utente.

Node.js

app.intent('List - OPTION', (conv, params, option) => {
  const SELECTED_ITEM_RESPONSES = {
    'SELECTION_KEY_ONE': 'You selected the first item',
    'SELECTION_KEY_GOOGLE_HOME': 'You selected the Google Home!',
    'SELECTION_KEY_GOOGLE_PIXEL': 'You selected the Google Pixel!',
  };
  conv.ask(SELECTED_ITEM_RESPONSES[option]);
  conv.ask('Which response would you like to see next?');
});

Java

@ForIntent("List - OPTION")
public ActionResponse listSelected(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  String selectedItem = request.getSelectedOption();
  String response;

  if (selectedItem.equals("SELECTION_KEY_ONE")) {
    response = "You selected the first item";
  } else if (selectedItem.equals("SELECTION_KEY_GOOGLE_HOME")) {
    response = "You selected the Google Home!";
  } else if (selectedItem.equals("SELECTION_KEY_GOOGLE_PIXEL")) {
    response = "You selected the Google Pixel!";
  } else {
    response = "You did not select a valid item";
  }
  return responseBuilder.add(response).add("Which response would you like to see next?").build();
}

Node.js

app.intent('actions.intent.OPTION', (conv, params, option) => {
  const SELECTED_ITEM_RESPONSES = {
    'SELECTION_KEY_ONE': 'You selected the first item',
    'SELECTION_KEY_GOOGLE_HOME': 'You selected the Google Home!',
    'SELECTION_KEY_GOOGLE_PIXEL': 'You selected the Google Pixel!',
  };
  conv.ask(SELECTED_ITEM_RESPONSES[option]);
  conv.ask('Which response would you like to see next?');
});

Java

  @ForIntent("actions.intent.OPTION")
  public ActionResponse listSelected(ActionRequest request) {
    ResponseBuilder responseBuilder = getResponseBuilder(request);
    String selectedItem = request.getSelectedOption();
    String response;

    if (selectedItem.equals("SELECTION_KEY_ONE")) {
      response = "You selected the first item";
    } else if (selectedItem.equals("SELECTION_KEY_GOOGLE_HOME")) {
      response = "You selected the Google Home!";
    } else if (selectedItem.equals("SELECTION_KEY_GOOGLE_PIXEL")) {
      response = "You selected the Google Pixel!";
    } else {
      response = "You did not select a valid item";
    }
    return responseBuilder.add(response).add("Which response would you like to see next?").build();
  }

  public ActionResponse carousel(ActionRequest request) {
    ResponseBuilder responseBuilder = getResponseBuilder(request);
    if (!request.hasCapability(Capability.SCREEN_OUTPUT.getValue())) {
      return responseBuilder
          .add("Sorry, try ths on a screen device or select the phone surface in the simulator.")
          .add("Which response would you like to see next?")
          .build();
    }

    responseBuilder
        .add("This is a carousel example.")
        .add(
            new SelectionCarousel()
                .setItems(
                    Arrays.asList(
                        new CarouselSelectCarouselItem()
                            .setTitle("Title of First List Item")
                            .setDescription("This is a description of a list item.")
                            .setImage(
                                new Image()
                                    .setUrl(
                                        "https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png")
                                    .setAccessibilityText("Image alternate text"))
                            .setOptionInfo(
                                new OptionInfo()
                                    .setSynonyms(
                                        Arrays.asList("synonym 1", "synonym 2", "synonym 3"))
                                    .setKey("SELECTION_KEY_ONE")),
                        new CarouselSelectCarouselItem()
                            .setTitle("Google Home")
                            .setDescription(
                                "Google Home is a voice-activated speaker powered by the Google Assistant.")
                            .setImage(
                                new Image()
                                    .setUrl(
                                        "https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png")
                                    .setAccessibilityText("Google Home"))
                            .setOptionInfo(
                                new OptionInfo()
                                    .setSynonyms(
                                        Arrays.asList(
                                            "Google Home Assistant",
                                            "Assistant on the Google Home"))
                                    .setKey("SELECTION_KEY_GOOGLE_HOME")),
                        new CarouselSelectCarouselItem()
                            .setTitle("Google Pixel")
                            .setDescription("Pixel. Phone by Google.")
                            .setImage(
                                new Image()
                                    .setUrl(
                                        "https://storage.googleapis.com/actionsresources/logo_assistant_2x_64dp.png")
                                    .setAccessibilityText("Google Pixel"))
                            .setOptionInfo(
                                new OptionInfo()
                                    .setSynonyms(
                                        Arrays.asList("Google Pixel XL", "Pixel", "Pixel XL"))
                                    .setKey("SELECTION_KEY_GOOGLE_PIXEL")))));
    return responseBuilder.build();
  }
}

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "responseId": "5d7732d1-d22d-4a0e-ad34-8bc0a7fde20c-21947381",
  "queryResult": {
    "queryText": "actions_intent_OPTION",
    "action": "List.List-custom",
    "parameters": {},
    "allRequiredParamsPresent": true,
    "fulfillmentText": "Webhook failed for intent: List - OPTION",
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            "Webhook failed for intent: List - OPTION"
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/df-responses-kohler/agent/sessions/ABwppHHsebncupHK11oKhsCTgyH96GRNYH-xpeeMTqb-cvOxbd67QenbRlZM4bGAIB8_KXdTfI7-7lYVKN1ovAhCaA/contexts/actions_capability_screen_output"
      },
      {
        "name": "projects/df-responses-kohler/agent/sessions/ABwppHHsebncupHK11oKhsCTgyH96GRNYH-xpeeMTqb-cvOxbd67QenbRlZM4bGAIB8_KXdTfI7-7lYVKN1ovAhCaA/contexts/actions_capability_account_linking"
      },
      {
        "name": "projects/df-responses-kohler/agent/sessions/ABwppHHsebncupHK11oKhsCTgyH96GRNYH-xpeeMTqb-cvOxbd67QenbRlZM4bGAIB8_KXdTfI7-7lYVKN1ovAhCaA/contexts/actions_capability_media_response_audio"
      },
      {
        "name": "projects/df-responses-kohler/agent/sessions/ABwppHHsebncupHK11oKhsCTgyH96GRNYH-xpeeMTqb-cvOxbd67QenbRlZM4bGAIB8_KXdTfI7-7lYVKN1ovAhCaA/contexts/actions_capability_audio_output"
      },
      {
        "name": "projects/df-responses-kohler/agent/sessions/ABwppHHsebncupHK11oKhsCTgyH96GRNYH-xpeeMTqb-cvOxbd67QenbRlZM4bGAIB8_KXdTfI7-7lYVKN1ovAhCaA/contexts/actions_capability_web_browser"
      },
      {
        "name": "projects/df-responses-kohler/agent/sessions/ABwppHHsebncupHK11oKhsCTgyH96GRNYH-xpeeMTqb-cvOxbd67QenbRlZM4bGAIB8_KXdTfI7-7lYVKN1ovAhCaA/contexts/google_assistant_input_type_touch"
      },
      {
        "name": "projects/df-responses-kohler/agent/sessions/ABwppHHsebncupHK11oKhsCTgyH96GRNYH-xpeeMTqb-cvOxbd67QenbRlZM4bGAIB8_KXdTfI7-7lYVKN1ovAhCaA/contexts/list-followup",
        "lifespanCount": 1
      },
      {
        "name": "projects/df-responses-kohler/agent/sessions/ABwppHHsebncupHK11oKhsCTgyH96GRNYH-xpeeMTqb-cvOxbd67QenbRlZM4bGAIB8_KXdTfI7-7lYVKN1ovAhCaA/contexts/actions_intent_option",
        "parameters": {
          "OPTION": "SELECTION_KEY_GOOGLE_PIXEL",
          "text": "Google Pixel"
        }
      }
    ],
    "intent": {
      "name": "projects/df-responses-kohler/agent/intents/88904350-193e-4472-a2de-977eb5d9e26e",
      "displayName": "List - OPTION"
    },
    "intentDetectionConfidence": 1,
    "languageCode": "en"
  },
  "originalDetectIntentRequest": {
    "source": "google",
    "version": "2",
    "payload": {
      "user": {
        "locale": "en-US",
        "lastSeen": "2019-08-04T23:56:32Z",
        "userVerificationStatus": "VERIFIED"
      },
      "conversation": {
        "conversationId": "ABwppHHsebncupHK11oKhsCTgyH96GRNYH-xpeeMTqb-cvOxbd67QenbRlZM4bGAIB8_KXdTfI7-7lYVKN1ovAhCaA",
        "type": "ACTIVE",
        "conversationToken": "[\"list-followup\"]"
      },
      "inputs": [
        {
          "intent": "actions.intent.OPTION",
          "rawInputs": [
            {
              "inputType": "TOUCH",
              "query": "Google Pixel"
            }
          ],
          "arguments": [
            {
              "name": "OPTION",
              "textValue": "SELECTION_KEY_GOOGLE_PIXEL"
            },
            {
              "name": "text",
              "rawText": "Google Pixel",
              "textValue": "Google Pixel"
            }
          ]
        }
      ],
      "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"
          }
        ]
      },
      "isInSandbox": true,
      "availableSurfaces": [
        {
          "capabilities": [
            {
              "name": "actions.capability.WEB_BROWSER"
            },
            {
              "name": "actions.capability.SCREEN_OUTPUT"
            },
            {
              "name": "actions.capability.AUDIO_OUTPUT"
            }
          ]
        }
      ],
      "requestType": "SIMULATOR"
    }
  },
  "session": "projects/df-responses-kohler/agent/sessions/ABwppHHsebncupHK11oKhsCTgyH96GRNYH-xpeeMTqb-cvOxbd67QenbRlZM4bGAIB8_KXdTfI7-7lYVKN1ovAhCaA"
}

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "user": {
    "locale": "en-US",
    "lastSeen": "2019-08-06T07:37:53Z",
    "userVerificationStatus": "VERIFIED"
  },
  "conversation": {
    "conversationId": "ABwppHGcqunXh1M6IE0lu2sVqXdpJfdpC5FWMkMSXQskK1nzb4IkSUSRqQzoEr0Ly0z_G3mwyZlk5rFtd1w",
    "type": "NEW"
  },
  "inputs": [
    {
      "intent": "actions.intent.OPTION",
      "rawInputs": [
        {
          "inputType": "TOUCH",
          "query": "Google Home"
        }
      ],
      "arguments": [
        {
          "name": "OPTION",
          "textValue": "SELECTION_KEY_GOOGLE_HOME"
        },
        {
          "name": "text",
          "rawText": "Google Home",
          "textValue": "Google Home"
        }
      ]
    }
  ],
  "surface": {
    "capabilities": [
      {
        "name": "actions.capability.AUDIO_OUTPUT"
      },
      {
        "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
      },
      {
        "name": "actions.capability.ACCOUNT_LINKING"
      },
      {
        "name": "actions.capability.SCREEN_OUTPUT"
      },
      {
        "name": "actions.capability.WEB_BROWSER"
      }
    ]
  },
  "isInSandbox": true,
  "availableSurfaces": [
    {
      "capabilities": [
        {
          "name": "actions.capability.WEB_BROWSER"
        },
        {
          "name": "actions.capability.AUDIO_OUTPUT"
        },
        {
          "name": "actions.capability.SCREEN_OUTPUT"
        }
      ]
    }
  ],
  "requestType": "SIMULATOR"
}

Data e ora

Puoi ottenere una data e un'ora dagli utenti richiedendo il completamento dell'intent actions.intent.DATETIME.

Chiamata a chi cerca aiuto

Il seguente esempio di codice mostra come chiamare l'helper utilizzando la libreria client. Gli snippet JSON mostrano la risposta webhook corrispondente.

Puoi specificare prompt personalizzati quando chiedi all'utente una data e un'ora utilizzando l'oggetto options durante la creazione dell'autorizzazione DateTime.

Node.js

app.intent('Date Time', (conv) => {
  const options = {
    prompts: {
      initial: 'When would you like to schedule the appointment?',
      date: 'What day was that?',
      time: 'What time works for you?',
    },
  };
  conv.ask(new DateTime(options));
});

Java

@ForIntent("Date Time")
public ActionResponse getDateTime(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);

  responseBuilder
      .add("PLACEHOLDER")
      .add(
          new DateTimePrompt()
              .setDateTimePrompt("When would you like to schedule the appointment?")
              .setDatePrompt("What day was that?")
              .setTimePrompt("What time works for you?"));
  return responseBuilder.build();
}

Node.js

const options = {
  prompts: {
    initial: 'When would you like to schedule the appointment?',
    date: 'What day was that?',
    time: 'What time works for you?',
  },
};
conv.ask(new DateTime(options));

Java

ResponseBuilder responseBuilder = getResponseBuilder(request);

responseBuilder
    .add("PLACEHOLDER")
    .add(
        new DateTimePrompt()
            .setDateTimePrompt("When would you like to schedule the appointment?")
            .setDatePrompt("What day was that?")
            .setTimePrompt("What time works for you?"));
return responseBuilder.build();

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "payload": {
    "google": {
      "expectUserResponse": true,
      "systemIntent": {
        "intent": "actions.intent.DATETIME",
        "data": {
          "@type": "type.googleapis.com/google.actions.v2.DateTimeValueSpec",
          "dialogSpec": {
            "requestDatetimeText": "When would you like to schedule the appointment?",
            "requestDateText": "What day was that?",
            "requestTimeText": "What time works for you?"
          }
        }
      }
    }
  }
}

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "possibleIntents": [
        {
          "intent": "actions.intent.DATETIME",
          "inputValueData": {
            "@type": "type.googleapis.com/google.actions.v2.DateTimeValueSpec",
            "dialogSpec": {
              "requestDatetimeText": "When would you like to schedule the appointment?",
              "requestDateText": "What day was that?",
              "requestTimeText": "What time works for you?"
            }
          }
        }
      ]
    }
  ]
}

Recupero dei risultati dell'helper in corso...

Il seguente esempio di codice mostra come accedere al risultato dell'helper utilizzando la libreria client. Gli snippet JSON rappresentano la richiesta e contengono il risultato dell'helper che riceverà il fulfillment.

Lo snippet seguente mostra come verificare se l'utente ha concesso l'accesso e come accedere ai dati.

Node.js

app.intent('Date Time Handler', (conv, params, datetime) => {
  const {month, day} = datetime.date;
  const {hours, minutes} = datetime.time;
  conv.ask(`<speak>` +
      `Great, we will see you on ` +
      `<say-as interpret-as="date" format="dm">${day}-${month}</say-as>` +
      `<say-as interpret-as="time" format="hms12" detail="2">${hours}` +
      `:${minutes || '00'}</say-as>` +
      `</speak>`);
  conv.ask('Would you like to try another helper?');
  conv.ask(new Suggestions([
    'Confirmation',
    'Permission',
    'Place',
  ]));
});

Java

@ForIntent("Date Time Handler")
public ActionResponse handleDateTime(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);

  DateTime dateTimeValue = request.getDateTime();
  Integer day = dateTimeValue.getDate().getDay();
  Integer month = dateTimeValue.getDate().getMonth();
  Integer hours = dateTimeValue.getTime().getHours();
  Integer minutes = dateTimeValue.getTime().getMinutes();
  String minutesStr = (minutes != null) ? String.valueOf(minutes) : "00";
  responseBuilder.add(
      "<speak>"
          + "Great, we will see you on "
          + "<say-as interpret-as=\"date\" format=\"dm\">"
          + day
          + "-"
          + month
          + "</say-as>"
          + "<say-as interpret-as=\"time\" format=\"hms12\" detail=\"2\">"
          + hours
          + ":"
          + minutesStr
          + "</say-as>"
          + "</speak>");
  responseBuilder
      .add("Would you like to try another helper?")
      .addSuggestions(new String[] {"Confirmation", "Permission", "Place"});
  return responseBuilder.build();
}

Node.js

app.intent('actions.intent.DATETIME', (conv) => {
  const datetime = conv.arguments.get('DATETIME');
  const {month, day} = datetime.date;
  const {hours, minutes} = datetime.time;
  conv.ask(`<speak>` +
      `Great, we will see you on ` +
      `<say-as interpret-as="date" format="dm">${day}-${month}</say-as>` +
      `<say-as interpret-as="time" format="hms12" detail="2">${hours}` +
      `:${minutes || '00'}</say-as>` +
      `</speak>`);
  conv.ask('Would you like to try another helper?');
  conv.ask(new Suggestions([
    'Confirmation',
    'Permission',
    'Place',
  ]));
});

Java

@ForIntent("actions.intent.DATETIME")
public ActionResponse datetimeHandler(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);

  DateTime dateTimeValue = request.getDateTime();
  Integer day = dateTimeValue.getDate().getDay();
  Integer month = dateTimeValue.getDate().getMonth();
  Integer hours = dateTimeValue.getTime().getHours();
  Integer minutes = dateTimeValue.getTime().getMinutes();
  String minutesStr = (minutes != null) ? String.valueOf(minutes) : "00";
  responseBuilder.add(
      "<speak>"
          + "Great, we will see you on "
          + "<say-as interpret-as=\"date\" format=\"dm\">"
          + day
          + "-"
          + month
          + "</say-as>"
          + "<say-as interpret-as=\"time\" format=\"hms12\" detail=\"2\">"
          + hours
          + ":"
          + minutesStr
          + "</say-as>"
          + "</speak>");
  responseBuilder
      .add("Would you like to try another helper?")
      .addSuggestions(new String[] {"Confirmation", "Permission", "Place"});
  return responseBuilder.build();
}

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "responseId": "2b0a039d-b033-4256-bd8a-ebb1f0ad90b4-712767ed",
  "queryResult": {
    "queryText": "actions_intent_DATETIME",
    "action": "DateTime.DateTime-custom",
    "parameters": {},
    "allRequiredParamsPresent": true,
    "fulfillmentText": "Webhook failed for intent: Date Time Handler",
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            "Webhook failed for intent: Date Time Handler"
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHHnU7RSIOU994H8vd2wLYXbnoIAs3rk-4zUeiRAaX3aJ0dp68Y50MgvddE2stYuI6Hlu-MfWO75Gz76EeY/contexts/actions_capability_audio_output"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHHnU7RSIOU994H8vd2wLYXbnoIAs3rk-4zUeiRAaX3aJ0dp68Y50MgvddE2stYuI6Hlu-MfWO75Gz76EeY/contexts/actions_capability_screen_output"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHHnU7RSIOU994H8vd2wLYXbnoIAs3rk-4zUeiRAaX3aJ0dp68Y50MgvddE2stYuI6Hlu-MfWO75Gz76EeY/contexts/actions_capability_media_response_audio"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHHnU7RSIOU994H8vd2wLYXbnoIAs3rk-4zUeiRAaX3aJ0dp68Y50MgvddE2stYuI6Hlu-MfWO75Gz76EeY/contexts/actions_capability_account_linking"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHHnU7RSIOU994H8vd2wLYXbnoIAs3rk-4zUeiRAaX3aJ0dp68Y50MgvddE2stYuI6Hlu-MfWO75Gz76EeY/contexts/actions_capability_web_browser"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHHnU7RSIOU994H8vd2wLYXbnoIAs3rk-4zUeiRAaX3aJ0dp68Y50MgvddE2stYuI6Hlu-MfWO75Gz76EeY/contexts/google_assistant_input_type_keyboard"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHHnU7RSIOU994H8vd2wLYXbnoIAs3rk-4zUeiRAaX3aJ0dp68Y50MgvddE2stYuI6Hlu-MfWO75Gz76EeY/contexts/datetime-followup",
        "lifespanCount": 1
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHHnU7RSIOU994H8vd2wLYXbnoIAs3rk-4zUeiRAaX3aJ0dp68Y50MgvddE2stYuI6Hlu-MfWO75Gz76EeY/contexts/actions_intent_datetime",
        "parameters": {
          "DATETIME": "2019-08-14T10:30:00",
          "text": "1030am"
        }
      }
    ],
    "intent": {
      "name": "projects/df-helpers-kohler/agent/intents/3c145f18-32fe-40aa-842e-b99ab28c3f2a",
      "displayName": "Date Time Handler"
    },
    "intentDetectionConfidence": 1,
    "languageCode": "en"
  },
  "originalDetectIntentRequest": {
    "source": "google",
    "version": "2",
    "payload": {
      "user": {
        "locale": "en-US",
        "userVerificationStatus": "VERIFIED"
      },
      "conversation": {
        "conversationId": "ABwppHHnU7RSIOU994H8vd2wLYXbnoIAs3rk-4zUeiRAaX3aJ0dp68Y50MgvddE2stYuI6Hlu-MfWO75Gz76EeY",
        "type": "ACTIVE",
        "conversationToken": "[\"datetime-followup\"]"
      },
      "inputs": [
        {
          "intent": "actions.intent.DATETIME",
          "rawInputs": [
            {
              "inputType": "KEYBOARD",
              "query": "1030am"
            }
          ],
          "arguments": [
            {
              "name": "DATETIME",
              "datetimeValue": {
                "date": {
                  "year": 2019,
                  "month": 8,
                  "day": 14
                },
                "time": {
                  "hours": 10,
                  "minutes": 30
                }
              }
            },
            {
              "name": "text",
              "rawText": "1030am",
              "textValue": "1030am"
            }
          ]
        }
      ],
      "surface": {
        "capabilities": [
          {
            "name": "actions.capability.AUDIO_OUTPUT"
          },
          {
            "name": "actions.capability.SCREEN_OUTPUT"
          },
          {
            "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
          },
          {
            "name": "actions.capability.ACCOUNT_LINKING"
          },
          {
            "name": "actions.capability.WEB_BROWSER"
          }
        ]
      },
      "availableSurfaces": [
        {
          "capabilities": [
            {
              "name": "actions.capability.AUDIO_OUTPUT"
            },
            {
              "name": "actions.capability.SCREEN_OUTPUT"
            },
            {
              "name": "actions.capability.WEB_BROWSER"
            }
          ]
        }
      ]
    }
  },
  "session": "projects/df-helpers-kohler/agent/sessions/ABwppHHnU7RSIOU994H8vd2wLYXbnoIAs3rk-4zUeiRAaX3aJ0dp68Y50MgvddE2stYuI6Hlu-MfWO75Gz76EeY"
}

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "user": {
    "profile": {
      "displayName": "Sachit Mishra",
      "givenName": "Sachit",
      "familyName": "Mishra"
    },
    "permissions": [
      "DEVICE_PRECISE_LOCATION",
      "NAME"
    ],
    "locale": "en-US",
    "userVerificationStatus": "VERIFIED"
  },
  "conversation": {
    "conversationId": "ABwppHEcidO2jguO4hS8maDeMVx8aasSCcBWZHrF3EmOMIaWRP9qF0BcACistiIoeyiSNTW6KD_tqN_U-xAIOXhPvA",
    "type": "NEW"
  },
  "inputs": [
    {
      "intent": "actions.intent.DATETIME",
      "rawInputs": [
        {
          "inputType": "KEYBOARD",
          "query": "430pm"
        }
      ],
      "arguments": [
        {
          "name": "DATETIME",
          "datetimeValue": {
            "date": {
              "year": 2019,
              "month": 8,
              "day": 18
            },
            "time": {
              "hours": 16,
              "minutes": 30
            }
          }
        },
        {
          "name": "text",
          "rawText": "430pm",
          "textValue": "430pm"
        }
      ]
    }
  ],
  "surface": {
    "capabilities": [
      {
        "name": "actions.capability.ACCOUNT_LINKING"
      },
      {
        "name": "actions.capability.WEB_BROWSER"
      },
      {
        "name": "actions.capability.AUDIO_OUTPUT"
      },
      {
        "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
      },
      {
        "name": "actions.capability.SCREEN_OUTPUT"
      }
    ]
  },
  "device": {
    "location": {
      "coordinates": {
        "latitude": 37.4197238,
        "longitude": -122.08212759999999
      },
      "formattedAddress": "Google Building 45 1585 Charleston Road, Mountain View, California 94043",
      "zipCode": "94043",
      "city": "Mountain View"
    }
  },
  "availableSurfaces": [
    {
      "capabilities": [
        {
          "name": "actions.capability.AUDIO_OUTPUT"
        },
        {
          "name": "actions.capability.SCREEN_OUTPUT"
        },
        {
          "name": "actions.capability.WEB_BROWSER"
        }
      ]
    }
  ]
}

Accesso all'account

Puoi consentire agli utenti di accedere ai propri account associati al tuo servizio richiedendo il completamento dell'intent actions.intent.SIGN_IN. Gli utenti non possono accedere con la voce tramite OAuth.

Chiamata a chi cerca aiuto

Il seguente esempio di codice mostra come chiamare l'helper utilizzando la libreria client. Gli snippet JSON mostrano la risposta webhook corrispondente.

Node.js

const {SignIn} = require('actions-on-google');
app.intent('ask_for_sign_in_detail', (conv) => {
  conv.ask(new SignIn());
});

Java

ResponseBuilder responseBuilder = getResponseBuilder(request);
return responseBuilder.add("This is the SignIn helper intent").add(new SignIn()).build();

JSON

{
  "payload": {
    "google": {
      "expectUserResponse": true,
      "systemIntent": {
        "intent": "actions.intent.SIGN_IN",
        "data": {
          "@type": "type.googleapis.com/google.actions.v2.SignInValueSpec"
        }
      }
    }
  }
}

JSON

{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "possibleIntents": [
        {
          "intent": "actions.intent.SIGN_IN",
          "inputValueData": {
            "@type": "type.googleapis.com/google.actions.v2.SignInValueSpec"
          }
        }
      ]
    }
  ]
}

Recupero dei risultati dell'helper in corso...

Il seguente esempio di codice mostra come accedere al risultato dell'helper utilizzando la libreria client. Gli snippet JSON rappresentano la richiesta e contengono il risultato dell'helper che riceverà il fulfillment.

Lo snippet seguente mostra come verificare se l'utente ha concesso l'accesso e come accedere ai dati.

Node.js

app.intent('ask_for_sign_in_confirmation', (conv, params, signin) => {
  if (signin.status !== 'OK') {
    return conv.ask('You need to sign in before using the app.');
  }
  // const access = conv.user.access.token;
  // possibly do something with access token
  return conv.ask('Great! Thanks for signing in.');
});

Java

ResponseBuilder responseBuilder = getResponseBuilder(request);
boolean signedIn = request.isSignInGranted();
return responseBuilder
    .add(signedIn ? "Great! Thanks for signin in." : "You must sign in before using the app.")
    .build();

JSON

{
  "responseId": "",
  "queryResult": {
    "queryText": "",
    "action": "",
    "parameters": {},
    "allRequiredParamsPresent": true,
    "fulfillmentText": "",
    "fulfillmentMessages": [],
    "outputContexts": [],
    "intent": {
      "name": "ask_for_sign_in_confirmation",
      "displayName": "ask_for_sign_in_confirmation"
    },
    "intentDetectionConfidence": 1,
    "diagnosticInfo": {},
    "languageCode": ""
  },
  "originalDetectIntentRequest": {
    "source": "google",
    "version": "2",
    "payload": {
      "isInSandbox": true,
      "surface": {
        "capabilities": [
          {
            "name": "actions.capability.SCREEN_OUTPUT"
          },
          {
            "name": "actions.capability.AUDIO_OUTPUT"
          },
          {
            "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
          },
          {
            "name": "actions.capability.WEB_BROWSER"
          }
        ]
      },
      "inputs": [
        {
          "rawInputs": [],
          "intent": "",
          "arguments": [
            {
              "name": "SIGN_IN",
              "extension": {
                "@type": "type.googleapis.com/google.actions.v2.SignInValue",
                "status": "OK"
              }
            }
          ]
        }
      ],
      "user": {},
      "conversation": {},
      "availableSurfaces": [
        {
          "capabilities": [
            {
              "name": "actions.capability.SCREEN_OUTPUT"
            },
            {
              "name": "actions.capability.AUDIO_OUTPUT"
            },
            {
              "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
            },
            {
              "name": "actions.capability.WEB_BROWSER"
            }
          ]
        }
      ]
    }
  },
  "session": ""
}

JSON

{
  "user": {},
  "device": {},
  "surface": {
    "capabilities": [
      {
        "name": "actions.capability.SCREEN_OUTPUT"
      },
      {
        "name": "actions.capability.AUDIO_OUTPUT"
      },
      {
        "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
      },
      {
        "name": "actions.capability.WEB_BROWSER"
      }
    ]
  },
  "conversation": {},
  "inputs": [
    {
      "rawInputs": [],
      "intent": "ask_for_sign_in_confirmation",
      "arguments": [
        {
          "name": "SIGN_IN",
          "extension": {
            "@type": "type.googleapis.com/google.actions.v2.SignInValue",
            "status": "OK"
          }
        }
      ]
    }
  ],
  "availableSurfaces": [
    {
      "capabilities": [
        {
          "name": "actions.capability.SCREEN_OUTPUT"
        },
        {
          "name": "actions.capability.AUDIO_OUTPUT"
        },
        {
          "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
        },
        {
          "name": "actions.capability.WEB_BROWSER"
        }
      ]
    }
  ]
}

Luogo e località

Puoi ottenere una località dagli utenti richiedendo il completamento dell'intent actions.intent.PLACE. Questo helper viene utilizzato per richiedere all'utente indirizzi e altre posizioni, inclusi gli indirizzi di casa/lavoro/contatti salvati su Google.

I luoghi salvati restituiranno solo l'indirizzo, non la mappatura associata (ad es. "Via Garibaldi 123" anziché "HOME = Via Roma 123").

Chiamata a chi cerca aiuto

Il seguente esempio di codice mostra come chiamare l'helper utilizzando la libreria client. Gli snippet JSON mostrano la risposta webhook corrispondente.

Node.js

app.intent('Place', (conv) => {
  const options = {
    context: 'To find a location',
    prompt: 'Where would you like to go?',
  };
  conv.ask(new Place(options));
});

Java

@ForIntent("Place")
public ActionResponse getPlace(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  responseBuilder
      .add("PLACEHOLDER")
      .add(
          new Place()
              .setRequestPrompt("Where would you like to go?")
              .setPermissionContext("To find  a location"));
  return responseBuilder.build();
}

Node.js

const options = {
  context: 'To find a location',
  prompt: 'Where would you like to go?',
};
conv.ask(new Place(options));

Java

ResponseBuilder responseBuilder = getResponseBuilder(request);
responseBuilder
    .add("PLACEHOLDER")
    .add(
        new Place()
            .setRequestPrompt("Where would you like to go?")
            .setPermissionContext("To find  a location"));
return responseBuilder.build();

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "payload": {
    "google": {
      "expectUserResponse": true,
      "systemIntent": {
        "intent": "actions.intent.PLACE",
        "data": {
          "@type": "type.googleapis.com/google.actions.v2.PlaceValueSpec",
          "dialogSpec": {
            "extension": {
              "@type": "type.googleapis.com/google.actions.v2.PlaceValueSpec.PlaceDialogSpec",
              "permissionContext": "To find a location",
              "requestPrompt": "Where would you like to go?"
            }
          }
        }
      }
    }
  }
}

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "possibleIntents": [
        {
          "intent": "actions.intent.PLACE",
          "inputValueData": {
            "@type": "type.googleapis.com/google.actions.v2.PlaceValueSpec",
            "dialogSpec": {
              "extension": {
                "@type": "type.googleapis.com/google.actions.v2.PlaceValueSpec.PlaceDialogSpec",
                "permissionContext": "To find a location",
                "requestPrompt": "Where would you like to go?"
              }
            }
          }
        }
      ]
    }
  ]
}

Recupero dei risultati dell'helper in corso...

Il seguente esempio di codice mostra come accedere al risultato dell'helper utilizzando la libreria client. Gli snippet JSON rappresentano la richiesta e contengono il risultato dell'helper che riceverà il fulfillment.

Lo snippet seguente mostra come verificare se l'utente ha concesso l'accesso e come accedere ai dati.

Node.js

app.intent('Place Handler', (conv, params, place) => {
  if (!place) {
    conv.ask(`Sorry, I couldn't get a location from you.`);
  } else {
    // Place also contains formattedAddress and coordinates
    const {name} = place;
    conv.ask(`${name} sounds like a great place to go!`);
  }
  conv.ask('Would you like to try another helper?');
  conv.ask(new Suggestions([
    'Confirmation',
    'DateTime',
    'Permission',
  ]));
});

Java

@ForIntent("Place Handler")
public ActionResponse handlePlace(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  Location location = request.getPlace();
  if (location == null) {
    responseBuilder.add("Sorry, I couldn't get a location from you.");
  } else {
    responseBuilder.add(location.getName() + " sounds like a great place to go!");
  }
  responseBuilder
      .add("Would you like to try another helper?")
      .addSuggestions(new String[] {"Confirmation", "DateTime", "Permission"});
  return responseBuilder.build();
}

Node.js

app.intent('actions.intent.PLACE', (conv) => {
  const place = conv.arguments.get('PLACE');
  if (!place) {
    conv.ask(`Sorry, I couldn't get a location from you.`);
  } else {
    // Place also contains formattedAddress and coordinates
    const {name} = place;
    conv.ask(`${name} sounds like a great place to go!`);
  }
  conv.ask('Would you like to try another helper?');
  conv.ask(new Suggestions([
    'Confirmation',
    'DateTime',
    'Permission',
  ]));
});

Java

@ForIntent("actions.intent.PLACE")
public ActionResponse handlePlace(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  Location location = request.getPlace();
  if (location == null) {
    responseBuilder.add("Sorry, I couldn't get a location from you.");
  } else {
    responseBuilder.add(location.getName() + " sounds like a great place to go!");
  }
  responseBuilder
      .add("Would you like to try another helper?")
      .addSuggestions(new String[] {"Confirmation", "DateTime", "Permission"});
  return responseBuilder.build();
}

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "responseId": "ce99fd40-b9ed-4151-bc99-f25db9eda8c5-712767ed",
  "queryResult": {
    "queryText": "actions_intent_PLACE",
    "action": "Place.Place-custom",
    "parameters": {},
    "allRequiredParamsPresent": true,
    "fulfillmentText": "Webhook failed for intent: Place Handler",
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            "Webhook failed for intent: Place Handler"
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA/contexts/actions_capability_audio_output"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA/contexts/actions_capability_screen_output"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA/contexts/actions_capability_media_response_audio"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA/contexts/actions_capability_account_linking"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA/contexts/actions_capability_web_browser"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA/contexts/google_assistant_input_type_keyboard"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA/contexts/place-followup",
        "lifespanCount": 1
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA/contexts/actions_intent_place",
        "parameters": {
          "PLACE": "KFC, 2523 North Carson Street, Carson City, NV 89706, United States",
          "text": "yes"
        }
      }
    ],
    "intent": {
      "name": "projects/df-helpers-kohler/agent/intents/4cf9e154-e151-44db-ae79-84d8c5a707de",
      "displayName": "Place Handler"
    },
    "intentDetectionConfidence": 1,
    "languageCode": "en"
  },
  "originalDetectIntentRequest": {
    "source": "google",
    "version": "2",
    "payload": {
      "user": {
        "permissions": [
          "DEVICE_PRECISE_LOCATION"
        ],
        "locale": "en-US",
        "userVerificationStatus": "VERIFIED"
      },
      "conversation": {
        "conversationId": "ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA",
        "type": "ACTIVE",
        "conversationToken": "[\"place-followup\"]"
      },
      "inputs": [
        {
          "intent": "actions.intent.PLACE",
          "rawInputs": [
            {
              "inputType": "KEYBOARD",
              "query": "Query handled by Actions on Google"
            }
          ],
          "arguments": [
            {
              "name": "PLACE",
              "placeValue": {
                "coordinates": {
                  "latitude": 39.182895,
                  "longitude": -119.7679113
                },
                "formattedAddress": "KFC, 2523 North Carson Street, Carson City, NV 89706, United States",
                "name": "KFC",
                "placeId": "ChIJZfBpmMEKmYARFsfc574LgB8"
              }
            },
            {
              "name": "text",
              "rawText": "yes",
              "textValue": "yes"
            }
          ]
        }
      ],
      "surface": {
        "capabilities": [
          {
            "name": "actions.capability.AUDIO_OUTPUT"
          },
          {
            "name": "actions.capability.SCREEN_OUTPUT"
          },
          {
            "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
          },
          {
            "name": "actions.capability.ACCOUNT_LINKING"
          },
          {
            "name": "actions.capability.WEB_BROWSER"
          }
        ]
      },
      "device": {
        "location": {
          "coordinates": {
            "latitude": 39.2814592,
            "longitude": -120.12421119999999
          },
          "formattedAddress": "Currant Road, Truckee, California 96161",
          "zipCode": "96161",
          "city": "Truckee"
        }
      },
      "availableSurfaces": [
        {
          "capabilities": [
            {
              "name": "actions.capability.WEB_BROWSER"
            },
            {
              "name": "actions.capability.SCREEN_OUTPUT"
            },
            {
              "name": "actions.capability.AUDIO_OUTPUT"
            }
          ]
        }
      ]
    }
  }
}

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "user": {
    "permissions": [
      "DEVICE_PRECISE_LOCATION"
    ],
    "locale": "en-US",
    "userVerificationStatus": "VERIFIED"
  },
  "conversation": {
    "conversationId": "ABwppHEcidO2jguO4hS8maDeMVx8aasSCcBWZHrF3EmOMIaWRP9qF0BcACistiIoeyiSNTW6KD_tqN_U-xAIOXhPvA",
    "type": "NEW"
  },
  "inputs": [
    {
      "intent": "actions.intent.PLACE",
      "rawInputs": [
        {
          "inputType": "KEYBOARD",
          "query": "Query handled by Actions on Google"
        }
      ],
      "arguments": [
        {
          "name": "PLACE",
          "placeValue": {
            "coordinates": {
              "latitude": 37.4219999,
              "longitude": -122.0840575
            },
            "formattedAddress": "Googleplex, 1600 Amphitheatre Parkway, Mountain View, CA 94043, United States",
            "name": "Googleplex",
            "placeId": "ChIJj61dQgK6j4AR4GeTYWZsKWw"
          }
        },
        {
          "name": "text",
          "rawText": "googleplex",
          "textValue": "googleplex"
        }
      ]
    }
  ],
  "surface": {
    "capabilities": [
      {
        "name": "actions.capability.AUDIO_OUTPUT"
      },
      {
        "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
      },
      {
        "name": "actions.capability.ACCOUNT_LINKING"
      },
      {
        "name": "actions.capability.SCREEN_OUTPUT"
      },
      {
        "name": "actions.capability.WEB_BROWSER"
      }
    ]
  },
  "device": {
    "location": {
      "coordinates": {
        "latitude": 37.4197238,
        "longitude": -122.08212759999999
      },
      "formattedAddress": "Google Building 45 1585 Charleston Road, Mountain View, California 94043",
      "zipCode": "94043",
      "city": "Mountain View"
    }
  },
  "availableSurfaces": [
    {
      "capabilities": [
        {
          "name": "actions.capability.SCREEN_OUTPUT"
        },
        {
          "name": "actions.capability.WEB_BROWSER"
        },
        {
          "name": "actions.capability.AUDIO_OUTPUT"
        }
      ]
    }
  ]
}

Conferma

Puoi porre una conferma generica all'utente (domanda con risposta sì/no) e ottenere la risposta risultante. La grammatica di "sì" e "no" si espande naturalmente a cose come "Sì" o "No", rendendola così utilizzabile in molte situazioni.

Chiamata a chi cerca aiuto

Il seguente esempio di codice mostra come chiamare l'helper utilizzando la libreria client. Gli snippet JSON mostrano la risposta webhook corrispondente.

Puoi specificare un prompt personalizzato quando chiedi all'utente una conferma.

Node.js

app.intent('Confirmation', (conv) => {
  conv.ask(new Confirmation('Can you confirm?'));
});

Java

@ForIntent("Confirmation")
public ActionResponse getConfirmation(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  responseBuilder
      .add("PLACEHOLDER")
      .add(new Confirmation().setConfirmationText("Can you confirm?"));
  return responseBuilder.build();
}

Node.js

conv.ask(new Confirmation('Can you confirm?'));

Java

ResponseBuilder responseBuilder = getResponseBuilder(request);
responseBuilder
    .add("PLACEHOLDER")
    .add(new Confirmation().setConfirmationText("Can you confirm?"));
return responseBuilder.build();

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "payload": {
    "google": {
      "expectUserResponse": true,
      "systemIntent": {
        "intent": "actions.intent.CONFIRMATION",
        "data": {
          "@type": "type.googleapis.com/google.actions.v2.ConfirmationValueSpec",
          "dialogSpec": {
            "requestConfirmationText": "Can you confirm?"
          }
        }
      }
    }
  }
}

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "possibleIntents": [
        {
          "intent": "actions.intent.CONFIRMATION",
          "inputValueData": {
            "@type": "type.googleapis.com/google.actions.v2.ConfirmationValueSpec",
            "dialogSpec": {
              "requestConfirmationText": "Can you confirm?"
            }
          }
        }
      ]
    }
  ]
}

Recupero dei risultati dell'helper in corso...

Il seguente esempio di codice mostra come accedere al risultato dell'helper utilizzando la libreria client. Gli snippet JSON rappresentano la richiesta e contengono il risultato dell'helper che riceverà il fulfillment.

Dopo che l'utente ha risposto all'helper, ricevi una richiesta per il fulfillment e puoi verificare se l'utente ha confermato o meno.

Node.js

app.intent('Confirmation Handler', (conv, params, confirmationGranted) => {
  conv.ask(confirmationGranted
    ? 'Thank you for confirming'
    : 'No problem, you have not confirmed');
  conv.ask('Would you like to try another helper?');
  conv.ask(new Suggestions([
    'DateTime',
    'Permission',
    'Place',
  ]));
});

Java

@ForIntent("Confirmation Handler")
public ActionResponse handleConfirmation(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  boolean userConfirmation = request.getUserConfirmation();
  responseBuilder
      .add(userConfirmation ? "Thank you for confirming" : "No problem, you have not confirmed")
      .addSuggestions(new String[] {"Place", "DateTime", "Permission"});
  return responseBuilder.build();
}

Node.js

app.intent('actions.intent.CONFIRMATION', (conv, confirmationGranted) => {
  conv.ask(confirmationGranted
    ? 'Thank you for confirming'
    : 'No problem, you have not confirmed');
  conv.ask('Would you like to try another helper?');
  conv.ask(new Suggestions([
    'DateTime',
    'Permission',
    'Place',
  ]));
});

Java

@ForIntent("actions.intent.CONFIRMATION")
public ActionResponse handleConfirmation(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  boolean userConfirmation = request.getUserConfirmation();
  responseBuilder
      .add(userConfirmation ? "Thank you for confirming" : "No problem, you have not confirmed")
      .addSuggestions(new String[] {"Place", "DateTime", "Permission"});
  return responseBuilder.build();
}

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "responseId": "26c3dd46-321c-4ab5-9f6c-a445f6d5de01-712767ed",
  "queryResult": {
    "queryText": "actions_intent_CONFIRMATION",
    "parameters": {},
    "allRequiredParamsPresent": true,
    "fulfillmentText": "Webhook failed for intent: Confirmation Handler",
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            "Webhook failed for intent: Confirmation Handler"
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA/contexts/actions_capability_account_linking"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA/contexts/actions_capability_media_response_audio"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA/contexts/actions_capability_audio_output"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA/contexts/actions_capability_web_browser"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA/contexts/actions_capability_screen_output"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA/contexts/google_assistant_input_type_keyboard"
      },
      {
        "name": "projects/df-helpers-kohler/agent/sessions/ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA/contexts/actions_intent_confirmation",
        "parameters": {
          "CONFIRMATION": true,
          "text": "yes"
        }
      }
    ],
    "intent": {
      "name": "projects/df-helpers-kohler/agent/intents/11cc7c8e-0710-42ea-9cd9-723aff03e97f",
      "displayName": "Confirmation Handler"
    },
    "intentDetectionConfidence": 1,
    "languageCode": "en"
  },
  "originalDetectIntentRequest": {
    "source": "google",
    "version": "2",
    "payload": {
      "user": {
        "locale": "en-US",
        "userVerificationStatus": "VERIFIED"
      },
      "conversation": {
        "conversationId": "ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA",
        "type": "ACTIVE",
        "conversationToken": "[]"
      },
      "inputs": [
        {
          "intent": "actions.intent.CONFIRMATION",
          "rawInputs": [
            {
              "inputType": "KEYBOARD",
              "query": "yes"
            }
          ],
          "arguments": [
            {
              "name": "CONFIRMATION",
              "boolValue": true
            },
            {
              "name": "text",
              "rawText": "yes",
              "textValue": "yes"
            }
          ]
        }
      ],
      "surface": {
        "capabilities": [
          {
            "name": "actions.capability.ACCOUNT_LINKING"
          },
          {
            "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
          },
          {
            "name": "actions.capability.AUDIO_OUTPUT"
          },
          {
            "name": "actions.capability.WEB_BROWSER"
          },
          {
            "name": "actions.capability.SCREEN_OUTPUT"
          }
        ]
      },
      "availableSurfaces": [
        {
          "capabilities": [
            {
              "name": "actions.capability.AUDIO_OUTPUT"
            },
            {
              "name": "actions.capability.SCREEN_OUTPUT"
            },
            {
              "name": "actions.capability.WEB_BROWSER"
            }
          ]
        }
      ]
    }
  },
  "session": "projects/df-helpers-kohler/agent/sessions/ABwppHEdLCo3vaqVs-pED_sPQDIUr_Ls5JYICyNks9vKbfUaIF8n4P7fYsKEYSiKvD3Vmnli9deu_uTB8s3nPeA"
}

JSON

Tieni presente che il JSON di seguito descrive una richiesta webhook.

{
  "user": {
    "locale": "en-US",
    "userVerificationStatus": "VERIFIED"
  },
  "conversation": {
    "conversationId": "ABwppHGY8XRtymCExS313Cc6Vp42zR0uQuGf6BwpSW0772Er-rxSTtFjs3KfGYu6jCDgHbA8IKVWjB8Gr9odc4yHhg",
    "type": "NEW"
  },
  "inputs": [
    {
      "intent": "actions.intent.CONFIRMATION",
      "rawInputs": [
        {
          "inputType": "KEYBOARD",
          "query": "yes"
        }
      ],
      "arguments": [
        {
          "name": "CONFIRMATION",
          "boolValue": true
        },
        {
          "name": "text",
          "rawText": "yes",
          "textValue": "yes"
        }
      ]
    }
  ],
  "surface": {
    "capabilities": [
      {
        "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
      },
      {
        "name": "actions.capability.SCREEN_OUTPUT"
      },
      {
        "name": "actions.capability.WEB_BROWSER"
      },
      {
        "name": "actions.capability.ACCOUNT_LINKING"
      },
      {
        "name": "actions.capability.AUDIO_OUTPUT"
      }
    ]
  },
  "availableSurfaces": [
    {
      "capabilities": [
        {
          "name": "actions.capability.AUDIO_OUTPUT"
        },
        {
          "name": "actions.capability.SCREEN_OUTPUT"
        },
        {
          "name": "actions.capability.WEB_BROWSER"
        }
      ]
    }
  ]
}