在 Google Chat 聊天室中更新用户的成员资格

本指南介绍了如何对 membership 资源使用 patch 方法 用于更改有关成员资格的属性,例如更改 将聊天室成员更改为聊天室管理员,或者将聊天室管理员更改为聊天室成员。

通过 Membership 资源 表示是否会邀请真人用户或 Google Chat 应用; 聊天室中的部分内容,或聊天室中缺失的内容。

前提条件

Python

  • Python 3.6 或更高版本
  • pip 软件包管理工具
  • 最新的 Google 客户端库。若要安装或更新这些应用 在命令行界面中运行以下命令:
    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    

Node.js

  • Node.js 14 或更高版本
  • npm 软件包管理工具
  • 最新的 Google 客户端库。若要安装或更新这些应用 在命令行界面中运行以下命令:
    npm install @google-cloud/local-auth @googleapis/chat
    

Apps 脚本

更新会员资格

如需更新聊天室成员资格,请在请求中传递以下内容:

  • 指定 chat.memberships 授权范围。
  • 调用 patch 方法 针对 Membership 资源, 并传递要更新的成员的 name,以及 updateMask 以及用于指定更新后的成员资格属性的 body
  • updateMask 指定要更新的成员资格的各个方面, 包括:
    • role:用户在 Chat 聊天室中的角色,该角色决定着用户是否可以使用 可在聊天室中执行操作。可能的值包括:
      • ROLE_MEMBER:聊天室成员。该用户拥有基本权限 比如向聊天室发送消息针对未命名的一对一群组对话 那么每个人都有这个角色。
      • ROLE_MANAGER:聊天室管理员。用户拥有所有基本权限,外加 授予管理权限,让他们可以管理聊天室,例如添加或 移除成员。仅适用于“spaceType”设为“SPACE”的聊天室 (命名的空格)。

将常规聊天室成员设为聊天室管理员

以下示例将常规聊天室成员设为聊天室管理员,方法是指定 rolebody 中以 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 脚本

此示例使用 高级聊天服务

  1. chat.memberships 授权范围添加到 Apps 脚本项目的 appsscript.json 文件:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. 将这样一个函数添加到 Apps 脚本项目的 代码:

    /**
     * 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 的实例 详细说明相关更改

将聊天室管理员设为正式成员

以下示例将聊天室管理员指定为聊天室的常规成员,方法是指定 rolebody 中以 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 脚本

此示例使用 高级聊天服务

  1. chat.memberships 授权范围添加到 Apps 脚本项目的 appsscript.json 文件:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. 将这样一个函数添加到 Apps 脚本项目的 代码:

    /**
     * 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 的实例 详细说明相关更改