Zapraszanie i dodawanie użytkownika, grupy dyskusyjnej Google lub aplikacji Google Chat do pokoju

Z tego przewodnika dowiesz się, jak używać metody create w zasobie membership interfejsu Google Chat API do zapraszania i dodawania użytkowników, grup dyskusyjnych Google lub aplikacji Google Chat do pokoju, inaczej nazywanego członkostwem. Jeśli podczas tworzenia członkostwa dany użytkownik ma wyłączoną zasadę automatycznego akceptowania, zostanie zaproszony i musi zaakceptować zaproszenie do pokoju, zanim dołączy. W przeciwnym razie utworzenie subskrypcji spowoduje dodanie użytkownika bezpośrednio do określonego pokoju.

Zasób Membership informuje o tym, czy użytkownik lub aplikacja Google Chat został zaproszony do pokoju, jego część lub brak w nim.

Wymagania wstępne

Python

  • Python w wersji 3.6 lub nowszej
  • Narzędzie do zarządzania pakietami pip
  • Najnowsze biblioteki klienta Google dla języka Python. Aby je zainstalować lub zaktualizować, uruchom to polecenie w interfejsie wiersza poleceń:

    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    
  • Projekt Google Cloud z włączonym i skonfigurowanym interfejsem Google Chat API. Instrukcje znajdziesz w artykule Tworzenie aplikacji w Google Chat.
  • Autoryzacja skonfigurowana dla aplikacji Google Chat. Tworzenie subskrypcji wymaga uwierzytelniania użytkownika z zakresem autoryzacji chat.memberships lub chat.memberships.app.

Node.js

  • Node.js i npm
  • Najnowsze biblioteki klienta Google dla środowiska Node.js. Aby je zainstalować, uruchom to polecenie w interfejsie wiersza poleceń:

    npm install @google-cloud/local-auth @googleapis/chat
    
  • Projekt Google Cloud z włączonym i skonfigurowanym interfejsem Google Chat API. Instrukcje znajdziesz w artykule Tworzenie aplikacji w Google Chat.
  • Autoryzacja skonfigurowana dla aplikacji Google Chat. Tworzenie subskrypcji wymaga uwierzytelniania użytkownika z zakresem autoryzacji chat.memberships lub chat.memberships.app.

Zapraszanie i dodawanie użytkownika do pokoju

Aby zaprosić lub dodać użytkownika do pokoju, przekaż w jego żądaniu:

  • Określ zakres autoryzacji chat.memberships.
  • Wywołaj metodę create w zasobie membership.
  • Ustaw parent na nazwę zasobu pokoju, w którym chcesz utworzyć subskrypcję.
  • Ustaw member na users/{user}, gdzie {user} to osoba, dla której chcesz utworzyć subskrypcję, i jest:
    • Identyfikator osoby w interfejsie People API. Jeśli np. osoba resourceName w interfejsie People API to people/123456789, ustaw membership.member.name na users/123456789.
    • Identyfikator użytkownika w interfejsie Directory API.
    • Adres e-mail użytkownika. Na przykład users/222larabrown@gmail.com lub users/larabrown@cymbalgroup.com. Jeśli użytkownik korzysta z konta Google lub należy do innej organizacji Google Workspace, musisz użyć jego adresu e-mail.

Ten przykład pozwala dodać użytkownika do pokoju:

Python

  1. W katalogu roboczym utwórz plik o nazwie chat_membership_user_create.py.
  2. Umieść w pliku chat_membership_user_create.py ten kod:

    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. Zastąp w kodzie następujące elementy:

    • SPACE: nazwa pokoju, którą można uzyskać za pomocą metody spaces.list w interfejsie Chat API lub z adresu URL pokoju.

    • USER: identyfikator użytkownika.

  4. W katalogu roboczym skompiluj i uruchom przykład:

    python3 chat_membership_user_create.py
    

Node.js

  1. W katalogu roboczym utwórz plik o nazwie add-user-to-space.js.
  2. Umieść w pliku add-user-to-space.js ten kod:

    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. Zastąp w kodzie następujące elementy:

    • SPACE: nazwa pokoju, którą można uzyskać za pomocą metody spaces.list w interfejsie Chat API lub z adresu URL pokoju.

    • USER: identyfikator użytkownika.

  4. W katalogu roboczym uruchom przykładowy kod:

    node add-user-to-space.js
    

Interfejs Chat API zwraca instancję membership, która zawiera szczegóły dotyczące utworzonej subskrypcji użytkownika.

Zapraszanie grup dyskusyjnych Google do pokoju i dodawanie ich do pokoju

Aby zaprosić lub dodać grupę dyskusyjną Google do pokoju, przekaż w żądaniu te informacje:

  • Określ zakres autoryzacji chat.memberships.
  • Wywołaj metodę create w zasobie membership.
  • Ustaw parent na nazwę zasobu pokoju, w którym chcesz utworzyć subskrypcję.
  • Ustaw groupMember na groups/{group}, gdzie {group} to identyfikator grupy, do której chcesz utworzyć członkostwo. Identyfikator grupy można pobrać za pomocą interfejsu Cloud Identity API. Jeśli na przykład interfejs Cloud Identity API zwraca grupę o nazwie groups/123456789, ustaw membership.groupMember.name na groups/123456789.

Grup dyskusyjnych Google nie można dodawać do czatu grupowego ani czatu, a jedynie do pokoju nazwanego. Ten przykład dodaje grupę do nazwanego pokoju:

Python

  1. W katalogu roboczym utwórz plik o nazwie chat_membership_group_create.py.
  2. Umieść w pliku chat_membership_group_create.py ten kod:

    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. Zastąp w kodzie następujące elementy:

    • SPACE: nazwa pokoju, którą można uzyskać za pomocą metody spaces.list w interfejsie Chat API lub z adresu URL pokoju.

    • GROUP: identyfikator grupy.

  4. W katalogu roboczym skompiluj i uruchom przykład:

    python3 chat_membership_group_create.py
    

Node.js

  1. W katalogu roboczym utwórz plik o nazwie add-group-to-space.js.
  2. Umieść w pliku add-group-to-space.js ten kod:

    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. Zastąp w kodzie następujące elementy:

    • SPACE: nazwa pokoju, którą można uzyskać za pomocą metody spaces.list w interfejsie Chat API lub z adresu URL pokoju.

    • GROUP: identyfikator grupy.

  4. W katalogu roboczym uruchom przykładowy kod:

    node add-group-to-space.js
    

Interfejs Chat API zwraca instancję membership, która zawiera szczegóły dotyczące utworzonego członkostwa w grupie.

Dodawanie aplikacji Google Chat do pokoju

Aplikacja do obsługi czatu nie może dodać innej aplikacji jako członka pokoju. Aby dodać aplikację Google Chat do pokoju lub czatu między 2 osobami, przekaż w prośbie:

  • Określ zakres autoryzacji chat.memberships.app.
  • Wywołaj metodę create w zasobie membership.
  • Ustaw parent na nazwę zasobu pokoju, w którym chcesz utworzyć subskrypcję.
  • Ustaw member na users/app; alias reprezentujący aplikację wywołującą interfejs Chat API.

Ten przykład dodaje aplikację Google Chat do pokoju:

Python

  1. W katalogu roboczym utwórz plik o nazwie chat_membership_app_create.py.
  2. Umieść w pliku chat_membership_app_create.py ten kod:

    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. W kodzie zastąp SPACE nazwą pokoju, którą możesz uzyskać za pomocą metody spaces.list w interfejsie Chat API lub z adresu URL pokoju.

  4. W katalogu roboczym skompiluj i uruchom przykład:

    python3 chat_membership_app_create.py
    

Node.js

  1. W katalogu roboczym utwórz plik o nazwie add-app-to-space.js.
  2. Umieść w pliku add-app-to-space.js ten kod:

    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. W kodzie zastąp SPACE nazwą pokoju, którą możesz uzyskać za pomocą metody spaces.list w interfejsie Chat API lub z adresu URL pokoju.

  4. W katalogu roboczym uruchom przykładowy kod:

    node add-app-to-space.js
    

Interfejs Chat API zwraca instancję membership, która zawiera szczegóły dotyczące utworzonej aplikacji.