Visualizar links

Para evitar a mudança de contexto quando os usuários compartilham um link no Google Chat, o app do Chat pode visualizar o link anexando um card à mensagem com mais informações e permitindo que as pessoas realizem ações diretamente no Google Chat.

Por exemplo, imagine um espaço do Google Chat que inclua todos os agentes de atendimento ao cliente de uma empresa e um app de chat chamado Case-y. Frequentemente, os agentes compartilham links para casos de atendimento ao cliente no espaço do Chat e, sempre que fazem isso, os colegas precisam abrir o link do caso para conferir detalhes como responsável, status e assunto. Da mesma forma, se alguém quiser assumir a propriedade de um caso ou alterar o status, precisará abrir o link.

Com a prévia do link, o app do Chat do espaço, Case-y, anexe um cartão que mostra o responsável, o status e o assunto sempre que alguém compartilha um link de caso. Os botões no card permitem que os agentes assumam a propriedade do caso e mudem o status diretamente no stream do chat.

Quando alguém adiciona um link à mensagem, um ícone aparece para informar que um app do Chat pode ter uma prévia do link.

Ícone indicando que um app do Chat pode visualizar um link

Após o envio, o link é enviado para o app do Chat, que gera e anexa o cartão à mensagem do usuário.

App do Chat que anexa um card à mensagem para visualizar um link

Além do link, o card fornece informações adicionais sobre o link, incluindo elementos interativos, como botões. Seu app do Chat pode atualizar o card anexado em resposta a interações do usuário, como cliques em botões.

Se uma pessoa não quiser que o app do Chat visualize o link anexando um card à mensagem, ela pode clicar em no ícone de visualização para impedir a visualização. Os usuários podem remover o cartão anexado a qualquer momento clicando em Remover visualização.

Pré-requisitos

Node.js

Um app do Google Chat com recursos interativos ativados. Para criar um interativo do Chat que usa um serviço HTTP, conclua este guia de início rápido.

Apps Script

Um app do Google Chat com recursos interativos ativados. Para criar um interativo com o app Chat no Apps Script, conclua este guia de início rápido.

Registre links específicos, como example.com, support.example.com e support.example.com/cases/, como padrões de URL na página de configuração do app do Chat no console do Google Cloud para que o app do Chat possa visualizá-los.

Menu de configuração das visualizações de link

  1. Abra o Console do Google Cloud.
  2. Ao lado de "Google Cloud", Clique na seta para baixo e abra o projeto do app do Chat.
  3. No campo de pesquisa, digite Google Chat API e clique em API Google Chat.
  4. Clique em Gerenciar > Configuração.
  5. Em Visualizações de link, adicione ou edite um padrão de URL.
    1. Para configurar visualizações de links para um novo padrão de URL, clique em Adicionar padrão de URL.
    2. Para editar a configuração de um padrão de URL atual, clique na seta para baixo .
  6. No campo Padrão de host, insira o domínio do padrão do URL. O app do Chat vai visualizar os links para este domínio.

    Se quiser que os links de visualização do app do Chat para um subdomínio específico, como subdomain.example.com, inclua o subdomínio.

    Para que os links de visualização do app do Chat sejam vinculados a todo o domínio, especifique um caractere curinga com um asterisco (*) como subdomínio. Por exemplo, *.example.com corresponde a subdomain.example.com e any.number.of.subdomains.example.com.

  7. No campo Prefixo do caminho, digite um caminho para anexar ao domínio do padrão de host.

    Para corresponder a todos os URLs no domínio do padrão de host, deixe o Prefixo do caminho vazio.

    Por exemplo, se o padrão do host for support.example.com, digite cases/ para corresponder aos URLs para casos hospedados em support.example.com/cases/.

  8. Clique em Concluído.

  9. Clique em Salvar.

Agora, sempre que alguém incluir um link que corresponde a um padrão de URL de visualização de link a uma mensagem em um espaço do Chat que inclui seu app do Chat, o app vai visualizar o link.

Depois de configurar a visualização de um determinado link, seu O app do Chat pode reconhecer e visualizar o link anexando mais informações a ele.

Nos espaços do Chat que incluem seus em um app do Chat, quando a mensagem de alguém inclui um link que corresponder a um padrão do URL de visualização do link, seu app do Chat recebe um Evento de interação MESSAGE. O arquivo JSON o payload do evento de interação contém o campo matchedUrl:

JSON

"message": {

  . . . // other message attributes redacted

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

  . . . // other message attributes redacted

}

Verificando a presença do campo matchedUrl no evento MESSAGE. payload, o app do Chat poderá adicionar informações ao com o link da prévia. Seu app do Chat pode: responda com uma mensagem de texto simples ou anexe um cartão.

Responder com uma mensagem de texto

Para respostas simples, o app do Chat pode visualizar um link respondendo com uma mensagem de texto simples a um link. Este exemplo anexa uma mensagem que repete o URL do link que corresponde a um padrão do URL de visualização do link.

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

Anexar um cartão

Para anexar um card a um link visualizado, retornar um ActionResponse do tipo UPDATE_USER_MESSAGE_CARDS. Este exemplo anexa um cartão simples.

App do Chat que anexa um card à mensagem para visualizar um link

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

Este exemplo envia uma mensagem de card retornando JSON do cartão. Você também pode usar o Serviço de card do 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.'};
}

Atualizar um cartão

Para atualizar o card anexado a um link visualizado, retorne uma ActionResponse do tipo UPDATE_USER_MESSAGE_CARDS. Os apps de chat só podem atualizar cards que mostram links como resposta a uma Evento de interação com o app do Chat. Os apps de chat não podem atualizar esses cards chamando a API Chat de forma assíncrona.

A visualização de links não é compatível com o retorno de um ActionResponse do tipo UPDATE_MESSAGE. Como o UPDATE_MESSAGE atualiza toda a mensagem, em vez de apenas o card, ele só vai funcionar se o app do Chat tiver criado a mensagem original. A prévia do link anexa um card a uma mensagem criada pelo usuário. Assim, o app do Chat não tem permissão para fazer atualizações.

Para garantir que uma função atualize os cards criados pelo usuário e pelo app no stream do Chat, defina dinamicamente o ActionResponse com base no fato de o app do Chat ou um usuário ter criado a mensagem.

  • Se um usuário criou a mensagem, defina ActionResponse como UPDATE_USER_MESSAGE_CARDS.
  • Se um app do Chat criou a mensagem, defina ActionResponse como UPDATE_MESSAGE.

Há duas maneiras de fazer isso: especificar e verificar se há um actionMethodName personalizado como parte da propriedade onclick do cartão anexado (que identifica a mensagem como criada pelo usuário) ou verificar se ela foi criada por um usuário.

Opção 1: procurar actionMethodName

Se quiser usar actionMethodName para processar corretamente eventos de interação CARD_CLICKED em cards visualizados, defina um actionMethodName personalizado como parte da propriedade onclick do card anexado:

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 o "actionMethodName": "assign" identifica o botão como parte de uma visualização de link, é possível retornar dinamicamente o ActionResponse correto, verificando se há um actionMethodName correspondente:

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

Este exemplo envia uma mensagem de card retornando JSON do cartão. Você também pode usar o Serviço de card do 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': [{}],
  };
}

Opção 2: verificar o tipo de remetente

Confira se message.sender.type é HUMAN ou BOT. Se HUMAN, defina ActionResponse como UPDATE_USER_MESSAGE_CARDS. Caso contrário, defina ActionResponse como UPDATE_MESSAGE. Veja como fazer isso:

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

Este exemplo envia uma mensagem de card retornando JSON do cartão. Você também pode usar o Serviço de card do 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': [{}],
  };
}

Um motivo comum para atualizar um card é em resposta a um clique no botão. Lembre-se do botão Atribuir a mim da seção anterior, Anexar um cartão. O exemplo completo a seguir atualiza o card para que ele indique que seja atribuído a "Você". depois que o usuário clicar em Atribuir a mim. O exemplo define ActionResponse dinamicamente, verificando o tipo de remetente.

Exemplo completo: Case-y, o app do Chat de atendimento ao cliente

Este é o código completo do Case-y, um app do Chat que mostra links para casos compartilhados em um espaço do Chat em que os agentes de atendimento ao cliente colaboram.

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

Este exemplo envia uma mensagem de card retornando JSON do cartão. Você também pode usar o Serviço de card do 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'}},
                },
              },
            ],
          }],
        }],
      },
    }],
  };
}

Limites e considerações

Ao configurar visualizações de links no seu app do Chat, preste atenção nestes limites e considerações:

  • Cada app do Chat é compatível com visualizações de links de até cinco padrões de URL.
  • Os apps de chat mostram um link por mensagem. Se vários links visualizáveis estiverem presentes em uma única mensagem, somente o primeiro será visualizado.
  • Os apps de chat exibem somente os links que começam com https://. Por isso, o https://support.example.com/cases/ é exibido, mas o support.example.com/cases/ não.
  • A menos que a mensagem inclua outras informações enviadas para o app do Chat, como um comando de barra, somente o URL do link é enviado para o app do Chat pelas visualizações de link.
  • Os cards anexados a links visualizados são compatíveis apenas com ActionResponse do tipo UPDATE_USER_MESSAGE_CARDS e somente em resposta a um evento de interação com o app do Chat. As visualizações de link não são compatíveis com UPDATE_MESSAGE ou solicitações assíncronas para atualizar cards anexados a um link visualizado usando a API Chat. Saiba mais em Atualizar um cartão.

Ao implementar as visualizações de links, talvez seja necessário depurar o app do Chat lendo os registros dele. Para ler os registros, acesse a Análise de registros no console do Google Cloud.