このガイドでは、サービス アカウントを設定して使用し、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 の認証と認可の概要で必要な認証の種類をご覧ください。
前提条件
このガイドの例を実行するには、次の前提条件を満たす必要があります。
- Google Chat へのアクセス権を持つ Google Workspace アカウント。
- Chat API が有効になっている Google Cloud プロジェクト。プロジェクトを作成して API を有効にするには、プロジェクトを作成して API を有効にするをご覧ください。
- Chat スペースにメンバーシップがある公開済みの Chat アプリ:
- Chat アプリを作成して公開するには、Cloud Functions を使用して Google Chat アプリを作成するをご覧ください。
- Chat アプリを Chat スペースに追加するには、Google Chat のスペースまたは会話にアプリを追加するをご覧ください。
さらに、次の言語固有の前提条件を満たす必要があります。
Java
Python
- Python 3.6 以降
- pip パッケージ管理ツール
Node.js
Apps Script
- Google Cloud プロジェクトに接続されている Apps Script プロジェクト。Apps Script プロジェクトを初期化するには、Google Apps Script Chat アプリのクイックスタートをご覧ください。
ステップ 1: Google Cloud コンソールでサービス アカウントを作成する
Chat アプリが Google API へのアクセスに使用できるサービス アカウントを作成します。
サービス アカウントを作成する
サービス アカウントを作成するには、次の操作を行います。
Google Cloud コンソール
- Google Cloud コンソールで、メニュー > [IAM と管理] > [サービス アカウント] に移動します。
- [サービス アカウントを作成] をクリックします。
- サービス アカウントの詳細を入力し、[作成して続行] をクリックします。
- 省略可: サービス アカウントにロールを割り当てて、Google Cloud プロジェクトのリソースへのアクセス権を付与します。詳細については、リソースへのアクセス権の付与、変更、取り消しをご覧ください。
- [続行] をクリックします。
- 省略可: このサービス アカウントで管理やアクションの実行を許可するユーザーまたはグループを入力します。詳しくは、サービス アカウントの権限借用を管理するをご覧ください。
- [完了] をクリックします。サービス アカウントのメールアドレスをメモしておきます。
gcloud CLI
- サービス アカウントを作成します。
gcloud iam service-accounts create
SERVICE_ACCOUNT_NAME
\ --display-name="SERVICE_ACCOUNT_NAME
" - 省略可: サービス アカウントにロールを割り当てて、Google Cloud プロジェクトのリソースへのアクセス権を付与します。詳細については、リソースへのアクセス権の付与、変更、取り消しをご覧ください。
[サービス アカウント] ページにサービス アカウントが表示されます。次に、サービス アカウントの秘密鍵を作成します。
秘密鍵を作成する
サービス アカウントの秘密鍵を作成してダウンロードする手順は次のとおりです。
- Google Cloud コンソールで、メニュー > [IAM と管理] > [サービス アカウント] に移動します。
- サービス アカウントを選択します。
- [鍵] > [鍵を追加] > [新しい鍵を作成] をクリックします。
- [JSON] を選択し、[作成] をクリックします。
新しい公開鍵と秘密鍵のペアが生成され、新しいファイルとしてマシンにダウンロードされます。ダウンロードした JSON ファイルを
credentials.json
として作業ディレクトリに保存します。このファイルはこの鍵の唯一のコピーです。キーを安全に保存する方法については、サービス アカウント キーの管理をご覧ください。 - [閉じる] をクリックします。
サービス アカウントの詳細については、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 プロジェクトにライブラリを追加するには:
- 左側の [エディタ] をクリックします。
- 左側の [ライブラリ] の横にある [ライブラリを追加] をクリックします。
- スクリプト ID
1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF
を入力します。 - [Look up] をクリックし、[Add] をクリックします。
このサンプルでは、Advanced Chat サービスを使用して Google Chat API を呼び出します。Apps Script プロジェクトでサービスを有効にするには:
- 左側の [エディタ] をクリックします。
- 左側の [サービス] の横にある [サービスを追加] をクリックします。
- [Google Chat API] を選択します。
- [バージョン] で [v1] を選択します。
- [Add] をクリックします。
Google のクライアント ライブラリでサポートされている任意の言語を使用できます。
ステップ 3: サービス アカウントを使用して Chat API で認証するスクリプトを作成する
次のコードは、サービス アカウントを使用して Chat API で認証し、Chat スペースにメッセージを投稿します。
Java
- プロジェクトのディレクトリで、
src/main/java/com/google/chat/app/authsample/App.java
ファイルを開きます。 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(); } }
コードで
SPACE_NAME
をスペース名に置き換えます。スペースは、Chat API のspaces.list
メソッドまたはスペースの URL から取得します。プロジェクトのディレクトリ内に
resources
という名前の新しいサブディレクトリを作成します。サービス アカウントの秘密鍵ファイルの名前が
credentials.json
であることを確認し、このファイルをresources
サブディレクトリにコピーします。プロジェクト パッケージに秘密鍵ファイルを含めるように Maven を構成するには、プロジェクトのディレクトリにある
pom.xml
ファイルを編集し、次の構成を<build>
セクションに追加します。<build> <!-- ... existing configurations ... --> <resources> <resource> <directory>resources</directory> </resource> </resources> </build>
プロジェクト パッケージに依存関係を組み込んでアプリケーションのメインクラスを実行するように 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
- 作業ディレクトリに、
chat_app_auth.py
という名前のファイルを作成します。 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)
コードで
SPACE_NAME
をスペース名に置き換えます。スペースは、Chat API のspaces.list
メソッドまたはスペースの URL から取得します。サービス アカウントの秘密鍵ファイルの名前がcredentials.json
であることを確認します。
Node.js
- プロジェクトのディレクトリに、
chat_app_auth.js
という名前のファイルを作成します。 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);
コードで
SPACE_NAME
をスペース名に置き換えます。スペースは、Chat API のspaces.list
メソッドまたはスペースの URL から取得します。サービス アカウントの秘密鍵ファイルの名前がcredentials.json
であることを確認します。
Apps Script
Apps Script エディタで、
appsscript.json
ファイルを編集し、外部リクエストを行ってサービス アカウントの OAuth トークンを取得するために必要な OAuth スコープを追加します。"oauthScopes": [ "https://www.googleapis.com/auth/script.external_request" ]
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()); }
コードで、
CREDENTIALS
をcredentials.json
ファイルの内容に置き換えます。コードで
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 のリファレンス ドキュメントをご覧ください。