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

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

目標

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

關於這個 Google Workspace 外掛程式

在這個範例中,您將建立 Google Workspace 外掛程式,並在 Google 文件中預覽 Google 圖書中的連結。當您在文件中輸入或貼上 Google 圖書網址時,外掛程式會辨識該連結並觸發連結預覽。如要預覽連結,您可以將連結轉換為智慧型方塊,並將滑鼠遊標懸停在連結上,即可查看顯示書籍詳細資訊的資訊卡。

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

運作方式

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

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

Apps Script 服務

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

先備知識

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

設定環境

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

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

如果尚未開啟,請開啟要用於這個範例的 Cloud 專案:

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

    選取 Cloud 專案

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

開啟 Google Books API

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

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

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

    前往 OAuth 同意畫面

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

  5. 查看應用程式註冊摘要。如要修改資訊,請按一下「編輯」。如果應用程式註冊正確無誤,請按一下「Back to Dashboard」(返回資訊主頁)

取得 Google Books API 的 API 金鑰

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

    前往「憑證」頁面

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

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

設定指令碼

以下各節會設定用於建構外掛程式的指令碼。

建立 Apps Script 專案

  1. 按一下以下按鈕,開啟從 Google 圖書預覽連結 Apps Script 專案。
    開啟專案
  2. 按一下「總覽」圖示
  3. 在總覽頁面上,按一下「用來建立副本的圖示 建立副本」
  4. 在 Apps Script 專案副本中,前往 Code.gs 檔案,並將 YOUR_API_KEY 替換為您在上一節產生的 API 金鑰。

複製 Cloud 專案編號

  1. 在 Google Cloud 控制台中,依序點選「選單」圖示 >「IAM 與管理」>>「設定」

    前往「IAM & Admin Settings」(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. 前往 docs.new 建立 Google 文件。
  2. 將下列網址貼到文件中,然後按下 Tab 鍵,將網址轉換為智慧型方塊: https://www.google.com/books/edition/Software_Engineering_at_Google/V3TTDwAAQBAJ
  3. 將遊標懸停在智慧型方塊上,然後在系統提示時,授權執行外掛程式。預覽資訊卡會顯示書籍的相關資訊

連結預覽圖片如下:

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

查看程式碼

如要查看這個外掛程式的 Apps Script 程式碼,請按一下「View source code」展開該部分:

查看原始碼

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();
  }
}