ユーザー、Google グループ、Google Chat アプリをスペースに招待または追加する

このガイドでは、Google Chat API の membership リソースの create メソッドを使用して、ユーザー、Google グループ、Chat アプリをスペース(メンバーシップの作成)に招待または追加する方法について説明します。メンバーシップを作成する際に、指定したメンバーが自動承諾ポリシーを無効にしている場合、そのメンバーは招待されます。スペースに参加する前に、スペースへの招待を承諾する必要があります。それ以外の場合、メンバーシップを作成すると、指定されたスペースにメンバーが直接追加されます。

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.memberships.app 承認スコープを使用したユーザー認証が必要です。

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.memberships.app 承認スコープを使用したユーザー認証が必要です。

スペースにユーザーを招待または追加する

スペースにユーザーを招待または追加するには、リクエストで次の内容を渡します。

  • chat.memberships 認可スコープを指定します。
  • membership リソースcreate メソッドを呼び出します。
  • parent を、メンバーシップを作成するスペースのリソース名に設定します。
  • memberusers/{user} に設定します。{user} は、メンバーシップを作成するユーザーで、次のいずれかです。
    • People API の人物の ID。たとえば、People API の人物resourceNamepeople/123456789 の場合は、membership.member.nameusers/123456789 に設定します。
    • Directory API のユーザーの ID。
    • ユーザーのメールアドレス。たとえば、users/222larabrown@gmail.comusers/larabrown@cymbalgroup.com です。ユーザーが Google アカウントを使用しているか、別の Google Workspace 組織に所属している場合は、ユーザーのメールアドレスを使用する必要があります。

次の例では、スペースにユーザーを追加します。

Python

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

    • SPACE: スペース名。Chat API の spaces.list メソッドまたはスペースの URL から取得できます。

    • USER: ユーザー ID。

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

    python3 chat_membership_user_create.py
    

Node.js

  1. 作業ディレクトリに、add-user-to-space.js という名前のファイルを作成します。
  2. add-user-to-space.js に次のコードを含めます。

    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. コードの次のように置き換えます。

    • SPACE: スペース名。Chat API の spaces.list メソッドまたはスペースの URL から取得できます。

    • USER: ユーザー ID。

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

    node add-user-to-space.js
    

Chat API は、作成されたユーザー メンバーシップの詳細を示す membership のインスタンスを返します。

Google グループをスペースに招待または追加する

Google グループをスペースに招待または追加するには、リクエストで次の内容を渡します。

  • chat.memberships 認可スコープを指定します。
  • membership リソースcreate メソッドを呼び出します。
  • parent を、メンバーシップを作成するスペースのリソース名に設定します。
  • groupMembergroups/{group} に設定します。{group} は、メンバーシップを作成するグループ ID です。グループの ID は、Cloud Identity API を使用して取得できます。たとえば、Cloud Identity APIgroups/123456789 という名前のグループを返す場合は、membership.groupMember.namegroups/123456789 に設定します。

Google グループは、グループ チャットやダイレクト メッセージには追加できません。追加できるのは名前付きスペースのみです。次の例では、名前付きスペースにグループを追加します。

Python

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

    • SPACE: スペース名。Chat API の spaces.list メソッドまたはスペースの URL から取得できます。

    • GROUP: グループ ID。

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

    python3 chat_membership_group_create.py
    

Node.js

  1. 作業ディレクトリに、add-group-to-space.js という名前のファイルを作成します。
  2. add-group-to-space.js に次のコードを含めます。

    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. コードの次のように置き換えます。

    • SPACE: スペース名。Chat API の spaces.list メソッドまたはスペースの URL から取得できます。

    • GROUP: グループ ID。

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

    node add-group-to-space.js
    

Chat API は、作成されたグループ メンバーの詳細を示す membership のインスタンスを返します。

スペースに Chat 用アプリを追加する

Chat アプリでは、別のアプリをメンバーとしてスペースに追加することはできません。2 人の人間のユーザー間のスペースまたはダイレクト メッセージに Chat 用アプリを追加するには、リクエストで次の内容を渡します。

  • chat.memberships.app 認可スコープを指定します。
  • membership リソースcreate メソッドを呼び出します。
  • parent を、メンバーシップを作成するスペースのリソース名に設定します。
  • memberusers/app に設定します。これは、Chat API を呼び出すアプリを表すエイリアスです。

次の例では、スペースに Chat 用アプリを追加します。

Python

  1. 作業ディレクトリに、chat_membership_app_create.py という名前のファイルを作成します。
  2. chat_membership_app_create.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.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. コードで SPACE をスペース名に置き換えます。スペースは、Chat API の spaces.list メソッドまたはスペースの URL から取得します。

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

    python3 chat_membership_app_create.py
    

Node.js

  1. 作業ディレクトリに、add-app-to-space.js という名前のファイルを作成します。
  2. add-app-to-space.js に次のコードを含めます。

    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. コードで SPACE をスペース名に置き換えます。スペースは、Chat API の spaces.list メソッドまたはスペースの URL から取得します。

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

    node add-app-to-space.js
    

Chat API は、作成されたアプリ メンバーシップの詳細を示す membership のインスタンスを返します。