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 lub dodawania użytkowników, grup dyskusyjnych Google lub do pokoju zwanego też tworzeniem czatu subskrypcji. Podczas tworzenia członkostwa, jeśli określony użytkownik ma zasady automatycznego akceptowania są wyłączone, następnie użytkownik otrzymuje zaproszenie i musi zaakceptować pokój zaproszenie przed dołączeniem. W przeciwnym razie utworzenie subskrypcji spowoduje dodanie jej bezpośrednio do określonego pokoju.

Membership zasób wskazuje, czy zaproszeni jest człowiek czy aplikacja Google Chat; które znajdują się w pokoju lub w ogóle ich nie ma.

Wymagania wstępne

Python

  • Python w wersji 3.6 lub nowszej
  • PIP narzędzie do zarządzania pakietami
  • Najnowsze biblioteki klienta Google dla języka Python. Aby je zainstalować lub zaktualizować: uruchom następujące 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 sekcji Utwórz aplikację Google Chat.
  • Skonfigurowano autoryzację dla aplikacji Google Chat. Tworzę członkostwo wymaga subskrypcji Uwierzytelnianie użytkowników 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 następujące 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 sekcji Utwórz aplikację Google Chat.
  • Skonfigurowano autoryzację dla aplikacji Google Chat. Tworzę członkostwo wymaga subskrypcji Uwierzytelnianie użytkowników 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 żądanie:

  • Określ zakres autoryzacji chat.memberships.
  • Wywołaj funkcję Metoda create w membership zasób.
  • Ustaw parent na nazwę zasobu pokoju, w którym chcesz utworzyć subskrypcję.
  • Ustaw member na users/{user}, gdzie {user} jest osobą, którą chcesz otworzyć utwórz członkostwo dla i jest:
    • Identyfikator elementu osoba w interfejsie People API. Jeśli na przykład interfejs People API osoba resourceName ma wartość people/123456789, a następnie ustaw membership.member.name do users/123456789.
    • Identyfikator elementu użytkownik w interfejsie Directory API.
    • Adres e-mail użytkownika. Na przykład users/[email protected] lub users/[email protected] Jeśli użytkownik korzysta z konta Google należy do innej organizacji Google Workspace, musisz użyć jej 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óra który znajdziesz w Metoda 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żesz uzyskać z Metoda 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 zawierające szczegóły dotyczące utworzonej subskrypcji.

Zapraszanie grup dyskusyjnych Google do pokoju i dodawanie ich do pokoju

Aby zaprosić lub dodać grupę dyskusyjną Google do pokoju, przekaż następujące informacje w swojej żądanie:

  • Określ zakres autoryzacji chat.memberships.
  • Wywołaj funkcję Metoda create w membership zasób.
  • Ustaw parent na nazwę zasobu pokoju, w którym chcesz utworzyć subskrypcję.
  • Ustaw groupMember na groups/{group}, gdzie {group} to identyfikator grupy dla których chcesz utworzyć subskrypcję. Identyfikator grupy można pobrać za pomocą Cloud Identity API Jeśli na przykład interfejs Cloud Identity API zwraca grupę o nazwie groups/123456789, a następnie ustawiono membership.groupMember.name do groups/123456789.

Grup dyskusyjnych Google nie można dodać do czatu grupowego ani do czatu, a tylko do nazwany pokój. 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óra który znajdziesz w Metoda 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żesz uzyskać z Metoda 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 zawierający 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 grupy kosmosu. Dodawanie aplikacji Google Chat do pokoju lub na czacie między 2 osobami użytkowników, przekaż w swoim żądaniu:

  • Określ zakres autoryzacji chat.memberships.app.
  • Wywołaj funkcję Metoda 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óra który znajdziesz w Metoda 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óra który znajdziesz w Metoda 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óry zawiera szczegółowe informacje o utworzonej subskrypcji aplikacji.