Informazioni sul processo inserite dagli utenti

Questa guida descrive come ricevere e leggere le informazioni inserite dagli utenti nei messaggi delle schede e nelle finestre di dialogo. Gli utenti possono inserire i dati che le app di chat ricevono, leggono e rispondono. Di seguito sono indicati i widget che consentono agli utenti di inserire informazioni:

  • TextInput per l'inserimento di testo in formato libero che supporta anche i suggerimenti.
  • SelectionInput per le voci dell'elenco e i menu, come caselle di controllo, pulsanti di opzione e menu a discesa.
  • DateTimePicker per le voci relative a data e ora.


Utilizza Card Builder per progettare e visualizzare l'anteprima dei messaggi delle schede JSON per le app di chat:

Apri Card Builder

La ricezione di input di dati dagli utenti consente alle app di chat di eseguire operazioni quali:

  • Aggiorna le richieste di assistenza clienti.
  • Creare ordini di lavoro.
  • Esegui l'autenticazione con i servizi web.

Come funziona la ricezione dei dati

Un'app di chat presenta informazioni all'utente in una finestra di dialogo o in un messaggio di scheda. In questo esempio, una finestra di dialogo chiede all'utente di inserire informazioni su un contatto utilizzando i widget TextInput e SelectionInput:

Una finestra di dialogo con una serie di widget diversi.

Al termine, l'app di Chat riceve i dati inseriti dagli utenti nella finestra di dialogo in formato JSON e un evento di interazione in cui:

Per ottenere i dati su ciò che gli utenti hanno inserito, utilizza il campo Event.common.formInputs nel payload dell'evento. Il campo formInputs è una mappa in cui le chiavi sono ID stringa assegnati a ciascun widget e i valori rappresentano l'input dell'utente per ogni widget. Oggetti diversi rappresentano tipi di dati di input diversi. Ad esempio, Event.common.formInputs.stringInputs rappresenta gli input stringa.

L'app può accedere al primo valore inserito dall'utente in event.common.formInputs.NAME.stringInputs.value[0], dove NAME è il campo name di un widget TextInput.

Ricevere dati dalle schede

Quando un utente inserisce dati in un messaggio di scheda, l'app di Chat riceve un evento di interazione con l'app di Chat, come nell'esempio seguente:

JSON

{
  "type": enum (EventType),
  "eventTime": string,
  "threadKey": string,
  "message": {
    object (Message)
  },
  "user": {
    object (User)
  },
  "space": {
    object (Space)
  },
  "action": {
    object (FormAction)
  },
  "configCompleteRedirectUrl": string,
  "common": {

    // Represents user data entered in a card.
    "formInputs": {

      // Represents user data entered for a specific field in a card.
      "NAME": {

        // Represents string data entered in a card, like text input fields
        // and check boxes.
        "stringInputs": {

          // An array of strings entered by the user in a card.
          "value": [
            string
          ]
        }
      }
    },
    "parameters": {
      string: string,
      ...
    },
    "invokedFunction": string
  }
}

Ricevi dati dalle finestre di dialogo

Quando un utente invia dati in una finestra di dialogo, l'app di Chat riceve un altro evento di interazione con l'app di Chat, come il seguente esempio:

JSON

{
  "type": enum (EventType),
  "eventTime": string,
  "threadKey": string,
  "message": {
    object (Message)
  },
  "user": {
    object (User)
  },
  "space": {
    object (Space)
  },
  "action": {
    object (FormAction)
  },
  "configCompleteRedirectUrl": string,

  // Indicates that this event is dialog-related.
  "isDialogEvent": true,

  // Indicates that a user clicked a button, and all data
  // they entered in the dialog is included in Event.common.formInputs.
  "dialogEventType": "SUBMIT_DIALOG",
  "common": {
    "userLocale": string,
    "hostApp": enum (HostApp),
    "platform": enum (Platform),
    "timeZone": {
      object (TimeZone)
    },

    // Represents user data entered in a dialog.
    "formInputs": {

      // Represents user data entered for a specific field in a dialog.
      "NAME": {

        // Represents string data entered in a dialog, like text input fields
        // and check boxes.
        "stringInputs": {

          // An array of strings entered by the user in a dialog.
          "value": [
            string
          ]
        }
      }
    },
    "parameters": {
      string: string,
      ...
    },
    "invokedFunction": string
  }
}

Rispondere ai dati raccolti da un messaggio della scheda o una finestra di dialogo

Dopo aver ricevuto i dati da un messaggio a scheda o una finestra di dialogo, l'app Chat risponde confermando la ricezione o restituendo un errore. Entrambe le operazioni vengono eseguite restituendo un ActionResponse:

  • Per confermare l'avvenuta ricezione, rispondi con un parametro ActionResponse con "actionStatus": "OK".
  • Per restituire un errore, rispondi con un parametro ActionResponse con "actionStatus": "ERROR MESSAGE".

Esempio

L'esempio seguente verifica la presenza di un valore name. Se non è presente, l'app restituisce un errore. Se presente, l'app conferma la ricezione dei dati del modulo e chiude la finestra di dialogo.

Node.js

/**
 * Checks for a form input error, the absence of
 * a "name" value, and returns an error if absent.
 * Otherwise, confirms successful receipt of a dialog.
 *
 * Confirms successful receipt of a dialog.
 *
 * @param {Object} event the event object from Chat API.
 *
 * @return {object} open a Dialog in Google Chat.
 */
function receiveDialog(event) {

  // Checks to make sure the user entered a name
  // in a dialog. If no name value detected, returns
  // an error message.
  if (event.common.formInputs.WIDGET_NAME.stringInputs.value[0] == "") {
    res.json({
      "actionResponse": {
        "type": "DIALOG",
        "dialogAction": {
          "actionStatus": "Don't forget to name your new contact!"
        }
      }
    });

  // Otherwise the app indicates that it received
  // form data from the dialog. Any value other than "OK"
  // gets returned as an error. "OK" is interpreted as
  // code 200, and the dialog closes.
  } else {
    res.json({
      "actionResponse": {
        "type": "DIALOG",
        "dialogAction": {
          "actionStatus": "OK"
        }
      }
    });
  }
}

Apps Script

In questo esempio viene inviato un messaggio relativo alle schede restituendo un JSON della scheda. Puoi anche utilizzare il servizio di schede di Apps Script.

/**
 * Checks for a form input error, the absence of
 * a "name" value, and returns an error if absent.
 * Otherwise, confirms successful receipt of a dialog.
 *
 * Confirms successful receipt of a dialog.
 *
 * @param {Object} event the event object from Chat API.
 *
 * @return {object} open a Dialog in Google Chat.
 */
function receiveDialog(event) {

  // Checks to make sure the user entered a name
  // in a dialog. If no name value detected, returns
  // an error message.
  if (event.common.formInputs.WIDGET_NAME[""].stringInputs.value[0] == "") {
    return {
      "actionResponse": {
        "type": "DIALOG",
        "dialogAction": {
          "actionStatus": "Don't forget to name your new contact!"
        }
      }
    };

  // Otherwise the app indicates that it received
  // form data from the dialog. Any value other than "OK"
  // gets returned as an error. "OK" is interpreted as
  // code 200, and the dialog closes.
  } else {
    return {
      "actionResponse": {
        "type": "DIALOG",
        "dialogAction": {
          "actionStatus": "OK"
        }
      }
    };
  }
}

Python

def receive_dialog(event: Mapping[str, Any]) -> Mapping[str, Any]:
  """Checks for a form input error, the absence of a "name" value, and returns
     an error if absent. Otherwise, confirms successful receipt of a dialog.

  Args:
      event (Mapping[str, Any]): the event object from Chat API.

  Returns:
      Mapping[str, Any]: the response.
  """

  if common := event.get('common'):
    if form_inputs := common.get('formInputs'):
      if contact_name := form_inputs.get('WIDGET_NAME'):
        if string_inputs := contact_name.get('stringInputs'):
          if name := string_inputs.get('value')[0]:
            return {
              'actionResponse': {
                'type': 'DIALOG',
                'dialogAction': {
                  'actionStatus': 'OK'
                }
              }
            }
          else:
            return {
              'actionResponse': {
                'type': 'DIALOG',
                'dialogAction': {
                  'actionStatus': 'Don\'t forget to name your new contact!'
                }
              }
            }

Risolvi il problema

Quando un'app o una scheda Google Chat restituisce un errore, nell'interfaccia di Chat viene visualizzato il messaggio "Si è verificato un problema" o "Impossibile elaborare la richiesta". A volte nell'interfaccia utente di Chat non vengono visualizzati messaggi di errore, ma l'app o la scheda Chat produce un risultato imprevisto; ad esempio, è possibile che non venga visualizzato un messaggio di scheda.

Anche se un messaggio di errore potrebbe non essere visualizzato nell'interfaccia utente di Chat, sono disponibili messaggi di errore descrittivi e dati di log per aiutarti a correggere gli errori quando la registrazione degli errori per le app di Chat è attivata. Per informazioni su visualizzazione, debug e correzione degli errori, consulta l'articolo Risolvere gli errori di Google Chat.