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, użytkownika pokoju na menedżera pokoju lub zmianę menedżera pokoju na użytkownika 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
  • narzędzie do zarządzania pakietami pip;
  • Najnowsze biblioteki klienta Google. Aby je zainstalować lub zaktualizować: uruchom następujące polecenie w interfejsie wiersza poleceń:
    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    

Node.js

  • Node.js w wersji 14 lub nowszej
  • npm narzędzie do zarządzania pakietami
  • Najnowsze biblioteki klienta Google. Aby je zainstalować lub zaktualizować: uruchom następujące polecenie w interfejsie wiersza poleceń:
    npm install @google-cloud/local-auth @googleapis/chat
    

Google Apps Script

Aktualizowanie subskrypcji

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

  • Określ zakres autoryzacji chat.memberships.
  • Wywołaj funkcję Metoda patch w Membership zasobie, i przekazać name subskrypcji, aby zaktualizować, oraz updateMask i body, który określa zaktualizowane atrybuty członkostwa.
  • updateMask określa aspekty subskrypcji do zaktualizowania. obejmuje następujące elementy:
    • role: rola użytkownika w pokoju czatu, która określa uprawnienia użytkownika. czynności w pokoju. Możliwe wartości to:
      • ROLE_MEMBER: osoba w pokoju. Użytkownik ma podstawowe uprawnienia, np. wysyłanie wiadomości do pokoju. W grupie 1:1 i bez nazwy rozmów, każdy ma tę rolę.
      • ROLE_MANAGER: menedżer pokoju. Użytkownik ma wszystkie podstawowe uprawnienia oraz uprawnienia administracyjne, które pozwalają im zarządzać pokojem, np. dodawać lub przez usunięcie członków. Obsługiwane tylko w pokojach, w których spaceType ma wartość SPACE (spacje z nazwami).

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

W przykładzie poniżej zwykły użytkownik pokoju staje się menedżerem pokoju przez określenie role jako ROLE_MANAGER w elemencie body, który określa zaktualizowaną subskrypcję atrybuty:

Python

  1. W katalogu roboczym utwórz plik o nazwie chat_membership_update.py.
  2. Umieść w pliku chat_membership_update.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 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 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.

    • MEMBERSHIP: nazwa subskrypcji, która który znajdziesz w Metoda 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ść w pliku chat_membership_update.js ten kod:

    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 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.

    • MEMBERSHIP: nazwa subskrypcji, która który znajdziesz w Metoda 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łujemy interfejs Chat API za pomocą parametru Zaawansowana usługa czatu.

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

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. Dodaj funkcję taką jak ta do kod:

    /**
     * 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);
      }
    }
    

Interfejs Google Chat API zmienia określoną przynależność na menedżera pokoju i zwraca wystąpienie instancji Membership ze szczegółowymi informacjami na temat tej zmiany.

Ustawianie menedżera pokoju jako zwykłego użytkownika

W przykładzie poniżej menedżer pokoju staje się zwykłym członkiem pokoju przez określenie role jako ROLE_MEMBER w elemencie body, który określa zaktualizowaną subskrypcję atrybuty:

Python

  1. W katalogu roboczym utwórz plik o nazwie chat_membership_update.py.
  2. Umieść w pliku chat_membership_update.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 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 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.

    • MEMBERSHIP: nazwa subskrypcji, która który znajdziesz w Metoda 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ść w pliku chat_membership_update.js ten kod:

    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 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.

    • MEMBERSHIP: nazwa subskrypcji, która który znajdziesz w Metoda 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łujemy interfejs Chat API za pomocą parametru Zaawansowana usługa czatu.

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

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. Dodaj funkcję taką jak ta do kod:

    /**
     * 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);
      }
    }
    

Interfejs Google Chat API zmienia określoną przynależność na menedżera pokoju i zwraca wystąpienie instancji Membership ze szczegółowymi informacjami na temat tej zmiany.