Aktualizowanie subskrypcji użytkownika w pokoju Google Chat

Z tego przewodnika dowiesz się, jak używać metody patch w zasobie membership interfejsu Google Chat API do zmiany atrybutów subskrypcji, np. zmiany użytkownika pokoju na menedżera pokoju lub jego menedżera w użytkownika pokoju.

Zasób Membership wskazuje, czy użytkownik lub aplikacja Google Chat są zaproszone do pokoju, które jest jego częścią lub poza nim.

Python

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

    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 Google Chat.
  • Autoryzacja dla aplikacji Google Chat została skonfigurowana. Aktualizacja subskrypcji wymaga uwierzytelniania użytkownika przy użyciu zakresu autoryzacji chat.memberships lub, w przypadku importowania danych do Google Chat, zakresu autoryzacji chat.import.

Node.js

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

    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 Google Chat.
  • Autoryzacja dla aplikacji Google Chat została skonfigurowana. Aktualizacja subskrypcji wymaga uwierzytelniania użytkownika przy użyciu zakresu autoryzacji chat.memberships lub, w przypadku importowania danych do Google Chat, zakresu autoryzacji chat.import.

Google Apps Script

Aktualizowanie subskrypcji

Aby zaktualizować członkostwo w pokoju, przekaż w swojej prośbie te informacje:

  • Określ zakres autoryzacji chat.memberships.
  • Wywołaj metodę patch w zasobie Membership i przekaż name subskrypcji do aktualizacji oraz updateMask i body, które określają zaktualizowane atrybuty subskrypcji.
  • updateMask określa aspekty członkostwa, które mają być aktualizowane, i zawiera:
    • role: rola użytkownika w pokoju czatu, która określa uprawnienia użytkownika w pokoju. Możliwe wartości:
      • ROLE_MEMBER: członek pokoju. Użytkownik ma podstawowe uprawnienia, takie jak wysyłanie wiadomości do pokoju. W rozmowach 1:1 i grupowych bez nazwy każdy ma tę rolę.
      • ROLE_MANAGER: menedżer pokoju. Użytkownik ma wszystkie podstawowe uprawnienia oraz uprawnienia administracyjne umożliwiające zarządzanie pokojem, na przykład dodawanie i usuwanie użytkowników. Obsługiwane tylko w pokojach, w których spaceType to SPACE (spacje z nazwami).

Ustawianie zwykłego członka pokoju jako menedżera pokoju

Ten przykład powoduje, że zwykły użytkownik pokoju jest menedżerem pokoju, podając role jako ROLE_MANAGER w body, który określa zaktualizowane atrybuty członkostwa:

Python

  1. W katalogu roboczym utwórz plik o nazwie chat_membership_update.py.
  2. Umieść ten kod w elemencie 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. Zastąp w nim ten fragment kodu:

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

    • MEMBERSHIP: nazwa subskrypcji, którą można uzyskać za pomocą metody spaces.members.list w interfejsie Chat API.

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

    python3 chat_membership_update.py
    

Node.js

  1. W katalogu roboczym utwórz plik o nazwie chat_membership_update.js.
  2. Umieść ten kod w elemencie 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. Zastąp w nim ten fragment kodu:

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

    • MEMBERSHIP: nazwa subskrypcji, którą można uzyskać za pomocą metody spaces.members.list w interfejsie Chat API.

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

    python3 chat_membership_update.js
    

Google Apps Script

W tym przykładzie wywołujesz interfejs Chat API za pomocą zaawansowanej usługi czatu.

  1. Dodaj zakres autoryzacji chat.memberships do pliku appsscript.json projektu Apps Script:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. Dodaj funkcję podobną do tej do kodu projektu 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);
      }
    }
    

Google Chat API zmienia określone członkostwo na menedżera pokoju i zwraca wystąpienie Membership ze szczegółami zmiany.

Ustawianie menedżera pokoju jako zwykłego członka

Ten przykład powoduje, że menedżer pokoju staje się zwykłym użytkownikiem pokoju, podając role jako ROLE_MEMBER w body, który określa zaktualizowane atrybuty członkostwa:

Python

  1. W katalogu roboczym utwórz plik o nazwie chat_membership_update.py.
  2. Umieść ten kod w elemencie 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. Zastąp w nim ten fragment kodu:

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

    • MEMBERSHIP: nazwa subskrypcji, którą można uzyskać za pomocą metody spaces.members.list w interfejsie Chat API.

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

    python3 chat_membership_update.py
    

Node.js

  1. W katalogu roboczym utwórz plik o nazwie chat_membership_update.js.
  2. Umieść ten kod w elemencie 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. Zastąp w nim ten fragment kodu:

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

    • MEMBERSHIP: nazwa subskrypcji, którą można uzyskać za pomocą metody spaces.members.list w interfejsie Chat API.

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

    python3 chat_membership_update.js
    

Google Apps Script

W tym przykładzie wywołujesz interfejs Chat API za pomocą zaawansowanej usługi czatu.

  1. Dodaj zakres autoryzacji chat.memberships do pliku appsscript.json projektu Apps Script:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. Dodaj funkcję podobną do tej do kodu projektu 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);
      }
    }
    

Google Chat API zmienia określone członkostwo na menedżera pokoju i zwraca wystąpienie Membership ze szczegółami zmiany.