Invitare o aggiungere un utente, un gruppo Google o un'app Google Chat a uno spazio

Questa guida spiega come utilizzare il metodo create nella risorsa membership dell'API Google Chat per invitare o aggiungere un utente, un gruppo Google o all'app di Chat in uno spazio noto anche come creazione di . Durante la creazione di un abbonamento, se il membro specificato ha i suoi l'accettazione automatica della norma è disattivata, l'utente verrà invitato e dovrà accettare lo spazio un invito prima di partecipare. Altrimenti, se crei un abbonamento, il membro verrà aggiunto. direttamente nello spazio specificato.

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
  • Il pip strumento di gestione dei pacchetti
  • Le librerie client di Google più recenti per Python. Per installarle o aggiornarle, esegui questo comando nell'interfaccia a riga di comando:

    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    
  • Un progetto Google Cloud con l'API Google Chat abilitata e configurata. Per i passaggi, vedi Crea un'app Google Chat.
  • Autorizzazione configurata per l'app Chat. Creazione in corso... un abbonamento richiede Autenticazione degli utenti con l'ambito di autorizzazione chat.memberships o chat.memberships.app.

Node.js

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

    npm install @google-cloud/local-auth @googleapis/chat
    
  • Un progetto Google Cloud con l'API Google Chat abilitata e configurata. Per i passaggi, vedi Crea un'app Google Chat.
  • Autorizzazione configurata per l'app Chat. Creazione in corso... un abbonamento richiede Autenticazione degli utenti con l'ambito di autorizzazione chat.memberships o chat.memberships.app.

Invitare o aggiungere un utente a uno spazio

Per invitare o aggiungere un utente a uno spazio, trasmetti quanto segue nel tuo richiesta:

  • Specifica l'ambito dell'autorizzazione chat.memberships.
  • Chiama il Metodo create il membership risorsa.
  • Imposta parent sul nome della risorsa dello spazio in cui creare l'appartenenza.
  • Imposta member su users/{user} dove {user} è la persona che vuoi creare un abbonamento per ed è:
    • L'ID per persona nell'API People. Ad esempio, se l'API People persona resourceName è people/123456789, poi imposta membership.member.name a users/123456789.
    • L'ID per utente nell'API Directory.
    • L'indirizzo email dell'utente. Ad esempio, users/[email protected] o users/[email protected]. Se l'utente utilizza un Account Google o appartiene a un'altra organizzazione Google Workspace, devi utilizzare la sua .

Nell'esempio seguente, un utente viene aggiunto a uno spazio:

Python

  1. Nella directory di lavoro, crea un file denominato chat_membership_user_create.py.
  2. Includi il seguente codice in chat_membership_user_create.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 adds a user to a Chat space by creating a membership.
        '''
    
        # 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().create(
    
            # The space in which to create a membership.
            parent = 'spaces/SPACE',
    
            # Specify which user the membership is for.
            body = {
              'member': {
                'name':'users/USER',
                'type': 'HUMAN'
              }
            }
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. Nel codice, sostituisci quanto segue:

    • SPACE: il nome di uno spazio, che che puoi ottenere Metodo spaces.list nell'API Chat o dall'URL di uno spazio.

    • USER: un ID utente.

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

    python3 chat_membership_user_create.py
    

Node.js

  1. Nella directory di lavoro, crea un file denominato add-user-to-space.js.
  2. Includi il seguente codice in add-user-to-space.js:

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Adds the user to the Chat space.
    * @return {!Promise<!Object>}
    */
    async function addUserToSpace() {
      const scopes = [
        'https://www.googleapis.com/auth/chat.memberships',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      return await chatClient.spaces.members.create({
        parent: 'spaces/SPACE',
        requestBody: {member: {name: 'users/USER', type: 'HUMAN'}}
      });
    }
    
    addUserToSpace().then(console.log);
    
  3. Nel codice, sostituisci quanto segue:

    • SPACE: il nome di uno spazio, che puoi ottenere Metodo spaces.list nell'API Chat o dall'URL di uno spazio.

    • USER: un ID utente.

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

    node add-user-to-space.js
    

L'API Chat restituisce un'istanza membership che descrive in dettaglio l'abbonamento utente creato.

Invitare o aggiungere un gruppo Google a uno spazio

Per invitare o aggiungere un gruppo Google a uno spazio, trasmetti quanto segue nel tuo richiesta:

  • Specifica l'ambito dell'autorizzazione chat.memberships.
  • Chiama il Metodo create il membership risorsa.
  • Imposta parent sul nome della risorsa dello spazio in cui creare l'appartenenza.
  • Imposta groupMember su groups/{group} dove {group} è l'ID gruppo che per cui vuoi creare un abbonamento. L'ID per il gruppo può essere recuperato utilizzando il metodo API Cloud Identity. Ad esempio, se l'API Cloud Identity restituisce un gruppo con il nome groups/123456789, quindi imposta Da membership.groupMember.name a groups/123456789.

Google Gruppi non può essere aggiunto a una chat di gruppo o a un messaggio diretto, ma solo a un spazio denominato. Nell'esempio seguente, un gruppo viene aggiunto a uno spazio denominato:

Python

  1. Nella directory di lavoro, crea un file denominato chat_membership_group_create.py.
  2. Includi il seguente codice in chat_membership_group_create.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 adds a group to a Chat space by creating a membership.
        '''
    
        # 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().create(
    
            # The named space in which to create a membership.
            parent = 'spaces/SPACE',
    
            # Specify which group the membership is for.
            body = {
              'groupMember': {
                'name':'groups/GROUP',
              }
            }
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. Nel codice, sostituisci quanto segue:

    • SPACE: il nome di uno spazio, che che puoi ottenere Metodo spaces.list nell'API Chat o dall'URL di uno spazio.

    • GROUP: un ID gruppo.

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

    python3 chat_membership_group_create.py
    

Node.js

  1. Nella directory di lavoro, crea un file denominato add-group-to-space.js.
  2. Includi il seguente codice in add-group-to-space.js:

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Adds the group to the Chat space.
    * @return {!Promise<!Object>}
    */
    async function addUserToSpace() {
      const scopes = [
        'https://www.googleapis.com/auth/chat.memberships',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      return await chatClient.spaces.members.create({
        parent: 'spaces/SPACE',
        requestBody: {groupMember: {name: 'groups/GROUP'}}
      });
    }
    
    addUserToSpace().then(console.log);
    
  3. Nel codice, sostituisci quanto segue:

    • SPACE: il nome di uno spazio, che puoi ottenere Metodo spaces.list nell'API Chat o dall'URL di uno spazio.

    • GROUP: un ID gruppo.

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

    node add-group-to-space.js
    

L'API Chat restituisce un'istanza membership che descrive in dettaglio l'appartenenza al gruppo creata.

Aggiungere un'app di Chat a uno spazio

Un'app di Chat non può aggiungere un'altra app come membro a un spazio. Per aggiungere un'app di Chat a uno spazio o un messaggio diretto tra due utenti, trasmetti quanto segue nella richiesta:

  • Specifica l'ambito dell'autorizzazione chat.memberships.app.
  • Chiama il Metodo create sulla risorsa membership.
  • Imposta parent sul nome della risorsa dello spazio in cui creare l'appartenenza.
  • Imposta member su users/app; un alias che rappresenta l'app che chiama API Chat.

Nell'esempio seguente viene aggiunta un'app di Chat a uno spazio:

Python

  1. Nella directory di lavoro, crea un file denominato chat_membership_app_create.py.
  2. Includi il seguente codice in chat_membership_app_create.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.app"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then adds the Chat app to a Chat space.
        '''
    
        # 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().create(
    
            # The space in which to create a membership.
            parent = 'spaces/SPACE',
    
            # Set the Chat app as the entity that gets added to the space.
            # 'app' is an alias for the Chat app calling the API.
            body = {
                'member': {
                  'name':'users/app',
                  'type': 'BOT'
                }
            }
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. Nel codice, sostituisci SPACE con il nome di uno spazio, che che puoi ottenere Metodo spaces.list nell'API Chat o dall'URL di uno spazio.

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

    python3 chat_membership_app_create.py
    

Node.js

  1. Nella directory di lavoro, crea un file denominato add-app-to-space.js.
  2. Includi il seguente codice in add-app-to-space.js:

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Adds the app to the Chat space.
    * @return {!Promise<!Object>}
    */
    async function addAppToSpace() {
      const scopes = [
        'https://www.googleapis.com/auth/chat.memberships.app',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      return await chatClient.spaces.members.create({
        parent: 'spaces/SPACE',
        requestBody: {member: {name: 'users/app', type: 'BOT'}}
      });
    }
    
    addAppToSpace().then(console.log);
    
  3. Nel codice, sostituisci SPACE con il nome di uno spazio, che che puoi ottenere Metodo spaces.list nell'API Chat o dall'URL di uno spazio.

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

    node add-app-to-space.js
    

L'API Chat restituisce un'istanza membership che descrive in dettaglio l'abbonamento all'app creato.