Vista previa de vínculos

Para evitar el cambio de contexto cuando los usuarios comparten un vínculo en Google Chat, la app de Chat puede obtener una vista previa del vínculo adjuntando una tarjeta al mensaje que proporcione más información y permita que las personas realicen acciones directamente desde Google Chat.

Por ejemplo, imagina un espacio de Google Chat que incluya a todos los agentes de atención al cliente de una empresa, además de una app de Chat llamada Case-y. Con frecuencia, los agentes comparten vínculos a casos de atención al cliente en el espacio de Chat y, cada vez que lo hagan, sus colegas deberán abrir el vínculo del caso para ver detalles como el destinatario, el estado y el asunto. Del mismo modo, si alguien desea hacerse cargo de un caso o cambiar el estado, deberá abrir el vínculo.

La vista previa de vínculos permite que Case-y, la app de Chat residente del espacio, adjunte una tarjeta que muestre al destinatario, el estado y el asunto cada vez que alguien comparte el vínculo de un caso. Los botones de la tarjeta permiten que los agentes se hagan cargo del caso y cambien el estado directamente desde el flujo del chat.

Cuando alguien agrega un vínculo a su mensaje, aparece un chip que le informa que una app de Chat podría obtener una vista previa del vínculo.

Chip que indica que una app de Chat podría obtener una vista previa de un vínculo

Después de enviar el mensaje, se envía el vínculo a la app de Chat, que genera la tarjeta y la adjunta al mensaje del usuario.

App de Chat adjuntando una tarjeta al mensaje para obtener una vista previa de un vínculo

Junto al vínculo, la tarjeta proporciona información adicional sobre el vínculo, incluidos elementos interactivos como botones. Tu app de Chat puede actualizar la tarjeta adjunta en respuesta a las interacciones del usuario, como los clics en botones.

Si alguien no desea que la app de Chat adjunte una tarjeta al mensaje para obtener una vista previa de su vínculo, puede hacer clic en en el chip de vista previa y evitar que se muestre la vista previa. Los usuarios pueden quitar la tarjeta adjunta en cualquier momento haciendo clic en Quitar vista previa.

Registra vínculos específicos, como example.com, support.example.com y support.example.com/cases/, como patrones de URL en la página de configuración de tu app de Chat en la consola de Google Cloud para que tu app de Chat pueda obtener una vista previa de ellos.

Menú de configuración de las vistas previas de vínculos

  1. Abre la consola de Google Cloud
  2. Junto a “Google Cloud”, haz clic en la flecha hacia abajo y abre el proyecto de tu app de Chat.
  3. En el campo de búsqueda, escribe Google Chat API y haz clic en API de Google Chat.
  4. Haz clic en Administrar > Configuración.
  5. En Vistas previas de vínculos, agrega o edita un patrón de URL.
    1. Si deseas configurar las vistas previas de vínculos para un patrón de URL nuevo, haz clic en Agregar patrón de URL.
    2. Para editar la configuración de un patrón de URL existente, haz clic en la flecha hacia abajo .
  6. En el campo Patrón de host, ingresa el dominio del patrón de URL. La app de Chat obtendrá una vista previa de los vínculos a este dominio.

    Para que la app de Chat obtenga una vista previa de los vínculos de un subdominio específico, como subdomain.example.com, incluye el subdominio.

    Para que la app de Chat obtenga una vista previa de los vínculos de todo el dominio, especifica un carácter comodín y un asterisco (*) como subdominio. Por ejemplo, *.example.com coincide con subdomain.example.com y any.number.of.subdomains.example.com.

  7. En el campo Prefijo de la ruta de acceso, ingresa una ruta de acceso para adjuntar al dominio del patrón de host.

    Para que todas las URLs del dominio del patrón de host coincidan, deja vacío el campo Prefijo de la ruta de acceso.

    Por ejemplo, si el patrón de host es support.example.com, ingresa cases/ para que coincida con las URLs de los casos alojados en support.example.com/cases/.

  8. Haz clic en Listo.

  9. Haz clic en Guardar.

Ahora, cada vez que alguien incluya un vínculo que coincida con un patrón de URL de vista previa del vínculo con un mensaje en un espacio de Chat que incluya tu app de Chat, la app obtendrá una vista previa del vínculo.

Una vez que configures la vista previa de un vínculo determinado, la app de Chat podrá reconocerlo y obtener una vista previa si le adjunta más información.

Dentro de los espacios de Chat que incluyen tu app de Chat, cuando el mensaje de una persona contiene un vínculo que coincide con un patrón de URL de vista previa del vínculo, tu app de Chat recibe un evento de interacción MESSAGE. La carga útil de JSON para el evento de interacción contiene el campo matchedUrl:

JSON

"message": {

  . . . // other message attributes redacted

  "matchedUrl": {
     "url": "https://support.example.com/cases/case123"
   },

  . . . // other message attributes redacted

}

Si verificas la presencia del campo matchedUrl en la carga útil del evento MESSAGE, tu app de Chat puede agregar información al mensaje con el vínculo de la vista previa. Tu app de Chat puede responder con un mensaje de texto simple o adjuntar una tarjeta.

Responder con un mensaje de texto

Para obtener respuestas simples, tu app de Chat puede obtener una vista previa de un vínculo respondiendo con un mensaje de texto simple a un vínculo. En este ejemplo, se adjunta un mensaje que repite la URL del vínculo que coincide con un patrón de URL de vista previa.

Node.js

node/preview-link/simple-text-message.js
/**
 * Responds to messages that have links whose URLs match URL patterns
 * configured for link previewing.
 *
 * @param {Object} req Request sent from Google Chat.
 * @param {Object} res Response to send back.
 */
exports.onMessage = (req, res) => {
  if (req.method === 'GET' || !req.body.message) {
    return res.send(
      'Hello! This function is meant to be used in a Google Chat Space.');
  }

  // Checks for the presence of event.message.matchedUrl and responds with a
  // text message if present
  if (req.body.message.matchedUrl) {
    return res.json({
      'text': 'req.body.message.matchedUrl.url: ' +
        req.body.message.matchedUrl.url,
    });
  }

  // If the Chat app doesn’t detect a link preview URL pattern, it says so.
  return res.json({'text': 'No matchedUrl detected.'});
};

Apps Script

apps-script/preview-link/simple-text-message.gs
/**
 * Responds to messages that have links whose URLs match URL patterns
 * configured for link previewing.
 *
 * @param {Object} event The event object from Chat API.
 *
 * @return {Object} Response from the Chat app attached to the message with
 * the previewed link.
 */
function onMessage(event) {
  // Checks for the presence of event.message.matchedUrl and responds with a
  // text message if present
  if (event.message.matchedUrl) {
    return {
      'text': 'event.message.matchedUrl.url: ' + event.message.matchedUrl.url,
    };
  }

  // If the Chat app doesn’t detect a link preview URL pattern, it says so.
  return {'text': 'No matchedUrl detected.'};
}

Adjuntar una tarjeta

Para adjuntar una tarjeta a un vínculo en la vista previa, muestra un objeto ActionResponse de tipo UPDATE_USER_MESSAGE_CARDS. En este ejemplo, se adjunta una tarjeta simple.

App de Chat adjuntando una tarjeta al mensaje para obtener una vista previa de un vínculo

Node.js

node/preview-link/attach-card.js
/**
 * Responds to messages that have links whose URLs match URL patterns
 * configured for link previewing.
 *
 * @param {Object} req Request sent from Google Chat.
 * @param {Object} res Response to send back.
 */
exports.onMessage = (req, res) => {
  if (req.method === 'GET' || !req.body.message) {
    return res.send(
      'Hello! This function is meant to be used in a Google Chat Space.');
  }

  // Checks for the presence of event.message.matchedUrl and attaches a card
  // if present
  if (req.body.message.matchedUrl) {
    return res.json({
      'actionResponse': {'type': 'UPDATE_USER_MESSAGE_CARDS'},
      'cardsV2': [
        {
          'cardId': 'attachCard',
          'card': {
            'header': {
              'title': 'Example Customer Service Case',
              'subtitle': 'Case basics',
            },
            'sections': [
              {
                'widgets': [
                  {'keyValue': {'topLabel': 'Case ID', 'content': 'case123'}},
                  {'keyValue': {'topLabel': 'Assignee', 'content': 'Charlie'}},
                  {'keyValue': {'topLabel': 'Status', 'content': 'Open'}},
                  {
                    'keyValue': {
                      'topLabel': 'Subject', 'content': 'It won"t turn on...',
                    }
                  },
                ],
              },
              {
                'widgets': [
                  {
                    'buttons': [
                      {
                        'textButton': {
                          'text': 'OPEN CASE',
                          'onClick': {
                            'openLink': {
                              'url': 'https://support.example.com/orders/case123',
                            },
                          },
                        },
                      },
                      {
                        'textButton': {
                          'text': 'RESOLVE CASE',
                          'onClick': {
                            'openLink': {
                              'url': 'https://support.example.com/orders/case123?resolved=y',
                            },
                          },
                        },
                      },
                      {
                        'textButton': {
                          'text': 'ASSIGN TO ME',
                          'onClick': {
                            'action': {
                              'actionMethodName': 'assign',
                            },
                          },
                        },
                      },
                    ],
                  },
                ],
              },
            ],
          },
        },
      ],
    });
  }

  // If the Chat app doesn’t detect a link preview URL pattern, it says so.
  return res.json({'text': 'No matchedUrl detected.'});
};

Apps Script

apps-script/preview-link/attach-card.gs
/**
 * Responds to messages that have links whose URLs match URL patterns
 * configured for link previewing.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app attached to the message with
 * the previewed link.
 */
function onMessage(event) {
  // Checks for the presence of event.message.matchedUrl and attaches a card
  // if present
  if (event.message.matchedUrl) {
    return {
      'actionResponse': {
        'type': 'UPDATE_USER_MESSAGE_CARDS',
      },
      'cardsV2': [{
        'cardId': 'attachCard',
        'card': {
          'header': {
            'title': 'Example Customer Service Case',
            'subtitle': 'Case basics',
          },
          'sections': [{
            'widgets': [
              {'keyValue': {'topLabel': 'Case ID', 'content': 'case123'}},
              {'keyValue': {'topLabel': 'Assignee', 'content': 'Charlie'}},
              {'keyValue': {'topLabel': 'Status', 'content': 'Open'}},
              {
                'keyValue': {
                  'topLabel': 'Subject', 'content': 'It won\'t turn on...',
                },
              },
            ],
          },
          {
            'widgets': [{
              'buttons': [
                {
                  'textButton': {
                    'text': 'OPEN CASE',
                    'onClick': {
                      'openLink': {
                        'url': 'https://support.example.com/orders/case123',
                      },
                    },
                  },
                },
                {
                  'textButton': {
                    'text': 'RESOLVE CASE',
                    'onClick': {
                      'openLink': {
                        'url': 'https://support.example.com/orders/case123?resolved=y',
                      },
                    },
                  },
                },
                {
                  'textButton': {
                    'text': 'ASSIGN TO ME',
                    'onClick': {'action': {'actionMethodName': 'assign'}},
                  },
                },
              ],
            }],
          }],
        },
      }],
    };
  }

  // If the Chat app doesn’t detect a link preview URL pattern, it says so.
  return {'text': 'No matchedUrl detected.'};
}

Actualizar una tarjeta

Para actualizar la tarjeta adjunta a un vínculo de la vista previa, muestra un ActionResponse de tipo UPDATE_USER_MESSAGE_CARDS. Las apps de chat solo pueden actualizar tarjetas con vistas previas de los vínculos como respuesta a un evento de interacción de la app de Chat. Las apps de Chat no pueden actualizar estas tarjetas llamando a la API de Chat de forma asíncrona.

La vista previa del vínculo no admite que se muestre un ActionResponse de tipo UPDATE_MESSAGE. Dado que UPDATE_MESSAGE actualiza todo el mensaje en lugar de solo la tarjeta, solo funciona si la app de Chat creó el mensaje original. La vista previa de vínculos adjunta una tarjeta a un mensaje creado por el usuario, por lo que la app de Chat no tiene permiso para actualizarla.

Para garantizar que una función actualice las tarjetas creadas por usuarios y por apps en el flujo de Chat, configura dinámicamente ActionResponse según si la app de Chat o un usuario creó el mensaje.

  • Si un usuario creó el mensaje, configura ActionResponse como UPDATE_USER_MESSAGE_CARDS.
  • Si una app de Chat creó el mensaje, configura ActionResponse como UPDATE_MESSAGE.

Existen dos maneras de hacerlo: especificar y verificar un actionMethodName personalizado como parte de la propiedad onclick de la tarjeta adjunta (que identifica el mensaje como creado por el usuario) o comprobar si un usuario creó el mensaje.

Opción 1: Busca actionMethodName

Para usar actionMethodName a fin de controlar correctamente los eventos de interacción con CARD_CLICKED en las tarjetas que ya tienen una vista previa, establece una actionMethodName personalizada como parte de la propiedad onclick de la tarjeta adjunta:

JSON

. . . // Preview card details
{
  "textButton": {
    "text": "ASSIGN TO ME",
    "onClick": {

      // actionMethodName identifies the button to help determine the
      // appropriate ActionResponse.
      "action": {
        "actionMethodName": "assign",
      }
    }
  }
}
. . . // Preview card details

Si "actionMethodName": "assign" identifica el botón como parte de la vista previa de un vínculo, es posible mostrar el ActionResponse correcto de forma dinámica si se busca un actionMethodName que coincida:

Node.js

node/preview-link/update-card.js
/**
 * Responds to messages that have links whose URLs match URL patterns
 * configured for link previewing.
 *
 * @param {Object} req Request sent from Google Chat.
 * @param {Object} res Response to send back.
 */
exports.onMessage = (req, res) => {
  if (req.method === 'GET' || !req.body.message) {
    return res.send(
      'Hello! This function is meant to be used in a Google Chat Space.');
  }

  // Respond to button clicks on attached cards
  if (req.body.type === 'CARD_CLICKED') {
    // Checks for the presence of "actionMethodName": "assign" and sets
    // actionResponse.type to "UPDATE_USER"MESSAGE_CARDS" if present or
    // "UPDATE_MESSAGE" if absent.
    const actionResponseType = req.body.action.actionMethodName === 'assign' ?
      'UPDATE_USER_MESSAGE_CARDS' :
      'UPDATE_MESSAGE';

    if (req.body.action.actionMethodName === 'assign') {
      return res.json({
        'actionResponse': {

          // Dynamically returns the correct actionResponse type.
          'type': actionResponseType,
        },

        // Preview card details
        'cardsV2': [{}],
      });
    }
  }
};

Apps Script

apps-script/preview-link/update-card.gs
/**
 * Updates a card that was attached to a message with a previewed link.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app. Either a new card attached to
 * the message with the previewed link, or an update to an existing card.
 */
function onCardClick(event) {
  // Checks for the presence of "actionMethodName": "assign" and sets
  // actionResponse.type to "UPDATE_USER"MESSAGE_CARDS" if present or
  // "UPDATE_MESSAGE" if absent.
  const actionResponseType = event.action.actionMethodName === 'assign' ?
    'UPDATE_USER_MESSAGE_CARDS' :
    'UPDATE_MESSAGE';

  if (event.action.actionMethodName === 'assign') {
    return assignCase(actionResponseType);
  }
}

/**
 * Updates a card to say that "You" are the assignee after clicking the Assign
 * to Me button.
 *
 * @param {String} actionResponseType Which actionResponse the Chat app should
 * use to update the attached card based on who created the message.
 * @return {Object} Response from the Chat app. Updates the card attached to
 * the message with the previewed link.
 */
function assignCase(actionResponseType) {
  return {
    'actionResponse': {

      // Dynamically returns the correct actionResponse type.
      'type': actionResponseType,
    },
    // Preview card details
    'cardsV2': [{}],
  };
}

Opción 2: Verifica el tipo de remitente

Verifica si message.sender.type es HUMAN o BOT. Si es HUMAN, establece ActionResponse en UPDATE_USER_MESSAGE_CARDS; de lo contrario, establece ActionResponse en UPDATE_MESSAGE. Aquí te indicamos cómo hacerlo:

Node.js

node/preview-link/sender-type.js
/**
 * Responds to messages that have links whose URLs match URL patterns
 * configured for link previewing.
 *
 * @param {Object} req Request sent from Google Chat.
 * @param {Object} res Response to send back.
 */
exports.onMessage = (req, res) => {
  if (req.method === 'GET' || !req.body.message) {
    return res.send(
      'Hello! This function is meant to be used in a Google Chat Space.');
  }

  // Respond to button clicks on attached cards
  if (req.body.type === 'CARD_CLICKED') {
    // Checks whether the message event originated from a human or a Chat app
    // and sets actionResponse.type to "UPDATE_USER_MESSAGE_CARDS if human or
    // "UPDATE_MESSAGE" if Chat app.
    const actionResponseType = req.body.action.actionMethodName === 'HUMAN' ?
      'UPDATE_USER_MESSAGE_CARDS' :
      'UPDATE_MESSAGE';

    return res.json({
      'actionResponse': {

        // Dynamically returns the correct actionResponse type.
        'type': actionResponseType,
      },

      // Preview card details
      'cardsV2': [{}],
    });
  }
};

Apps Script

apps-script/preview-link/sender-type.gs
/**
 * Updates a card that was attached to a message with a previewed link.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app. Either a new card attached to
 * the message with the previewed link, or an update to an existing card.
 */
function onCardClick(event) {
  // Checks whether the message event originated from a human or a Chat app
  // and sets actionResponse.type to "UPDATE_USER_MESSAGE_CARDS if human or
  // "UPDATE_MESSAGE" if Chat app.
  const actionResponseType = event.message.sender.type === 'HUMAN' ?
    'UPDATE_USER_MESSAGE_CARDS' :
    'UPDATE_MESSAGE';

  return assignCase(actionResponseType);
}

/**
 * Updates a card to say that "You" are the assignee after clicking the Assign
 * to Me button.
 *
 * @param {String} actionResponseType Which actionResponse the Chat app should
 * use to update the attached card based on who created the message.
 * @return {Object} Response from the Chat app. Updates the card attached to
 * the message with the previewed link.
 */
function assignCase(actionResponseType) {
  return {
    'actionResponse': {

      // Dynamically returns the correct actionResponse type.
      'type': actionResponseType,
    },
    // Preview card details
    'cardsV2': [{}],
  };
}

Un motivo típico para actualizar una tarjeta es en respuesta a un clic en un botón. Recuerda el botón Asignar a mí de la sección anterior, Adjuntar una tarjeta. En el siguiente ejemplo completo, se actualiza la tarjeta para que indique que se asignó a “Tú” cuando un usuario hace clic en Asignar a mí. En el ejemplo, se verifica el tipo de remitente para establecer ActionResponse de forma dinámica.

Ejemplo completo: Case-y, la app de Chat de atención al cliente

Este es el código completo de Case‐y, una app de chat que muestra una vista previa de los vínculos a casos compartidos en un espacio de Chat en el que colaboran los agentes de atención al cliente.

Node.js

node/preview-link/preview-link.js
/**
 * Responds to messages that have links whose URLs match URL patterns
 * configured for link previewing.
 *
 * @param {Object} req Request sent from Google Chat.
 * @param {Object} res Response to send back.
 */
exports.onMessage = (req, res) => {
  if (req.method === 'GET' || !req.body.message) {
    return res.send(
      'Hello! This function is meant to be used in a Google Chat Space.');
  }

  // Respond to button clicks on attached cards
  if (req.body.type === 'CARD_CLICKED') {
    // Checks whether the message event originated from a human or a Chat app
    // and sets actionResponse.type to "UPDATE_USER_MESSAGE_CARDS if human or
    // "UPDATE_MESSAGE" if Chat app.
    const actionResponseType = req.body.action.actionMethodName === 'HUMAN' ?
      'UPDATE_USER_MESSAGE_CARDS' :
      'UPDATE_MESSAGE';

    if (req.body.action.actionMethodName === 'assign') {
      return res.json(createMessage(actionResponseType, 'You'));
    }
  }

  // Checks for the presence of event.message.matchedUrl and attaches a card
  // if present
  if (req.body.message.matchedUrl) {
    return res.json(createMessage());
  }

  // If the Chat app doesn’t detect a link preview URL pattern, it says so.
  return res.json({'text': 'No matchedUrl detected.'});
};

/**
 * Message to create a card with the correct response type and assignee.
 *
 * @param {string} actionResponseType
 * @param {string} assignee
 * @return {Object} a card with URL preview
 */
function createMessage(
  actionResponseType = 'UPDATE_USER_MESSAGE_CARDS',
  assignee = 'Charlie'
) {
  return {
    'actionResponse': {'type': actionResponseType},
    'cardsV2': [
      {
        'cardId': 'previewLink',
        'card': {
          'header': {
            'title': 'Example Customer Service Case',
            'subtitle': 'Case basics',
          },
          'sections': [
            {
              'widgets': [
                {'keyValue': {'topLabel': 'Case ID', 'content': 'case123'}},
                {'keyValue': {'topLabel': 'Assignee', 'content': assignee}},
                {'keyValue': {'topLabel': 'Status', 'content': 'Open'}},
                {
                  'keyValue': {
                    'topLabel': 'Subject', 'content': 'It won"t turn on...',
                  },
                },
              ],
            },
            {
              'widgets': [
                {
                  'buttons': [
                    {
                      'textButton': {
                        'text': 'OPEN CASE',
                        'onClick': {
                          'openLink': {
                            'url': 'https://support.example.com/orders/case123',
                          },
                        },
                      },
                    },
                    {
                      'textButton': {
                        'text': 'RESOLVE CASE',
                        'onClick': {
                          'openLink': {
                            'url': 'https://support.example.com/orders/case123?resolved=y',
                          },
                        },
                      },
                    },
                    {
                      'textButton': {
                        'text': 'ASSIGN TO ME',
                        'onClick': {
                          'action': {
                            'actionMethodName': 'assign',
                          },
                        },
                      },
                    },
                  ],
                },
              ],
            },
          ],
        }
      },
    ],
  };
}

Apps Script

apps-script/preview-link/preview-link.gs
/**
 * Responds to messages that have links whose URLs match URL patterns
 * configured for link previews.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app attached to the message with
 * the previewed link.
 */
function onMessage(event) {
  // Checks for the presence of event.message.matchedUrl and attaches a card
  // if present
  if (event.message.matchedUrl) {
    return {
      'actionResponse': {
        'type': 'UPDATE_USER_MESSAGE_CARDS',
      },
      'cardsV2': [{
        'cardId': 'previewLink',
        'card': {
          'header': {
            'title': 'Example Customer Service Case',
            'subtitle': 'Case basics',
          },
          'sections': [{
            'widgets': [
              {'keyValue': {'topLabel': 'Case ID', 'content': 'case123'}},
              {'keyValue': {'topLabel': 'Assignee', 'content': 'Charlie'}},
              {'keyValue': {'topLabel': 'Status', 'content': 'Open'}},
              {
                'keyValue': {
                  'topLabel': 'Subject', 'content': 'It won\'t turn on...',
                }
              },
            ],
          },
          {
            'widgets': [{
              'buttons': [
                {
                  'textButton': {
                    'text': 'OPEN CASE',
                    'onClick': {
                      'openLink': {
                        'url': 'https://support.example.com/orders/case123',
                      },
                    },
                  },
                },
                {
                  'textButton': {
                    'text': 'RESOLVE CASE',
                    'onClick': {
                      'openLink': {
                        'url': 'https://support.example.com/orders/case123?resolved=y',
                      },
                    },
                  },
                },
                {
                  'textButton': {
                    'text': 'ASSIGN TO ME',
                    'onClick': {'action': {'actionMethodName': 'assign'}}
                  },
                },
              ],
            }],
          }],
        },
      }],
    };
  }

  // If the Chat app doesn’t detect a link preview URL pattern, it says so.
  return {'text': 'No matchedUrl detected.'};
}

/**
 * Updates a card that was attached to a message with a previewed link.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app. Either a new card attached to
 * the message with the previewed link, or an update to an existing card.
 */
function onCardClick(event) {
  // Checks whether the message event originated from a human or a Chat app
  // and sets actionResponse to "UPDATE_USER_MESSAGE_CARDS if human or
  // "UPDATE_MESSAGE" if Chat app.
  const actionResponseType = event.message.sender.type === 'HUMAN' ?
    'UPDATE_USER_MESSAGE_CARDS' :
    'UPDATE_MESSAGE';

  // To respond to the correct button, checks the button's actionMethodName.
  if (event.action.actionMethodName === 'assign') {
    return assignCase(actionResponseType);
  }
}

/**
 * Updates a card to say that "You" are the assignee after clicking the Assign
 * to Me button.
 *
 * @param {String} actionResponseType Which actionResponse the Chat app should
 * use to update the attached card based on who created the message.
 * @return {Object} Response from the Chat app. Updates the card attached to
 * the message with the previewed link.
 */
function assignCase(actionResponseType) {
  return {
    'actionResponse': {

      // Dynamically returns the correct actionResponse type.
      'type': actionResponseType,
    },
    'cardsV2': [{
      'cardId': 'assignCase',
      'card': {
        'header': {
          'title': 'Example Customer Service Case',
          'subtitle': 'Case basics',
        },
        'sections': [{
          'widgets': [
            {'keyValue': {'topLabel': 'Case ID', 'content': 'case123'}},
            {'keyValue': {'topLabel': 'Assignee', 'content': 'You'}},
            {'keyValue': {'topLabel': 'Status', 'content': 'Open'}},
            {
              'keyValue': {
                'topLabel': 'Subject', 'content': 'It won\'t turn on...',
              }
            },
          ],
        },
        {
          'widgets': [{
            'buttons': [
              {
                'textButton': {
                  'text': 'OPEN CASE',
                  'onClick': {
                    'openLink': {
                      'url': 'https://support.example.com/orders/case123',
                    },
                  },
                },
              },
              {
                'textButton': {
                  'text': 'RESOLVE CASE',
                  'onClick': {
                    'openLink': {
                      'url': 'https://support.example.com/orders/case123?resolved=y',
                    },
                  },
                },
              },
              {
                'textButton': {
                  'text': 'ASSIGN TO ME',
                  'onClick': {'action': {'actionMethodName': 'assign'}},
                },
              },
            ],
          }],
        }],
      },
    }],
  };
}

Límites y consideraciones

Cuando configures las vistas previas de vínculos para tu app de Chat, ten en cuenta estos límites y consideraciones:

  • Cada app de Chat admite vistas previas de vínculos para un máximo de 5 patrones de URL.
  • Las apps de chat obtienen una vista previa de un vínculo por mensaje. Si un único mensaje contiene varios vínculos con vista previa, solo se mostrará la vista previa del primer vínculo.
  • Las apps de Chat solo obtienen una vista previa de los vínculos que comienzan con https://, por lo que se usa https://support.example.com/cases/ para obtener una vista previa, pero support.example.com/cases/ no lo hace.
  • A menos que el mensaje incluya otra información que se envía a la app de Chat, como un comando de barra, solo la URL del vínculo se envía a la app de Chat a través de las vistas previas.
  • Las tarjetas adjuntas a los vínculos de vista previa solo admiten un elemento ActionResponse de tipo UPDATE_USER_MESSAGE_CARDS y solo en respuesta a un evento de interacción de la app de Chat. Las vistas previas de vínculos no admiten UPDATE_MESSAGE ni solicitudes asíncronas para actualizar tarjetas adjuntas a un vínculo de vista previa mediante la API de Chat. Para obtener más información, consulta Cómo actualizar una tarjeta.

Cuando implementes vistas previas de vínculos, es posible que debas leer sus registros para depurar tu app de Chat. Para leer los registros, visita el Explorador de registros en la consola de Google Cloud.