Apps Script を使用すると、Google Chat でチャットアプリを簡単に作成できます。
- ブラウザから直接、わずか数分でアプリを実行できます。
- サーバーの実行と管理、継続的なメンテナンスまたは運用のコスト、開発環境のダウンロードと設定について心配する必要はありません。
- Google API(特にGoogle Workspace API)は簡単に呼び出すことができます。Apps Script を使用すると、ダウンロードやセットアップは必要なく、認証は自動的に処理され、Google API の呼び出しはネイティブ関数の呼び出しと同様です。
このガイドでは、Apps Script を使用してアプリを作成し、登録する方法について説明します。
使用を開始する
このセクションでは、Apps Script を使用してチャットアプリをすばやく作成する方法について説明します。
ステップ 1: Apps Script テンプレートをコピーする
Apps Script アプリの作成を開始する最も簡単な方法は、Chat テンプレートを使用することです。これにより、必要なメソッドを含む Apps Script プロジェクトが作成されます。その後、必要に応じて、アプリロジックの実装やビルドしたアプリとの統合に必要なメソッドを入力します。次のコードは、シンプルなアプリに入力されるテンプレートの例を示しています。
/** * Responds to a MESSAGE event in Google Chat. * * @param {Object} event the event object from Google Chat */ function onMessage(event) { var name = ""; if (event.space.type == "DM") { name = "You"; } else { name = event.user.displayName; } var message = name + " said \"" + event.message.text + "\""; return { "text": message }; } /** * Responds to an ADDED_TO_SPACE event in Google Chat. * * @param {Object} event the event object from Google Chat */ function onAddToSpace(event) { var message = ""; if (event.space.singleUserBotDm) { message = "Thank you for adding me to a DM, " + event.user.displayName + "!"; } else { message = "Thank you for adding me to " + (event.space.displayName ? event.space.displayName : "this chat"); } if (event.message) { // Bot added through @mention. message = message + " and you said: \"" + event.message.text + "\""; } return { "text": message }; } /** * Responds to a REMOVED_FROM_SPACE event in Google Chat. * * @param {Object} event the event object from Google Chat */ function onRemoveFromSpace(event) { console.info("Bot removed from ", (event.space.name ? event.space.name : "this chat")); }
ステップ 2: onMessage 関数を編集する
デフォルトでは、テンプレートの onMessage
関数は、テキストと単純なカードを含む Message
オブジェクトを返します。この関数を編集して、テキストまたは特定のカード ウィジェットを返すことができます。
function onMessage(e) {
return { 'text': 'You said: \`' + e.message.text + '\`' };
}
ステップ 3: 導入 ID を取得する
アプリを登録する前に、このアプリの DeploymentID を取得する必要があります。
- [デプロイ] > [新しいデプロイ] をクリックします。
- [Select type] で、[アドオン] をクリックします。
- オプションを入力して [デプロイ] をクリックします。
- [Deployment ID] で [コピー] をクリックします。
デプロイ ID の使用に関するベスト プラクティスについては、リリース管理ガイドをご覧ください。
ステップ 4: アプリを登録する
アプリは Google Cloud コンソールから登録できます。アプリの登録画面で、アプリ名、アバターの URL、説明を入力します。テストでは、[アプリにメッセージを直接送信できます] と [アプリは複数のユーザーが存在するスペースで動作します] を有効にできます。[接続設定] で [Apps Script] を選択し、前の手順でコピーしたデプロイ ID を貼り付けます。
ステップ 5: アプリをテストする
アプリをテストするには、そのアプリを使用して DM を開始するか、スペースに名前リンクを付けます。これに話しかけると、ステップ 2 のメッセージのレスポンスに応答します。 完了です!
Apps Script アプリのコンセプト
イベント
Apps Script は、アプリが実装できる複数のイベント ハンドラ関数をサポートしています。各関数は異なるイベントタイプを処理し、各関数は単一のイベント e(イベント オブジェクト)を受け取ります。
onAddToSpace(e)
- この関数は、スペースにアプリが追加されると実行されます。アプリはスペースに直接追加するか、名前リンク付きで追加できます。2 番目のケースでは、イベント e にも
message
プロパティがあります。この関数は、Message
オブジェクトを返します。これは通常、アプリまたは @mention に対するレスポンスをエンドユーザーに知らせるためのウェルカム メッセージです。 onMessage(e)
- アプリがすでにスペース内にあり、ユーザーがアプリに名前リンクを付けると、この関数が呼び出されます。アプリのレスポンスを含む
Message
オブジェクトが返されます。 onRemoveFromSpace(e)
- ユーザーが DM リストまたはスペースからアプリを削除すると、この関数は呼び出されます。アプリは削除され、これ以上メッセージを投稿できないため、この関数の戻り値は無視されます。
次の例では、onAddToSpace
と onRemoveFromSpace
を実装しています。
// onAddToSpace() is invoked when the app is added to a space or when
// a user initiates / re-initiates a direct message with the app.
function onAddToSpace(e) {
if (!e.space.singleUserBotDm) {
return { 'text': 'Thanks for adding me to "' +
(e.space.displayName ? e.space.displayName : "this chat") + '"!' };
} else {
return { 'text': 'Thanks for adding me to a DM!' };
}
}
// onRemoveFromSpace() is invoked when app is removed from a space
// or when a user removes a direct message with the app.
function onRemoveFromSpace(e) {}
人間間のダイレクト メッセージに e.space.displayName
が存在しない可能性があります。
インタラクティブなカード
他のアプリと同様に、Apps Script アプリはインタラクティブなカードを表示できます。カードをインタラクティブにする方法については、インタラクティブ カードに関するドキュメントをご覧ください。Apps Script アプリとの主な違いは、action.actionMethodName と action.parameters の Key-Value ペアをメソッド パラメータとして使用して、onClick イベントがトリガーされたときに呼び出す特定のメソッドを指定できることです。
承認
保護されたリソースにアクセスする Apps Script アプリでは、このアクセスを各ユーザーに対して初めて実行する際に、ユーザーに承認してもらう必要があります。この操作は必要ありません。ただし、ユーザーがアプリを初めて使用するときに承認ダイアログが表示される場合があります。
Apps Script はスクリプト レベルで認可を処理します。承認が必要なアプリは、エンドユーザーがアプリを承認するまで、アクションを実行できません。アプリが承認済みでなく、スペースに直接追加されたときにウェルカム メッセージを表示する場合は、マニフェストでフォールバック メッセージを指定します。アプリで初期化ロジックが必要な場合は、onMessage
アクションでこのロジックを複製する必要がある場合があります。例:
function onMessage(event) {
var userProperties = PropertiesService.getUserProperties();
if (!userProperties.getProperty('initialized')) {
// handle the onAddToSpace initialization logic here.
...
userProperties.setProperties({initialized: 'true'});
}
// Handle normal onMessage logic.
...
}
非同期メッセージ
一部のアプリでは、Apps Script の時間ベースのトリガーなど、外部トリガーに基づいて Google Chat にメッセージを送信する必要があります。
このユースケースでは、Google Chat API を Apps Script にネイティブに統合する予定です。それまでの間、これを行うための唯一の方法は、外部 HTTP API を使用することです(ドキュメントをご覧ください)。この場合、OAuth2 for Apps Script ライブラリを介して Cloud サービス アカウント(ドキュメントを参照)を使用する必要があります。
次のすべてのサンプルアプリは、そのスペース内のすべてのメッセージを 1 分ごとに投稿します。
// Example app for Google Chat that demonstrates app-initiated messages
// by spamming the user every minute.
//
// This app makes use of the Apps Script OAuth2 library at:
// https://github.com/googlesamples/apps-script-oauth2
//
// Follow the instructions there to add the library to your script.
// When added to a space, we store the space's ID in ScriptProperties.
function onAddToSpace(e) {
PropertiesService.getScriptProperties()
.setProperty(e.space.name, '');
return {
'text': 'Hi! I\'ll post a message here every minute. ' +
'Please remove me after testing or I\'ll keep spamming you!'
};
}
// When removed from a space, we remove the space's ID from ScriptProperties.
function onRemoveFromSpace(e) {
PropertiesService.getScriptProperties()
.deleteProperty(e.space.name);
}
// Add a trigger that invokes this function every minute via the
// "Edit > Current Project's Triggers" menu. When it runs, it will
// post in each space the app was added to.
function onTrigger() {
var spaceIds = PropertiesService.getScriptProperties()
.getKeys();
var message = { 'text': 'Hi! It\'s now ' + (new Date()) };
for (var i = 0; i < spaceIds.length; ++i) {
postMessage(spaceIds[i], message);
}
}
var SCOPE = 'https://www.googleapis.com/auth/chat.bot';
// The values below are copied from the JSON file downloaded upon
// service account creation.
// For SERVICE_ACCOUNT_PRIVATE_KEY, remember to include the BEGIN and END lines of the private key
var SERVICE_ACCOUNT_PRIVATE_KEY = '...';
var SERVICE_ACCOUNT_EMAIL = 'service-account@project-id.iam.gserviceaccount.com';
// Posts a message into the given space ID via the API, using
// service account authentication.
function postMessage(spaceId, message) {
var service = OAuth2.createService('chat')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(SERVICE_ACCOUNT_PRIVATE_KEY)
.setClientId(SERVICE_ACCOUNT_EMAIL)
.setPropertyStore(PropertiesService.getUserProperties())
.setScope(SCOPE);
if (!service.hasAccess()) {
Logger.log('Authentication error: %s', service.getLastError());
return;
}
var url = 'https://chat.googleapis.com/v1/' + spaceId + '/messages';
UrlFetchApp.fetch(url, {
method: 'post',
headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
contentType: 'application/json',
payload: JSON.stringify(message),
});
}
マニフェスト ファイル
スクリプトに付属する Apps Script マニフェスト ファイルの例を次に示します。
Chat テンプレートからプロジェクトを開始していない場合は、マニフェスト ファイルを編集して "chat": {}
オブジェクトを追加する必要があります。
マニフェスト ファイルで、ランタイムを Rhino("runtimeVersion": "DEPRECATED_ES5"
)に設定します。Chat アプリは Apps Script V8 ランタイムを完全にはサポートしていないため、"runtimeVersion": "V8"
を指定すると、チャットアプリでエラーが発生する可能性があります。たとえば、V8 ランタイムで構築された Chat アプリでは、JSON レスポンスの構造が予期せず変更される場合があります。
{
"timeZone": "America/Los_Angeles",
"dependencies": {},
"chat": {
"addToSpaceFallbackMessage": "Thank you for adding me!"
},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "DEPRECATED_ES5"
}
アプリを承認する前に、ユーザーがスペースにアプリを追加することは可能です。この場合、アプリはスペースへの追加イベントに応答できません。その場合は、addToSpaceFallbackMessage
フィールドを使用してウェルカム メッセージを表示できます。
マニフェスト ファイルの名前は appsscript.json
で、Apps Script プロジェクトの一部です。Apps Script エディタでマニフェスト ファイルを表示するには、[表示] > [マニフェスト ファイルを表示] を選択します。