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 アプリ自体がスペースのメンバーである必要があります。

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. [閉じる] をクリックします。

サービス アカウントの詳細については、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

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

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

このサンプルでは、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. コードで、CREDENTIALScredentials.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 のリファレンス ドキュメントをご覧ください。