Cloud Functions로 HTTP Google Chat 앱 빌드

이 페이지에서는 HTTP 채팅 앱을 만드는 방법을 설명합니다. 이 아키텍처를 구현하는 방법에는 여러 가지가 있습니다. Google Cloud에서는 Cloud Functions, Cloud Run, App Engine을 사용할 수 있습니다 이 빠른 시작에서는 채팅 앱이 사용자의 메시지에 응답하는 데 사용하는 Cloud 함수를 작성하고 배포합니다.

이 아키텍처에서는 다음 다이어그램과 같이 HTTP를 사용하여 Google Cloud 또는 온프레미스 서버와 통합되도록 Chat을 구성합니다.

온프레미스 서버에서 웹 서비스를 사용하는 채팅 앱의 아키텍처

앞의 다이어그램에서 HTTP 채팅 앱과 상호작용하는 사용자는 다음과 같은 정보 흐름을 보입니다.

  1. 사용자가 Chat의 메시지를 채팅 앱 또는 Chat 스페이스로 보냅니다.
  2. HTTP 요청은 채팅 앱 로직이 포함된 클라우드 또는 온프레미스 시스템인 웹 서버로 전송됩니다.
  3. 원하는 경우 채팅 앱 로직을 Google Workspace 서비스 (예: Calendar 및 Sheets), 다른 Google 서비스(예: 지도, YouTube, Vertex AI) 또는 다른 웹 서비스 (예: 프로젝트 관리 시스템 또는 티켓팅 도구)와 통합할 수 있습니다.
  4. 웹 서버에서는 Chat의 Chat 앱 서비스에 HTTP 응답을 다시 보냅니다.
  5. 응답은 사용자에게 전달됩니다.
  6. 원하는 경우 채팅 앱에서 Chat API를 호출하여 비동기식으로 메시지를 게시하거나 다른 작업을 실행할 수 있습니다.

이 아키텍처에서는 시스템에 이미 존재하는 기존 라이브러리와 구성요소를 유연하게 사용할 수 있는 유연성을 제공합니다. 이러한 Chat 앱은 다양한 프로그래밍 언어를 사용하여 설계할 수 있기 때문입니다.

목표

  • 환경을 설정합니다.
  • Cloud 함수를 만들고 배포합니다.
  • Chat에 앱을 게시합니다.
  • 앱을 테스트합니다.

기본 요건

  • 인증되지 않은 Google Cloud 함수 호출을 허용하는 Google Workspace 조직의 Google Chat에 액세스할 수 있는 Google Workspace 계정

환경 설정

Google API를 사용하려면 먼저 Google Cloud 프로젝트에서 사용 설정해야 합니다. 단일 Google Cloud 프로젝트에서 하나 이상의 API를 사용 설정할 수 있습니다.
  • Google Cloud 콘솔에서 Google Chat API, Cloud Build API, Cloud Functions API, Cloud Pub/Sub API, Cloud Logging API, Artifact Registry API, Cloud Run API를 사용 설정합니다.

    API 사용 설정

Cloud 함수 생성 및 배포

보낸 사람의 표시 이름과 아바타 이미지를 사용하여 채팅 카드를 생성하는 Cloud 함수를 만들고 배포합니다. 채팅 앱이 메시지를 수신하면 함수를 실행하고 카드로 응답합니다.

채팅 앱에 사용할 함수를 만들고 배포하려면 다음 단계를 완료하세요.

Node.js

  1. Google Cloud 콘솔에서 Cloud Functions 페이지로 이동합니다.

    Cloud Functions로 이동

    채팅 앱의 프로젝트가 선택되어 있는지 확인합니다.

  2. 함수 만들기를 클릭합니다.

  3. 함수 만들기 페이지에서 함수를 설정합니다.

    1. 환경에서 2세대를 선택합니다.
    2. 함수 이름QuickStartChatApp을 입력합니다.
    3. 리전에서 리전을 선택합니다.
    4. 인증에서 인증되지 않은 호출 허용을 선택합니다.
    5. 다음을 클릭합니다.
  4. 런타임에서 Node.js 20을 선택합니다.

  5. 소스 코드에서 인라인 편집기를 선택합니다.

  6. 진입점에서 기본 텍스트를 삭제하고 helloChat를 입력합니다.

  7. index.js의 내용을 다음 코드로 바꿉니다.

    node/avatar-app/index.js
    /**
     * Google Cloud Function that responds to messages sent from a
     * Google Chat room.
     *
     * @param {Object} req Request sent from Google 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 Google 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 {
        text: 'Here\'s your avatar',
        cardsV2: [{
          cardId: 'avatarCard',
          card: {
            name: 'Avatar Card',
            header: cardHeader,
            sections: [avatarSection],
          }
        }],
      };
    }

  8. 배포를 클릭합니다.

Python

  1. Google Cloud 콘솔에서 Cloud Functions 페이지로 이동합니다.

    Cloud Functions로 이동

    채팅 앱의 프로젝트가 선택되어 있는지 확인합니다.

  2. 함수 만들기를 클릭합니다.

  3. 함수 만들기 페이지에서 함수를 설정합니다.

    1. 함수 이름QuickStartChatApp을 입력합니다.
    2. 트리거 유형에서 HTTP를 선택합니다.
    3. 인증에서 인증되지 않은 호출 허용을 선택합니다.
    4. 저장을 클릭합니다.
    5. 다음을 클릭합니다.
  4. 런타임에서 Python 3.10을 선택합니다.

  5. 소스 코드에서 인라인 편집기를 선택합니다.

  6. 진입점에서 기본 텍스트를 삭제하고 hello_chat를 입력합니다.

  7. main.py의 내용을 다음 코드로 바꿉니다.

    python/avatar-app/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) -> Mapping[str, Any]:
      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 = {
          "text": "Here's your avatar",
          "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. 함수 이름QuickStartChatApp을 입력합니다.
    2. 트리거 유형에서 HTTP를 선택합니다.
    3. 인증에서 인증되지 않은 호출 허용을 선택합니다.
    4. 저장을 클릭합니다.
    5. 다음을 클릭합니다.
  4. 런타임에서 자바 11을 선택합니다.

  5. 소스 코드에서 인라인 편집기를 선택합니다.

  6. 진입점에서 기본 텍스트를 삭제하고 HelloChat를 입력합니다.

  7. src/main/java/com/example/Example.java의 이름을 src/main/java/HelloChat.java로 바꿉니다.

  8. HelloChat.java의 내용을 다음 코드로 바꿉니다.

    java/avatar-app/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.setText("Here's your avatar");
        message.setCardsV2(List.of(cardWithId));
    
        return message;
      }
    }

  9. pom.xml의 내용을 다음 코드로 바꿉니다.

    자바/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/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. 함수 세부정보 페이지에서 트리거를 클릭합니다.

  4. 트리거 URL에서 URL을 복사합니다.

  5. 'Google Chat API'를 검색하고 Google Chat API를 클릭한 다음 관리를 클릭합니다.

    Chat API로 이동

  6. 구성을 클릭하고 Google Chat 앱을 설정합니다.

    1. 앱 이름Quickstart App를 입력합니다.
    2. 아바타 URLhttps://developers.google.com/chat/images/quickstart-app-avatar.png를 입력합니다.
    3. 설명Quickstart app을 입력합니다.
    4. 기능에서 1:1 메시지 수신스페이스 및 그룹 대화 참여를 선택합니다.
    5. 연결 설정에서 앱 URL을 선택하고 Cloud 함수 트리거의 URL을 상자에 붙여넣습니다.
    6. 공개 상태에서 이 Google Chat 앱을 도메인의 특정 사용자 및 그룹에서 사용할 수 있도록 설정을 선택하고 이메일 주소를 입력합니다.
    7. 로그에서 Logging에 오류 로깅을 선택합니다.
  7. 저장을 클릭합니다.

채팅 앱이 Chat에서 메시지를 수신하고 응답할 준비가 되었습니다.

채팅 앱 테스트

채팅 앱을 테스트하려면 앱에 채팅 메시지를 보냅니다.

  1. Google Chat을 엽니다.
  2. 앱에 채팅 메시지를 보내려면 채팅 시작 을 클릭하고 표시되는 창에서 앱 찾기를 클릭합니다.
  3. 앱 찾기 대화상자에서 Quickstart App를 검색합니다.
  4. 앱과의 채팅 메시지를 열려면 빠른 시작 앱을 찾아 추가 > 채팅을 클릭합니다.
  5. 채팅 메시지에 Hello라고 입력하고 enter 키를 누릅니다.

채팅 앱의 응답에는 다음 이미지와 같이 발신자의 이름과 아바타 이미지를 표시하는 카드 메시지가 포함됩니다.

보낸 사람의 표시 이름과 아바타 이미지가 표시된 카드로 응답하는 채팅 앱

신뢰할 수 있는 테스터를 추가하고 양방향 기능 테스트에 관한 자세한 내용은 Google Chat 앱의 양방향 기능 테스트를 참고하세요.

문제 해결

Google Chat 앱 또는 카드에서 오류를 반환하면 Chat 인터페이스에 '문제 발생' 또는 '요청을 처리할 수 없습니다'라는 메시지가 표시됩니다. 채팅 UI에는 오류 메시지가 표시되지 않지만 채팅 앱 또는 카드에서 예기치 않은 결과가 발생하는 경우가 있습니다. 예를 들어 카드 메시지가 표시되지 않을 수 있습니다.

Chat UI에 오류 메시지가 표시되지 않더라도 채팅 앱에 대한 오류 기록이 사용 설정되어 있을 때 오류를 수정하는 데 도움이 되는 자세한 오류 메시지와 로그 데이터가 제공됩니다. 오류를 확인, 디버깅, 수정하는 데 도움이 필요하면 Google Chat 오류 문제 해결 및 수정하기를 참고하세요.

삭제

이 튜토리얼에서 사용한 리소스 비용이 Google Cloud 계정에 청구되지 않도록 하려면 Cloud 프로젝트를 삭제하는 것이 좋습니다.

  1. Google Cloud 콘솔에서 리소스 관리 페이지로 이동합니다. 메뉴 > IAM 및 관리자 > 리소스 관리를 클릭합니다.

    Resource Manager로 이동

  2. 프로젝트 목록에서 삭제할 프로젝트를 선택하고 삭제 를 클릭합니다.
  3. 대화상자에서 프로젝트 ID를 입력한 후 종료를 클릭하여 프로젝트를 삭제합니다.