Memperbarui keanggotaan pengguna di ruang Google Chat

Panduan ini menjelaskan cara menggunakan metode patch pada resource membership Google Chat API untuk mengubah atribut keanggotaan, seperti mengubah anggota ruang menjadi pengelola ruang, atau mengubah pengelola ruang menjadi anggota ruang.

Resource Membership mewakili apakah pengguna manusia atau aplikasi Google Chat diundang ke, sebagian, atau tidak ada dalam ruang.

Python

  • Python 3.6 atau yang lebih baru
  • Alat pengelolaan paket pip
  • Library klien Google terbaru untuk Python. Untuk menginstal atau mengupdatenya, jalankan perintah berikut di antarmuka command line Anda:

    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    
  • Project Google Cloud dengan Google Chat API yang diaktifkan dan dikonfigurasi. Untuk mengetahui langkah-langkahnya, lihat Mem-build aplikasi Google Chat.
  • Otorisasi dikonfigurasi untuk aplikasi Chat. Pembaruan keanggotaan memerlukan Autentikasi pengguna dengan cakupan otorisasi chat.memberships, atau cakupan otorisasi chat.import jika mengimpor data ke Chat.

Node.js

  • Node.js & npm
  • Library klien Google terbaru untuk Node.js. Untuk menginstalnya, jalankan perintah berikut di antarmuka command line Anda:

    npm install @google-cloud/local-auth @googleapis/chat
    
  • Project Google Cloud dengan Google Chat API yang diaktifkan dan dikonfigurasi. Untuk mengetahui langkah-langkahnya, lihat Mem-build aplikasi Google Chat.
  • Otorisasi dikonfigurasi untuk aplikasi Chat. Pembaruan keanggotaan memerlukan Autentikasi pengguna dengan cakupan otorisasi chat.memberships, atau cakupan otorisasi chat.import jika mengimpor data ke Chat.

Apps Script

Memperbarui langganan

Untuk memperbarui keanggotaan ruang, teruskan hal berikut dalam permintaan Anda:

  • Tentukan cakupan otorisasi chat.memberships.
  • Panggil metode patch pada resource Membership, dan teruskan name keanggotaan untuk diperbarui, serta updateMask dan body yang menentukan atribut keanggotaan yang diperbarui.
  • updateMask menentukan aspek keanggotaan yang akan diperbarui, dan menyertakan hal-hal berikut:
    • role: Peran pengguna dalam ruang Chat, yang menentukan tindakan yang diizinkan di ruang. Kemungkinan nilainya adalah:
      • ROLE_MEMBER: Anggota ruang. Pengguna memiliki izin dasar, seperti mengirim pesan ke ruang. Dalam percakapan grup 1:1 dan tanpa nama, semua orang memiliki peran ini.
      • ROLE_MANAGER: Pengelola ruang. Pengguna memiliki semua izin dasar ditambah izin administratif yang memungkinkannya mengelola ruang, seperti menambahkan atau menghapus anggota. Hanya didukung dalam ruang yang spaceType adalah SPACE (ruang bernama).

Menjadikan anggota ruang reguler sebagai pengelola ruang

Contoh berikut menjadikan anggota ruang reguler sebagai pengelola ruang dengan menentukan role sebagai ROLE_MANAGER di body yang menentukan atribut keanggotaan yang diperbarui:

Python

  1. Di direktori kerja Anda, buat file bernama chat_membership_update.py.
  2. Sertakan kode berikut di 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. Dalam kode, ganti kode berikut:

  4. Di direktori kerja Anda, buat dan jalankan contoh:

    python3 chat_membership_update.py
    

Node.js

  1. Di direktori kerja Anda, buat file bernama chat_membership_update.js.
  2. Sertakan kode berikut di 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. Dalam kode, ganti kode berikut:

  4. Di direktori kerja Anda, buat dan jalankan contoh:

    python3 chat_membership_update.js
    

Apps Script

Contoh ini memanggil Chat API menggunakan Advanced Chat Service.

  1. Tambahkan cakupan otorisasi chat.memberships ke file appsscript.json project Apps Script:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. Tambahkan fungsi seperti ini ke kode project 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 mengubah keanggotaan yang ditentukan menjadi pengelola ruang dan menampilkan instance Membership yang menjelaskan perubahan tersebut.

Menjadikan pengelola ruang sebagai anggota reguler

Contoh berikut menjadikan pengelola ruang sebagai anggota ruang reguler dengan menentukan role sebagai ROLE_MEMBER di body yang menentukan atribut keanggotaan yang diperbarui:

Python

  1. Di direktori kerja Anda, buat file bernama chat_membership_update.py.
  2. Sertakan kode berikut di 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. Dalam kode, ganti kode berikut:

  4. Di direktori kerja Anda, buat dan jalankan contoh:

    python3 chat_membership_update.py
    

Node.js

  1. Di direktori kerja Anda, buat file bernama chat_membership_update.js.
  2. Sertakan kode berikut di 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. Dalam kode, ganti kode berikut:

  4. Di direktori kerja Anda, buat dan jalankan contoh:

    python3 chat_membership_update.js
    

Apps Script

Contoh ini memanggil Chat API menggunakan Advanced Chat Service.

  1. Tambahkan cakupan otorisasi chat.memberships ke file appsscript.json project Apps Script:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. Tambahkan fungsi seperti ini ke kode project 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 mengubah keanggotaan yang ditentukan menjadi pengelola ruang dan menampilkan instance Membership yang menjelaskan perubahan tersebut.