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

本指南介绍了如何在 Google Chat API 的 membership 资源中使用 patch 方法来更改成员资格的相关属性,例如将聊天室成员更改为聊天室管理员,或将聊天室管理员更改为聊天室成员。

Membership 资源表示真人用户或 Google Chat 应用是受邀加入聊天室、参与聊天室还是出席聊天室。

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.memberships 授权范围进行用户身份验证;如果是将数据导入 Chat,则需要 chat.import 授权范围。

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.memberships 授权范围进行用户身份验证;如果是将数据导入 Chat,则需要 chat.import 授权范围。

Apps 脚本

更新会员资格

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

  • 指定 chat.memberships 授权范围。
  • Membership 资源调用 patch 方法,并传递要更新的成员资格的 name,以及指定更新后的成员资格属性的 updateMaskbody
  • 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 脚本

此示例使用高级聊天服务调用 Chat API。

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

    "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 实例以详细说明更改情况。

将聊天室管理员设为普通成员

以下示例将聊天室管理员设为聊天室的常规成员,具体方法是,在指定已更新的成员资格属性的 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 脚本

此示例使用高级聊天服务调用 Chat API。

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

    "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 实例以详细说明更改情况。