Tạo ứng dụng Google Chat loại HTTP

Trang này giải thích cách tạo một ứng dụng trò chuyện HTTP. Có nhiều cách để triển khai cấu trúc này. Trên Google Cloud, bạn có thể sử dụng Cloud Functions, Cloud Run và App Engine. Trong hướng dẫn nhanh này, bạn sẽ viết và triển khai một Cloud Function mà ứng dụng Chat dùng để phản hồi tin nhắn của người dùng.

Với cấu trúc này, bạn có thể định cấu hình Chat để tích hợp với Google Cloud hoặc một máy chủ tại cơ sở bằng cách sử dụng HTTP, như minh hoạ trong sơ đồ sau:

Cấu trúc của một ứng dụng Chat sử dụng dịch vụ web trong máy chủ tại cơ sở.

Trong sơ đồ trước đó, một người dùng tương tác với ứng dụng HTTP Chat sẽ có luồng thông tin như sau:

  1. Người dùng gửi tin nhắn trong Chat cho một ứng dụng Chat, có thể là trong tin nhắn trực tiếp hoặc trong một không gian Chat.
  2. Yêu cầu HTTP được gửi đến một máy chủ web là hệ thống trên đám mây hoặc tại cơ sở chứa logic của ứng dụng Chat.
  3. Bạn có thể tích hợp logic của ứng dụng Chat với các dịch vụ của Google Workspace (như Lịch và Trang tính), các dịch vụ khác của Google (như Maps, YouTube và Vertex AI) hoặc các dịch vụ web khác (như hệ thống quản lý dự án hoặc công cụ phát hành vé).
  4. Máy chủ web gửi phản hồi HTTP trở lại dịch vụ ứng dụng Chat trong Chat.
  5. Câu trả lời được gửi đến người dùng.
  6. Ngoài ra, ứng dụng Chat có thể gọi Chat API để đăng tin nhắn không đồng bộ hoặc thực hiện các thao tác khác.

Cấu trúc này giúp bạn linh hoạt sử dụng các thư viện và thành phần hiện có trong hệ thống vì các ứng dụng trò chuyện này có thể được thiết kế bằng nhiều ngôn ngữ lập trình.

Mục tiêu

  • Thiết lập môi trường.
  • Tạo và triển khai một Cloud Function.
  • Xuất bản ứng dụng lên Chat.
  • Kiểm thử ứng dụng.

Điều kiện tiên quyết

Thiết lập môi trường

Trước khi sử dụng API của Google, bạn cần bật các API đó trong một dự án Google Cloud. Bạn có thể bật một hoặc nhiều API trong một dự án Google Cloud.
  • Trong Google Cloud Console, hãy bật Google Chat API, Cloud Build API, Cloud Functions API, Cloud Pub/Sub API, Cloud Logging API, Artifact Registry API và Cloud Run API.

    Bật các API

Tạo và triển khai một Cloud Function

Tạo và triển khai một Cloud Function tạo thẻ Chat có tên hiển thị và hình đại diện của người gửi. Khi ứng dụng Chat nhận được một tin nhắn, ứng dụng sẽ chạy hàm và phản hồi bằng thẻ.

Để tạo và triển khai hàm cho ứng dụng Chat, hãy hoàn tất các bước sau:

Node.js

  1. Trong Google Cloud Console, hãy chuyển đến trang Cloud Functions:

    Chuyển đến Cloud Functions

    Đảm bảo rằng bạn đã chọn dự án cho ứng dụng Chat.

  2. Nhấp vào Tạo hàm.

  3. Trên trang Tạo hàm, hãy thiết lập hàm của bạn:

    1. Trong Environment (Môi trường), hãy chọn Cloud Run Function (Hàm Cloud Run).
    2. Trong Tên hàm, hãy nhập QuickStartChatApp.
    3. Trong phần Khu vực, hãy chọn một khu vực.
    4. Trong phần Xác thực, hãy chọn Yêu cầu xác thực.
    5. Nhấp vào Tiếp theo.
  4. Trong Thời gian chạy, hãy chọn phiên bản Node.js gần đây nhất.

  5. Trong Source code (Mã nguồn), hãy chọn Inline Editor (Trình chỉnh sửa nội tuyến).

  6. Trong Điểm truy cập, hãy xoá văn bản mặc định rồi nhập avatarApp.

  7. Thay thế nội dung của index.js bằng đoạn mã sau:

    node/avatar-app/index.js
    const functions = require('@google-cloud/functions-framework');
    
    // Command IDs (configure these in Google Chat API)
    const ABOUT_COMMAND_ID = 1; // ID for the "/about" slash command
    const HELP_COMMAND_ID = 2; // ID for the "Help" quick command
    
    /**
     * Google Cloud Function that handles HTTP requests from Google Chat.
     *
     * @param {Object} req - The HTTP request object sent from Google Chat.
     * @param {Object} res - The HTTP response object.
     */
    functions.http('avatarApp', (req, res) => {
      const event = req.body;
    
      if (event.appCommandMetadata) {
        handleAppCommands(event, res);
      } else {
        handleRegularMessage(event, res);
      }
    });
    
    /**
     * Handles slash and quick commands.
     *
     * @param {Object} event - The Google Chat event.
     * @param {Object} res - The HTTP response object.
     */
    function handleAppCommands(event, res) {
      const {appCommandId, appCommandType} = event.appCommandMetadata;
    
      switch (appCommandId) {
        case ABOUT_COMMAND_ID:
          return res.send({
            privateMessageViewer: event.user,
            text: 'The Avatar app replies to Google Chat messages.'
          });
        case HELP_COMMAND_ID:
          return res.send({
            privateMessageViewer: event.user,
            text: 'The Avatar app replies to Google Chat messages.'
          });
      }
    }
    
    /**
     * Handles regular messages (not commands).
     *
     * @param {Object} event - The Google Chat event.
     * @param {Object} res - The HTTP response object.
     */
    function handleRegularMessage(event, res) {
      const messageData = createMessage(event.user);
      res.send(messageData);
    }
    
    /**
     * Creates a card message with the user's avatar.
     *
     * @param {Object} user - The user who sent the message.
     * @param {string} user.displayName - The user's display name.
     * @param {string} user.avatarUrl - The URL of the user's avatar.
     * @return {Object} - The card message object.
     */
    function createMessage({displayName, avatarUrl}) {
      return {
        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. Nhấp vào Triển khai.

Python

  1. Trong Google Cloud Console, hãy chuyển đến trang Cloud Functions:

    Chuyển đến Cloud Functions

    Đảm bảo rằng bạn đã chọn dự án cho ứng dụng Chat.

  2. Nhấp vào Tạo hàm.

  3. Trên trang Tạo hàm, hãy thiết lập hàm của bạn:

    1. Trong Environment (Môi trường), hãy chọn Cloud Run Function (Hàm Cloud Run).
    2. Trong Tên hàm, hãy nhập QuickStartChatApp.
    3. Trong phần Khu vực, hãy chọn một khu vực.
    4. Trong phần Xác thực, hãy chọn Yêu cầu xác thực.
    5. Nhấp vào Tiếp theo.
  4. Trong Thời gian chạy, hãy chọn phiên bản Python gần đây nhất.

  5. Trong Source code (Mã nguồn), hãy chọn Inline Editor (Trình chỉnh sửa nội tuyến).

  6. Trong Điểm truy cập, hãy xoá văn bản mặc định rồi nhập avatar_app.

  7. Thay thế nội dung của main.py bằng đoạn mã sau:

    python/avatar-app/main.py
    from typing import Any, Mapping
    
    import flask
    import functions_framework
    
    # Command IDs (configure these in Google Chat API)
    ABOUT_COMMAND_ID = 1  # ID for the "/about" slash command
    HELP_COMMAND_ID = 2  # ID for the "Help" quick command
    
    
    @functions_framework.http
    def avatar_app(req: flask.Request) -> Mapping[str, Any]:
        """Google Cloud Function that handles HTTP requests from Google Chat.
    
        Args:
            flask.Request: the request
    
        Returns:
            Mapping[str, Any]: the response
        """
        event = req.get_json(silent=True)
    
        if event and "appCommandMetadata" in event:
            return handle_app_commands(event)
        else:
            return handle_regular_message(event)
    
    
    def handle_app_commands(event: Mapping[str, Any]) -> Mapping[str, Any]:
        """Handles slash and quick commands.
    
        Args:
            Mapping[str, Any] event: The Google Chat event.
    
        Returns:
            Mapping[str, Any]: the response
        """
        app_command_id = event["appCommandMetadata"]["appCommandId"]
    
        if app_command_id == ABOUT_COMMAND_ID:
            return {
                "privateMessageViewer": event["user"],
                "text": "The Avatar app replies to Google Chat messages.",
            }
        elif app_command_id == HELP_COMMAND_ID:
            return {
                "privateMessageViewer": event["user"],
                "text": "The Avatar app replies to Google Chat messages.",
            }
        return {}
    
    
    
    
    def handle_regular_message(event: Mapping[str, Any]) -> Mapping[str, Any]:
        """Handles regular messages (not commands).
    
        Args:
            Mapping[str, Any] event: The Google Chat event.
    
        Returns:
            Mapping[str, Any]: the response
        """
    
        if not event or "user" not in event:
            return "Invalid request."
    
        message_data = create_message(event["user"])
        return message_data
    
    
    def create_message(user: Mapping[str, Any]) -> Mapping[str, Any]:
        """Creates a card message with the user's avatar.
    
        Args:
            Mapping[str, Any] user: The user who sent the message.
    
        Returns:
            Mapping[str, Any]: a card with the user's avatar.
        """
        display_name = user.get("displayName", "")
        avatar_url = user.get("avatarUrl", "")
    
        return {
            "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. Nhấp vào Triển khai.

Java

  1. Trong Google Cloud Console, hãy chuyển đến trang Cloud Functions:

    Chuyển đến Cloud Functions

    Đảm bảo rằng bạn đã chọn dự án cho ứng dụng Chat.

  2. Nhấp vào Tạo hàm.

  3. Trên trang Tạo hàm, hãy thiết lập hàm của bạn:

    1. Trong Environment (Môi trường), hãy chọn Cloud Run Function (Hàm Cloud Run).
    2. Trong Tên hàm, hãy nhập QuickStartChatApp.
    3. Trong phần Khu vực, hãy chọn một khu vực.
    4. Trong phần Xác thực, hãy chọn Yêu cầu xác thực.
    5. Nhấp vào Tiếp theo.
  4. Trong Runtime (Thời gian chạy), hãy chọn phiên bản Java mới nhất.

  5. Trong Source code (Mã nguồn), hãy chọn Inline Editor (Trình chỉnh sửa nội tuyến).

  6. Trong Điểm truy cập, hãy xoá văn bản mặc định rồi nhập App.

  7. Đổi tên src/main/java/com/example/Example.java thành src/main/java/AvatarApp.java.

  8. Thay thế nội dung của AvatarApp.java bằng đoạn mã sau:

    java/avatar-app/src/main/java/AvatarApp.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.api.services.chat.v1.model.User;
    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 AvatarApp implements HttpFunction {
      private static final Gson gson = new Gson();
    
      // Command IDs (configure these in Google Chat API)
      private static final int ABOUT_COMMAND_ID = 1; // ID for the "/about" slash command
      private static final int HELP_COMMAND_ID = 2; // ID for the "Help" quick command
    
      @Override
      public void service(HttpRequest request, HttpResponse response) throws Exception {
        JsonObject event = gson.fromJson(request.getReader(), JsonObject.class);
    
        if (event.has("appCommandMetadata")) {
          handleAppCommands(event, response);
        } else {
          handleRegularMessage(event, response);
        }
      }
    
      /**
       * Handles slash and quick commands.
       *
       * @param event    The Google Chat event.
       * @param response The HTTP response object.
       */
      private void handleAppCommands(JsonObject event, HttpResponse response) throws Exception {
        int appCommandId = event.getAsJsonObject("appCommandMetadata").get("appCommandId").getAsInt();
    
        switch (appCommandId) {
          case ABOUT_COMMAND_ID:
            Message aboutMessage = new Message();
            aboutMessage.setText("The Avatar app replies to Google Chat messages.");
            aboutMessage.setPrivateMessageViewer(new User()
                .setName(event.getAsJsonObject("user").get("name").getAsString()));
            response.getWriter().write(gson.toJson(aboutMessage));
            return;
          case HELP_COMMAND_ID:
            Message helpMessage = new Message();
            helpMessage.setText("The Avatar app replies to Google Chat messages.");
            helpMessage.setPrivateMessageViewer(new User()
                .setName(event.getAsJsonObject("user").get("name").getAsString()));
            response.getWriter().write(gson.toJson(helpMessage));
            return;
        }
      }
    
      /**
       * Handles regular messages (not commands).
       *
       * @param event    The Google Chat event.
       * @param response The HTTP response object.
       */
      private void handleRegularMessage(JsonObject event, HttpResponse response) throws Exception {
    
        if (!event.has("user")) {
          response.getWriter().write("Invalid request.");
          return;
        }
    
        JsonObject user = event.getAsJsonObject("user");
        String displayName = user.has("displayName") ? user.get("displayName").getAsString() : "";
        String avatarUrl = user.has("avatarUrl") ? user.get("avatarUrl").getAsString() : "";
        Message message = createMessage(displayName, avatarUrl);
        response.getWriter().write(gson.toJson(message));
      }
    
      /**
       * Creates a card message with the user's avatar.
       *
       * @param displayName The user's display name.
       * @param avatarUrl   The URL of the user's avatar.
       * @return The card message object.
       */
      private Message createMessage(String displayName, String avatarUrl) {
        return new Message()
            .setText("Here's your avatar")
            .setCardsV2(List.of(new CardWithId()
                .setCardId("avatarCard")
                .setCard(new GoogleAppsCardV1Card()
                    .setName("Avatar Card")
                    .setHeader(new GoogleAppsCardV1CardHeader()
                        .setTitle(String.format("Hello %s!", displayName)))
                    .setSections(List.of(new GoogleAppsCardV1Section().setWidgets(List.of(
                        new GoogleAppsCardV1Widget()
                            .setTextParagraph(new GoogleAppsCardV1TextParagraph()
                                .setText("Your avatar picture:")),
                        new GoogleAppsCardV1Widget()
                            .setImage(new GoogleAppsCardV1Image().setImageUrl(avatarUrl)))))))));
      }
    }

  9. Thay thế nội dung của pom.xml bằng đoạn mã sau:

    java/avatar-app/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/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>gcfv2</groupId>
      <artifactId>avatar-app</artifactId>
      <version>0.0.1</version>
      <name>Avatar App</name>
    
      <properties>
        <maven.compiler.release>21</maven.compiler.release>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>com.google.cloud.functions</groupId>
          <artifactId>functions-framework-api</artifactId>
          <version>1.1.4</version>
        </dependency>
    
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
          <groupId>com.google.code.gson</groupId>
          <artifactId>gson</artifactId>
          <version>2.12.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-rev20250116-2.0.0</version>
        </dependency>
    
      </dependencies>
    
    </project>

  10. Nhấp vào Triển khai.

Trang chi tiết về Cloud Functions sẽ mở ra và hàm của bạn sẽ xuất hiện cùng với 2 chỉ báo tiến trình: một chỉ báo cho bản dựng và một chỉ báo cho dịch vụ. Khi cả hai chỉ báo tiến trình đều biến mất và được thay thế bằng dấu kiểm, tức là hàm của bạn đã được triển khai và sẵn sàng.

Uỷ quyền cho Google Chat gọi hàm của bạn

Để cho phép Google Chat gọi hàm của bạn, hãy thêm tài khoản dịch vụ Google Chat có vai trò Cloud Run Invoker (Đối tượng gọi Cloud Run).

  1. Trong Google Cloud Console, hãy chuyển đến trang Cloud Run:

    Chuyển đến Cloud Run

  2. Trong danh sách dịch vụ Cloud Run, hãy chọn hộp đánh dấu bên cạnh hàm nhận. (Đừng nhấp vào chính hàm đó.)

  3. Nhấp vào Quyền. Bảng điều khiển Quyền sẽ mở ra.

  4. Nhấp vào Thêm đối tượng chính.

  5. Trong Bên giao đại diện mới, hãy nhập chat@system.gserviceaccount.com.

  6. Trong phần Chọn vai trò, hãy chọn Cloud Run > Cloud Run Invoker (Đối tượng gọi Cloud Run).

  7. Nhấp vào Lưu.

Phát hành ứng dụng lên Google Chat

Sau khi triển khai Cloud Functions, hãy làm theo các bước sau để biến Cloud Functions thành một ứng dụng Google Chat:

  1. Trong Bảng điều khiển Google Cloud, hãy nhấp vào Trình đơn > Cloud Functions.

    Chuyển đến Cloud Functions

    Đảm bảo rằng bạn đã chọn dự án mà bạn đã bật Cloud Functions.

  2. Trong danh sách hàm, hãy nhấp vào QuickStartChatApp.

  3. Nhấp vào thẻ Trình kích hoạt.

  4. Trong phần HTTPS, hãy sao chép URL.

  5. Tìm "Google Chat API" rồi nhấp vào Google Chat API, sau đó nhấp vào Quản lý.

    Chuyển đến Chat API

  6. Nhấp vào Cấu hình rồi thiết lập ứng dụng Google Chat:

    1. Trong Tên ứng dụng, hãy nhập Quickstart App.
    2. Trong URL hình đại diện, hãy nhập https://developers.google.com/chat/images/quickstart-app-avatar.png.
    3. Trong phần Nội dung mô tả, hãy nhập Quickstart app.
    4. Trong phần Chức năng, hãy chọn Tham gia không gian và cuộc trò chuyện nhóm.
    5. Trong phần Connection settings (Chế độ cài đặt kết nối), hãy chọn HTTP endpoint URL (URL điểm cuối HTTP) rồi dán URL cho trình kích hoạt Cloud Functions vào hộp.
    6. Trong phần Đối tượng xác thực, hãy chọn URL điểm cuối HTTP.
    7. Trong phần Chế độ hiển thị, hãy chọn Cung cấp ứng dụng Google Chat này cho một số người và nhóm cụ thể trong miền của bạn rồi nhập địa chỉ email của bạn.
    8. Trong mục Nhật ký, hãy chọn Ghi lỗi vào Nhật ký.
  7. Nhấp vào Lưu.

Ứng dụng Chat đã sẵn sàng nhận và trả lời tin nhắn trên Chat.

Kiểm thử ứng dụng Chat

Để kiểm thử ứng dụng Chat, hãy mở một không gian nhắn tin trực tiếp bằng ứng dụng Chat rồi gửi một tin nhắn:

  1. Mở Google Chat bằng tài khoản Google Workspace mà bạn đã cung cấp khi thêm chính mình làm người kiểm thử tin cậy.

    Truy cập vào Google Chat

  2. Nhấp vào biểu tượng Cuộc trò chuyện mới.
  3. Trong trường Thêm một hoặc nhiều người, hãy nhập tên của ứng dụng Chat.
  4. Chọn ứng dụng Chat trong kết quả. Một tin nhắn trực tiếp sẽ mở ra.

  5. Trong tin nhắn trực tiếp mới với ứng dụng, hãy nhập Hello rồi nhấn enter.

Phản hồi của ứng dụng Chat chứa một thông báo dạng thẻ hiển thị tên và hình đại diện của người gửi, như minh hoạ trong hình ảnh sau:

Ứng dụng Chat phản hồi bằng một thẻ có tên hiển thị và hình đại diện của người gửi

Để thêm người kiểm thử đáng tin cậy và tìm hiểu thêm về việc kiểm thử các tính năng tương tác, hãy xem bài viết Kiểm thử các tính năng tương tác cho ứng dụng Google Chat.

Khắc phục sự cố

Khi một ứng dụng Google Chat hoặc thẻ trả về lỗi, giao diện Chat sẽ hiển thị thông báo "Đã xảy ra lỗi". hoặc "Không thể xử lý yêu cầu của bạn". Đôi khi, giao diện người dùng Chat không hiển thị bất kỳ thông báo lỗi nào, nhưng ứng dụng hoặc thẻ Chat lại tạo ra kết quả không mong muốn; ví dụ: thông báo thẻ có thể không xuất hiện.

Mặc dù thông báo lỗi có thể không xuất hiện trong giao diện người dùng Chat, nhưng bạn có thể sử dụng thông báo lỗi mô tả và dữ liệu nhật ký để khắc phục lỗi khi bật tính năng ghi nhật ký lỗi cho ứng dụng Chat. Để được trợ giúp xem, gỡ lỗi và khắc phục lỗi, hãy xem bài viết Khắc phục lỗi trong Google Chat.

Dọn dẹp

Để tránh phát sinh phí cho tài khoản Google Cloud của bạn đối với các tài nguyên được dùng trong hướng dẫn này, bạn nên xoá dự án trên Cloud.

  1. Trong Google Cloud Console, hãy chuyển đến trang Quản lý tài nguyên. Nhấp vào Trình đơn > IAM và Quản trị viên > Quản lý tài nguyên.

    Chuyển đến Resource Manager

  2. Trong danh sách dự án, hãy chọn dự án bạn muốn xoá rồi nhấp vào biểu tượng Xoá .
  3. Trong hộp thoại, hãy nhập mã dự án rồi nhấp vào Tắt để xoá dự án.