Aggiornare l'iscrizione di un utente a uno spazio di Google Chat

Questa guida spiega come utilizzare il metodo patch nella risorsa membership dell'API Google Chat per cambiare gli attributi di un abbonamento, ad esempio cambiando a gestore dello spazio o la modifica di un gestore dello spazio in membro dello spazio.

La Membership risorsa indica se un utente umano o un'app Google Chat è invitato, parte di o assente in uno spazio.

Prerequisiti

Python

  • Python 3.6 o versioni successive
  • Lo strumento di gestione dei pacchetti pip
  • Le librerie client di Google più recenti. Per installarle o aggiornarle, esegui questo comando nell'interfaccia a riga di comando:
    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    

Node.js

  • Node.js 14 o versioni successive
  • npm strumento di gestione dei pacchetti
  • Le librerie client di Google più recenti. Per installarle o aggiornarle, esegui questo comando nell'interfaccia a riga di comando:
    npm install @google-cloud/local-auth @googleapis/chat
    

Apps Script

Aggiornare un abbonamento

Per aggiornare l'appartenenza a uno spazio, inserisci quanto segue nella richiesta:

  • Specifica l'ambito dell'autorizzazione chat.memberships.
  • Chiama il Metodo patch sulla risorsa Membership, e superare il name dell'abbonamento da aggiornare, oltre a un updateMask e un body che specifica gli attributi di appartenenza aggiornati.
  • L'updateMask specifica gli aspetti dell'abbonamento da aggiornare. include:
    • role: il ruolo dell'utente all'interno di uno spazio di Chat, che ne determina la possibilità azioni nello spazio. I valori possibili sono:
      • ROLE_MEMBER: un membro dello spazio. L'utente dispone di autorizzazioni di base, ad esempio inviare messaggi allo spazio. In un gruppo 1:1 e senza nome tutte le conversazioni hanno questo ruolo.
      • ROLE_MANAGER: un gestore dello spazio. L'utente dispone di tutte le autorizzazioni di base più autorizzazioni amministrative che gli consentono di gestire lo spazio, come l'aggiunta o rimuovendo membri. Supportata solo negli spazi in cui spaceType è SPACE (spazi con nome).

Impostare un normale membro dello spazio come gestore dello spazio

Nell'esempio seguente, un membro normale dello spazio diventa un gestore dello spazio specificando role come ROLE_MANAGER nel body che specifica un abbonamento aggiornato attributi:

Python

  1. Nella directory di lavoro, crea un file denominato chat_membership_update.py.
  2. Includi il seguente codice 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. Nel codice, sostituisci quanto segue:

  4. Nella directory di lavoro, crea ed esegui l'esempio:

    python3 chat_membership_update.py
    

Node.js

  1. Nella directory di lavoro, crea un file denominato chat_membership_update.js.
  2. Includi il seguente codice 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. Nel codice, sostituisci quanto segue:

  4. Nella directory di lavoro, crea ed esegui l'esempio:

    python3 chat_membership_update.js
    

Apps Script

In questo esempio viene chiamata l'API Chat utilizzando Servizio Chat avanzato.

  1. Aggiungi l'ambito dell'autorizzazione chat.memberships al File appsscript.json del progetto Apps Script:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. Aggiungi una funzione come questa all'interfaccia codice:

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

L'API Google Chat modifica l'appartenenza specificata in un gestore dello spazio e restituisce un'istanza di Membership che descrive nel dettaglio la modifica.

Impostare un gestore dello spazio come normale membro

Nell'esempio seguente, un gestore dello spazio diventa un normale membro dello spazio specificando role come ROLE_MEMBER nel body che specifica un abbonamento aggiornato attributi:

Python

  1. Nella directory di lavoro, crea un file denominato chat_membership_update.py.
  2. Includi il seguente codice 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. Nel codice, sostituisci quanto segue:

  4. Nella directory di lavoro, crea ed esegui l'esempio:

    python3 chat_membership_update.py
    

Node.js

  1. Nella directory di lavoro, crea un file denominato chat_membership_update.js.
  2. Includi il seguente codice 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. Nel codice, sostituisci quanto segue:

  4. Nella directory di lavoro, crea ed esegui l'esempio:

    python3 chat_membership_update.js
    

Apps Script

In questo esempio viene chiamata l'API Chat utilizzando Servizio Chat avanzato.

  1. Aggiungi l'ambito dell'autorizzazione chat.memberships al File appsscript.json del progetto Apps Script:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. Aggiungi una funzione come questa all'interfaccia codice:

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

L'API Google Chat modifica l'appartenenza specificata in un gestore dello spazio e restituisce un'istanza di Membership che descrive nel dettaglio la modifica.