使用智慧型方塊預覽 Google 圖書中的連結

程式設計層級:中級
時間長度:30 分鐘
專案類型:Google Workspace 外掛程式

目標

  • 瞭解外掛程式的功能。
  • 瞭解如何使用 以及瞭解 Apps Script 以及服務
  • 設定環境。
  • 設定指令碼。
  • 執行指令碼。

關於這個 Google Workspace 外掛程式

在這個示例中,您將建立 Google Workspace 外掛程式,用來預覽 Google 圖書, Google 文件。當你在 這個外掛程式會辨識 並觸發連結預覽。如要預覽連結,可以將 連結到智慧型方塊,然後將滑鼠遊標懸停在連結上,即可查看 會顯示書籍詳細資訊。

這個外掛程式的用途 Apps Script 的 UrlFetch 服務 連結至 Google 圖書 API 並取得 要在 Google 文件中顯示之 Google 圖書的相關資訊。

運作方式

在 Google Workspace 外掛程式的資訊清單中 檔案,指令碼會設定 適用於擴充 Google 文件和觸發條件連結的外掛程式 符合 Google 圖書網站中特定格式的網址預覽 (https://books.google.com).

在程式碼檔案中,指令碼會連線至 Google Books API,並使用該網址 取得書籍相關資訊 (這是 Volume 的執行個體 資源)。 指令碼會使用這項資訊產生智慧型方塊,顯示書籍的 標題和預覽資訊卡,其中顯示摘要、頁數、 書籍封面和評分次數。

Apps Script 服務

這個外掛程式使用下列服務:

必要條件

如要使用這個範例,您必須具備下列先決條件:

  • Google 帳戶 (Google Workspace 帳戶可能會 需要管理員核准)。
  • 可存取網際網路的網路瀏覽器。

  • Google Cloud 專案 以及相關聯的帳單帳戶詳情請參閱為 專案

設定環境

以下各節將設定環境,以便建構 外掛程式。

在 Google Cloud 控制台中開啟 Cloud 專案

如果沒有開啟,請開啟您要使用的 Cloud 專案 定義:

  1. 在 Google Cloud 控制台中,前往「選取專案」頁面。

    選取 Cloud 專案

  2. 選取要使用的 Google Cloud 專案。或是按一下「建立專案」,然後按照畫面上的指示操作。如要建立 Google Cloud 專案,您可能需要開啟該專案的計費功能

開啟 Google Books API

這個外掛程式會連線至 Google Books API。 您必須先在 Google Cloud 專案中啟用這些 Google API,才能使用這些 API。 您可以在單一 Google Cloud 專案中啟用一或多個 API。

這個外掛程式需要有 Cloud 專案 設定同意畫面設定 OAuth 同意畫面會定義 Google 會向使用者顯示並註冊您的應用程式,方便您發布

  1. 在 Google Cloud 控制台中,前往「選單」圖示 > API 與服務 >「OAuth 同意畫面」

    前往 OAuth 同意畫面

  2. 在「使用者類型」部分選取「內部」,然後按一下「建立」
  3. 填寫應用程式註冊表單,然後按一下「儲存並繼續」
  4. 您現在可以略過新增範圍的步驟,然後按一下「儲存並繼續」。 日後您可以製作並使用應用程式 Google Workspace 機構,您必須將「使用者類型」變更為「外部」, 新增應用程式所需的授權範圍。

  5. 查看應用程式註冊摘要。如要修改資訊,請按一下「編輯」。如果應用程式 註冊看起來沒有問題,請按一下 [返回資訊主頁]

取得 Google Books API 的 API 金鑰

  1. 前往 Google Cloud 控制台。 請確定您已啟用計費功能的專案已開啟。
  2. 在 Google Cloud 控制台中,前往「選單」圖示 > API 與服務 >「憑證」

    前往「憑證」頁面

  3. 依序按一下「建立憑證」>「API 金鑰」

  4. 記下 API 金鑰,以便在後續步驟中使用。

設定指令碼

以下各節將設定用於建構 外掛程式。

建立 Apps Script 專案

  1. 點選下方按鈕,即可開啟「預覽 Google 圖書的連結」 Apps Script 專案。
    開啟專案
  2. 按一下「總覽」圖示
  3. 在總覽頁面上,按一下「用來建立副本的圖示 建立副本」
  4. 在 Apps Script 專案副本中,前往 Code.gs 檔案,並將 YOUR_API_KEY 換成您在 請參閱上一節的說明。

複製 Cloud 專案編號

  1. 在 Google Cloud 控制台中,前往「選單」圖示 > IAM 與管理員 >「設定」

    前往「IAM &」(身分與存取權管理) 頁面管理員設定

  2. 複製「Project number」欄位中的值。

設定 Apps Script 專案的 Cloud 專案

  1. 在您的 Apps Script 專案中, 按一下 專案設定圖示 「Project Settings」
  2. 在「Google Cloud Platform (GCP) Project」(Google Cloud Platform (GCP) 專案) 下方,按一下 [變更專案]
  3. 在「GCP 專案編號」中,貼上 Google Cloud 專案編號。
  4. 按一下「設定專案」

測試外掛程式

以下各節會測試您建立的外掛程式。

安裝測試部署作業

  1. 在 Apps Script 專案中按一下 「編輯器」
  2. YOUR_API_KEY 替換為 Google Books API 的 API 金鑰 (建立位置: 先前的章節
  3. 依序點選「部署」>「測試部署作業」
  4. 依序點選「安裝」>「完成」
  1. 在 建立 Google 文件: docs.new.
  2. 將下列網址貼到文件中,然後按 Tab 鍵 將網址轉換為智慧型方塊: https://www.google.com/books/edition/Software_Engineering_at_Google/V3TTDwAAQBAJ
  3. 將遊標懸停在智慧型方塊上,然後在系統提示時授權存取 執行外掛程式預覽資訊卡會隨即顯示 書籍的相關資訊

連結預覽圖片如下:

Google 軟體工程部門書籍的連結預覽。

查看程式碼

查看 Apps Script 程式碼 外掛程式,請按一下「查看原始碼」展開 區段:

查看原始碼

appsscript.json

solutions/add-on/book-smartchip/appsscript.json
{
  "timeZone": "America/Los_Angeles",
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "oauthScopes": [
    "https://www.googleapis.com/auth/workspace.linkpreview",
    "https://www.googleapis.com/auth/script.external_request"
  ],
  "urlFetchWhitelist": [
    "https://www.googleapis.com/books/v1/volumes/"
  ],
  "addOns": {
    "common": {
      "name": "Preview Books Add-on",
      "logoUrl": "https://developers.google.com/workspace/add-ons/images/library-icon.png",
      "layoutProperties": {
        "primaryColor": "#dd4b39"
      }
    },
    "docs": {
      "linkPreviewTriggers": [
        {
          "runFunction": "bookLinkPreview",
          "patterns": [
            {
              "hostPattern": "*.google.*",
              "pathPrefix": "books"
            },
            {
              "hostPattern": "*.google.*",
              "pathPrefix": "books/edition"
            }
          ],
          "labelText": "Book",
          "logoUrl": "https://developers.google.com/workspace/add-ons/images/book-icon.png",
          "localizedLabelText": {
            "es": "Libros"
          }
        }
      ]
    }
  }
}

Code.gs

solutions/add-on/book-smartchip/Code.js
function getBook(id) {
  const apiKey = 'YOUR_API_KEY'; // Replace with your API key
  const apiEndpoint = `https://www.googleapis.com/books/v1/volumes/${id}?key=${apiKey}&country=US`;
  const response = UrlFetchApp.fetch(apiEndpoint);
  return JSON.parse(response);
}

function bookLinkPreview(event) {
 if (event.docs.matchedUrl.url) {
    const segments = event.docs.matchedUrl.url.split('/');
    const volumeID = segments[segments.length - 1];

    const bookData = getBook(volumeID);
    const bookTitle = bookData.volumeInfo.title;
    const bookDescription = bookData.volumeInfo.description;
    const bookImage = bookData.volumeInfo.imageLinks.small;
    const bookAuthors = bookData.volumeInfo.authors;
    const bookPageCount = bookData.volumeInfo.pageCount;

    const previewHeader = CardService.newCardHeader()
      .setSubtitle('By ' + bookAuthors)
      .setTitle(bookTitle);

    const previewPages = CardService.newDecoratedText()
      .setTopLabel('Page count')
      .setText(bookPageCount);

    const previewDescription = CardService.newDecoratedText()
      .setTopLabel('About this book')
      .setText(bookDescription).setWrapText(true);

    const previewImage = CardService.newImage()
      .setAltText('Image of book cover')
      .setImageUrl(bookImage);

    const buttonBook = CardService.newTextButton()
      .setText('View book')
      .setOpenLink(CardService.newOpenLink()
        .setUrl(event.docs.matchedUrl.url));

    const cardSectionBook = CardService.newCardSection()
      .addWidget(previewImage)
      .addWidget(previewPages)
      .addWidget(CardService.newDivider())
      .addWidget(previewDescription)
      .addWidget(buttonBook);

    return CardService.newCardBuilder()
    .setHeader(previewHeader)
    .addSection(cardSectionBook)
    .build();
  }
}