建構 HTTP Google Chat 應用程式

本頁面說明如何使用 HTTP 服務,建構可在 Google Chat 中運作的 Google Workspace 外掛程式。

本快速入門導覽課程說明如何使用 Google Cloud 服務建構 HTTP 服務。如要建構 Chat 應用程式,請編寫並部署 Cloud 函式,讓 Chat 應用程式用於回應使用者的訊息。

在 HTTP 架構中,您可以使用 HTTP 將 Chat 整合至 Google Cloud 或內部伺服器,如以下圖表所示:

使用內部伺服器中的網路服務,即時通訊應用程式的架構。

在上方的圖表中,使用者與 HTTP Chat 應用程式互動時,資訊會按照以下流程傳送:

  1. 使用者在 Chat 中傳送訊息給 Chat 應用程式,可能是透過即時訊息或 Chat 聊天室。
  2. 系統會將 HTTP 要求傳送至網路伺服器,該伺服器是雲端或內部系統,其中包含 Chat 應用程式邏輯。
  3. 您可以選擇讓 Chat 應用程式邏輯整合 Google Workspace 服務 (例如日曆和試算表)、其他 Google 服務 (例如地圖、YouTube 和 Vertex AI),或其他網路服務 (例如專案管理系統或支援單工具)。
  4. 網路伺服器會將 HTTP 回應傳回至 Chat 中的 Chat 應用程式服務。
  5. 系統會將回應傳送給使用者。
  6. 如有需要,Chat 應用程式可以呼叫 Chat API,以非同步方式發布訊息或執行其他作業。

由於 Chat 應用程式可使用不同的程式設計語言設計,因此這個架構可讓您靈活使用系統中現有的程式庫和元件。

目標

  • 設定環境。
  • 建立及部署 Cloud 函式。
  • 為 Chat 應用程式設定 Google Workspace 外掛程式。
  • 測試應用程式。

必要條件

設定環境

使用 Google API 前,您必須先在 Google Cloud 專案中啟用這些 API。您可以在單一 Google Cloud 專案中啟用一或多個 API。
  • 在 Google Cloud 控制台中啟用 Cloud Build API、Cloud Functions API、Cloud Pub/Sub API、Cloud Logging API、Artifact Registry API 和 Cloud Run API。

    啟用 API

建立及部署 Cloud 函式

建立及部署 Cloud 函式,產生 Chat 資訊卡,其中包含傳送者的顯示名稱和顯示圖片。當 Chat 應用程式收到訊息時,就會執行函式並回應資訊卡。

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

Node.js

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

    前往 Cloud Functions 頁面

    確認已選取 Chat 應用程式的專案。

  2. 按一下 「Create Function」(建立函式)

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

    1. 在「環境」中,選取「Cloud Run 函式」
    2. 在「Function name」 中輸入 AddOnChatApp
    3. 在「Region」中選取區域。
    4. 在「驗證」下方,選取「需要驗證」
    5. 點選 [下一步]。
  4. 在「Runtime」中,選取 Node.js 的最新版本。

  5. 在「Source code」中,選取「Inline Editor」

  6. 在「Entry point」中,刪除預設文字並輸入 avatarApp

  7. 使用下列程式碼取代 index.js 的內容:

    /**
     * Google Cloud Function that responds to messages sent from a
     * Google Chat space.
     *
     * @param {Object} req Request sent from Google Chat space
     * @param {Object} res Response to send back
     */
    exports.avatarApp = function avatarApp(req, res) {
        if (req.method === 'GET' || !req.body.chat) {
            return res.send('Hello! This function is meant to be used ' +
                'in a Google Chat Space.');
        }
    
        // Stores the Google Chat event as a variable.
        const chatMessage = req.body.chat.messagePayload.message;
    
        // Replies with the sender's avatar in a card.
        const displayName = chatMessage.sender.displayName;
        const avatarUrl = chatMessage.sender.avatarUrl;
        res.send({ hostAppDataAction: { chatDataAction: { createMessageAction: { message: {
            text: 'Here\'s your avatar',
            cardsV2: [{
                cardId: 'avatarCard',
                card: {
                    name: 'Avatar Card',
                    header: {
                        title: `Hello ${displayName}!`,
                    },
                    sections: [{
                        widgets: [{
                            textParagraph: { text: 'Your avatar picture: ' }
                        }, {
                            image: { imageUrl: avatarUrl }
                        }]
                    }]
                }
            }]
        }}}}});
    };
    
  8. 按一下 [Deploy] (部署)

Python

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

    前往 Cloud Functions 頁面

    確認已選取 Chat 應用程式的專案。

  2. 按一下 「Create Function」(建立函式)

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

    1. 在「環境」中,選取「Cloud Run 函式」
    2. 在「Function name」 中輸入 AddOnChatApp
    3. 在「Region」中選取區域。
    4. 在「驗證」下方,選取「需要驗證」
    5. 點選 [下一步]。
  4. 在「Runtime」中,選取 Python 的最新版本。

  5. 在「Source code」中,選取「Inline Editor」

  6. 在「Entry point」中,刪除預設文字並輸入 avatar_app

  7. 使用下列程式碼取代 main.py 的內容:

    from typing import Any, Mapping
    
    import flask
    import functions_framework
    
    @functions_framework.http
    def avatar_app(req: flask.Request) -> Mapping[str, Any]:
        """Google Cloud Function that handles requests from Google Chat
    
        Args:
            flask.Request: the request
    
        Returns:
            Mapping[str, Any]: the response
        """
        if req.method == "GET":
            return "Hello! This function must be called from Google Chat."
    
        request_json = req.get_json(silent=True)
    
        # Stores the Google Chat event as a variable.
        chat_message = request_json["chat"]["messagePayload"]["message"]
    
        # Replies with the sender's avatar in a card.
        display_name = chat_message["sender"]["displayName"]
        avatar_url = chat_message["sender"]["avatarUrl"]
        return { "hostAppDataAction": { "chatDataAction": { "createMessageAction": { "message": {
            "text": "Here's your avatar",
            "cardsV2": [{
                "cardId": "avatarCard",
                "card": {
                    "name": "Avatar Card",
                    "header": { "title": f"Hello {display_name}!" },
                    "sections": [{
                        "widgets": [{
                            "textParagraph": { "text": "Your avatar picture:" }
                        }, {
                            "image": { "imageUrl": avatar_url }
                        }]
                    }]
                }
            }]
        }}}}}
    
  8. 按一下 [Deploy] (部署)

Java

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

    前往 Cloud Functions 頁面

    確認已選取 Chat 應用程式的專案。

  2. 按一下 「Create Function」(建立函式)

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

    1. 在「環境」中,選取「Cloud Run 函式」
    2. 在「Function name」 中輸入 AddOnChatApp
    3. 在「Region」中選取區域。
    4. 在「驗證」下方,選取「需要驗證」
    5. 點選 [下一步]。
  4. 在「執行階段」中,選取 Java 的最新版本。

  5. 在「Source code」中,選取「Inline Editor」

  6. 在「Entry point」中,刪除預設文字並輸入 AvatarApp

  7. 將預設 Java 檔案重新命名為 src/main/java/AvatarApp.java

  8. 使用下列程式碼取代 AvatarApp.java 的內容:

    import java.util.List;
    
    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;
    
    public class AvatarApp 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("chat")) {
                response.getWriter().write("Hello! This function is meant to be used " +
                    "in a Google Chat Space..");
                return;
            }
    
            // Stores the Google Chat event as a variable.
            JsonObject chatMessage = body.getAsJsonObject("chat")
                .getAsJsonObject("messagePayload").getAsJsonObject("message");
    
            // Replies with the sender's avatar in a card.
            String displayName = chatMessage.getAsJsonObject("sender").get("displayName").getAsString();
            String avatarUrl = chatMessage.getAsJsonObject("sender").get("avatarUrl").getAsString();
            Message message = createMessage(displayName, avatarUrl);
    
            JsonObject createMessageAction = new JsonObject();
            createMessageAction.add("message", gson.fromJson(gson.toJson(message), JsonObject.class));
    
            JsonObject chatDataAction = new JsonObject();
            chatDataAction.add("createMessageAction", createMessageAction);
    
            JsonObject hostAppDataAction = new JsonObject();
            hostAppDataAction.add("chatDataAction", chatDataAction);
    
            JsonObject dataActions = new JsonObject();
            dataActions.add("hostAppDataAction", hostAppDataAction);
            response.getWriter().write(gson.toJson(dataActions));
        }
    
        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("avatarCard");
            cardWithId.setCard(card);
    
            Message message = new Message();
            message.setText("Here's your avatar");
            message.setCardsV2(List.of(cardWithId));
    
            return message;
        }
    }
    
  9. 使用下列程式碼取代 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</groupId>
        <artifactId>avatar-app</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <properties>
            <maven.compiler.target>17</maven.compiler.target>
            <maven.compiler.source>17</maven.compiler.source>
        </properties>
    
        <dependencies>
            <dependency>
            <groupId>com.google.cloud.functions</groupId>
            <artifactId>functions-framework-api</artifactId>
            <version>1.0.4</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 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. 按一下 [Deploy] (部署)

Cloud Functions 詳細資料頁面隨即開啟,並顯示函式和兩個進度指標:一個是建構指標,另一個是服務指標。當兩個進度指標都消失,並且被勾號取代時,函式就會部署完成並準備就緒。

設定外掛程式

部署 Cloud 函式後,請按照下列步驟建立外掛程式並部署 Google Chat 應用程式:

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

    前往 Cloud Functions 頁面

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

  2. 在函式清單中,按一下「AddOnChatApp」AddOnChatApp

  3. 按一下「觸發條件」分頁標籤。

  4. 在「HTTPS」HTTPS下方複製網址。

  5. 搜尋「Google Chat API」,然後按一下「Google Chat API」和「管理」

    前往 Chat API

  6. 按一下「設定」,然後設定 Google Chat 應用程式:

    1. 在「應用程式名稱」中輸入 Add-on Chat app
    2. 在「顯示圖片網址」中輸入 https://developers.google.com/workspace/add-ons/images/quickstart-app-avatar.png
    3. 在「Description」中輸入 Add-on Chat app
    4. 在「功能」下方,選取「接收一對一訊息」和「加入聊天室和群組對話」
    5. 在「連線設定」下方,選取「HTTP 端點網址」,然後在方塊中貼上 Cloud 函式觸發事件的網址。
    6. 在「Authentication Audience」中,選取「HTTP 端點網址」
    7. 在「瀏覽權限」下方,選取「將這個 Google Chat 應用程式提供給網域中的特定使用者和群組」,然後輸入您的電子郵件地址。
    8. 在「記錄」下方,選取「將錯誤記錄至 Logging」
  7. 按一下 [儲存]

接下來,請授權 Chat 應用程式叫用 Cloud 函式。

授權 Google Chat 叫用函式

如要授權 Google Workspace 外掛程式叫用函式,請新增 Google Workspace 外掛程式服務帳戶,並指派 Cloud Run 叫用者 角色。

  1. 前往 Google Cloud 控制台中的 Cloud Run 頁面:

    前往 Cloud Run

  2. 在 Cloud Run 服務清單中,選取接收函式旁的核取方塊。(請勿按一下函式本身)。

  3. 按一下 [權限],「Permissions」面板隨即開啟。

  4. 按一下「新增主體」

  5. 在「新增主體」中,輸入與專案相關聯的 Google Workspace 外掛服務帳戶電子郵件地址。在 Chat API 設定頁面中,依序前往「連線設定」 >「HTTP 端點網址」 >「服務帳戶電子郵件」,即可找到服務帳戶電子郵件地址:

    前往 Chat API 設定

  6. 在「請選擇角色」中,依序選取「Cloud Run」 >「Cloud Run Invoker」

  7. 按一下 [儲存]

Chat 應用程式已準備好接收及回覆 Chat 中的訊息。

測試 Chat 應用程式

如要測試 Chat 應用程式,請使用 Chat 應用程式開啟即時訊息聊天室並傳送訊息:

  1. 使用您新增自己為信任測試人員時提供的 Google Workspace 帳戶,開啟 Google Chat。

    前往 Google Chat

  2. 按一下 「發起即時通訊」
  3. 在「新增 1 位或多位使用者」欄位中,輸入 Chat 應用程式的名稱。
  4. 從搜尋結果中選取 Chat 應用程式。即時訊息會隨即開啟。

  5. 在與應用程式互傳的新即時訊息中,輸入 Hello 並按下 enter

Chat 應用程式的訊息包含顯示傳送者名稱和顯示圖片的資訊卡,如下圖所示:

Chat 應用程式回覆的卡片,其中顯示傳送者的顯示名稱和顯示圖片

如要新增信任的測試人員,並進一步瞭解如何測試互動功能,請參閱「測試 Google Chat 應用程式的互動功能」。

疑難排解

當 Google Chat 應用程式或資訊卡傳回錯誤時,Chat 介面會顯示「發生錯誤」的訊息。或「無法處理您的要求」。有時 Chat UI 不會顯示任何錯誤訊息,但 Chat 應用程式或資訊卡會產生意外結果,例如資訊卡訊息可能不會顯示。

雖然 Chat UI 可能不會顯示錯誤訊息,但當您開啟 Chat 應用程式的錯誤記錄功能時,系統會提供描述性錯誤訊息和記錄資料,協助您修正錯誤。如需查看、偵錯及修正錯誤的相關說明,請參閱「排解及修正 Google Chat 錯誤」。

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取本教學課程中所用資源的相關費用,建議您刪除 Cloud 專案。

  1. 在 Google Cloud 控制台中前往「管理資源」頁面。依序點選「選單」>「IAM 與管理」>「管理資源」

    前往 Resource Manager

  2. 在專案清單中選取要刪除的專案,然後按一下「刪除」圖示
  3. 在對話方塊中輸入專案 ID,然後按一下「Shut down」(關閉) 即可刪除專案。