Vista previa de vínculos

Para evitar el cambio de contexto cuando los usuarios comparten un vínculo en Google Chat, tu app de Chat puede obtener una vista previa del vínculo. Para ello, debe adjuntar una tarjeta a su mensaje que brinde más información y permita a las personas realizar acciones directamente desde Google Chat.

Por ejemplo, imagina un espacio de Google Chat que incluye todos los agentes de atención al cliente de una empresa y una app de chat llamada Case-y. Los agentes suelen compartir vínculos a casos de servicio al cliente en el espacio de Chat y, cada vez que hacen un trabajo, sus colegas deben abrir el vínculo del caso para ver detalles como el destinatario, el estado y el asunto. Del mismo modo, si alguien quiere apropiarse de un caso o cambiar el estado, debe abrir el vínculo.

La vista previa de vínculos permite que la app de chat residente de Cases-y adjunte una tarjeta que muestra el 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 de chat.

Cuando alguien agrega un vínculo a su mensaje, aparece un chip que le indica 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, el vínculo se envía a la aplicación de Chat, que genera y adjunta la tarjeta al mensaje del usuario.

Adjunte una tarjeta al mensaje y obtenga una vista previa de un vínculo en la app de Chat

Junto al vínculo, la tarjeta proporciona información adicional sobre este, incluidos los elementos interactivos, como los botones. La app de Chat puede actualizar la tarjeta adjunta en respuesta a las interacciones del usuario, como cuando se hace clic en un botón.

Si alguien no desea que la app de Chat obtenga una vista previa de su vínculo y adjunta una tarjeta a su mensaje, puede hacer clic en en el chip de vista previa para evitar 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 Google Cloud Console para que tu app de Chat pueda obtener una vista previa.

Menú de configuración de 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, escriba Google Chat API y haga clic en API de Google Chat.
  4. Haz clic en Administrar > Configuración.
  5. En Vistas previas de vínculos, agregue o edite un patrón de URL.
    1. Para configurar vistas previas de vínculos para un patrón de URL nuevo, haga 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.

    A fin de tener los vínculos de vista previa de la app de Chat para un subdominio específico, como subdomain.example.com, debes incluirlo.

    A fin de tener vínculos de vista previa de la app de Chat para todo el dominio, especifica un carácter comodín con 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 el dominio del patrón de host.

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

    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. Haga clic en Listo.

  9. Haz clic en Guardar.

Ahora bien, cada vez que un usuario incluye un vínculo que hace coincidir un patrón de URL de vista previa de un vínculo con un mensaje en un espacio de Chat que incluye su aplicación de Chat, la aplicación obtiene una vista previa del vínculo.

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

Dentro de los espacios de Chat que incluyen su aplicación de Chat, cuando el mensaje de una persona contiene un vínculo que coincide con un patrón de URL de vista previa de un vínculo, el vínculo se envía a su aplicación de Chat como el atributo matchedUrl del objeto message:

JSON

message {

  . . . // other message attributes redacted

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

  . . . // other message attributes redacted

}

Cuando verificas la presencia del atributo matchedUrl en el objeto message, la 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 al 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 de vínculos.

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) {
    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) {
    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.
  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 de vista previa, muestra una ActionResponse de tipo UPDATE_USER_MESSAGE_CARDS. En este ejemplo, se adjunta una tarjeta simple.

Adjunte una tarjeta al mensaje y obtenga una vista previa de un vínculo en la app de Chat

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) {
    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) {
    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.
  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.'};
}

Cómo actualizar una tarjeta

Para actualizar la tarjeta adjunta a un vínculo de vista previa, muestra un ActionResponse de tipo UPDATE_USER_MESSAGE_CARDS. Las tarjetas adjuntas a los vínculos de vista previa solo se actualizan en respuesta a solicitudes síncronas de eventos de Chat. No se admiten las solicitudes asíncronas para actualizar tarjetas adjuntas a un vínculo de vista previa mediante la API de REST de Chat.

La vista previa del vínculo no admite mostrar un ActionResponse de tipo UPDATE_MESSAGE. Dado que UPDATE_MESSAGE actualiza el mensaje completo en lugar de solo la tarjeta, solo funcionará si la app de Chat creó el mensaje original. La vista previa del vínculo adjunta una tarjeta a un mensaje creado por el usuario, de modo que la aplicación de Chat no tiene permiso para actualizarla.

Para garantizar que una función actualice las tarjetas creadas por el usuario y por la aplicación en el flujo de Chat, configura ActionResponse de forma dinámica en función de si la app de Chat o un usuario crearon el mensaje.

  • Si un usuario creó el mensaje, establece ActionResponse en UPDATE_USER_MESSAGE_CARDS.
  • Si una app de Chat creó el mensaje, establece ActionResponse en 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

Si deseas usar actionMethodName para controlar correctamente los eventos en los que se hace clic en las tarjetas de la 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

Como "actionMethodName": "assign" identifica el botón como parte de la vista previa de un vínculo, es posible mostrar de forma dinámica el ActionResponse correcto mediante la comprobación de una actionMethodName coincidente:

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) {
    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') {
      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. A continuación, le 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) {
    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';

    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. Recupera el botón Asignar a mí de la sección anterior, Adjuntar una tarjeta. El siguiente ejemplo completo actualiza la tarjeta para que diga que está asignada a ti después de que un usuario hace clic en Asignar a mí. En el ejemplo, se configura el ActionResponse de forma dinámica verificando el tipo de remitente.

Ejemplo completo: Caso de uso de la aplicación de chat de atención al cliente

Este es el código completo de Case-y, una app de chat que muestra vistas previas de vínculos a casos compartidos en un espacio de Chat en el que colaboran 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) {
    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) {
    res.json(createMessage());
  }

  // 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') {
      res.json(createMessage(actionResponseType, 'You'));
    }
  }

  // If the Chat app doesn’t detect a link preview URL pattern, it says so.
  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 de tu app de Chat, ten en cuenta estos límites y consideraciones:

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

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