設定有初始成員的聊天室

本指南說明如何在 Google Chat API 的 Space 資源上使用 setup 方法,設定 Google Chat 聊天室。設定聊天室後,系統會建立聊天室,並將特定使用者加入聊天室。

Space 資源代表使用者和 Chat 應用程式可以傳送訊息、共用檔案及協同合作的地方。聊天室分為幾種類型:

  • 即時訊息 (DM) 是兩個使用者或使用者和 Chat 應用程式之間的對話。
  • 群組通訊是三位以上的使用者和 Chat 應用程式之間的對話。
  • 已命名的聊天室是永久供使用者傳送訊息、分享檔案及協同合作的地方。

設定聊天室時,請注意下列事項:

  • 呼叫 (已驗證) 使用者會自動新增至聊天室,因此您不必在要求中指定使用者的成員資格。
  • 在建立即時訊息 (DM) 時,如果兩個使用者之間存在即時訊息,系統會傳回 DM。否則,系統會建立即時訊息。
  • 建立群組通訊時,如果要求中提供的成員都未成功加入群組通訊 (例如權限問題),系統可能會建立空白的群組通訊 (包括只有發出呼叫的使用者)。
  • 您無法設定含有討論串回覆的聊天室,也無法新增 Google Workspace 以外的使用者。
  • 系統會篩除要求中提供的重複成員資格 (包括發出呼叫的使用者),而非導致要求錯誤。

必要條件

Python

  • Python 3.6 或更高版本
  • pip 套件管理工具
  • 最新的 Python 專用 Google 用戶端程式庫。如要安裝或更新,請在指令列介面中執行下列指令:

    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    
  • 已啟用並設定 Google Chat API 的 Google Cloud 專案。相關步驟請參閱「建構 Google Chat 應用程式」。
  • 已為 Chat 應用程式設定授權。設定聊天室時,您必須使用 chat.spaces.createchat.spaces 授權範圍使用者驗證

Node.js

  • Node.js 與 npm
  • 最新的 Node.js 專用 Google 用戶端程式庫。如要安裝,請在指令列介面中執行下列指令:

    npm install @google-cloud/local-auth @googleapis/chat
    
  • 已啟用並設定 Google Chat API 的 Google Cloud 專案。相關步驟請參閱「建構 Google Chat 應用程式」。
  • 已為 Chat 應用程式設定授權。建立聊天室需要使用 chat.spaces.createchat.spaces 授權範圍使用者驗證

設定聊天室

如要設定聊天室,請在要求中傳遞以下內容:

  • 指定 chat.spaces.createchat.spaces 授權範圍。
  • 呼叫 Space 資源上的 setup 方法
  • 如要將人類使用者新增為聊天室成員,請指定 users/{user},其中 {user} 是 People API 中 person{person_id},或 Directory API 中 user 的 ID。舉例來說,如果 People API 使用者 resourceNamepeople/123456789,您就可以加入擁有 users/123456789 做為 member.name 的成員,將使用者新增至聊天室。
  • 如要在發出呼叫的使用者和另一位真人使用者之間建立即時訊息,請在要求中指定真人使用者的成員資格。
  • 如要在發出呼叫的使用者和呼叫應用程式之間建立即時訊息,請將 Space.singleUserBotDm 設為 true,且不要指定任何成員。您只能使用這個方法,透過呼叫應用程式設定即時訊息。如要將呼叫應用程式新增為聊天室成員,或兩位真人使用者之間的現有即時訊息,請參閱「建立成員資格」。

以下範例會建立已命名的聊天室,並為三位人類 (已驗證的使用者) 和另外兩名指定使用者建立該空間的成員資格:

Python

  1. 在工作目錄中,建立名為 chat_space_setup.py 的檔案。
  2. chat_space_setup.py 中加入下列程式碼:

    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 sets up a Chat space by creating a space and adding members.
        '''
    
        # Authenticate with Google Workspace
        # and get user authorization.
        flow = InstalledAppFlow.from_client_secrets_file(
                          'client_secrets.json', SCOPES)
        creds = flow.run_local_server()
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds)
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().setup(
    
          # Details about the space to set up.
          body = {
    
            # Attributes of the space to set up, like space type and display name.
            'space': {
    
                # To set up a named space, set spaceType to SPACE.
                'spaceType': 'SPACE',
    
                # The user-visible name of the space
                'displayName': 'API-setup'
            },
    
            # The people and app to add to the space.
            #
            # The authenticated user is automatically added to the space,
            # and doesn't need to be specified in the memberships array.
            'memberships': [
                {
                  'member': {
                    'name':'users/123456789',
                    'type': 'HUMAN'
                  }
                },
                {
                  'member': {
                    'name':'users/987654321',
                    'type': 'HUMAN'
                  }
                }
            ]
          }
    
          ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 在工作目錄中,建構並執行範例:

    python3 chat_space_setup.py
    

Node.js

  1. 在工作目錄中,建立名為 setup-space.js 的檔案。
  2. setup-space.js 中加入下列程式碼:

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Sets up a new Chat space with users.
    * @return {!Promise<!Object>}
    */
    async function setupSpace() {
      const scopes = [
        'https://www.googleapis.com/auth/chat.spaces.create',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      return await chatClient.spaces.setup({
        requestBody: {
          space: {
            spaceType: 'SPACE',
            displayName: 'API-made',
          },
          memberships: [
            {member: {name: 'users/123456789', type: 'HUMAN'}},
            {member: {name: 'users/987654321', type: 'HUMAN'}},
          ]
        }
      });
    }
    
    setupSpace().then(console.log);
    
  3. 在工作目錄中,執行範例:

    node setup-space.js
    

已設定一個已命名的聊天室,其中有三位使用者 (包括已驗證的使用者)。

如要前往聊天室,請使用聊天室的資源 ID 建立聊天室網址。您可以從 Google Chat 回應主體中從聊天室 name 取得資源 ID。舉例來說,如果聊天室的 namespaces/1234567,您可以使用以下網址前往該聊天室:https://mail.google.com/chat/u/0/#chat/space/1234567