將 Google Chat 應用程式建構為 Webhook

本頁說明如何設定 Webhook,將非同步訊息傳送到 使用外部觸發條件的 Chat 聊天室。舉例來說: 設定監控應用程式,以通知值班人員 在伺服器故障時進行即時通訊。傳送同步郵件 連結即時通訊應用程式,請參閱 傳送訊息

在這個架構下 就無法與 Webhook 或外部連至的外部連線 因為通訊是單向通訊Webhook 並非對話式。 他們無法回覆或接收來自使用者的訊息 Chat 應用程式互動事件: 如要回覆訊息, 建構 Chat 擴充應用程式 而不是 Webhook

在技術上 Chat 應用程式:Webhook 會使用 HTTP 要求:這個網頁將其稱為 Chat 應用程式 簡化作業每個 Webhook 僅適用於以下項目的 Chat 聊天室: 註冊編號傳入的 Webhook 可在即時訊息中運作,但僅適用於 所有使用者 已啟用 Chat 擴充應用程式。 您無法將 Webhook 發布至 Google Workspace Marketplace。

下圖顯示已連線至 Webhook 的 Webhook 架構 即時通訊:

將非同步訊息傳送至 Chat 的連入 Webhook 架構。

在上圖中,Chat 應用程式的功能如下 資訊流通:

  1. Chat 應用程式邏輯會從 例如專案管理系統或 票務工具
  2. Chat 應用程式邏輯託管於雲端或 這個內部部署系統可以使用 Webhook 網址,將訊息傳送至 特定 Chat 聊天室。
  3. 使用者可在下列位置接收 Chat 應用程式的訊息: 特定 Chat 聊天室,但無法與 Chat 應用程式。

必要條件

Python

  • 企業或企業 具有存取權的 Google Workspace 帳戶 Google Chat。 您的 Google Workspace 機構必須允許使用者 新增及使用連入的 Webhook
  • Python 3.6 以上版本
  • pip 套件管理工具
  • httplib2 程式庫。如要安裝程式庫,請在指令列介面中執行下列指令:

    pip install httplib2
    
  • Google Chat 聊天室。如要使用 Google Chat API 建立聊天室,請參閱 建立聊天室。如要在 Chat 中建立聊天室,請按照下列步驟操作: 請前往 說明中心文件

Node.js

Java

Apps Script

建立 Webhook

如要建立 Webhook,請在所需 Chat 聊天室中註冊 Webhook 接收訊息,然後編寫用來傳送訊息的指令碼。

註冊連入 Webhook

  1. 在瀏覽器中開啟 即時通訊。 無法透過 Chat 行動應用程式設定 Webhook。
  2. 前往要新增 Webhook 的聊天室。
  3. 按一下聊天室標題旁邊的 展開更多箭頭,然後按一下「應用程式與」整合
  4. 按一下 「Add Webhooks」(新增 Webhook)

  5. 在「Name」(名稱) 欄位中輸入 Quickstart Webhook

  6. 在「顯示圖片」欄位中輸入 https://developers.google.com/chat/images/chat-product-icon.png

  7. 按一下 [儲存]

  8. 如要複製 Webhook 網址,請按一下 更多,然後按一下 複製連結。

編寫 Webhook 指令碼

Webhook 指令碼範例會將訊息傳送到 Webhook 所在的聊天室 方法是將 POST 要求傳送至 Webhook 網址。 Chat API 會透過 Message

請選取語言,瞭解如何建立 Webhook 指令碼:

Python

  1. 在工作目錄中,建立名為 quickstart.py 的檔案。

  2. quickstart.py 中,貼上下列程式碼:

    python/webhook/quickstart.py
    from json import dumps
    from httplib2 import Http
    
    # Copy the webhook URL from the Chat space where the webhook is registered.
    # The values for SPACE_ID, KEY, and TOKEN are set by Chat, and are included
    # when you copy the webhook URL.
    
    def main():
        """Google Chat incoming webhook quickstart."""
        url = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN"
        app_message = {"text": "Hello from a Python script!"}
        message_headers = {"Content-Type": "application/json; charset=UTF-8"}
        http_obj = Http()
        response = http_obj.request(
            uri=url,
            method="POST",
            headers=message_headers,
            body=dumps(app_message),
        )
        print(response)
    
    
    if __name__ == "__main__":
        main()
  3. url 變數的值替換成執行以下 Webhook 網址的 Webhook 網址: 您在註冊 Webhook 時所複製的程式碼。

Node.js

  1. 在工作目錄中,建立名為 index.js 的檔案。

  2. index.js 中,貼上下列程式碼:

    node/webhook/index.js
    /**
     * Sends asynchronous message to Google Chat
     * @return {Object} response
     */
    async function webhook() {
      const url = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages"
      const res = await fetch(url, {
        method: "POST",
        headers: {"Content-Type": "application/json; charset=UTF-8"},
        body: JSON.stringify({text: "Hello from a Node script!"})
      });
      return await res.json();
    }
    
    webhook().then(res => console.log(res));
  3. url 變數的值替換成執行以下 Webhook 網址的 Webhook 網址: 您在註冊 Webhook 時所複製的程式碼。

Java

  1. 在工作目錄中,建立名為 pom.xml 的檔案。

  2. pom.xml 中複製及貼上以下內容:

    java/webhook/pom.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.google.chat.webhook</groupId>
      <artifactId>java-webhook-app</artifactId>
      <version>0.1.0</version>
    
      <name>java-webhook-app</name>
      <url>https://github.com/googleworkspace/google-chat-samples/tree/main/java/webhook</url>
    
      <properties>
        <maven.compiler.target>11</maven.compiler.target>
        <maven.compiler.source>11</maven.compiler.source>
      </properties>
    
      <dependencies>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.9.1</version>
        </dependency>
      </dependencies>
    
      <build>
        <pluginManagement>
          <plugins>
            <plugin>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>3.8.0</version>
            </plugin>
          </plugins>
        </pluginManagement>
      </build>
    </project>
  3. 在工作目錄中建立以下目錄結構 src/main/java

  4. src/main/java 目錄中,建立名為 App.java 的檔案。

  5. App.java 中,貼上下列程式碼:

    java/webhook/src/main/java/com/google/chat/webhook/App.java
    import com.google.gson.Gson;
    import java.net.http.HttpClient;
    import java.net.http.HttpRequest;
    import java.net.http.HttpResponse;
    import java.util.Map;
    import java.net.URI;
    
    public class App {
      private static final String URL = "https://chat.googleapis.com/v1/spaces/AAAAGCYeSRY/messages";
      private static final Gson gson = new Gson();
      private static final HttpClient client = HttpClient.newHttpClient();
    
      public static void main(String[] args) throws Exception {
        String message = gson.toJson(Map.of("text", "Hello from Java!"));
    
        HttpRequest request = HttpRequest.newBuilder(
            URI.create(URL))
            .header("accept", "application/json; charset=UTF-8")
            .POST(HttpRequest.BodyPublishers.ofString(message))
            .build();
    
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    
        System.out.println(response.body());
      }
    }
  6. URL 變數的值替換成您產生的 Webhook 網址 會在您註冊 Webhook 時複製。

Apps Script

  1. 使用瀏覽器前往 Apps Script

  2. 按一下「New Project」

  3. 貼上下列程式碼:

    apps-script/webhook/webhook.gs
    function webhook() {
      const url = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages"
      const options = {
        "method": "post",
        "headers": {"Content-Type": "application/json; charset=UTF-8"},
        "payload": JSON.stringify({"text": "Hello from Apps Script!"})
      };
      const response = UrlFetchApp.fetch(url, options);
      console.log(response);
    }
  4. url 變數的值替換成您產生的 Webhook 網址 會在您註冊 Webhook 時複製。

執行 Webhook 指令碼

在 CLI 中,執行指令碼:

Python

  python3 quickstart.py

Node.js

  node index.js

Java

  mvn compile exec:java -Dexec.mainClass=App

Apps Script

  • 按一下「執行」

執行程式碼時,Webhook 會傳送訊息至您所在的聊天室 已註冊。

發起或回覆訊息串

  1. 請說明 spaces.messages.thread.threadKey敬上 做為訊息要求內文的一部分根據您要啟動 回覆執行緒時,請將下列 threadKey 值用於:

    • 如要啟動執行緒,請將 threadKey 設為任意字串,但 請記下這個值,回覆討論串。

    • 如要回覆討論串,請指定threadKey在回覆 已啟動討論串。舉例來說,如果您要對 初始訊息使用 MY-THREAD,請設定 MY-THREAD

  2. 如果找不到指定的 threadKey,請定義執行緒行為:

    • 回覆討論串或發起新討論串。將 messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD 參數加到 Webhook 網址傳送此網址參數後,Chat 就會 使用指定的 threadKey 尋找現有執行緒。如果有 發現之後,該訊息即是回覆該討論串的回覆。如果沒有: 訊息找到之後,訊息即會開啟新的討論串 threadKey

    • 回覆討論串或不採取任何行動。將 messageReplyOption=REPLY_MESSAGE_OR_FAIL 參數連結到 Webhook 網址。 傳送此網址參數後,Chat 就會 使用指定的 threadKey 尋找現有執行緒。如果有 發現之後,該訊息即是回覆該討論串的回覆。如果沒有: ,因此訊息不會傳送。

    詳情請參閱 messageReplyOption

以下程式碼範例會開始或回覆訊息串:

Python

python/webhook/thread-reply.py
from json import dumps
from httplib2 import Http

# Copy the webhook URL from the Chat space where the webhook is registered.
# The values for SPACE_ID, KEY, and TOKEN are set by Chat, and are included
# when you copy the webhook URL.
#
# Then, append messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD to the
# webhook URL.


def main():
    """Google Chat incoming webhook that starts or replies to a message thread."""
    url = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN&messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"
    app_message = {
        "text": "Hello from a Python script!",
        # To start a thread, set threadKey to an arbitratry string.
        # To reply to a thread, specify that thread's threadKey value.
        "thread": {"threadKey": "THREAD_KEY_VALUE"},
    }
    message_headers = {"Content-Type": "application/json; charset=UTF-8"}
    http_obj = Http()
    response = http_obj.request(
        uri=url,
        method="POST",
        headers=message_headers,
        body=dumps(app_message),
    )
    print(response)


if __name__ == "__main__":
    main()

Node.js

node/webhook/thread-reply.js
/**
 * Sends asynchronous message to Google Chat
 * @return {Object} response
 */
async function webhook() {
  const url = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN&messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"
  const res = await fetch(url, {
    method: "POST",
    headers: {"Content-Type": "application/json; charset=UTF-8"},
    body: JSON.stringify({
      text: "Hello from a Node script!",
      thread: {threadKey: "THREAD_KEY_VALUE"}
    })
  });
  return await res.json();
}

webhook().then(res => console.log(res));

Apps Script

apps-script/webhook/thread-reply.gs
function webhook() {
  const url = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN&messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"
  const options = {
    "method": "post",
    "headers": {"Content-Type": "application/json; charset=UTF-8"},
    "payload": JSON.stringify({
      "text": "Hello from Apps Script!",
      "thread": {"threadKey": "THREAD_KEY_VALUE"}
    })
  };
  const response = UrlFetchApp.fetch(url, options);
  console.log(response);
}