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 modificare gli attributi di un'iscrizione, ad esempio cambiare un membro dello spazio in gestore dello spazio o cambiare un gestore in un membro dello spazio.

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

Python

  • Python 3.6 o versioni successive
  • Lo strumento di gestione dei pacchetti pip
  • Le librerie client di Google più recenti per Python. Per installarli o aggiornarli, esegui questo comando nell'interfaccia a riga di comando:

    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    
  • Un progetto Google Cloud in cui l'API Google Chat è abilitata e configurata. Per i passaggi da seguire, consulta Creare un'app Google Chat.
  • Autorizzazione configurata per l'app di Chat. L'aggiornamento di un'iscrizione richiede l'autenticazione degli utenti con l'ambito di autorizzazione chat.memberships o, in caso di importazione di dati in Chat, l'ambito di autorizzazione chat.import.

Node.js

  • Node.js e npm
  • Le librerie client di Google più recenti per Node.js. Per installarle, esegui questo comando nell'interfaccia a riga di comando:

    npm install @google-cloud/local-auth @googleapis/chat
    
  • Un progetto Google Cloud in cui l'API Google Chat è abilitata e configurata. Per i passaggi da seguire, consulta Creare un'app Google Chat.
  • Autorizzazione configurata per l'app di Chat. L'aggiornamento di un'iscrizione richiede l'autenticazione degli utenti con l'ambito di autorizzazione chat.memberships o, in caso di importazione di dati in Chat, l'ambito di autorizzazione chat.import.

Apps Script

Aggiornare un abbonamento

Per aggiornare un'iscrizione a uno spazio, trasmetti quanto segue nella richiesta:

  • Specifica l'ambito dell'autorizzazione chat.memberships.
  • Chiama il metodo patch sulla risorsa Membership e passa il name dell'appartenenza da aggiornare, nonché un updateMask e un body che specificano gli attributi di appartenenza aggiornati.
  • L'updateMask specifica gli aspetti dell'abbonamento da aggiornare e include quanto segue:
    • role: il ruolo dell'utente all'interno di uno spazio di Chat, che determina le azioni consentite nello spazio. I valori possibili sono:
      • ROLE_MEMBER: un membro dello spazio. L'utente dispone delle autorizzazioni di base, come l'invio di messaggi allo spazio. Nelle conversazioni 1:1 e di gruppo senza nome, tutti hanno questo ruolo.
      • ROLE_MANAGER: un gestore dello spazio. L'utente dispone di tutte le autorizzazioni di base e delle autorizzazioni amministrative che consentono di gestire lo spazio, come l'aggiunta o la rimozione dei membri. Funzionalità supportata solo negli spazi in cui spaceType è SPACE (spazi con nome).

Impostare un membro regolare dello spazio come gestore dello spazio

Nell'esempio seguente, un membro normale dello spazio diventa gestore dello spazio specificando role come ROLE_MANAGER nel campo body che specifica gli attributi di appartenenza aggiornati:

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. Sostituisci quanto segue nel codice:

  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. Sostituisci quanto segue nel codice:

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

    python3 chat_membership_update.js
    

Apps Script

Questo esempio chiama l'API Chat utilizzando il 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 al codice del progetto 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);
      }
    }
    

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

Impostare un gestore dello spazio come membro regolare

Nell'esempio seguente, un gestore dello spazio diventa un membro normale dello spazio specificando role come ROLE_MEMBER nel criterio body, che specifica gli attributi di appartenenza aggiornati:

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. Sostituisci quanto segue nel codice:

  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. Sostituisci quanto segue nel codice:

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

    python3 chat_membership_update.js
    

Apps Script

Questo esempio chiama l'API Chat utilizzando il 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 al codice del progetto 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);
      }
    }
    

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