Procesar la información ingresada por los usuarios

En esta guía, se describe cómo recibir y leer la información que los usuarios ingresan en mensajes de tarjeta y diálogos. Los usuarios pueden ingresar datos que las apps de Chat reciben, leen y responden. Los widgets que permiten a los usuarios ingresar información incluyen los siguientes:

  • TextInput para la entrada de texto de formato libre que también admite sugerencias
  • SelectionInput para los elementos de lista y los menús, como casillas de verificación, botones de selección y menús desplegables.
  • DateTimePicker para las entradas de fecha y hora


Usa el Creador de tarjetas para diseñar mensajes de tarjetas JSON y obtener una vista previa de ellos en las apps de Chat:

Abre el Creador de tarjetas

Recibir entradas de datos de los usuarios permite que las apps de Chat realicen acciones como las siguientes:

  • Actualiza los casos de atención al cliente.
  • Crear órdenes de trabajo
  • Autentica con servicios web.

Cómo funciona la recepción de datos

Una app de Chat presenta información al usuario mediante un diálogo o un mensaje de tarjeta. En este ejemplo, un diálogo le pide al usuario que ingrese información sobre un contacto mediante los widgets TextInput y SelectionInput:

Un diálogo con una variedad de widgets diferentes.

Cuando finaliza, la app de Chat recibe los datos que los usuarios ingresaron en el diálogo en formato JSON y un evento de interacción en el que sucede lo siguiente:

Para obtener datos sobre lo que ingresaron los usuarios, usa el campo Event.common.formInputs en la carga útil del evento. El campo formInputs es un mapa en el que las claves son IDs de cadenas asignados a cada widget, y los valores representan las entradas del usuario para cada widget. Los distintos objetos representan distintos tipos de datos de entrada. Por ejemplo, Event.common.formInputs.stringInputs representa las entradas de cadena.

La app puede acceder al primer valor que ingresó el usuario en event.common.formInputs.NAME.stringInputs.value[0], donde NAME es el campo name de un widget TextInput.

Cómo recibir datos de las tarjetas

Cuando un usuario ingresa datos en un mensaje de tarjeta, tu app de Chat recibe un evento de interacción de la app de Chat, como el siguiente ejemplo:

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

Cómo recibir datos de diálogos

Cuando un usuario envía datos en un diálogo, tu app de Chat recibe otro evento de interacción con esta app, como el siguiente ejemplo:

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

Responde a los datos recopilados de un mensaje o diálogo de tarjeta

Después de recibir los datos de un mensaje o diálogo de tarjeta, la app de Chat responde mediante un acuse de recibo o un error. Para ambos casos, se muestra un ActionResponse:

  • Para confirmar la recepción exitosa, responde con un parámetro ActionResponse que tenga "actionStatus": "OK".
  • Para mostrar un error, responde con un parámetro ActionResponse que tenga "actionStatus": "ERROR MESSAGE".

Ejemplo

En el siguiente ejemplo, se verifica la presencia de un valor name. Si no está presente, la app muestra un error. Si están presentes, la app confirma la recepción de los datos del formulario y cierra el diálogo.

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

En este ejemplo, se muestra el JSON de la tarjeta para enviar un mensaje de tarjeta. También puedes usar el servicio de tarjetas de 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!'
                }
              }
            }

Solucionar problemas

Cuando una app de Google Chat o una tarjeta devuelve un error, la interfaz de Chat muestra un mensaje que dice “Se produjo un error” o “No se pudo procesar tu solicitud”. A veces, la IU de Chat no muestra ningún mensaje de error, pero la app o la tarjeta de Chat producen un resultado inesperado; por ejemplo, es posible que no aparezca un mensaje de tarjeta.

Si bien es posible que no se muestre un mensaje de error en la IU de Chat, hay mensajes de error descriptivos y datos de registro disponibles que te ayudarán a corregir errores cuando se activa el registro de errores para las apps de Chat. Si necesitas ayuda para ver, depurar y corregir errores, consulta Cómo solucionar problemas de Google Chat.