更新 Google Chat 聊天室中的使用者和成員身分

本指南說明如何針對 membership 資源使用 patch 方法 Google Chat API 的套件,可變更成員資格屬性,例如變更 從聊天室成員擔任聊天室管理員,或是將聊天室管理員變更為聊天室成員。

Membership 項資源 代表受邀參加的使用者或 Google Chat 應用程式 屬於或不存在於空格中。

必要條件

Python

Node.js

Apps Script

更新會員方案

如要更新聊天室成員資格,請在要求中傳遞以下內容:

  • 指定 chat.memberships 授權範圍。
  • patch 方法Membership 資源執行動作 並傳遞會員的 name 來更新,以及 updateMask 以及指定已更新成員屬性的 body
  • updateMask 會指定要更新成員資格的各個層面,以及 包含下列項目:
    • role:使用者在 Chat 聊天室中的角色 (決定使用者允許哪些權限) 聊天室中執行的動作。可能的值包括:
      • ROLE_MEMBER:聊天室成員。使用者俱備基本權限 例如傳送訊息到聊天室在 1:1 和未命名的群組中 每個人都具備這個角色
      • ROLE_MANAGER:聊天室管理員。使用者擁有所有基本權限 讓他們管理聊天室的管理員權限,例如新增或 正在移除成員僅適用於 spaceTypeSPACE 的聊天室 (已命名的空格)。

將一般聊天室成員設為聊天室管理員

以下範例會將一般聊天室成員指定為聊天室管理員 在 body 中將 role 視為 ROLE_MANAGER,並指定更新後的成員 屬性:

Python

  1. 在工作目錄中,建立名為 chat_membership_update.py 的檔案。
  2. chat_membership_update.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.memberships"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then updates a specified space member to change
        it from a regular member to a space manager.
        '''
    
        # 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().members().patch(
    
            # The membership to update, and the updated role.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            #
            # Replace MEMBERSHIP with a membership name.
            # Obtain the membership name from the membership of Chat API.
            name='spaces/SPACE/members/MEMBERSHIP',
            updateMask='role',
            body={'role': 'ROLE_MANAGER'}
    
          ).execute()
    
        # Prints details about the updated membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 請在程式碼中替換下列內容:

  4. 在工作目錄中建構並執行範例:

    python3 chat_membership_update.py
    

Node.js

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

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Updates a membership in a Chat space to change it from
    * a space member to a space manager.
    * @return {!Promise<!Object>}
    */
    async function updateSpace() {
    
      /**
      * Authenticate with Google Workspace
      * and get user authorization.
      */
      const scopes = [
        'https://www.googleapis.com/auth/chat.memberships',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      /**
      * Build a service endpoint for Chat API.
      */
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      /**
      * Use the service endpoint to call Chat API.
      */
      return await chatClient.spaces.patch({
    
        /**
        * The membership to update, and the updated role.
        *
        * Replace SPACE with a space name.
        * Obtain the space name from the spaces resource of Chat API,
        * or from a space's URL.
        *
        * Replace MEMBERSHIP with a membership name.
        * Obtain the membership name from the membership of Chat API.
        */
        name: 'spaces/SPACE/members/MEMBERSHIP',
        updateMask: 'role',
        requestBody: {
          role: 'ROLE_MANAGER'
        }
      });
    }
    
    /**
    * Use the service endpoint to call Chat API.
    */
    updateSpace().then(console.log);
    
  3. 請在程式碼中替換下列內容:

  4. 在工作目錄中建構並執行範例:

    python3 chat_membership_update.js
    

Apps Script

本範例使用 進階 Chat 服務

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

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. 將像這樣的函式新增至 Apps Script 專案的 程式碼:

    /**
     * Updates a membership from space member to space manager.
     * @param {string} memberName The resource name of the membership.
    */
    function updateMembershipToSpaceManager(memberName) {
      try {
        const body = {'role': 'ROLE_MANAGER'};
        Chat.Spaces.Members.patch(memberName, body);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log('Failed to create message with error %s', err.message);
      }
    }
    

Google Chat API 會將指定成員資格變更為聊天室管理員,並傳回 Membership 的執行個體 詳細說明變更

將聊天室管理員設為一般成員

以下範例會指定聊天室管理員,並將其設為一般聊天室成員 在 body 中將 role 視為 ROLE_MEMBER,並指定更新後的成員 屬性:

Python

  1. 在工作目錄中,建立名為 chat_membership_update.py 的檔案。
  2. chat_membership_update.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.memberships"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then updates a specified space member to change
        it from a regular member to a space manager.
        '''
    
        # 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().members().patch(
    
            # The membership to update, and the updated role.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            #
            # Replace MEMBERSHIP with a membership name.
            # Obtain the membership name from the membership of Chat API.
            name='spaces/SPACE/members/MEMBERSHIP',
            updateMask='role',
            body={'role': 'ROLE_MEMBER'}
    
          ).execute()
    
        # Prints details about the updated membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 請在程式碼中替換下列內容:

  4. 在工作目錄中建構並執行範例:

    python3 chat_membership_update.py
    

Node.js

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

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Updates a membership in a Chat space to change it from
    * a space manager to a space member.
    * @return {!Promise<!Object>}
    */
    async function updateSpace() {
    
      /**
      * Authenticate with Google Workspace
      * and get user authorization.
      */
      const scopes = [
        'https://www.googleapis.com/auth/chat.memberships',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      /**
      * Build a service endpoint for Chat API.
      */
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      /**
      * Use the service endpoint to call Chat API.
      */
      return await chatClient.spaces.patch({
    
        /**
        * The membership to update, and the updated role.
        *
        * Replace SPACE with a space name.
        * Obtain the space name from the spaces resource of Chat API,
        * or from a space's URL.
        *
        * Replace MEMBERSHIP with a membership name.
        * Obtain the membership name from the membership of Chat API.
        */
        name: 'spaces/SPACE/members/MEMBERSHIP',
        updateMask: 'role',
        requestBody: {
          role: 'ROLE_MEMBER'
        }
      });
    }
    
    /**
    * Use the service endpoint to call Chat API.
    */
    updateSpace().then(console.log);
    
  3. 請在程式碼中替換下列內容:

  4. 在工作目錄中建構並執行範例:

    python3 chat_membership_update.js
    

Apps Script

本範例使用 進階 Chat 服務

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

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. 將像這樣的函式新增至 Apps Script 專案的 程式碼:

    /**
     * Updates a membership from space manager to space member.
     * @param {string} memberName The resource name of the membership.
    */
    function updateMembershipToSpaceMember(memberName) {
      try {
        const body = {'role': 'ROLE_MEMBER'};
        Chat.Spaces.Members.patch(memberName, body);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log('Failed to create message with error %s', err.message);
      }
    }
    

Google Chat API 會將指定成員資格變更為聊天室管理員,並傳回 Membership 的執行個體 詳細說明變更