Visualizar links

Para evitar a troca 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 que permita que as pessoas realizem ações diretamente no Google Chat.

Por exemplo, imagine um espaço do Google Chat com todos os agentes de atendimento ao cliente de uma empresa e um app do Chat chamado Case-y. Os agentes costumam compartilhar links para casos de atendimento ao cliente no espaço do Chat e, sempre que o fazem, os colegas precisam abrir o link do caso para conferir detalhes como o responsável, o status e o assunto. Da mesma forma, se alguém quiser se tornar o proprietário de um caso ou alterar o status, precisará abrir o link.

Com a visualização de links, o app do Chat residente do espaço, Case-y, anexe um card mostrando o responsável, o status e o assunto sempre que alguém compartilhar um link de caso. Com os botões no card, os agentes podem assumir a propriedade do caso e mudar o status diretamente no stream do chat.

Quando uma pessoa adiciona um link à mensagem, aparece um ícone que informa que um app do Chat pode visualizar o 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 de chat com uma prévia de um link anexando um cartão à mensagem

Juntamente com o link, o card traz mais informações sobre o link, incluindo elementos interativos, como botões. O app do Chat pode atualizar o cartão 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 acesse a prévia do link anexando um card à mensagem, ela pode impedir a visualização clicando em no ícone de visualização. Os usuários podem remover o cartão anexado a qualquer momento clicando em Remover visualização.

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 links

  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 link 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 existente, clique na seta para baixo .
  6. No campo Padrão de host, digite o domínio do padrão de URL. O app do Chat vai visualizar os links para este domínio.

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

    Se você quiser que os links de visualização do app do Chat para todo o domínio sejam exibidos, 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 do host.

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

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

  8. Clique em Concluído.

  9. Clique em Salvar.

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

Depois que você configurar a visualização de um determinado link, o app do Chat poderá reconhecer e visualizar o link anexando mais informações a ele.

Dentro dos espaços do Chat que incluem o app do Chat, quando a mensagem de alguém contém um link correspondente a um padrão de URL de visualização de link, o app do Chat recebe um evento de interação MESSAGE. O payload do JSON 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

}

Ao verificar a presença do campo matchedUrl no payload do evento MESSAGE, seu app do Chat pode adicionar informações à mensagem com o link visualizado. O app de chat pode responder com uma mensagem de texto simples ou anexar 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 de URL de visualização de 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 cartão a um link visualizado, retorne uma ActionResponse do tipo UPDATE_USER_MESSAGE_CARDS. Neste exemplo, um cartão simples é anexado.

App de chat com uma prévia de um link anexando um cartão à mensagem

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

Atualizar um cartão

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

A visualização de links não oferece suporte ao retorno de um ActionResponse do tipo UPDATE_MESSAGE. Como o UPDATE_MESSAGE atualiza a mensagem inteira em vez de apenas o card, ele só funciona se o app do Chat tiver criado a mensagem original. A visualização de links anexa um card a uma mensagem criada pelo usuário. Assim, o app do Chat não tem permissão para atualizá-lo.

Para garantir que uma função atualize cards criados pelo usuário ou por um app no stream do Chat, defina dinamicamente o ActionResponse com base no status de criação da mensagem do app do Chat ou do usuário.

  • Se um usuário criou a mensagem, defina ActionResponse como UPDATE_USER_MESSAGE_CARDS.
  • Se a mensagem foi criada por um app do Chat, 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 card 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

Com a "actionMethodName": "assign" identificando o botão como parte da visualização de um 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

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

Verifique se message.sender.type é HUMAN ou BOT. Se for 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

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 típico para atualizar um card é em resposta ao clique de um 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 informe que ele foi atribuído a "Você" depois que um usuário clicar em Atribuir a mim. O exemplo define ActionResponse dinamicamente verificando o tipo de remetente.

Exemplo completo: o app do Chat para 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

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 app do Chat, observe estes limites e considerações:

  • Cada app de chat tem suporte a visualizações de links de até cinco padrões de URL.
  • Os apps de chat mostram um link por mensagem. Se houver vários links que podem ser visualizados em uma única mensagem, somente os primeiros serão exibidos.
  • Os apps de chat só mostram uma prévia dos links que começam com https://. Portanto, o https://support.example.com/cases/ é visualizado, mas o support.example.com/cases/ não.
  • A menos que a mensagem inclua outras informações enviadas ao app do Chat, como um comando de barra, somente o URL do link será enviado ao app do Chat por visualizações de link.
  • Os cards anexados aos links visualizados só são compatíveis com ActionResponse do tipo UPDATE_USER_MESSAGE_CARDS e apenas em resposta a um evento de interação com o app do Chat. As visualizações de links 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. Para saber mais, consulte Atualizar um cartão.

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