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

このガイドでは、Google Chat API の membership リソースの create メソッドを使用して、ユーザーまたは 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 の person の 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.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/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 のインスタンスを返します。

スペースに 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 のインスタンスを返します。