Xem trước đường liên kết

Để tránh việc chuyển đổi ngữ cảnh khi người dùng chia sẻ một đường liên kết trong Google Chat, ứng dụng Chat của bạn có thể xem trước đường liên kết đó bằng cách đính kèm một thẻ vào tin nhắn để cung cấp thêm thông tin và cho phép mọi người thực hiện hành động ngay trong Google Chat.

Ví dụ: Hãy tưởng tượng một không gian trong Google Chat có tất cả nhân viên hỗ trợ dịch vụ khách hàng của một công ty và một ứng dụng Chat có tên làCase-y. Nhân viên hỗ trợ thường xuyên chia sẻ đường liên kết đến các yêu cầu liên quan đến dịch vụ khách hàng trong phòng Chat. Mỗi khi thực hiện, đồng nghiệp của họ phải mở đường liên kết đến yêu cầu đó để xem thông tin chi tiết như người được giao, trạng thái và chủ đề. Tương tự, nếu người nào đó muốn nắm quyền sở hữu một trường hợp hoặc thay đổi trạng thái, thì họ cần phải mở đường liên kết.

Khi có người chia sẻ đường liên kết đến trường hợp, tính năng xem trước đường liên kết cho phép ứng dụng Chat (trò chuyện) thường trú của không gian (Case-y) đính kèm một thẻ cho biết người được giao, trạng thái và tiêu đề mỗi khi có người chia sẻ đường liên kết đến trường hợp. Các nút trên thẻ cho phép nhân viên hỗ trợ nắm quyền sở hữu yêu cầu và thay đổi trạng thái ngay trong luồng trò chuyện.

Khi có người thêm đường liên kết vào tin nhắn, một khối sẽ xuất hiện cho người dùng biết rằng ứng dụng Chat có thể xem trước đường liên kết đó.

Khối cho biết ứng dụng Chat có thể xem trước đường liên kết

Sau khi người dùng gửi tin nhắn, đường liên kết sẽ được gửi đến ứng dụng Chat, sau đó ứng dụng này sẽ tạo và đính kèm thẻ vào tin nhắn của người dùng.

Ứng dụng Chat xem trước một đường liên kết bằng cách đính kèm một thẻ vào tin nhắn

Ngoài đường liên kết, thẻ còn cung cấp thêm thông tin về đường liên kết, bao gồm các thành phần tương tác như nút. Ứng dụng Chat có thể cập nhật thẻ đính kèm để phản hồi hoạt động tương tác của người dùng, chẳng hạn như lượt nhấp vào nút.

Nếu người dùng không muốn ứng dụng Chat xem trước đường liên kết của mình bằng cách đính kèm một thẻ vào tin nhắn, thì họ có thể không cho phép xem trước bằng cách nhấp vào dấu trên khối xem trước. Người dùng có thể xoá thẻ đính kèm bất cứ lúc nào bằng cách nhấp vào Xoá bản xem trước.

Điều kiện tiên quyết

Node.js

Một ứng dụng Google Chat đã bật các tính năng tương tác. Để tạo một ứng dụng Chat tương tác bằng dịch vụ HTTP, hãy hoàn thành phần bắt đầu nhanh này.

Apps Script

Một ứng dụng Google Chat đã bật các tính năng tương tác. Để tạo một ứng dụng Chat tương tác trong Apps Script, hãy hoàn thành phần bắt đầu nhanh này.

Đăng ký các đường liên kết cụ thể, chẳng hạn như example.com, support.example.comsupport.example.com/cases/, dưới dạng mẫu URL trên trang cấu hình của ứng dụng Chat trong bảng điều khiển của Google Cloud để ứng dụng Chat có thể xem trước những đường liên kết đó.

Trình đơn cấu hình bản xem trước đường liên kết

  1. Mở bảng điều khiển Google Cloud.
  2. Bên cạnh "Google Cloud", nhấp vào biểu tượng Mũi tên xuống rồi mở dự án của ứng dụng Chat.
  3. Trong trường tìm kiếm, hãy nhập Google Chat API rồi nhấp vào API Google Chat.
  4. Nhấp vào Quản lý > Cấu hình.
  5. Trong phần Bản xem trước đường liên kết, hãy thêm hoặc chỉnh sửa một mẫu URL.
    1. Để định cấu hình bản xem trước đường liên kết cho một mẫu URL mới, hãy nhấp vào Thêm mẫu URL.
    2. Để chỉnh sửa cấu hình cho mẫu URL hiện có, hãy nhấp vào biểu tượng Mũi tên xuống .
  6. Trong trường Mẫu máy chủ lưu trữ, hãy nhập miền của mẫu URL. Ứng dụng Chat sẽ xem trước các đường liên kết đến miền này.

    Để thiết lập đường liên kết xem trước ứng dụng trong Chat cho một miền con cụ thể (chẳng hạn như subdomain.example.com), hãy thêm miền con.

    Để cung cấp đường liên kết xem trước ứng dụng Chat cho toàn bộ miền, hãy chỉ định một ký tự đại diện có dấu hoa thị (*) làm miền con. Ví dụ: *.example.com khớp với subdomain.example.comany.number.of.subdomains.example.com.

  7. Trong trường Tiền tố đường dẫn, nhập đường dẫn để thêm vào miền mẫu máy chủ lưu trữ.

    Để khớp tất cả các URL trong miền mẫu máy chủ lưu trữ, hãy để trống Tiền tố đường dẫn.

    Ví dụ: nếu Mẫu máy chủ lưu trữ là support.example.com, để khớp URL cho các trường hợp được lưu trữ tại support.example.com/cases/, hãy nhập cases/.

  8. Nhấp vào Xong.

  9. Nhấp vào Lưu.

Giờ đây, mỗi khi có người thêm đường liên kết khớp với mẫu URL xem trước đường liên kết vào tin nhắn trong phòng Chat có ứng dụng Chat của bạn, ứng dụng của bạn sẽ xem trước đường liên kết đó.

Sau khi bạn định cấu hình xem trước liên kết cho một liên kết nhất định, Ứng dụng Chat có thể nhận dạng và xem trước đường liên kết bằng cách đính kèm thêm thông tin vào đó.

Bên trong các phòng Chat có Ứng dụng Chat, khi tin nhắn của ai đó chứa đường liên kết khớp với mẫu URL xem trước đường liên kết, ứng dụng Chat của bạn nhận được một Sự kiện tương tác MESSAGE. JSON tải trọng cho sự kiện tương tác chứa trường matchedUrl:

JSON

"message": {

  . . . // other message attributes redacted

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

  . . . // other message attributes redacted

}

Bằng cách kiểm tra sự hiện diện của trường matchedUrl trong sự kiện MESSAGE tải trọng, ứng dụng Chat của bạn có thể thêm thông tin vào kèm theo đường liên kết được xem trước. Ứng dụng Chat có thể hãy trả lời bằng một tin nhắn văn bản đơn giản hoặc đính kèm một tấm thẻ.

Trả lời bằng tin nhắn văn bản

Đối với các câu trả lời đơn giản, ứng dụng Chat có thể xem trước một đường liên kết bằng cách trả lời bằng một tin nhắn văn bản đơn giản vào một liên kết. Ví dụ này đính kèm một tin nhắn lặp lại URL liên kết khớp với mẫu URL xem trước đường liên kết.

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

Đính kèm thẻ

Cách đính kèm một thẻ vào đường liên kết đã xem trước: trả về một ActionResponse thuộc loại UPDATE_USER_MESSAGE_CARDS. Ví dụ này đính kèm một thẻ đơn giản.

Ứng dụng Chat xem trước một đường liên kết bằng cách đính kèm một thẻ vào tin nhắn

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

Ví dụ này gửi thông báo thẻ bằng cách quay lại tệp JSON của thẻ. Bạn cũng có thể sử dụng Dịch vụ thẻ Apps Script.

apps-script/preview-link/attach-card.gs
/**
 * Responds to messages that have links whose URLs match URL patterns
 * configured for link previewing.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app attached to the message with
 * the previewed link.
 */
function onMessage(event) {
  // Checks for the presence of event.message.matchedUrl and attaches a card
  // if present
  if (event.message.matchedUrl) {
    return {
      'actionResponse': {
        'type': 'UPDATE_USER_MESSAGE_CARDS',
      },
      'cardsV2': [{
        'cardId': 'attachCard',
        'card': {
          'header': {
            'title': 'Example Customer Service Case',
            'subtitle': 'Case basics',
          },
          'sections': [{
            'widgets': [
              {'keyValue': {'topLabel': 'Case ID', 'content': 'case123'}},
              {'keyValue': {'topLabel': 'Assignee', 'content': 'Charlie'}},
              {'keyValue': {'topLabel': 'Status', 'content': 'Open'}},
              {
                'keyValue': {
                  'topLabel': 'Subject', 'content': 'It won\'t turn on...',
                },
              },
            ],
          },
          {
            'widgets': [{
              'buttons': [
                {
                  'textButton': {
                    'text': 'OPEN CASE',
                    'onClick': {
                      'openLink': {
                        'url': 'https://support.example.com/orders/case123',
                      },
                    },
                  },
                },
                {
                  'textButton': {
                    'text': 'RESOLVE CASE',
                    'onClick': {
                      'openLink': {
                        'url': 'https://support.example.com/orders/case123?resolved=y',
                      },
                    },
                  },
                },
                {
                  'textButton': {
                    'text': 'ASSIGN TO ME',
                    'onClick': {'action': {'actionMethodName': 'assign'}},
                  },
                },
              ],
            }],
          }],
        },
      }],
    };
  }

  // If the Chat app doesn’t detect a link preview URL pattern, it says so.
  return {'text': 'No matchedUrl detected.'};
}

Cập nhật thẻ

Để cập nhật thẻ được đính kèm vào một đường liên kết đã xem trước, hãy trả về một ActionResponse thuộc loại UPDATE_USER_MESSAGE_CARDS. Các ứng dụng trong Chat chỉ có thể cập nhật các thẻ xem trước đường liên kết dưới dạng phản hồi cho một Sự kiện tương tác với ứng dụng Chat. Các ứng dụng Chat không thể cập nhật những thẻ này bằng cách gọi API Chat một cách không đồng bộ.

Tính năng xem trước đường liên kết không hỗ trợ trả về ActionResponse thuộc loại UPDATE_MESSAGE. Vì UPDATE_MESSAGE cập nhật toàn bộ tin nhắn thay vì chỉ cập nhật thẻ, nên tính năng này chỉ hoạt động nếu ứng dụng Chat tạo tin nhắn ban đầu. Tính năng xem trước đường liên kết sẽ đính kèm một thẻ vào tin nhắn do người dùng tạo, vì vậy, ứng dụng Chat không có quyền cập nhật thẻ đó.

Để đảm bảo một chức năng cập nhật cả thẻ do người dùng tạo và thẻ do ứng dụng tạo trong luồng trò chuyện, hãy đặt ActionResponse một cách linh động dựa vào việc ứng dụng Chat hay người dùng đã tạo tin nhắn.

  • Nếu người dùng đã tạo thông báo, hãy đặt ActionResponse thành UPDATE_USER_MESSAGE_CARDS.
  • Nếu một ứng dụng trong Chat đã tạo tin nhắn, hãy đặt ActionResponse thành UPDATE_MESSAGE.

Có hai cách để thực hiện việc này: chỉ định và kiểm tra actionMethodName tuỳ chỉnh trong thuộc tính onclick của thẻ đính kèm (xác định thư là do người dùng tạo) hoặc kiểm tra xem thư có phải do người dùng tạo hay không.

Cách 1: Kiểm tra để tìm actionMethodName

Để sử dụng actionMethodName nhằm xử lý đúng cách các sự kiện tương tác CARD_CLICKED trên thẻ xem trước, hãy đặt một actionMethodName tuỳ chỉnh trong thuộc tính onclick của thẻ đính kèm:

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

Với "actionMethodName": "assign" xác định nút là một phần của bản xem trước đường liên kết, bạn có thể linh động trả về ActionResponse chính xác bằng cách kiểm tra xem có actionMethodName trùng khớp không:

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

Ví dụ này gửi thông báo thẻ bằng cách quay lại tệp JSON của thẻ. Bạn cũng có thể sử dụng Dịch vụ thẻ 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': [{}],
  };
}

Cách 2: Kiểm tra loại người gửi

Kiểm tra xem message.sender.typeHUMAN hay BOT. Nếu là HUMAN, hãy đặt ActionResponse thành UPDATE_USER_MESSAGE_CARDS, nếu không, đặt ActionResponse thành UPDATE_MESSAGE. Cách làm như sau:

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

Ví dụ này gửi thông báo thẻ bằng cách quay lại tệp JSON của thẻ. Bạn cũng có thể sử dụng Dịch vụ thẻ 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': [{}],
  };
}

Một lý do thông thường để cập nhật thẻ là để phản hồi một lượt nhấp vào nút. Hãy nhớ nút Giao cho tôi ở phần trước, Đính kèm thẻ. Ví dụ hoàn chỉnh sau đây cập nhật thẻ để thẻ được chỉ định cho "Bạn" sau khi người dùng nhấp vào Giao cho tôi. Ví dụ này sẽ đặt ActionResponse một cách linh động bằng cách kiểm tra loại người gửi.

Ví dụ đầy đủ: Trường hợp y cho ứng dụng Chat dịch vụ khách hàng

Sau đây là mã hoàn chỉnh cho case-y, một ứng dụng Chat giúp xem trước đường liên kết đến các yêu cầu hỗ trợ được chia sẻ trong một phòng Chat mà nhân viên dịch vụ khách hàng cộng tác.

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

Ví dụ này gửi thông báo thẻ bằng cách quay lại tệp JSON của thẻ. Bạn cũng có thể sử dụng Dịch vụ thẻ 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'}},
                },
              },
            ],
          }],
        }],
      },
    }],
  };
}

Giới hạn và cân nhắc

Khi bạn định cấu hình bản xem trước đường liên kết cho ứng dụng Chat, hãy lưu ý các giới hạn và điểm cần cân nhắc sau đây:

  • Mỗi ứng dụng trong Chat hỗ trợ bản xem trước đường liên kết cho tối đa 5 mẫu URL.
  • Các ứng dụng nhắn tin sẽ xem trước một đường liên kết cho mỗi tin nhắn. Nếu có nhiều đường liên kết có thể xem trước trong một thông báo, thì chỉ những đường liên kết có thể xem trước đầu tiên.
  • Các ứng dụng nhắn tin chỉ xem trước các đường liên kết bắt đầu bằng https://, vì vậy, https://support.example.com/cases/ sẽ xem trước còn support.example.com/cases/ thì không.
  • Trừ phi tin nhắn có thông tin khác được gửi tới ứng dụng Chat, chẳng hạn như lệnh dấu gạch chéo, chỉ có URL đường liên kết được gửi đến ứng dụng Chat bằng bản xem trước đường liên kết.
  • Những thẻ được đính kèm vào đường liên kết xem trước chỉ hỗ trợ ActionResponse thuộc loại UPDATE_USER_MESSAGE_CARDS và chỉ để phản hồi sự kiện tương tác trong ứng dụng Chat. Bản xem trước đường liên kết không hỗ trợ UPDATE_MESSAGE hoặc các yêu cầu không đồng bộ để cập nhật thẻ được đính kèm vào đường liên kết xem trước thông qua Chat API. Để tìm hiểu thêm, hãy xem bài viết Cập nhật thẻ.

Khi triển khai bản xem trước đường liên kết, bạn có thể cần gỡ lỗi ứng dụng Chat bằng cách đọc nhật ký của ứng dụng. Để đọc nhật ký, hãy truy cập vào Trình khám phá nhật ký trên bảng điều khiển Google Cloud.