Skip to content

非公式 / UnofficialCloudflare, Inc. 非提携。アカウント情報は入力しないでください。Not affiliated with Cloudflare, Inc. Do not enter Cloudflare credentials here.Official docsこのサイトについてプライバシー

Google Chat

最終更新 Markdown で表示Agent セットアップ

Google Chat Pages Plugin は、メッセージに応答できる Google Chat ボットを作成します。ユーザー入力なしで Google Chat とやり取りする API(メッセージ作成など)も含まれます。この API はアラートなどの用途に向きます。

インストール

npm i @cloudflare/pages-plugin-google-chat

使い方

import googleChatPlugin from "@cloudflare/pages-plugin-google-chat";

export const onRequest: PagesFunction = googleChatPlugin(async (message) => {
	if (message.text.includes("ping")) {
		return { text: "pong" };
	}

	return { text: "Sorry, I could not understand your message." };
});

Plugin は関数を 1 つ受け取ります。その関数は受信メッセージを受け取り、応答メッセージの Promise を返します(応答しない場合は void)。

Plugin が公開するルートは 1 つだけです。ボット作成時に Google Cloud Console へ設定する URL として、このルートを使います。

Google Cloud Console の Google Chat API Connection Settings。App URL が選択され、App URL 入力欄に https://example.com/google-chat が入力されています。

API

Google Chat API は、GoogleChatAPI クラスで直接呼び出せます。

import { GoogleChatAPI } from "@cloudflare/pages-plugin-google-chat/api";

export const onRequest: PagesFunction = () => {
	// Initialize a GoogleChatAPI with your service account's credentials
	const googleChat = new GoogleChatAPI({
		credentials: {
			client_email: "SERVICE_ACCOUNT_EMAIL_ADDRESS",
			private_key: "SERVICE_ACCOUNT_PRIVATE_KEY",
		},
	});

	// Post a message
	// https://developers.google.com/chat/api/reference/rest/v1/spaces.messages/create
	const message = await googleChat.createMessage(
		{ parent: "spaces/AAAAAAAAAAA" },
		undefined,
		{
			text: "I'm an alert!",
		},
	);

	return new Response("Alert sent.");
};

サービスアカウントの認証情報は、上記のような平文ではなく、KV に保存することをおすすめします。

GoogleChatAPI インスタンスでは、次の関数を使えます。それぞれ最大 3 つの引数を取ります。パスパラメーターのオブジェクト、クエリパラメーターのオブジェクト、リクエストボディのオブジェクトです。詳細は Google Chat API のドキュメント ↗ を参照してください。

役に立ちましたか?