以 Google Chat 使用者身分進行驗證與授權

本指南說明如何使用 OAuth 2.0 和使用者的 Google 憑證,存取 Chat API。使用者憑證的驗證和授權功能可讓 Chat 應用程式存取使用者資料,並代表已驗證的使用者執行作業。應用程式可代表使用者進行驗證,因此具備與該使用者相同的權限,並能執行該使用者執行的動作。

使用者憑證驗證及授權 API 呼叫後,Chat 應用程式可執行下列操作:

  • 建立 Chat 聊天室。
  • 將使用者加入 Chat 聊天室和群組對話。
  • 使用其他 Workspace API 中的使用者資料,例如:

當應用程式執行使用者驗證動作 (例如建立聊天室) 時,Google Chat 會顯示歸因訊息,告知使用者為使用者執行該動作的應用程式名稱。

Google Chat 應用程式為使用者建立聊天室。
圖 1. Google Chat 在 Chat 應用程式代表使用者建立聊天室時,顯示的歸屬訊息。

如要進一步瞭解 Chat 擴充應用程式何時需要驗證,以及應使用哪種驗證方式,請參閱 Chat API 驗證和授權總覽中的「需要驗證的類型」。

以 Google Workspace 管理員身分進行驗證及授權

本節說明 Google Workspace 工作區管理員如何透過使用者驗證,管理機構內的 Google Chat 應用程式和聊天室。

使用全網域委派功能進行驗證和授權

如果您是網域管理員,可以授予全網域授權委派,授權應用程式的服務帳戶存取使用者資料,且不必逐一取得使用者同意。設定全網域委派後,服務帳戶可以冒用使用者帳戶。雖然服務帳戶用於驗證,但全網域委派會冒用使用者身分,因此屬於使用者驗證。您可以使用全網域委派功能,執行任何需要使用者驗證的功能。

使用管理員權限進行驗證與授權

如果您是網域管理員或具備管理員權限的委派管理員,只要在適用方法的要求中設定 useAdminAccess 欄位,即可透過管理員權限驗證並授權呼叫 Google Chat API。詳情請參閱 API 參考說明文件

請注意,當 Google Chat 應用程式以管理員權限執行動作時,Chat 不會向使用者告知執行該動作的 Chat 應用程式名稱,也不會告知授權該動作的管理員名稱,只會告訴使用者該動作是由機構管理員執行。

必要條件

Java

  • 具備 Google Chat 存取權的 Google Workspace 企業或進階版帳戶。
  • 建立 Google Cloud 專案
  • 啟用並設定 Google Chat API,並為 Chat 應用程式提供名稱、圖示和說明。
  • JDK 1.7 以上版本
  • Maven 套件管理工具
  • 已初始化的 Maven 專案。如要初始化新專案,請在指令列介面中執行下列指令:
    mvn archetype:generate -DgroupId=com.google.chat.app.authsample -DartifactId=auth-sample-app -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false

Python

Node.js

Apps Script

步驟 1:設定 OAuth 同意畫面、指定範圍,並註冊應用程式

如果您使用 OAuth 2.0 進行授權,Google 會向使用者顯示同意畫面,內容包括專案摘要、政策,以及要求的授權範圍。設定應用程式的 OAuth 同意畫面,可定義 Google 向使用者和應用程式審查人員顯示的內容,並註冊應用程式,以便日後發布。

所有使用 OAuth 2.0 的應用程式都需要同意畫面設定,但您只需要列出 Google Workspace 機構外部使用者使用的應用程式範圍。

  1. 在 Google Cloud 控制台中,依序前往「選單」圖示 >>「品牌」

    前往「品牌」

  2. 如果您已設定,則可以在「品牌」、「目標對象」和「資料存取權」中設定下列 OAuth 同意畫面設定。如果畫面上顯示「尚未設定」 ,請按一下「開始使用」

    1. 在「App Information」(應用程式資訊) 下方的「App name」(應用程式名稱) 中,輸入「App name」(應用程式名稱)
    2. 在「使用者支援電子郵件」中,選擇使用者有同意聲明相關問題時可與您聯絡的支援電子郵件地址。
    3. 點選「下一步」。
    4. 在「觀眾」下方,選取「內部」。如果無法選取「Internal」(內部),請選取「External」(外部)
    5. 點選「下一步」。
    6. 在「聯絡資訊」下方,輸入您用於接收專案異動通知的電子郵件地址。
    7. 點選「下一步」。
    8. 在「完成」下方,詳閱《Google API 服務使用者資料政策》,如果同意,請選取「我同意 Google API 服務:使用者資料政策」
    9. 按一下「繼續」
    10. 按一下「建立」
    11. 如果您選取的使用者類型為「外部」,請新增測試使用者:
      1. 按一下「目標對象」
      2. 在「測試使用者」下方,點選「新增使用者」
      3. 輸入您的電子郵件地址和其他授權測試使用者,然後按一下「儲存」
  3. 依序按一下「資料存取」>「新增或移除範圍」。面板隨即顯示您在 Google Cloud 專案中啟用的每個 API 的範圍清單。

    1. 在「手動新增範圍」下方,貼上 https://www.googleapis.com/auth/chat.spaces.create,這是執行本指南中的驗證範例所需的範圍。如要查看 Chat API 的可用範圍,請參閱驗證總覽中的「Chat API 範圍」。
    2. 按一下「新增至表格」
    3. 按一下「更新」
    4. 選取應用程式所需的範圍後,請在「資料存取」頁面中按一下「儲存」

步驟 2:在 Google Cloud 控制台中建立 OAuth 用戶端 ID 憑證

如要以使用者的身分進行驗證,並存取應用程式中的使用者資料,您需要建立一或多個 OAuth 2.0 用戶端 ID。用戶端 ID 可讓 Google 的 OAuth 伺服器識別單一應用程式。如果您的應用程式在多個平台上執行 (例如 Android、iOS 和網頁),您需要為每個平台建立專屬的用戶端 ID。

建立 OAuth 用戶端 ID 憑證

請選擇應用程式類型,查看如何建立 OAuth 用戶端 ID 的具體操作說明:

網頁應用程式

  1. 在 Google Cloud 控制台中,依序前往「選單」 >>「Clients」

    前往「客戶」

  2. 按一下「Create Client」
  3. 依序按一下「Application type」>「Web application」
  4. 在「Name」欄位中輸入憑證名稱。這個名稱只會顯示在 Google Cloud 控制台中。
  5. 新增與應用程式相關的授權 URI:
    • 用戶端應用程式 (JavaScript):在「已授權的 JavaScript 來源」下方,按一下「新增 URI」。接著,輸入要用於瀏覽器要求的 URI。這會識別應用程式可將 API 要求傳送至 OAuth 2.0 伺服器的網域。
    • 伺服器端應用程式 (Java、Python 等):按一下「Authorized redirect URIs」下方的「Add URI」。接著,輸入 OAuth 2.0 伺服器可傳送回應的端點 URI。
  6. 按一下 [Create] (建立)

    新建立的憑證會顯示在「OAuth 2.0 Client IDs」下方。

    請記下用戶端 ID。用戶端密鑰不適用於網頁應用程式。

Android

  1. 在 Google Cloud 控制台中,依序前往「選單」 >>「Clients」

    前往「客戶」

  2. 按一下「Create Client」
  3. 依序按一下「應用程式類型」>「Android」
  4. 在「名稱」欄位中輸入憑證名稱。這個名稱只會顯示在 Google Cloud 控制台中。
  5. 在「套件名稱」欄位中,輸入 AndroidManifest.xml 檔案中的套件名稱。
  6. 在「SHA-1 憑證指紋」欄位中,輸入您產生的 SHA-1 憑證指紋
  7. 按一下 [Create] (建立)

    新建立的憑證會顯示在「OAuth 2.0 用戶端 ID」下方。

iOS

  1. 在 Google Cloud 控制台中,依序前往「選單」 >>「Clients」

    前往「客戶」

  2. 按一下「Create Client」
  3. 依序按一下「應用程式類型」>「iOS」
  4. 在「名稱」欄位中輸入憑證名稱。這個名稱只會顯示在 Google Cloud 控制台中。
  5. 在「軟體包 ID」欄位中,輸入應用程式 Info.plist 檔案中列出的軟體包 ID。
  6. 選用:如果您的應用程式已在 Apple App Store 中上架,請輸入 App Store ID。
  7. 選用:在「團隊 ID」欄位中,輸入 Apple 產生並指派給您團隊的專屬字串 (共 10 個字元)。
  8. 按一下 [Create] (建立)

    新建立的憑證會顯示在「OAuth 2.0 用戶端 ID」下方。

Chrome 應用程式

  1. 在 Google Cloud 控制台中,依序前往「選單」 >>「Clients」

    前往「客戶」

  2. 按一下「Create Client」
  3. 依序按一下「應用程式類型」>「Chrome 擴充功能」
  4. 在「名稱」欄位中輸入憑證名稱。這個名稱只會顯示在 Google Cloud 控制台中。
  5. 在「項目 ID」欄位中,輸入應用程式的專屬 32 個字元 ID 字串。您可以在應用程式的 Chrome 線上應用程式商店網址和 Chrome 線上應用程式商店開發人員資訊主頁中找到這個 ID 值。
  6. 按一下 [Create] (建立)

    新建立的憑證會顯示在「OAuth 2.0 用戶端 ID」下方。

電腦版應用程式

  1. 在 Google Cloud 控制台中,依序前往「選單」 >>「Clients」

    前往「客戶」

  2. 按一下「Create Client」
  3. 依序點選「應用程式類型」>「桌面應用程式」
  4. 在「Name」欄位中輸入憑證名稱。這個名稱只會顯示在 Google Cloud 控制台中。
  5. 按一下 [Create] (建立)

    新建立的憑證會顯示在「OAuth 2.0 用戶端 ID」下方。

電視和受限制的輸入裝置

  1. 在 Google Cloud 控制台中,依序前往「選單」 >>「Clients」

    前往「客戶」

  2. 按一下「Create Client」
  3. 依序點選「應用程式類型」「電視和輸入受限的裝置」
  4. 在「名稱」欄位中輸入憑證名稱。這個名稱只會顯示在 Google Cloud 控制台中。
  5. 按一下 [Create] (建立)

    新建立的憑證會顯示在「OAuth 2.0 用戶端 ID」下方。

通用 Windows 平台 (UWP)

  1. 在 Google Cloud 控制台中,依序前往「選單」 >>「Clients」

    前往「客戶」

  2. 按一下「Create Client」
  3. 依序按一下「應用程式類型」>「通用 Windows 平台 (UWP)」
  4. 在「名稱」欄位中輸入憑證名稱。這個名稱只會顯示在 Google Cloud 控制台中。
  5. 在「商店 ID」欄位中,輸入應用程式的專屬 12 個字元 Microsoft 商店 ID 值。您可以在應用程式的 Microsoft Store 網址和 Partner Center 中找到這個 ID。
  6. 按一下 [Create] (建立)

    新建立的憑證會顯示在「OAuth 2.0 用戶端 ID」下方。

下載用戶端密鑰 JSON 檔案

用戶端密鑰檔案是 OAuth 用戶端 ID 憑證的 JSON 表示法,可供 Chat 應用程式在提供憑證時參照。

  1. 在 Google Cloud 控制台中,依序前往「選單」圖示 >「API 和服務」 >「憑證」

    前往「憑證」

  2. 在「OAuth 2.0 Client IDs」下方,點選您建立的用戶端 ID。

  3. 按一下「Download JSON」

  4. 將檔案儲存為 client_secrets.json

步驟 3:安裝 Google 用戶端程式庫和其他依附元件

安裝 Google 用戶端程式庫和專案所需的其他依附元件。

Java

如要在 Maven 專案中新增 Google 用戶端程式庫和其他必要依附元件,請編輯專案目錄中的 pom.xml 檔案,並新增下列依附元件:

<dependencies>
  <!-- ... existing dependencies ... -->
  <dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-chat</artifactId>
    <version>v1-rev20230905-2.0.0</version>
  </dependency>
  <dependency>
    <groupId>com.google.auth</groupId>
    <artifactId>google-auth-library-oauth2-http</artifactId>
    <version>1.19.0</version>
  </dependency>
  <dependency>
    <groupId>com.google.oauth-client</groupId>
    <artifactId>google-oauth-client-jetty</artifactId>
    <version>1.34.1</version>
  </dependency>
  <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.10.1</version>
  </dependency>
</dependencies>

Python

如果您尚未安裝 Python 適用的 Google 用戶端程式庫,請在指令列介面中執行下列指令:

pip3 install --upgrade google-api-python-client google-auth-oauthlib

Node.js

如要在 Node.js 專案中新增 Google 用戶端程式庫和其他必要依附元件,請切換至專案目錄,然後在指令列介面中執行下列指令:

npm install "@googleapis/chat" open server-destroy

Apps Script

這個範例會使用進階 Chat 服務呼叫 Google Chat API。如要為 Apps Script 專案啟用服務,請按照下列步驟操作:

  1. 按一下左側的「編輯器」圖示
  2. 在左側的「服務」旁,按一下「新增服務」圖示
  3. 選取「Google Chat API」
  4. 在「Version」中,選取「v1」
  5. 按一下 [新增]。

您可以使用用戶端程式庫支援的任何語言。

步驟 4:編寫呼叫 Chat API 的指令碼

使用 OAuth 授權呼叫 API 是一項多步驟程序。在網頁或電腦應用程式中,這個程序通常如下:

  1. 應用程式會將使用者導向至授權頁面,要求存取授權範圍指定的使用者資料。應用程式會使用用戶端 ID 憑證識別自身。
  2. 使用者會查看應用程式要求的權限,並核准要求。
  3. Google 驗證伺服器會將瀏覽器重新導向至應用程式的 HTTP 端點,並傳送授權碼。
  4. 應用程式會向 Google 授權伺服器傳送另一項要求,以便將授權碼換成存取權杖。
  5. 應用程式會使用存取權杖,代表使用者呼叫 API。

如要進一步瞭解 OAuth 授權程序,請參閱「使用 OAuth 2.0 存取 Google API 指南」。

以下 Java、Python 和 Node.js 程式碼範例使用用戶端程式庫執行 OAuth 授權流程。它會開啟本機 HTTP 伺服器,以便接收授權伺服器傳回的授權碼,然後交換存取權杖。在 Apps Script 程式碼範例中,這個授權流程由 Apps Script 處理。

完成驗證流程後,指令碼會使用使用者的存取權權杖,透過 Chat API 進行驗證,然後建立聊天室。

Java

  1. 在專案目錄中,開啟 src/main/java/com/google/chat/app/authsample/App.java 檔案。
  2. 使用下列程式碼取代 App.java 中的內容:

    package com.google.chat.app.authsample;
    
    import com.google.api.client.auth.oauth2.Credential;
    import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
    import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
    import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
    import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.gson.GsonFactory;
    import com.google.api.client.util.store.FileDataStoreFactory;
    import com.google.api.services.chat.v1.HangoutsChat;
    import com.google.api.services.chat.v1.model.Space;
    
    import java.io.InputStreamReader;
    import java.util.Collection;
    import java.util.Collections;
    
    /**
     * Authenticates with Chat API via user credentials, then creates a Chat space.
     */
    public class App {
        // Application OAuth credentials.
        private static final String KEYS_RESOURCE_URI = "/client_secrets.json";
    
        // Define your app's authorization scopes.
        private static final Collection<String> SCOPES =
            Collections.singleton("https://www.googleapis.com/auth/chat.spaces.create");
    
        // Directory to store user credentials.
        private static final java.io.File DATA_STORE_DIR =
            new java.io.File(System.getProperty("user.home"), ".store/auth-sample-app");
    
        // Global instance of the JSON factory.
        private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    
        // Global instance of the HTTP transport.
        private static HttpTransport httpTransport;
    
        // Global instance of the DataStoreFactory. The best practice is to make it a single
        // globally shared instance across your application.
        private static FileDataStoreFactory dataStoreFactory;
    
        public static void main( String[] args ) {
            try {
                // Run app.
                httpTransport = GoogleNetHttpTransport.newTrustedTransport();
                dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
                Credential userCredential = authorize();
                Space response = App.createChatSpace(userCredential);
                // Print details about the created space.
                System.out.println(response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * Authorizes the installed application to access user's protected data.
         */
        private static Credential authorize() throws Exception {
            // Load client secrets.
            GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
                new InputStreamReader(App.class.getResourceAsStream("/client_secrets.json")));
            // Set up authorization code flow.
            GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                httpTransport, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(dataStoreFactory)
                .build();
            // Authorize.
            return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
        }
    
        /**
         * Creates a Chat space.
         */
        private static Space createChatSpace(Credential userCredential) throws Exception {
            // Build the Chat API client and authenticate with the user account.
            HangoutsChat chatService = new HangoutsChat.Builder(
                httpTransport, JSON_FACTORY, userCredential)
                .setApplicationName("auth-sample-app")
                .build();
    
            // Create a Chat space.
            Space space = new Space()
                // To create a named space, set spaceType to SPACE.
                .setSpaceType("SPACE")
                // The user-visible name of the space.
                .setDisplayName("API-made");
            return chatService.spaces().create(space).execute();
        }
    }
    
  3. 在專案目錄中建立名為 resources 的新子目錄。

  4. client_secrets.json 檔案複製到 resources 子目錄。

  5. 如要設定 Maven 在專案套件中加入用戶端機密檔案,請編輯專案目錄中的 pom.xml 檔案,然後將以下設定新增至 <build> 區段:

    <build>
      <!-- ... existing configurations ... -->
      <resources>
        <resource>
          <directory>resources</directory>
        </resource>
      </resources>
    </build>
    
  6. 如要設定 Maven 以納入專案套件中的依附元件,並執行應用程式的主類別,請編輯專案目錄中的 pom.xml 檔案,並在 <plugins> 區段中新增下列設定:

    <plugins>
      <!-- ... existing configurations ... -->
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.google.chat.app.authsample.App</mainClass>
            </manifest>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
      </plugin>
    </plugins>
    

Python

  1. 將以下程式碼儲存至名為 chat_space_create_named.py 的檔案中,該檔案必須儲存在含有 client_secrets.json 的相同目錄中:

    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    
    # Define your app's authorization scopes.
    # When modifying these scopes, delete the file token.json, if it exists.
    SCOPES = ["https://www.googleapis.com/auth/chat.spaces.create"]
    
    def main():
      '''
      Authenticates with Chat API via user credentials,
      then creates a Chat space.
      '''
    
      flow = InstalledAppFlow.from_client_secrets_file(
                        'client_secrets.json', SCOPES)
      creds = flow.run_local_server()
    
      # Build a service endpoint for Chat API.
      service = build('chat', 'v1', credentials=creds)
    
      # Use the service endpoint to call Chat API.
      result = service.spaces().create(
    
        # Details about the space to create.
        body = {
    
          # To create a named space, set spaceType to SPACE.
          'spaceType': 'SPACE',
    
          # The user-visible name of the space.
          'displayName': 'API-made'
    
        }
    
      ).execute()
    
      # Prints details about the created space.
      print(result)
    
    if __name__ == '__main__':
      main()
    

Node.js

  1. 將以下程式碼儲存至名為 chat_space_create_named.js 的檔案中,該檔案必須儲存在儲存 Node.js 專案和 client_secrets.json 的相同目錄中:

    const fs = require('fs');
    const path = require('path');
    const http = require('http');
    const url = require('url');
    const destroyer = require('server-destroy');
    
    const chat = require('@googleapis/chat');
    
    // Application OAuth credentials.
    const keys = require('./client_secrets.json').installed;
    
    // Define your app's authorization scopes.
    // When modifying these scopes, delete the file token.json, if it exists.
    const scopes = ["https://www.googleapis.com/auth/chat.spaces.create"];
    
    // Create a new OAuth2 client with the configured keys.
    const oauth2Client = new chat.auth.OAuth2(
      keys.client_id,
      keys.client_secret,
      'http://localhost:3000'
    );
    
    /**
     * Opens an HTTP server to accept the OAuth callback.
     * In this simple example, the only request to our webserver is to /?code=<code>.
     */
    async function authenticate(scopes) {
      const opn = (await import('open')).default;
    
      return new Promise((resolve, reject) => {
        // Generate the URL for authorization.
        const authorizeUrl = oauth2Client.generateAuthUrl({
          access_type: 'offline',
          scope: scopes.join(' '),
        });
        // Start the HTTP server to listen for the callback.
        const server = http
          .createServer(async (req, res) => {
            try {
              const qs = new url.URL(req.url, 'http://localhost:3000').searchParams;
              res.end('Authentication successful! Please return to the console.');
              server.destroy();
              const { tokens } = await oauth2Client.getToken(qs.get('code'));
              oauth2Client.credentials = tokens;
              resolve(oauth2Client);
            } catch (e) {
              reject(e);
            }
          })
          .listen(3000, () => {
            // Open the browser to the authorize URL to start the workflow.
            opn(authorizeUrl, { wait: false }).then(cp => cp.unref());
          });
        destroyer(server);
      });
    }
    
    /**
     * Authenticates with Chat API via user credentials, then creates a Chat space.
     */
    async function createSpace() {
      // Create the Chat API client and authenticate with the authorized user.
      const chatClient = await chat.chat({
        version: 'v1',
        auth: oauth2Client
      });
    
      // Call the Chat API to create a space.
      const result = await chatClient.spaces.create({
    
        // Details about the space to create.
        requestBody: {
    
          // To create a named space, set spaceType to SPACE.
          'spaceType': 'SPACE',
    
          // The user-visible name of the space.
          'displayName': 'API-made'
    
        }
    
      });
      return result;
    }
    
    // Authenticate the user, execute the function,
    // then print details about the created space.
    authenticate(scopes)
      .then(createSpace)
      .then(console.log);
    

Apps Script

  1. 在 Apps Script 編輯器中,編輯 appsscript.json 檔案,並新增呼叫 API 所需的 OAuth 範圍:

      "oauthScopes": [
        "https://www.googleapis.com/auth/chat.spaces.create"
      ]
    
  2. 將下列程式碼儲存至 Apps Script 專案中名為 ChatSpaceCreateNamed.gs 的檔案:

    /**
     * Authenticates with Chat API via user credentials, then creates a
     * Chat space.
     */
    function createSpace() {
      try {
        // Details about the space to create.
        // To create a named space, set spaceType to SPACE.
        // The user-visible name of the space is displayName.
        const space = {'displayName': 'API-made', 'spaceType': 'SPACE'};
    
        // Call Chat API with user credentials to create the space.
        const result = Chat.Spaces.create(space);
    
        // Log details about the created space.
        console.log(result);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log('Failed to create space with error %s', err.message);
      }
    }
    

步驟 5:執行範例指令碼

如要執行範例,請從指令列前往儲存專案檔案的目錄,然後執行下列指令:

Java

mvn compile assembly:single
java -jar target/auth-sample-app-1.0-SNAPSHOT-jar-with-dependencies.jar

Python

python3 chat_space_create_named.py

Node.js

node chat_space_create_named.js

Apps Script

在 Apps Script 編輯器中開啟檔案 ChatSpaceCreateNamed.gs,然後按一下「Run」

瀏覽器會隨即開啟,並提示您登入 Google 帳戶:

登入帳戶授權 Chat 應用程式。

圖 2. OAuth 同意畫面,您可以在其中選取要驗證應用程式的帳戶。

登入後,系統會顯示 OAuth 同意畫面,要求您授予應用程式權限。

授予權限後,指令碼會呼叫 Chat API,並回應建立顯示名稱為 API-made 的 Chat 聊天室。主控台會列印 API 呼叫的詳細資料。如要查看聊天室,請前往 Google Chat 的「聊天室」面板。

排解範例問題

執行 chat_space_create_named.py 時,您可能會收到以下錯誤訊息:

Expected a JSON object with a single property for a "web" or "installed" application

這則錯誤訊息表示您從 Google Cloud 控制台下載的 client_secrets.json 檔案並未以 "web""installed" 屬性開頭。使用下載的檔案進行驗證後,如果程式碼未將存取權杖儲存在 token.json 等新檔案中,則存取權杖會寫入 client_secrets.json,這可能會在後續授權嘗試期間導致此錯誤。

如要解決這項錯誤,請再次從 Google Cloud 控制台下載用戶端機密金鑰檔案,然後將新檔案儲存在目前檔案的位置。