AIイノベーションズ

Node.jsでGoogleChatにWebhookメッセージを送信する

Node.jsを使ってGoogleChatにWebhookメッセージを送信する方法を解説。シンプルなコードで実装できる自動通知システムの作り方や、エラーハンドリング、レスポンスの確認方法まで、実践的なサンプルコード付きで紹介します。

Webhook URLを取得する

まず、Webhook URLを取得しましょう。

コード

以下のコードの関数を実行することでGoogleChatに送信できます。(Node.js v18~)

// GoogleChatのWebhook URLにメッセージを送信する関数
const sendMessageToGoogleChat = async (message) => {
  if (!message) {
    throw new Error("No message content provided.");
  }
  const GoogleChatWebhookUrl = process.env.GOOGLE_CHAT_WEBHOOK_URL;
 
  const config = {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-type": "application/json",
    },
    body: JSON.stringify({ text: message }),
  };
 
  try {
    const response = await fetch(GoogleChatWebhookUrl, config);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const contentType = response.headers.get("content-type");
    if (contentType && contentType.includes("application/json")) {
      const data = await response.json();
      console.log("Message sent:", message);
      console.log("Response data:", data);
    } else {
      console.log("Message sent:", message);
      console.log("Unexpected content type:", contentType);
    }
    return true;
  } catch (error) {
    console.error(`Error sending message "${message}": ${error}`);
    throw error;
  }
};

ここでは1つのWebhook URLにだけ送信するようになっていますが、引数にURLを設定することでさまざまなWebhook URL(=チャンネル)に送ることができます。

適宜そこは変更してください。

On this page