使用 Google Cloud Functions 建構即時通訊應用程式

透過集合功能整理內容 你可以依據偏好儲存及分類內容。

本頁面說明如何使用 Google Cloud Functions 建立即時通訊應用程式並進行互動。

如要建構應用程式,請編寫及部署一個 Cloud 函式,讓應用程式用來處理 Google Chat 訊息事件的回應。回應是顯示寄件者名稱和顯示圖片的資訊卡,如下圖所示:

即時通訊應用程式回應卡片,當中有寄件者的顯示名稱和顯示圖片

目標

  • 設定環境。
  • 建立及部署 Cloud 函式。
  • 將應用程式發布到 Google Chat。
  • 測試應用程式。

必要條件

設定環境

您必須先在 Google Cloud 專案中啟用 Google API,才能使用 Google API。您可以在單一 Google Cloud 專案中啟用一或多個 API。
  • 在 Google Cloud 控制台中,啟用 Google Chat API、Cloud Build API、Cloud Functions API 和 Cloud Pub/Sub API。

    啟用 API

建立及部署 Cloud 函式

建立及部署 Cloud 函式,以便產生使用寄件者的顯示名稱和顯示圖片的 Chat 資訊卡。即時通訊應用程式收到訊息時,將執行函式並回應卡片。

如要為即時通訊應用程式建立及部署函式,請完成下列步驟:

Node.js

  1. 前往 Google Cloud 控制台中的「Cloud Functions」頁面:

    前往 Cloud Functions 頁面

    確認已選取即時通訊應用程式的專案。

  2. 按一下 [建立函式]

  3. 在「建立函式」頁面中設定函式:

    1. 在「Function name」(函式名稱) 中輸入「QuickStartChatApp」。
    2. 在「Trigger type」(觸發條件類型) 中選取 [HTTP]
    3. 在 [驗證] 下方,選取 [允許未經驗證的叫用]

      如要進一步瞭解 Google Workspace 驗證程序,請參閱驗證及授權即時通訊應用程式和 API 要求

    4. 按一下「儲存」

    5. 點選「下一步」。

  4. 在「Runtime」(執行階段) 中選取 Node.js 10

  5. 在「原始碼」中,選取 [內嵌編輯器]

  6. 在 [進入點] 中,刪除預設文字並輸入 helloChat

  7. index.js 內容替換為下列程式碼:

    node/avatar-bot/index.js
    /**
     * Google Cloud Function that responds to messages sent from a
     * Hangouts Chat room.
     *
     * @param {Object} req Request sent from Hangouts Chat room
     * @param {Object} res Response to send back
     */
    exports.helloChat = function helloChat(req, res) {
      if (req.method === 'GET' || !req.body.message) {
        res.send('Hello! This function is meant to be used in a Hangouts Chat ' +
          'Room.');
      }
    
      const sender = req.body.message.sender.displayName;
      const image = req.body.message.sender.avatarUrl;
    
      const data = createMessage(sender, image);
    
      res.send(data);
    };
    
    /**
     * Creates a card with two widgets.
     * @param {string} displayName the sender's display name
     * @param {string} imageUrl the URL for the sender's avatar
     * @return {Object} a card with the user's avatar.
     */
    function createMessage(displayName, imageUrl) {
      const cardHeader = {
        title: `Hello ${displayName}!`,
      };
    
      const avatarWidget = {
        textParagraph: {text: 'Your avatar picture: '},
      };
    
      const avatarImageWidget = {
        image: {imageUrl},
      };
    
      const avatarSection = {
        widgets: [
          avatarWidget,
          avatarImageWidget,
        ],
      };
    
      return {
        cardsV2: [{
          cardId: 'avatarCard',
          card: {
            name: 'Avatar Card',
            header: cardHeader,
            sections: [avatarSection],
          }
        }],
      };
    }

  8. 按一下「部署」

Python

  1. 前往 Google Cloud 控制台中的「Cloud Functions」頁面:

    前往 Cloud Functions 頁面

    確認已選取即時通訊應用程式的專案。

  2. 按一下 [建立函式]

  3. 在「建立函式」頁面中設定函式:

    1. 在「Function name」(函式名稱) 中輸入「QuickStartChatApp」。
    2. 在「Trigger type」(觸發條件類型) 中選取 [HTTP]
    3. 在 [驗證] 下方,選取 [允許未經驗證的叫用]

      如要進一步瞭解 Google Workspace 驗證程序,請參閱驗證及授權即時通訊應用程式和 API 要求

    4. 按一下「儲存」

    5. 點選「下一步」。

  4. 在「Runtime」(執行階段) 中選取 Python 3.10

  5. 在「原始碼」中,選取 [內嵌編輯器]

  6. 在 [進入點] 中,刪除預設文字並輸入 hello_chat

  7. main.py 內容替換為下列程式碼:

    python/avatar-bot/main.py
    from typing import Any, Mapping
    
    import flask
    import functions_framework
    
    # Google Cloud Function that responds to messages sent in
    # Google Chat.
    #
    # @param {Object} req Request sent from Google Chat.
    # @param {Object} res Response to send back.
    @functions_framework.http
    def hello_chat(req: flask.Request):
        if req.method == "GET":
            return "Hello! This function must be called from Google Chat."
    
        request_json = req.get_json(silent=True)
    
        display_name = request_json["message"]["sender"]["displayName"]
        avatar = request_json["message"]["sender"]["avatarUrl"]
    
        response = create_message(name=display_name, image_url=avatar)
    
        return response
    
    
    # Creates a card with two widgets.
    # @param {string} name the sender's display name.
    # @param {string} image_url the URL for the sender's avatar.
    # @return {Object} a card with the user's avatar.
    def create_message(name: str, image_url: str) -> Mapping[str, Any]:
        avatar_image_widget = {"image": {"imageUrl": image_url}}
        avatar_text_widget = {"textParagraph": {"text": "Your avatar picture:"}}
        avatar_section = {"widgets": [avatar_text_widget, avatar_image_widget]}
    
        header = {"title": f"Hello {name}!"}
    
        cards = {
            "cardsV2": [
                {
                    "cardId": "avatarCard",
                    "card": {
                        "name": "Avatar Card",
                        "header": header,
                        "sections": [avatar_section],
                    },
                }
            ]
        }
    
        return cards
    
    

  8. 按一下「部署」

Java

  1. 前往 Google Cloud 控制台中的「Cloud Functions」頁面:

    前往 Cloud Functions 頁面

    確認已選取即時通訊應用程式的專案。

  2. 按一下 [建立函式]

  3. 在「建立函式」頁面中設定函式:

    1. 在「Function name」(函式名稱) 中輸入「QuickStartChatApp」。
    2. 在「Trigger type」(觸發條件類型) 中選取 [HTTP]
    3. 在 [驗證] 下方,選取 [允許未經驗證的叫用]

      如要進一步瞭解 Google Workspace 驗證程序,請參閱驗證及授權 Chat 應用程式和 API 要求

    4. 按一下「儲存」

    5. 點選「下一步」。

  4. 在「Runtime」(執行階段) 中選取「Java 11」

  5. 在「原始碼」中,選取 [內嵌編輯器]

  6. 在 [進入點] 中,刪除預設文字並輸入 HelloChat

  7. src/main/java/com/example/Example.java 重新命名為 src/main/java/HelloChat.java

  8. HelloChat.java 內容替換為下列程式碼:

    java/avatar-bot/src/main/java/HelloChat.java
    import com.google.api.services.chat.v1.model.CardWithId;
    import com.google.api.services.chat.v1.model.GoogleAppsCardV1Card;
    import com.google.api.services.chat.v1.model.GoogleAppsCardV1CardHeader;
    import com.google.api.services.chat.v1.model.GoogleAppsCardV1Image;
    import com.google.api.services.chat.v1.model.GoogleAppsCardV1Section;
    import com.google.api.services.chat.v1.model.GoogleAppsCardV1TextParagraph;
    import com.google.api.services.chat.v1.model.GoogleAppsCardV1Widget;
    import com.google.api.services.chat.v1.model.Message;
    import com.google.cloud.functions.HttpFunction;
    import com.google.cloud.functions.HttpRequest;
    import com.google.cloud.functions.HttpResponse;
    import com.google.gson.Gson;
    import com.google.gson.JsonObject;
    import java.util.List;
    
    public class HelloChat implements HttpFunction {
      private static final Gson gson = new Gson();
    
      @Override
      public void service(HttpRequest request, HttpResponse response) throws Exception {
        JsonObject body = gson.fromJson(request.getReader(), JsonObject.class);
    
        if (request.getMethod().equals("GET") || !body.has("message")) {
          response.getWriter().write("Hello! This function must be called from Google Chat.");
          return;
        }
    
        JsonObject sender = body.getAsJsonObject("message").getAsJsonObject("sender");
        String displayName = sender.has("displayName") ? sender.get("displayName").getAsString() : "";
        String avatarUrl = sender.has("avatarUrl") ? sender.get("avatarUrl").getAsString() : "";
        Message message = createMessage(displayName, avatarUrl);
    
        response.getWriter().write(gson.toJson(message));
      }
    
      Message createMessage(String displayName, String avatarUrl) {
        GoogleAppsCardV1CardHeader cardHeader = new GoogleAppsCardV1CardHeader();
        cardHeader.setTitle(String.format("Hello %s!", displayName));
    
        GoogleAppsCardV1TextParagraph textParagraph = new GoogleAppsCardV1TextParagraph();
        textParagraph.setText("Your avatar picture: ");
    
        GoogleAppsCardV1Widget avatarWidget = new GoogleAppsCardV1Widget();
        avatarWidget.setTextParagraph(textParagraph);
    
        GoogleAppsCardV1Image image = new GoogleAppsCardV1Image();
        image.setImageUrl(avatarUrl);
    
        GoogleAppsCardV1Widget avatarImageWidget = new GoogleAppsCardV1Widget();
        avatarImageWidget.setImage(image);
    
        GoogleAppsCardV1Section section = new GoogleAppsCardV1Section();
        section.setWidgets(List.of(avatarWidget, avatarImageWidget));
    
        GoogleAppsCardV1Card card = new GoogleAppsCardV1Card();
        card.setName("Avatar Card");
        card.setHeader(cardHeader);
        card.setSections(List.of(section));
    
        CardWithId cardWithId = new CardWithId();
        cardWithId.setCardId("previewLink");
        cardWithId.setCard(card);
    
        Message message = new Message();
        message.setCardsV2(List.of(cardWithId));
    
        return message;
      }
    }

  9. pom.xml 內容替換為下列程式碼:

    java/avatar-bot/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>cloudfunctions</groupId>
      <artifactId>http-function</artifactId>
      <version>1.0-SNAPSHOT</version>
    
      <properties>
        <maven.compiler.target>11</maven.compiler.target>
        <maven.compiler.source>11</maven.compiler.source>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>com.google.cloud.functions</groupId>
          <artifactId>functions-framework-api</artifactId>
          <version>1.0.1</version>
        </dependency>
    
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.9.1</version>
        </dependency>
    
        <!-- https://mvnrepository.com/artifact/com.google.apis/google-api-services-chat -->
        <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-chat</artifactId>
          <version>v1-rev20230115-2.0.0</version>
        </dependency>
      </dependencies>
    
      <!-- Required for Java 11 functions in the inline editor -->
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
              <excludes>
                <exclude>.google/</exclude>
              </excludes>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>

  10. 按一下「部署」

系統會開啟「Cloud Functions」頁面,並會在函式名稱旁邊顯示部署進度指標。當進度指標消失且勾號出現時,系統就會部署您的函式。

將應用程式發布至 Google Chat

部署 Cloud 函式後,請按照下列步驟將其轉換成 Google Chat 應用程式:

  1. 在 Google Cloud 控制台中,依序點選「選單」圖示 > [Cloud Functions]

    前往 Cloud Functions 頁面

    確認您已選取已啟用 Cloud Functions 的專案。

  2. 在函式清單中,按一下 [QuickStartChatApp]

  3. 在「Function details」(函式詳細資料) 頁面中,按一下 [Trigger] (觸發條件)

  4. 複製「觸發條件網址」下方的網址。

  5. 搜尋「Google Chat API」,然後按一下 [Google Chat API]

  6. 按一下 [Manage] (管理)

  7. 按一下 [Configuration] (設定),然後設定 Google Chat 應用程式:

    1. 在「App name」(應用程式名稱) 中輸入 Quickstart App
    2. 在「Avatar URL」中輸入 https://developers.google.com/chat/images/quickstart-app-avatar.png
    3. 在「Description」(說明) 中輸入 Quickstart app
    4. 在「功能」下方,選取 [接收 1:1 訊息]、[加入聊天室和群組對話] 和 [將錯誤記錄至 Cloud Logging]
    5. 在「連線設定」之下,選取 [應用程式網址],然後將 Cloud 函式觸發條件的網址貼到方塊中。
    6. 在「權限」之下,選取 [您網域中的特定使用者和群組],然後輸入您的電子郵件地址。
  8. 按一下「儲存」

你現在可以透過 Google Chat 接收及回覆訊息。

測試即時通訊應用程式

如要測試即時通訊應用程式,請將即時訊息傳送給應用程式:

  1. 開啟 Google Chat
  2. 如要傳送即時訊息給應用程式,請按一下「發起即時通訊」圖示 ,然後在隨即顯示的視窗中按一下 [尋找應用程式]
  3. 在「Find apps」對話方塊中搜尋「Quickstart App」。
  4. 若要開啟與應用程式互傳的即時訊息,請找到「快速入門」應用程式,然後依序按一下「Add」>「Chat」
  5. 在即時訊息中輸入 Hello,然後按下 enter

應用程式會傳回一張內含顯示名稱和顯示圖片的資訊卡。

後續步驟

如要排解 Chat 應用程式的偵錯問題並進行偵錯,請參閱下列網頁:

  • 建構 Chat 應用程式時,您可能需要讀取應用程式的錯誤記錄進行偵錯。如要讀取記錄,請前往 Google Cloud 控制台的「Logs Explorer」(記錄檔探索工具)
  • 疑難排解

如要在 Chat 應用程式中加入更多功能,請參閱下列指南:

  • 建立互動式資訊卡:資訊卡訊息支援已定義的版面配置、按鈕等互動式 UI 元素,以及圖片等互動式多媒體。使用資訊卡訊息來呈現詳細資訊、收集使用者資訊,並引導使用者採取後續行動。
  • 支援斜線指令 - 斜線指令可讓您註冊及宣傳特定指令,讓使用者能夠輸入開頭為正斜線 (/) 的指令 (例如 /help)。
  • 啟動對話方塊 — 對話方塊是指以視窗為基礎的介面,應用程式可開啟,與使用者互動。可以依序將多張卡片合併在一起,協助使用者完成多步驟程序,例如填寫表單資料。

如要進一步瞭解 Google Chat API,請參閱參考說明文件