Anteprima link

Per impedire il cambio di contesto quando gli utenti condividono un link in Google Chat, l'app Chat può visualizzare l'anteprima del link allegando una scheda al messaggio che contiene più informazioni e consente alle persone di eseguire azioni direttamente da Google Chat.

Ad esempio, immagina uno spazio di Google Chat che include tutti gli agenti dell'assistenza clienti di un'azienda più un'app di chat di nome Case-y. Gli agenti condividono spesso link alle richieste di assistenza clienti nello spazio di Chat e, ogni volta che lo fanno, i loro colleghi devono aprire il link della richiesta per visualizzare dettagli come assegnatario, stato e oggetto. Allo stesso modo, se qualcuno vuole assumere la proprietà di una richiesta o modificarne lo stato, deve aprire il link.

L'anteprima dei link consente all'app Chat residente dello spazio, Case-y, di allegare una scheda che mostra l'assegnatario, lo stato e il soggetto ogni volta che qualcuno condivide il link di una richiesta. I pulsanti sulla scheda consentono agli agenti di gestire la richiesta e modificarne lo stato direttamente dallo stream della chat.

Quando qualcuno aggiunge un link a un messaggio, viene visualizzato un chip che la informa che l'app di Chat potrebbe visualizzare l'anteprima del link.

Chip che indica che un'app di Chat potrebbe visualizzare l'anteprima di un link

Dopo l'invio del messaggio, il link viene inviato all'app Chat, che a sua volta genera e allega la scheda al messaggio dell'utente.

App di chat che visualizza l'anteprima di un link allegando una scheda al messaggio

Oltre al link, la scheda fornisce ulteriori informazioni sul link, inclusi elementi interattivi come i pulsanti. L'app di chat può aggiornare la scheda allegata in risposta alle interazioni degli utenti, ad esempio ai clic sui pulsanti.

Se qualcuno non vuole che l'app Chat visualizzi l'anteprima del link allegando una scheda al messaggio, può impedire la visualizzazione dell'anteprima facendo clic su nel chip di anteprima. Gli utenti possono rimuovere la scheda allegata in qualsiasi momento facendo clic su Rimuovi anteprima.

Registra link specifici, come example.com, support.example.com e support.example.com/cases/, come pattern URL nella pagina di configurazione dell'app Chat in Google Cloud Console in modo che l'app Chat possa visualizzarne l'anteprima.

Menu di configurazione delle anteprime del link

  1. Apri la console Google Cloud.
  2. Accanto a "Google Cloud", fai clic sulla Freccia giù e apri il progetto dell'app Chat.
  3. Nel campo di ricerca, digita Google Chat API e fai clic su API Google Chat.
  4. Fai clic su Gestisci > Configurazione.
  5. In Anteprime link, aggiungi o modifica un pattern URL.
    1. Per configurare le anteprime dei link per un nuovo pattern URL, fai clic su Aggiungi pattern URL.
    2. Per modificare la configurazione di un pattern URL esistente, fai clic sulla Freccia giù .
  6. Nel campo Pattern host, inserisci il dominio del pattern URL. L'app Chat mostrerà l'anteprima dei link a questo dominio.

    Per avere i link di anteprima dell'app Chat per un sottodominio specifico, come subdomain.example.com, includi il sottodominio.

    Per visualizzare i link di anteprima dell'app Chat per l'intero dominio, specifica un carattere jolly con un asterisco (*) come sottodominio. Ad esempio, *.example.com corrisponde a subdomain.example.com e any.number.of.subdomains.example.com.

  7. Nel campo Prefisso percorso, inserisci un percorso da aggiungere al dominio del pattern host.

    Per trovare la corrispondenza con tutti gli URL nel dominio del pattern host, lascia vuoto il campo Prefisso percorso.

    Ad esempio, se il pattern host è support.example.com, inserisci cases/ per trovare corrispondenze con gli URL per i casi ospitati sul sito support.example.com/cases/.

  8. Fai clic su Fine.

  9. Fai clic su Salva.

Ora, ogni volta che qualcuno include un link che corrisponde a un pattern URL di anteprima del link a un messaggio in uno spazio di Chat che include la tua app Chat, l'app visualizza l'anteprima del link.

Dopo aver configurato l'anteprima del link per un determinato link, l'app Chat può riconoscere e visualizzare l'anteprima del link allegando ulteriori informazioni.

All'interno degli spazi di Chat che includono la tua app Chat, quando il messaggio di un utente contiene un link che corrisponde a un pattern URL di anteprima link, l'app Chat riceve un evento di interazione MESSAGE. Il payload JSON per l'evento di interazione contiene il campo matchedUrl:

JSON

"message": {

  . . . // other message attributes redacted

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

  . . . // other message attributes redacted

}

Se verifichi la presenza del campo matchedUrl nel payload dell'evento MESSAGE, la tua app Chat può aggiungere informazioni al messaggio con il link in anteprima. L'app Chat può rispondere con un semplice messaggio di testo o allegare una scheda.

Rispondi con un SMS

Per risposte semplici, l'app Chat può visualizzare l'anteprima di un link rispondendo con un semplice messaggio di testo a un link. Questo esempio allega un messaggio che ripete l'URL del link che corrisponde a un pattern URL di anteprima 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.'};
}

Allega una carta

Per allegare una scheda a un link visualizzato in anteprima, restituisci un elemento ActionResponse di tipo UPDATE_USER_MESSAGE_CARDS. In questo esempio è allegata una scheda semplice.

App di chat che visualizza l'anteprima di un link allegando una scheda al messaggio

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

In questo esempio viene inviato un messaggio relativo alle schede restituendo un JSON della scheda. Puoi anche utilizzare il servizio di schede di 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.'};
}

Aggiornare una carta

Per aggiornare la scheda allegata a un link di anteprima, restituisci un elemento ActionResponse di tipo UPDATE_USER_MESSAGE_CARDS. Le app di chat possono aggiornare solo le schede che visualizzano l'anteprima dei link in risposta a un evento di interazione con l'app di Chat. Le app di chat non possono aggiornare queste schede chiamando l'API Chat in modo asincrono.

L'anteprima dei link non supporta la restituzione di un elemento ActionResponse di tipo UPDATE_MESSAGE. Poiché UPDATE_MESSAGE aggiorna l'intero messaggio anziché solo la scheda, funziona solo se l'app Chat ha creato il messaggio originale. L'anteprima del link allega una scheda a un messaggio creato dall'utente, quindi l'app Chat non dispone dell'autorizzazione per aggiornarla.

Per fare in modo che una funzione aggiorni le schede create dall'utente e dall'app nello stream di Chat, imposta in modo dinamico il valore ActionResponse a seconda che il messaggio sia stato creato dall'app Chat o da un utente.

  • Se il messaggio è stato creato da un utente, imposta ActionResponse su UPDATE_USER_MESSAGE_CARDS.
  • Se il messaggio è stato creato da un'app di chat, imposta ActionResponse su UPDATE_MESSAGE.

Puoi farlo in due modi: specificando una actionMethodName personalizzata che fa parte della proprietà onclick della scheda allegata (che identifica il messaggio come creato dall'utente) oppure controllando se il messaggio è stato creato da un utente.

Opzione 1: controlla se è presente actionMethodName

Per utilizzare actionMethodName per gestire correttamente gli eventi di interazione CARD_CLICKED nelle schede in anteprima, imposta un'actionMethodName personalizzata come parte della proprietà onclick della scheda allegata:

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

Se "actionMethodName": "assign" identifica il pulsante come parte di un'anteprima link, è possibile restituire in modo dinamico il valore ActionResponse corretto verificando un actionMethodName corrispondente:

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

In questo esempio viene inviato un messaggio relativo alle schede restituendo un JSON della scheda. Puoi anche utilizzare il servizio di schede di 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': [{}],
  };
}

Opzione 2: controlla il tipo di mittente

Controlla se message.sender.type è HUMAN o BOT. Se HUMAN, imposta ActionResponse su UPDATE_USER_MESSAGE_CARDS, altrimenti imposta ActionResponse su UPDATE_MESSAGE. Ecco come:

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

In questo esempio viene inviato un messaggio relativo alle schede restituendo un JSON della scheda. Puoi anche utilizzare il servizio di schede di 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 tipico per aggiornare una scheda è la risposta al clic su un pulsante. Ricorda il pulsante Assegna a me della sezione precedente, Allegare una scheda. Il seguente esempio completo aggiorna la scheda in modo che risulti assegnata a "Tu " dopo che l'utente fa clic su Assegna a me. Nell'esempio viene impostato in modo dinamico ActionResponse controllando il tipo di mittente.

Esempio completo: Case-y, l'app Chat dell'assistenza clienti

Ecco il codice completo per Case-y, un'app di chat che mostra in anteprima i link alle richieste condivise in uno spazio di Chat in cui collaborano gli agenti dell'assistenza clienti.

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

In questo esempio viene inviato un messaggio relativo alle schede restituendo un JSON della scheda. Puoi anche utilizzare il servizio di schede di 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'}},
                },
              },
            ],
          }],
        }],
      },
    }],
  };
}

Limiti e considerazioni

Quando configuri le anteprime dei link per l'app Chat, tieni presente questi limiti e considerazioni:

  • Ogni app di chat supporta le anteprime dei link per un massimo di 5 pattern URL.
  • Le app di chat visualizzano l'anteprima di un link per messaggio. Se in un singolo messaggio sono presenti più link visualizzabili in anteprima, viene visualizzato in anteprima solo il primo link di anteprima.
  • Le app di chat visualizzano l'anteprima solo dei link che iniziano con https://, perciò l'anteprima di https://support.example.com/cases/ non viene mostrata in support.example.com/cases/.
  • A meno che il messaggio non includa altre informazioni che vengono inviate all'app Chat, ad esempio un comando slash, all'app Chat viene inviato solo l'URL del link tramite le anteprime del link.
  • Le schede allegate ai link in anteprima supportano solo ActionResponse di tipo UPDATE_USER_MESSAGE_CARDS e solo in risposta a un evento di interazione nell'app Chat. Le anteprime link non supportano UPDATE_MESSAGE o richieste asincrone di aggiornamento delle schede collegate a un link in anteprima tramite l'API Chat. Per ulteriori informazioni, consulta la sezione Aggiornare una carta.

Durante l'implementazione delle anteprime dei link, potresti dover eseguire il debug dell'app Chat leggendo i log dell'app. Per leggere i log, visita Esplora log nella console Google Cloud.