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 un'app di chat a uno spazio, ovvero creare un abbonamento. Quando crei un abbonamento, se l'abbonato specificato ha disattivato la policy di accettazione automatica, viene invitato e deve accettare l'invito allo spazio prima di potervi accedere. In caso contrario, la creazione di un abbonamento aggiunge il membro direttamente allo spazio specificato.

Se sei un amministratore di Google Workspace, puoi aggiungere utenti, Gruppi Google o app di Chat a qualsiasi spazio della tua organizzazione Google Workspace.

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

Prerequisiti

Node.js

Python

Java

Apps Script

Invitare o aggiungere un utente a uno spazio come utente

Per invitare o aggiungere un utente a uno spazio con autenticazione utente, passa quanto segue nella richiesta:

  • Specifica l'ambito di autorizzazione chat.memberships.
  • Chiama il metodo CreateMembership().
  • Passa parent come nome della risorsa dello spazio in cui creare l'abbonamento.
  • Trasmetti membership come istanza di Membership con il campo member impostato come segue:
    • Il campo type impostato su HUMAN.
    • Il campo name è impostato su users/{user}, dove {user} è la persona che vuoi aggiungere allo spazio. Per specificare l'utente Chat, sostituisci {user} con uno dei seguenti valori:
      • L'ID della persona nell'API People. Ad esempio, se l'person resourceName dell'API People è people/123456789, utilizza il valore users/123456789.
      • L'ID dell'utente nell'API Directory.
      • L'indirizzo email dell'utente. Ad esempio, users/222larabrown@gmail.com o users/larabrown@cymbalgroup.com. Se l'utente utilizza un Account Google o appartiene a un'altra organizzazione Google Workspace, devi utilizzare il suo indirizzo email.

L'esempio seguente aggiunge un utente a uno spazio con autenticazione utente:

Node.js

chat/client-libraries/cloud/create-membership-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.memberships'];

// This sample shows how to create membership with user credential for a human user
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    membership: {
      member: {
        // Replace USER_NAME here
        name: 'users/USER_NAME',
        // User type for the membership
        type: 'HUMAN'
      }
    }
  };

  // Make the request
  const response = await chatClient.createMembership(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_membership_user_cred.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.memberships"]

# This sample shows how to create membership with user credential for a human
# user
def create_membership_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMembershipRequest(
        # Replace SPACE_NAME here
        parent = "spaces/SPACE_NAME",
        membership = {
            "member": {
                # Replace USER_NAME here
                "name": "users/USER_NAME",
                # user type for the membership
                "type_": "HUMAN"
            }
        }
    )

    # Make the request
    response = client.create_membership(request)

    # Handle the response
    print(response)

create_membership_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMembershipRequest;
import com.google.chat.v1.Membership;
import com.google.chat.v1.SpaceName;
import com.google.chat.v1.User;

// This sample shows how to create membership with user credential for a human
// user.
public class CreateMembershipUserCred {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.memberships";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMembershipRequest.Builder request = CreateMembershipRequest.newBuilder()
        // replace SPACE_NAME here
        .setParent("spaces/SPACE_NAME")
        .setMembership(Membership.newBuilder()
          .setMember(User.newBuilder()
            // replace USER_NAME here
            .setName("users/USER_NAME")
            // user type for the membership
            .setType(User.Type.HUMAN)));
      Membership response = chatServiceClient.createMembership(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to create membership with user credential for a human user
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.memberships'
 * referenced in the manifest file (appsscript.json).
 */
function createMembershipUserCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  const membership = {
    member: {
      // TODO(developer): Replace USER_NAME here
      name: 'users/USER_NAME',
      // User type for the membership
      type: 'HUMAN'
    }
  };

  // Make the request
  const response = Chat.Spaces.Members.create(membership, parent);

  // Handle the response
  console.log(response);
}

Per eseguire l'esempio, sostituisci quanto segue:

  • SPACE_NAME: l'ID di name dello spazio. Puoi ottenere l'ID chiamando il metodo ListSpaces() o dall'URL dello spazio.
  • USER_NAME: un ID utente.

L'API Chat restituisce un'istanza di Membership che descrive in dettaglio l'appartenenza dell'utente creata.

Invitare o aggiungere un gruppo Google a uno spazio

Per invitare o aggiungere un gruppo Google a uno spazio con autenticazione utente (l'autenticazione app non supporta l'invito o l'aggiunta di un gruppo Google a uno spazio), trasmetti quanto segue nella richiesta:

  • Specifica l'ambito di autorizzazione chat.memberships.
  • Chiama il metodo CreateMembership().
  • Passa parent come nome della risorsa dello spazio in cui creare l'abbonamento.
  • Passa membership come istanza di Membership con il campo name di groupMember impostato su groups/{group}, dove {group} è l'ID gruppo per cui vuoi creare l'iscrizione. L'ID del gruppo può essere recuperato utilizzando l'API Cloud Identity.

I gruppi Google non possono essere aggiunti a una chat di gruppo o a un messaggio diretto, ma solo a uno spazio con nome.

L'esempio seguente aggiunge un gruppo a uno spazio denominato con l'autenticazione utente:

Node.js

chat/client-libraries/cloud/create-membership-user-cred-for-group.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.memberships'];

// This sample shows how to create membership with user credential for a group
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    membership: {
      groupMember: {
        // Replace GROUP_NAME here
        name: 'groups/GROUP_NAME'
      }
    }
  };

  // Make the request
  const response = await chatClient.createMembership(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_membership_user_cred_for_group.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.memberships"]

# This sample shows how to create membership with user credential for a group
def create_membership_with_user_cred_for_group():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMembershipRequest(
        # Replace SPACE_NAME here
        parent = "spaces/SPACE_NAME",
        membership = {
            "groupMember": {
                # Replace GROUP_NAME here
                "name": "groups/GROUP_NAME"
            }
        }
    )

    # Make the request
    response = client.create_membership(request)

    # Handle the response
    print(response)

create_membership_with_user_cred_for_group()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForGroup.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMembershipRequest;
import com.google.chat.v1.Membership;
import com.google.chat.v1.SpaceName;
import com.google.chat.v1.Group;

// This sample shows how to create membership with user credential for a group.
public class CreateMembershipUserCredForGroup {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.memberships";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMembershipRequest.Builder request = CreateMembershipRequest.newBuilder()
        // replace SPACE_NAME here
        .setParent("spaces/SPACE_NAME")
        .setMembership(Membership.newBuilder()
          .setGroupMember(Group.newBuilder()
            // replace GROUP_NAME here
            .setName("groups/GROUP_NAME")));
      Membership response = chatServiceClient.createMembership(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to create membership with user credential for a group
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.memberships'
 * referenced in the manifest file (appsscript.json).
 */
function createMembershipUserCredForGroup() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  const membership = {
    groupMember: {
      // TODO(developer): Replace GROUP_NAME here
      name: 'groups/GROUP_NAME'
    }
  };

  // Make the request
  const response = Chat.Spaces.Members.create(membership, parent);

  // Handle the response
  console.log(response);
}

Per eseguire l'esempio, sostituisci quanto segue:

  • SPACE_NAME: l'ID di name dello spazio. Puoi ottenere l'ID chiamando il metodo ListSpaces() o dall'URL dello spazio.
  • GROUP_NAME: un ID gruppo.

L'API Chat restituisce un'istanza di Membership che descrive in dettaglio l'appartenenza dell'utente creata.

Aggiungere un'app di Chat a uno spazio

Un'app di chat non può aggiungere un'altra app come membro di uno spazio. Per aggiungere un'app di chat a uno spazio o a un messaggio diretto tra due utenti umani, trasmetti quanto segue nella richiesta con l'autenticazione utente (l'autenticazione app non supporta l'invito o l'aggiunta di un'app di chat a uno spazio):

  • Specifica l'ambito di autorizzazione chat.memberships.app.
  • Chiama il metodo CreateMembership().
  • Passa parent come nome della risorsa dello spazio in cui creare l'abbonamento.
  • Trasmetti membership come istanza di Membership con il campo member impostato come segue:
    • Il campo type impostato su BOT.
    • Il campo name impostato su users/app; un alias che rappresenta l'app che chiama l'API Chat.

Il seguente esempio aggiunge un'app di Chat a uno spazio:

Node.js

chat/client-libraries/cloud/create-membership-user-cred-for-app.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.memberships.app'];

// This sample shows how to create membership with app credential for an app
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    membership: {
      member: {
        // Member name for app membership, do not change this
        name: 'users/app',
        // User type for the membership
        type: 'BOT'
      }
    }
  };

  // Make the request
  const response = await chatClient.createMembership(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_membership_user_cred_for_app.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.memberships.app"]

# This sample shows how to create membership with app credential for an app
def create_membership_with_user_cred_for_app():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMembershipRequest(
        # Replace SPACE_NAME here
        parent = "spaces/SPACE_NAME",
        membership = {
            "member": {
                # member name for app membership, do not change this.
                "name": "users/app",
                # user type for the membership
                "type_": "BOT"
            }
        }
    )

    # Make the request
    response = client.create_membership(request)

    # Handle the response
    print(response)

create_membership_with_user_cred_for_app()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForApp.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMembershipRequest;
import com.google.chat.v1.Membership;
import com.google.chat.v1.SpaceName;
import com.google.chat.v1.User;

// This sample shows how to create membership with user credential for the
// calling app.
public class CreateMembershipUserCredForApp {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.memberships.app";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMembershipRequest.Builder request = CreateMembershipRequest.newBuilder()
        // replace SPACE_NAME here
        .setParent("spaces/SPACE_NAME")
        .setMembership(Membership.newBuilder()
          .setMember(User.newBuilder()
            // member name for app membership, do not change this.
            .setName("users/app")
            // user type for the membership
            .setType(User.Type.BOT)));
      Membership response = chatServiceClient.createMembership(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to create membership with app credential for an app
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.memberships.app'
 * referenced in the manifest file (appsscript.json).
 */
function createMembershipUserCredForApp() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  const membership = {
    member: {
      // Member name for app membership, do not change this
      name: 'users/app',
      // User type for the membership
      type: 'BOT'
    }
  };

  // Make the request
  const response = Chat.Spaces.Members.create(membership, parent);

  // Handle the response
  console.log(response);
}

Per eseguire l'esempio, sostituisci SPACE_NAME con l'ID dello spazio name. Puoi ottenere l'ID chiamando il metodo ListSpaces() o dall'URL dello spazio.

L'API Chat restituisce un'istanza di Membership che descrive in dettaglio l'appartenenza dell'utente creata.

Invitare o aggiungere un utente a uno spazio come app di Chat

L'autenticazione dell'app richiede l'approvazione dell'amministratore una sola volta.

Per invitare o aggiungere un utente a uno spazio con autenticazione dell'app, trasmetti quanto segue nella richiesta:

  • Specifica l'ambito di autorizzazione chat.app.memberships.
  • Chiama il metodo create sulla risorsa membership.
  • Imposta parent sul nome della risorsa dello spazio in cui creare l'abbonamento.
  • Imposta member su users/{user}, dove {user} è la persona per cui vuoi creare l'abbonamento e può essere:
    • L'ID della persona nell'API People. Ad esempio, se l'API People person resourceName è people/123456789, imposta membership.member.name su users/123456789.
    • L'ID dell'utente nell'API Directory.
    • L'indirizzo email dell'utente. Ad esempio, users/222larabrown@gmail.com o users/larabrown@cymbalgroup.com. Se l'utente utilizza un Account Google o appartiene a un'altra organizzazione Google Workspace, devi utilizzare il suo indirizzo email.

Crea una chiave API

Per chiamare un metodo API di anteprima per gli sviluppatori, devi utilizzare una versione di anteprima per gli sviluppatori non pubblica del documento di rilevamento API. Per autenticare la richiesta, devi passare una chiave API.

Per creare la chiave API, apri il progetto Google Cloud della tua app e svolgi i seguenti passaggi:

  1. Nella console Google Cloud, vai a Menu > API e servizi > Credenziali.

    Vai a credenziali

  2. Fai clic su Crea credenziali > Chiave API.
  3. Viene visualizzata la nuova chiave API.
    • Fai clic su Copia per copiare la chiave API da utilizzare nel codice dell'app. La chiave API può essere trovata anche nella sezione "Chiavi API" delle credenziali del progetto.
    • Fai clic su Limita chiave per aggiornare le impostazioni avanzate e limitare l'utilizzo della chiave API. Per maggiori dettagli, consulta Applicare le limitazioni relative alle chiavi API.

Scrivere uno script che chiama l'API Chat

Il seguente esempio aggiunge un utente a uno spazio con autenticazione dell'app:

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.oauth2 import service_account
    from apiclient.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.app.memberships"]
    
    def main():
        '''
        Authenticates with Chat API using app authentication,
        then adds a user to a Chat space by creating a membership.
        '''
    
        # Specify service account details.
        creds = (
            service_account.Credentials.from_service_account_file('credentials.json')
            .with_scopes(SCOPES)
        )
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds, discoveryServiceUrl='https://chat.googleapis.com/$discovery/rest?version=v1&labels=DEVELOPER_PREVIEW&key=API_KEY')
    
        # 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:

    • API_KEY: la chiave API che hai creato per creare l'endpoint del servizio per l'API Chat.

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

    • USER: un ID utente.

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

    python3 chat_membership_app_create.py

Aggiungere utenti o gruppi Google a uno spazio come amministratore di Google Workspace

Se sei un amministratore di Google Workspace, puoi chiamare il metodo create() per aggiungere utenti, Gruppi Google o app di Chat a qualsiasi spazio della tua organizzazione Google Workspace.

Per chiamare questo metodo in qualità di amministratore di Google Workspace, procedi nel seguente modo:

  • Chiama il metodo utilizzando l'autenticazione utente e specifica un ambito di autorizzazione che supporti la chiamata del metodo utilizzando privilegi amministrativi.
  • Nella richiesta, specifica il parametro di query useAdminAccess su true.

Per ulteriori informazioni ed esempi, vedi Gestire gli spazi di Google Chat come amministratore di Google Workspace.

Limitazioni e considerazioni

  • Con l'autenticazione delle app, un'app di chat può invitare o aggiungere utenti, ma non Google Gruppi o app di chat. Per aggiungersi, un'app di chat deve utilizzare l'autenticazione utente con l'ambito di autorizzazione chat.memberships.