Google Chat アプリとして認証する

このガイドでは、サービス アカウントを設定して使用し、Chat アプリに代わって Google Chat API にアクセスする方法について説明します。まず、サービス アカウントを作成する方法について説明します。次に、サービス アカウントを使用して Chat API で認証し、Chat スペースにメッセージを投稿するスクリプトを作成する方法を示します。

Chat アプリでは、Google Chat API を非同期で呼び出すときにサービス アカウントを使用して認証できるため、次のことが可能になります。

  • spaces.messages.create を使用して Google Chat にメッセージを送信し、以下の操作を行うことができます。
    • 長時間実行されているバックグラウンド ジョブの実行が終了したときにユーザーに通知します。
    • サーバーがオフラインになったことをユーザーに通知します。
    • カスタマー サポート担当者に、新たにオープンしたお客様のケースに対応するよう依頼します。
  • 以前に送信したメッセージを spaces.messages.update で次のように更新します。
    • 進行中のオペレーションのステータスを変更します。
    • タスクの割り当て先または期限を更新する。
  • spaces.members.list でスペース内のユーザーを一覧表示し、以下の操作を行います。
    • スペースに参加しているユーザーを確認する。
    • スペースのメンバーシップにチームの全員が含まれていることを確認します。

サービス アカウントで認証される場合、Chat スペースに関するデータを取得したり、アクションを実行したりするには、Chat アプリにスペースのメンバーシップが必要です。たとえば、スペースのメンバーを一覧表示するには、またはスペースでメッセージを作成するには、Chat アプリ自体がスペースのメンバーである必要があります。

Chat アプリがユーザーデータへのアクセスや、ユーザーに代わってアクションを実行する必要がある場合は、代わりにユーザーとして認証します。

ドメイン管理者はドメイン全体の権限の委任を付与して、ユーザーごとに同意を求めることなくアプリケーションのサービス アカウントがユーザーデータにアクセスできるように承認できます。ドメイン全体の委任を構成したら、サービス アカウントを使用して API 呼び出しを行い、ユーザー アカウントの権限を借用できます。サービス アカウントは認証に使用されますが、ドメイン全体の委任はユーザーの権限を借用するため、ユーザー認証と見なされます。ユーザー認証を必要とする機能であれば、ドメイン全体の委任を使用できます。

Chat アプリで認証が必要になるタイミングと、使用する認証の種類の詳細については、Chat API の認証と承認の概要の必要な認証の種類をご覧ください。

前提条件

このガイドの例を実行するには、次の前提条件を満たす必要があります。

また、次の言語固有の前提条件も必要です。

Java

  • JDK 1.7 以降
  • Maven パッケージ管理ツール
  • 初期化された Maven プロジェクト。新しいプロジェクトを初期化するには、コマンドライン インターフェースで次のコマンドを実行します。

    mvn archetype:generate -DgroupId=com.google.chat.app.authsample -DartifactId=auth-sample-app -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
    

Python

  • Python 3.6 以降
  • pip パッケージ管理ツール

Node.js

  • Node.js
  • npm パッケージ管理ツール
  • 初期化された Node.js プロジェクト。新しいプロジェクトを初期化するには、新しいフォルダを作成して切り替え、コマンドライン インターフェースで次のコマンドを実行します。

    npm init
    

Apps Script

ステップ 1: Google Cloud コンソールでサービス アカウントを作成する

Chat アプリが Google API へのアクセスに使用するサービス アカウントを作成します。

サービス アカウントを作成する

サービス アカウントを作成するには、次の操作を行います。

Google Cloud コンソール

  1. Google Cloud コンソールで、メニュー > [IAM と管理] > [サービス アカウント] に移動します。

    [サービス アカウント] に移動

  2. [サービス アカウントを作成] をクリックします。
  3. サービス アカウントの詳細を入力し、[作成して続行] をクリックします。
  4. 省略可: サービス アカウントにロールを割り当てて、Google Cloud プロジェクトのリソースへのアクセス権を付与します。詳しくは、リソースへのアクセス権の付与、変更、取り消しをご覧ください。
  5. [続行] をクリックします。
  6. 省略可: このサービス アカウントを使用してアクションを管理、実行できるユーザーまたはグループを入力します。詳しくは、サービス アカウントの権限借用を管理するをご覧ください。
  7. [完了] をクリックします。サービス アカウントのメールアドレスをメモします。

gcloud CLI

  1. サービス アカウント
    gcloud iam service-accounts create SERVICE_ACCOUNT_NAME \
      --display-name="SERVICE_ACCOUNT_NAME"
    を作成します。
  2. 省略可: サービス アカウントにロールを割り当てて、Google Cloud プロジェクトのリソースへのアクセス権を付与します。詳しくは、リソースへのアクセス権の付与、変更、取り消しをご覧ください。

サービス アカウントがサービス アカウント ページに表示されます。次に、サービス アカウントの秘密鍵を作成します。

秘密鍵を作成する

サービス アカウントの秘密鍵を作成してダウンロードする手順は次のとおりです。

  1. Google Cloud コンソールで、メニュー > [IAM と管理] > [サービス アカウント] に移動します。

    [サービス アカウント] に移動

  2. サービス アカウントを選択します。
  3. [] > [鍵を追加] > [新しい鍵を作成] をクリックします。
  4. [JSON] を選択し、[作成] をクリックします。

    新しい公開鍵と秘密鍵のペアが生成され、新しいファイルとしてマシンにダウンロードされます。ダウンロードした JSON ファイルを credentials.json という名前で作業ディレクトリに保存します。この鍵のコピーはこのファイルのみです。鍵を安全に保管する方法については、サービス アカウント キーの管理をご覧ください。

  5. [Close] をクリックします。

サービス アカウントの詳細については、Google Cloud IAM ドキュメントのサービス アカウントをご覧ください。

ステップ 2: Google クライアント ライブラリとその他の依存関係をインストールする

Google クライアント ライブラリと、プロジェクトに必要なその他の依存関係をインストールします。

Java

Google クライアント ライブラリとその他の必要な依存関係を Maven プロジェクトに追加するには、プロジェクトのディレクトリ内の pom.xml ファイルを編集して、次の依存関係を追加します。

<dependencies>
  <!-- ... existing dependencies ... -->
  <dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-chat</artifactId>
    <version>v1-rev20230905-2.0.0</version>
  </dependency>
  <dependency>
    <groupId>com.google.auth</groupId>
    <artifactId>google-auth-library-oauth2-http</artifactId>
    <version>1.19.0</version>
  </dependency>
  <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.10.1</version>
  </dependency>
</dependencies>

Python

Python 用の Google クライアント ライブラリをまだインストールしていない場合は、コマンドライン インターフェースで次のコマンドを実行します。

pip3 install --upgrade google-api-python-client google-auth

Node.js

Google クライアント ライブラリを Node.js プロジェクトに追加するには、プロジェクトのディレクトリに切り替えて、コマンドライン インターフェースで次のコマンドを実行します。

npm install "@googleapis/chat"

Apps Script

このサンプルでは、OAuth2 for Apps Script ライブラリを使用して、サービス アカウント認証用の JWT トークンを生成します。ライブラリを Apps Script プロジェクトに追加するには:

  1. 左側の [エディタ] をクリックします。
  2. 左側の [ライブラリ] の隣にある [ライブラリを追加] をクリックします。
  3. スクリプト ID 1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF を入力します。
  4. [Look up]、[追加] の順にクリックします。

このサンプルでは、Advanced Chat サービスを使用して Google Chat API を呼び出します。Apps Script プロジェクトのサービスを有効にするには:

  1. 左側の [エディタ] をクリックします。
  2. 左側の [サービス] の隣にある [サービスを追加] をクリックします。
  3. [Google Chat API] を選択します。
  4. [バージョン] で [v1] を選択します。
  5. [Add] をクリックします。

Google のクライアント ライブラリでサポートされている任意の言語を使用できます。

ステップ 3: サービス アカウントを使用して Chat API で認証するスクリプトを作成する

次のコードは、サービス アカウントを使用して Chat API で認証を行い、Chat スペースにメッセージを投稿します。

Java

  1. プロジェクトのディレクトリで、src/main/java/com/google/chat/app/authsample/App.java ファイルを開きます。
  2. App.java の内容を次のコードに置き換えます。

    package com.google.chat.app.authsample;
    
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.http.HttpRequestInitializer;
    import com.google.api.client.json.gson.GsonFactory;
    import com.google.api.services.chat.v1.HangoutsChat;
    import com.google.api.services.chat.v1.model.Message;
    import com.google.auth.http.HttpCredentialsAdapter;
    import com.google.auth.oauth2.GoogleCredentials;
    
    /**
     * Authenticates with Chat API via service account credentials,
     * then creates a Chat message.
     */
    public class App {
        // Specify required scopes.
        private static final String CHAT_SCOPE = "https://www.googleapis.com/auth/chat.bot";
    
        // Specify service account details.
        private static final String PRIVATE_KEY_RESOURCE_URI = "/credentials.json";
    
        public static void main( String[] args ) {
            try {
                // Run app.
                Message response = App.createChatMessage();
                // Print details about the created message.
                System.out.println(response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        private static Message createChatMessage() throws Exception {
            // Build the Chat API client and authenticate with the service account.
            GoogleCredentials credentials = GoogleCredentials.fromStream(
                App.class.getResourceAsStream(PRIVATE_KEY_RESOURCE_URI))
                .createScoped(CHAT_SCOPE);
            HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
            HangoutsChat chatService = new HangoutsChat.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                GsonFactory.getDefaultInstance(),
                requestInitializer)
                .setApplicationName("auth-sample-app")
                .build();
    
            // The space to create the message in.
            //
            // Replace SPACE_NAME with a space name.
            // Obtain the space name from the spaces resource of Chat API,
            // or from a space's URL.
            String spaceName = "spaces/SPACE_NAME";
    
            // Create a Chat message.
            Message message = new Message().setText("Hello, world!");
            return chatService.spaces().messages().create(spaceName, message).execute();
        }
    }
    
  3. コードで SPACE_NAME をスペース名に置き換えます。スペース名は、Chat API の spaces.list メソッドまたはスペースの URL から取得できます。

  4. プロジェクトのディレクトリに resources という名前の新しいサブディレクトリを作成します。

  5. サービス アカウントの秘密鍵ファイルの名前が credentials.json であることを確認し、resources サブディレクトリにコピーします。

  6. プロジェクト パッケージに秘密鍵ファイルを含めるように Maven を構成するには、プロジェクトのディレクトリで pom.xml ファイルを編集し、次の構成を <build> セクションに追加します。

    <build>
      <!-- ... existing configurations ... -->
      <resources>
        <resource>
          <directory>resources</directory>
        </resource>
      </resources>
    </build>
    
  7. プロジェクト パッケージに依存関係を含めてアプリケーションのメインクラスを実行するように Maven を構成するには、プロジェクトのディレクトリ内の pom.xml ファイルを編集し、次の構成を <plugins> セクションに追加します。

    <plugins>
      <!-- ... existing configurations ... -->
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.google.chat.app.authsample.App</mainClass>
            </manifest>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
      </plugin>
    </plugins>
    

Python

  1. 作業ディレクトリに、chat_app_auth.py という名前のファイルを作成します。
  2. chat_app_auth.py に次のコードを追加します。

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE_NAME with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE_NAME',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    # Prints details about the created message.
    print(result)
    
  3. コードで SPACE_NAME をスペース名に置き換えます。スペース名は、Chat API の spaces.list メソッドまたはスペースの URL から取得できます。サービス アカウントの秘密鍵ファイルの名前は credentials.json にしてください。

Node.js

  1. プロジェクトのディレクトリに、chat_app_auth.js という名前のファイルを作成します。
  2. chat_app_auth.js に次のコードを追加します。

    const chat = require('@googleapis/chat');
    
    async function createMessage() {
      const auth = new chat.auth.GoogleAuth({
    
        // Specify service account details.
        keyFilename: 'credentials.json',
    
        // Specify required scopes.
        scopes: ['https://www.googleapis.com/auth/chat.bot']
    
      });
      const authClient = await auth.getClient();
    
      // Create the Chat API client and authenticate with the service account.
      const chatClient = await chat.chat({
        version: 'v1',
        auth: authClient
      });
    
      // Create a Chat message.
      const result = await chatClient.spaces.messages.create({
    
        // The space to create the message in.
        //
        // Replace SPACE_NAME with a space name.
        // Obtain the space name from the spaces resource of Chat API,
        // or from a space's URL.
        parent: 'spaces/SPACE_NAME',
    
        // The message to create.
        requestBody: { 'text': 'Hello, world!' }
    
      });
      return result;
    }
    
    // Execute function then print details about the created message.
    createMessage().then(console.log);
    
  3. コードで SPACE_NAME をスペース名に置き換えます。スペース名は、Chat API の spaces.list メソッドまたはスペースの URL から取得できます。サービス アカウントの秘密鍵ファイルの名前は credentials.json にしてください。

Apps Script

  1. Apps Script エディタで、appsscript.json ファイルを編集し、サービス アカウントの OAuth トークンを取得する外部リクエストを行うために必要な OAuth スコープを追加します。

      "oauthScopes": [
        "https://www.googleapis.com/auth/script.external_request"
      ]
    
  2. 次のコードを Apps Script プロジェクトの ChatAppAuth.gs という名前のファイルに保存します。

    // Specify the contents of the file credentials.json.
    const CREDENTIALS = CREDENTIALS;
    
    const SCOPE = 'https://www.googleapis.com/auth/chat.bot';
    
    // The space to create the message in.
    //
    // Replace SPACE_NAME with a space name.
    // Obtain the space name from the spaces resource of Chat API,
    // or from a space's URL.
    const PARENT = 'spaces/SPACE_NAME'
    
    /**
     * Authenticates with Chat API via app credentials, then posts a message.
     */
    function createMessageWithAppCredentials() {
      try {
        const service = getService_();
        if (!service.hasAccess()) {
          console.error(service.getLastError());
          return;
        }
    
        // Specify the message to create.
        const message = {'text': 'Hello world!'};
    
        // Call Chat API with a service account to create a message.
        const result = Chat.Spaces.Messages.create(
            message,
            PARENT,
            {},
            // Authenticate with the service account token.
            {'Authorization': 'Bearer ' + service.getAccessToken()});
    
        // Log details about the created message.
        console.log(result);
    
      } catch (err) {
        // TODO (developer) - Handle exception.
        console.log('Failed to create message with error %s', err.message);
      }
    }
    
    /**
     * Configures the OAuth library to authenticate with the service account.
     */
    function getService_() {
      return OAuth2.createService(CREDENTIALS.client_email)
          .setTokenUrl('https://oauth2.googleapis.com/token')
          .setPrivateKey(CREDENTIALS.private_key)
          .setIssuer(CREDENTIALS.client_email)
          .setSubject(CREDENTIALS.client_email)
          .setScope(SCOPE)
          .setPropertyStore(PropertiesService.getScriptProperties());
    }
    
  3. コードで、CREDENTIALS をファイル credentials.json の内容に置き換えます。

  4. コードで SPACE_NAME をスペース名に置き換えます。スペース名は、Chat API の spaces.list メソッドまたはスペースの URL から取得できます。

ステップ 4: サンプル全体を実行する

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

Java

mvn compile assembly:single
java -jar target/auth-sample-app-1.0-SNAPSHOT-jar-with-dependencies.jar

Python

python3 chat_app_auth.py

Node.js

node chat_app_auth.js

Apps Script

Apps Script エディタで ChatAppAuth.gs ファイルを開き、[実行] をクリックします。

スクリプトが Chat API に認証済みリクエストを行います。この API は、Chat アプリとして Chat スペースにメッセージを送信することで応答します。

例のトラブルシューティング

このセクションでは、このサンプルの実行中に発生する可能性のある一般的な問題について説明します。

このアプリの使用は許可されていません

スクリプトを実行すると、次のようなエラーが表示されることがあります。

<HttpError 403 when requesting https://chat.googleapis.com/v1/spaces/{space}/messages?alt=json returned "You are not permitted to use this app". Details: "You are not permitted to use this app">

このエラー メッセージは、指定された Chat スペースに Chat メッセージを作成する権限が Chat アプリにないことを意味します。

エラーを解決するには、スクリプトで指定された Chat スペースに Chat アプリを追加します。

Chat API で他に何ができるかについては、Chat API のリファレンス ドキュメントをご覧ください。