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 al messaggio una scheda che fornisce maggiori informazioni e consente agli utenti di eseguire azioni direttamente da Google Chat.

Ad esempio, immagina uno spazio di Google Chat che includa tutti gli agenti dell'assistenza clienti di un'azienda più un'app di Chat chiamata Case-y. Gli agenti condividono spesso i link alle richieste di assistenza clienti nello spazio di Chat e, ogni volta che lo fanno, i colleghi devono aprire il link della richiesta per visualizzare dettagli come l'assegnatario, lo stato e l'oggetto. Allo stesso modo, se qualcuno vuole prendere in carico una richiesta o modificare lo stato, deve aprire il link.

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

Quando una persona aggiunge un link al proprio messaggio, viene visualizzato un chip che comunica che un'app di Chat potrebbe visualizzare l'anteprima del link.

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

Una volta inviato il messaggio, il link viene inviato all'app Chat, che genera e allega la scheda al messaggio dell'utente.

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

Insieme al link, la scheda fornisce informazioni aggiuntive sul link, inclusi elementi interattivi come i pulsanti. L'app Chat può aggiornare la scheda allegata in risposta alle interazioni degli utenti, come i clic sui pulsanti.

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

Prerequisiti

Node.js

Un'app di Google Chat abilitata per le funzionalità interattive. Per creare un un'app di chat interattiva utilizzando un servizio HTTP, completa questa guida rapida.

Apps Script

Un'app di Google Chat abilitata per le funzionalità interattive. Per creare un app di Chat interattiva in Apps Script, completa questa guida rapida.

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

Menu di configurazione dell'anteprima del link

  1. Apri la console Google Cloud.
  2. Accanto a "Google Cloud", fai clic sulla Freccia giù e apri il progetto dell'app di 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 fare in modo che i link di anteprima dell'app Chat per un sottodominio specifico, ad esempio subdomain.example.com, siano inclusi, includi il sottodominio.

    Per fare in modo che l'app Chat visualizzi i link di anteprima 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 corrispondenze di 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 delle richieste ospitate in support.example.com/cases/.

  8. Fai clic su Fine.

  9. Fai clic su Salva.

Ora, ogni volta che un utente 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 mostra l'anteprima del link.

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

All'interno degli spazi di Chat che includono Chat, quando un messaggio di qualcuno contiene un link che corrisponde a un pattern URL di anteprima del link, la tua app Chat riceve un Evento di interazione MESSAGE. Il file JSON Il payload 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

}

Verificando la presenza del campo matchedUrl nell'evento MESSAGE payload, l'app Chat può aggiungere informazioni con il link visualizzato in anteprima. L'app Chat può rispondi con un semplice messaggio o allega un biglietto.

Rispondi con un messaggio

Per risposte semplici, l'app Chat può visualizzare l'anteprima di un link rispondendo con un semplice messaggio a un link. Questo esempio allega un messaggio che ripete l'URL del link corrisponde a un pattern URL di anteprima del 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: restituisce un ActionResponse di tipo UPDATE_USER_MESSAGE_CARDS. In questo esempio viene 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

Questo esempio invia un messaggio di una scheda restituendo JSON card. Puoi utilizzare anche Servizio di schede 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 in anteprima, restituisci ActionResponse di tipo UPDATE_USER_MESSAGE_CARDS. Le app di chat possono solo aggiornarsi schede che mostrano l'anteprima dei link in risposta a una Evento di interazione con l'app di Chat. Le app di chat non possono aggiornare queste schede chiamando l'API Chat in modo asincrono.

La visualizzazione dell'anteprima del 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 assicurarti che una funzione aggiorni le schede create dall'utente e dall'app nello stream di Chat, imposta in modo dinamico la 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 e controllando la presenza di un actionMethodName personalizzato all'interno 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: cerca actionMethodName

Per utilizzare actionMethodName in modo da gestire correttamente gli eventi di interazione CARD_CLICKED nelle schede visualizzate in anteprima, imposta un valore actionMethodName personalizzato 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 dell'anteprima di un link, è possibile restituire in modo dinamico il valore ActionResponse corretto verificando la corrispondenza di actionMethodName:

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

Questo esempio invia un messaggio di una scheda restituendo JSON card. Puoi utilizzare anche Servizio di schede 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

Questo esempio invia un messaggio di una scheda restituendo JSON card. Puoi utilizzare anche Servizio di schede 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, Allega una scheda. Il seguente esempio completo aggiorna la scheda in modo che sia assegnata a "Tu" Dopo che un utente fa clic su Assegna a me. L'esempio imposta 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

Questo esempio invia un messaggio di una scheda restituendo JSON card. Puoi utilizzare anche Servizio di schede 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 visualizzabile in anteprima.
  • Le app di chat mostrano in anteprima solo i link che iniziano con https://, quindi https://support.example.com/cases/ mostra l'anteprima, ma non support.example.com/cases/.
  • A meno che il messaggio non includa altre informazioni inviate all'app Chat, ad esempio un comando slash, solo l'URL del link viene inviato all'app Chat tramite le anteprime del link.
  • Le schede allegate ai link in anteprima supportano solo un elemento ActionResponse di tipo UPDATE_USER_MESSAGE_CARDS e solo in risposta a un evento di interazione con l'app Chat. Le anteprime link non supportano UPDATE_MESSAGE o le richieste asincrone di aggiornamento delle schede allegate a un link in anteprima tramite l'API Chat. Per scoprire di più, consulta 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, vai a Esplora log nella console Google Cloud.