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

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

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

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

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

Chat 用アプリでユーザーデータにアクセスしたり、ユーザーの 代わりにユーザーとして認証します。

ドメイン管理者は、Google Chat のメッセージ履歴を ドメイン全体の権限の委任 アプリケーションのサービス アカウントがユーザーのデータを ユーザーごとに同意を求めることも可能ドメイン全体の委任を設定したら、 できます。 サービス アカウントを使用して API 呼び出しを行い、ユーザー アカウントの権限を借用する。サービス アカウントは、Kubernetes サービス ドメイン全体の委任はユーザーの権限を借用するため、 ユーザー認証とみなされます。ユーザーによる操作を必要とする ドメイン全体の委任を使用できます。

Chat 用アプリで認証が必要な場合と、 詳しくは、このモジュールの 必要な認証の種類 をご覧ください。

前提条件

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

さらに、次の言語固有の前提条件を満たす必要があります。

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 プロジェクトのリソースへのアクセス権を付与します。詳細については、リソースへのアクセス権の付与、変更、取り消しをご覧ください。

[サービス アカウント] ページにサービス アカウントが表示されます。次に、限定公開の Google Cloud 鍵を作成します。

秘密鍵を作成する

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

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

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

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

    新しい公開鍵/秘密鍵のペアが生成され、 新しいファイルとしてエクスポートします。ダウンロードした JSON ファイルを credentials.json という名前で保存します。 作成されます。このファイルはこの鍵の唯一のコピーです。Google Cloud Storage バケットを 保護する方法については、以下をご覧ください。 サービス アカウント キーを管理する

  5. [閉じる] をクリックします。

サービス アカウントの詳細については、このモジュールの サービス アカウント ドキュメントをご覧ください

ステップ 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] をクリックし、[Add] をクリックします。

このサンプルでは、 高度な Chat サービス Google Chat API を呼び出すことができます。組織でサービスを有効にするには、 Apps Script プロジェクト:

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

Google Cloud でサポートされているすべての言語を クライアント ライブラリ

ステップ 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 をスペースに置き換えます。 名前。これは 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 をスペースに置き換えます。 名前。これは 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 をスペースに置き換えます。 名前。これは spaces.list から取得できます。 メソッド、またはスペースの URL から取得できます。必ず、 サービス アカウントの秘密鍵ファイルの名前は credentials.json です。

Apps Script

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

      "oauthScopes": [
        "https://www.googleapis.com/auth/script.external_request"
      ]
    
  2. 次のコードを 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 をスペースに置き換えます。 名前。これは 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

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

スクリプトは、認証済みのリクエストを Chat API。メッセージを投稿して応答します。 スペースで 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 のその他の機能を確認する リファレンス ドキュメントをご覧ください。