Google Chat スペースでユーザーのメンバーシップを更新する

このガイドでは、Google Chat API の membership リソースの patch メソッドを使用して、スペースのメンバーをスペースの管理者に変更する、スペースの管理者をスペースのメンバーに変更するなど、メンバーシップに関する属性を変更する方法について説明します。

Membership リソースは、人間のユーザーまたは Google Chat アプリがスペースに招待されているか、スペースに含まれているか、またはスペースから退出しているかを表します。

Python

  • Python 3.6 以降
  • pip パッケージ管理ツール
  • Python 用の最新の Google クライアント ライブラリ。これらをインストールまたは更新するには、コマンドライン インターフェースで次のコマンドを実行します。

    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    
  • Google Chat API が有効で構成された Google Cloud プロジェクト。手順については、Google Chat アプリを作成するをご覧ください。
  • Chat アプリ用に構成された認可。メンバーシップを更新するには、chat.memberships 認可スコープを持つユーザー認証が必要です。または、Chat にデータをインポートする場合は、chat.import 認可スコープが必要です。

Node.js

  • Node.js と npm
  • Node.js 用の最新の Google クライアント ライブラリ。これらをインストールするには、コマンドライン インターフェースで次のコマンドを実行します。

    npm install @google-cloud/local-auth @googleapis/chat
    
  • Google Chat API が有効で構成された Google Cloud プロジェクト。手順については、Google Chat アプリを作成するをご覧ください。
  • Chat アプリ用に構成された認可。メンバーシップを更新するには、chat.memberships 認可スコープを持つユーザー認証が必要です。または、Chat にデータをインポートする場合は、chat.import 認可スコープが必要です。

Apps Script

  • Google Chat へのアクセス権を持つ Google Workspace アカウント。
  • 公開されている Chat アプリ。Chat アプリを作成するには、このquickstartの手順に沿ってください。
  • Chat アプリ用に構成された認可。メンバーシップを更新するには、chat.memberships 認可スコープを持つユーザー認証が必要です。または、Chat にデータをインポートする場合は、chat.import 認可スコープが必要です。

メンバーシップを更新する

スペースのメンバーシップを更新するには、リクエストに以下を渡します。

  • chat.memberships 承認スコープを指定します。
  • Membership リソースpatch メソッドを呼び出し、更新するメンバーシップの name と、更新されたメンバーシップ属性を指定する updateMaskbody を渡します。
  • updateMask は、更新するメンバーシップの要素を指定します。これには以下が含まれます。
    • role: Chat スペース内のユーザーのロール。これにより、スペース内で許可されるアクションが決まります。有効な値は次のとおりです。
      • ROLE_MEMBER: このスペースのメンバー。ユーザーには、スペースへのメッセージ送信などの基本的な権限が付与されます。1 対 1 および名前のないグループの会話では、全員がこの役割を持ちます。
      • ROLE_MANAGER: スペースの管理者。ユーザーは、すべての基本的な権限に加えて、メンバーの追加や削除など、スペースを管理できる管理者権限を持ちます。spaceTypeSPACE(名前付きスペース)のスペースでのみサポートされます。

スペースの通常のメンバーをスペースの管理者にする

次の例では、更新されたメンバーシップ属性を指定する bodyroleROLE_MANAGER として指定して、通常のスペース メンバーをスペースの管理者にします。

Python

  1. 作業ディレクトリに、chat_membership_update.py という名前のファイルを作成します。
  2. 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. コードで、次のように置き換えます。

  4. 作業ディレクトリで、サンプルをビルドして実行します。

    python3 chat_membership_update.py
    

Node.js

  1. 作業ディレクトリに、chat_membership_update.js という名前のファイルを作成します。
  2. 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. コードで、次のように置き換えます。

  4. 作業ディレクトリで、サンプルをビルドして実行します。

    python3 chat_membership_update.js
    

Apps Script

この例では、高度なチャット サービスを使用して Chat API を呼び出します。

  1. chat.memberships 承認スコープを Apps Script プロジェクトの appsscript.json ファイルに追加します。

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. 次のような関数を 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 は、指定されたメンバーシップをスペースの管理者に変更し、変更の詳細を示す Membership のインスタンスを返します。

スペースの管理者を通常のメンバーにする

次の例では、更新されたメンバーシップ属性を指定する bodyroleROLE_MEMBER として指定し、スペースの管理者をスペースの通常のメンバーにします。

Python

  1. 作業ディレクトリに、chat_membership_update.py という名前のファイルを作成します。
  2. 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. コードで、次のように置き換えます。

  4. 作業ディレクトリで、サンプルをビルドして実行します。

    python3 chat_membership_update.py
    

Node.js

  1. 作業ディレクトリに、chat_membership_update.js という名前のファイルを作成します。
  2. 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. コードで、次のように置き換えます。

  4. 作業ディレクトリで、サンプルをビルドして実行します。

    python3 chat_membership_update.js
    

Apps Script

この例では、高度なチャット サービスを使用して Chat API を呼び出します。

  1. chat.memberships 承認スコープを Apps Script プロジェクトの appsscript.json ファイルに追加します。

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships"
    ]
    
  2. 次のような関数を 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 は、指定されたメンバーシップをスペースの管理者に変更し、変更の詳細を示す Membership のインスタンスを返します。