Update a user's membership in a Google Chat space

This guide explains how to use the patch method on the membership resource of the Google Chat API to change attributes about a membership, like changing a space member to a space manager, or changing a space manager to a space member.

The Membership resource represents whether a human user or Google Chat app is invited to, part of, or absent from a space.

Python

  • Python 3.6 or greater
  • The pip package management tool
  • The latest Google client libraries for Python. To install or update them, run the following command in your command-line interface:

    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    
  • A Google Cloud project with the Google Chat API enabled and configured. For steps, see Build a Google Chat app.
  • Authorization configured for the Chat app. Updating a membership requires User authentication with the chat.memberships authorization scope, or, if importing data into Chat, the chat.import authorization scope.

Node.js

  • Node.js & npm
  • The latest Google client libraries for Node.js. To install them, run the following command in your command-line interface:

    npm install @google-cloud/local-auth @googleapis/chat
    
  • A Google Cloud project with the Google Chat API enabled and configured. For steps, see Build a Google Chat app.
  • Authorization configured for the Chat app. Updating a membership requires User authentication with the chat.memberships authorization scope, or, if importing data into Chat, the chat.import authorization scope.

Apps Script

Update a membership

To update a space membership, pass the following in your request:

  • Specify the chat.memberships authorization scope.
  • Call the patch method on the Membership resource, and pass the name of the membership to update, as well as an updateMask and a body that specifies the updated membership attributes.
  • The updateMask specifies the aspects of the membership to update, and includes the following:
    • role: User's role within a Chat space, which determines their permitted actions in the space. Possible values are:
      • ROLE_MEMBER: A member of the space. The user has basic permissions, like sending messages to the space. In 1:1 and unnamed group conversations, everyone has this role.
      • ROLE_MANAGER: A space manager. The user has all basic permissions plus administrative permissions that let them manage the space, like adding or removing members. Only supported in spaces where spaceType is SPACE (named spaces).

Make a regular space member a space manager

The following example makes a regular space member a space manager by specifying role as ROLE_MANAGER in the body that specifies updated membership attributes:

Python

  1. In your working directory, create a file named chat_membership_update.py.
  2. Include the following code in 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. In the code, replace the following:

  4. In your working directory, build and run the sample:

    python3 chat_membership_update.py
    

Node.js

  1. In your working directory, create a file named chat_membership_update.js.
  2. Include the following code in 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. In the code, replace the following:

  4. In your working directory, build and run the sample:

    python3 chat_membership_update.js
    

Apps Script

This example calls the Chat API using the Advanced Chat Service.

  1. Add the chat.memberships authorization scope to the Apps Script project's appsscript.json file:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. Add a function like this one to the Apps Script project's code:

    /**
     * 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);
      }
    }
    

The Google Chat API changes the specified membership to a space manager and returns an instance of Membership detailing the change.

Make a space manager a regular member

The following example makes a space manager a regular space member by specifying role as ROLE_MEMBER in the body that specifies updated membership attributes:

Python

  1. In your working directory, create a file named chat_membership_update.py.
  2. Include the following code in 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. In the code, replace the following:

  4. In your working directory, build and run the sample:

    python3 chat_membership_update.py
    

Node.js

  1. In your working directory, create a file named chat_membership_update.js.
  2. Include the following code in 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. In the code, replace the following:

  4. In your working directory, build and run the sample:

    python3 chat_membership_update.js
    

Apps Script

This example calls the Chat API using the Advanced Chat Service.

  1. Add the chat.memberships authorization scope to the Apps Script project's appsscript.json file:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. Add a function like this one to the Apps Script project's code:

    /**
     * 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);
      }
    }
    

The Google Chat API changes the specified membership to a space manager and returns an instance of Membership detailing the change.