Google Chat Pages Plugin は、メッセージに応答できる Google Chat ボットを作成します。ユーザー入力なしで Google Chat とやり取りする API(メッセージ作成など)も含まれます。この API はアラートなどの用途に向きます。
npm i @cloudflare/pages-plugin-google-chatyarn add @cloudflare/pages-plugin-google-chatpnpm add @cloudflare/pages-plugin-google-chatbun add @cloudflare/pages-plugin-google-chatimport 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 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 のドキュメント ↗ を参照してください。