進階即時通訊服務

Advanced Chat 服務可讓您在 Apps Script 中使用 Google Chat API。這個 API 可讓指令碼尋找、建立及修改 Chat 聊天室,在聊天室中新增或移除成員,以及讀取或發布含有文字、資訊卡、附件和表情符號的訊息。

必要條件

參考資料

如要進一步瞭解這項服務,請參閱 Chat API 參考說明文件。與 Apps Script 中的所有進階服務一樣,Chat 服務使用的物件、方法和參數與公開 API 相同。

程式碼範例

這些範例說明如何使用進階服務,執行常見的 Google Chat API 動作。

使用使用者憑證發布訊息

以下範例說明如何代表使用者將訊息發布至 Chat 空間。

  1. chat.messages.create 授權範圍新增至 Apps Script 專案的 appsscript.json 檔案:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.messages.create"
    ]
    
  2. 在 Apps Script 專案的程式碼中加入類似下列的函式:

    advanced/chat.gs
    /**
     * Posts a new message to the specified space on behalf of the user.
     * @param {string} spaceName The resource name of the space.
     */
    function postMessageWithUserCredentials(spaceName) {
      try {
        const message = {'text': 'Hello world!'};
        Chat.Spaces.Messages.create(message, spaceName);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log('Failed to create message with error %s', err.message);
      }
    }

使用應用程式憑證發布訊息

下列範例說明如何代表應用程式將訊息發布至 Google Chat 空間。使用進階 Google Chat 服務和服務帳戶時,您不需要在 appsscript.json 中指定授權範圍。如要瞭解如何使用服務帳戶進行驗證,請參閱「以 Google Chat 應用程式身分進行驗證」。

advanced/chat.gs
/**
 * Posts a new message to the specified space on behalf of the app.
 * @param {string} spaceName The resource name of the space.
 */
function postMessageWithAppCredentials(spaceName) {
  try {
    // See https://developers.google.com/chat/api/guides/auth/service-accounts
    // for details on how to obtain a service account OAuth token.
    const appToken = getToken_();
    const message = {'text': 'Hello world!'};
    Chat.Spaces.Messages.create(
        message,
        spaceName,
        {},
        // Authenticate with the service account token.
        {'Authorization': 'Bearer ' + appToken});
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log('Failed to create message with error %s', err.message);
  }
}

取得儲存空間

下列範例示範如何取得 Chat 空間的相關資訊。

  1. chat.spaces.readonly 授權範圍新增至 Apps Script 專案的 appsscript.json 檔案:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.spaces.readonly"
    ]
    
  2. 在 Apps Script 專案的程式碼中加入類似下列的函式:

    advanced/chat.gs
    /**
     * Gets information about a Chat space.
     * @param {string} spaceName The resource name of the space.
     */
    function getSpace(spaceName) {
      try {
        const space = Chat.Spaces.get(spaceName);
        console.log('Space display name: %s', space.displayName);
        console.log('Space type: %s', space.spaceType);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log('Failed to get space with error %s', err.message);
      }
    }

建立聊天室

以下範例說明如何建立 Chat 聊天室。

  1. chat.spaces.create 授權範圍新增至 Apps Script 專案的 appsscript.json 檔案:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.spaces.create"
    ]
    
  2. 在 Apps Script 專案的程式碼中加入類似下列的函式:

    advanced/chat.gs
    /**
     * Creates a new Chat space.
     */
    function createSpace() {
      try {
        const space = {'displayName': 'New Space', 'spaceType': 'SPACE'};
        Chat.Spaces.create(space);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log('Failed to create space with error %s', err.message);
      }
    }

列出成員資格

以下範例說明如何列出 Chat 空間的所有成員。

  1. chat.memberships.readonly 授權範圍新增至 Apps Script 專案的 appsscript.json 檔案:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships.readonly"
    ]
    
  2. 在 Apps Script 專案的程式碼中加入類似下列的函式:

    advanced/chat.gs
    /**
     * Lists all the members of a Chat space.
     * @param {string} spaceName The resource name of the space.
     */
    function listMemberships(spaceName) {
      let response;
      let pageToken = null;
      try {
        do {
          response = Chat.Spaces.Members.list(spaceName, {
            pageSize: 10,
            pageToken: pageToken
          });
          if (!response.memberships || response.memberships.length === 0) {
            pageToken = response.nextPageToken;
            continue;
          }
          response.memberships.forEach((membership) => console.log(
              'Member resource name: %s (type: %s)',
              membership.name,
              membership.member.type));
          pageToken = response.nextPageToken;
        } while (pageToken);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log('Failed with error %s', err.message);
      }
    }

疑難排解

如果遇到 Error 400: invalid_scope 錯誤訊息 Some requested scopes cannot be shown,表示您未在 Apps Script 專案的 appsscript.json 檔案中指定任何授權範圍。在大多數情況下,Apps Script 會自動判斷指令碼需要的範圍,但使用 Chat 進階服務時,您必須手動將指令碼使用的授權範圍新增至 Apps Script 專案的資訊清單檔案。請參閱「設定明確範圍」。

如要解決這項錯誤,請在 oauthScopes 陣列中,將適當的授權範圍新增至 Apps Script 專案的 appsscript.json 檔案。舉例來說,如要呼叫 spaces.messages.create 方法,請新增下列項目:

"oauthScopes": [
  "https://www.googleapis.com/auth/chat.messages.create"
]

限制和注意事項

進階即時通訊服務不支援:

如要下載郵件附件或呼叫開發人員預覽版方法,請改用 UrlFetchApp