Google Cloud Functions로 채팅 앱 빌드

컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.

이 페이지에서는 Google Cloud Functions를 사용하여 Chat 앱을 만들고 상호작용하는 방법을 설명합니다.

앱을 빌드하려면 앱이 Google Chat 메시지 이벤트에 대한 응답을 처리하는 데 사용하는 Cloud 함수를 작성하고 배포합니다. 응답은 다음 이미지와 같이 발신자의 이름과 아바타 이미지를 표시하는 카드입니다.

발신자의 표시 이름과 아바타 이미지가 표시된 카드로 응답하는 채팅 앱

목표

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

기본 요건

환경 설정

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

    API 사용 설정

Cloud 함수 생성 및 배포

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

Chat 앱의 함수를 만들고 배포하려면 다음 단계를 완료하세요.

Node.js

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

    Cloud Functions로 이동

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

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

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

    1. 함수 이름에 'QuickStartChatApp'을 입력합니다.
    2. 트리거 유형에서 HTTP를 선택합니다.
    3. 인증에서 인증되지 않은 호출 허용을 선택합니다.

      Google Workspace 인증에 관한 자세한 내용은 Chat 앱 및 API 요청 인증 및 승인을 참고하세요.

    4. 저장을 클릭합니다.

    5. 다음을 클릭합니다.

  4. 런타임에서 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로 이동

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

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

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

    1. 함수 이름에 'QuickStartChatApp'을 입력합니다.
    2. 트리거 유형에서 HTTP를 선택합니다.
    3. 인증에서 인증되지 않은 호출 허용을 선택합니다.

      Google Workspace 인증에 관한 자세한 내용은 Chat 앱 및 API 요청 인증 및 승인을 참고하세요.

    4. 저장을 클릭합니다.

    5. 다음을 클릭합니다.

  4. 런타임에서 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. 배포를 클릭합니다.

자바

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

    Cloud Functions로 이동

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

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

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

    1. 함수 이름에 'QuickStartChatApp'을 입력합니다.
    2. 트리거 유형에서 HTTP를 선택합니다.
    3. 인증에서 인증되지 않은 호출 허용을 선택합니다.

      Google Workspace 인증에 관한 자세한 내용은 Chat 앱 및 API 요청 인증 및 승인을 참고하세요.

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

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

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

  6. 관리를 클릭합니다.

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

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

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

Chat 앱 테스트하기

Chat 앱을 테스트하려면 앱에 채팅 메시지를 보내세요.

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

앱에서 표시 이름 및 아바타 사진이 포함된 카드를 반환합니다.

다음 단계

Chat 앱의 문제를 해결하고 디버그하려면 다음 페이지를 참고하세요.

  • Chat 앱을 빌드할 때 앱의 오류 로그를 읽어 디버그해야 할 수도 있습니다. 로그를 읽으려면 Google Cloud 콘솔에서 로그 탐색기로 이동합니다.
  • 문제 해결

Chat 앱에 더 많은 기능을 추가하려면 다음 가이드를 참고하세요.

  • 양방향 카드 만들기 - 카드 메시지는 정의된 레이아웃, 버튼과 같은 대화형 UI 요소, 이미지와 같은 리치 미디어를 지원합니다. 카드 메시지를 사용하여 자세한 정보를 표시하고, 사용자로부터 정보를 수집하고, 사용자에게 다음 단계를 안내할 수 있습니다.
  • 슬래시 명령어 지원 - 슬래시 명령어를 사용하면 /help와 같이 슬래시 (/)로 시작하는 명령어를 입력하여 사용자가 앱에 제공할 수 있는 특정 명령어를 등록하고 광고할 수 있습니다.
  • 시작 대화상자 — 앱에서 사용자와 상호작용하기 위해 앱에서 열 수 있는 창 기반 카드 기반 인터페이스입니다. 여러 카드를 순차적으로 함께 사용할 수 있으므로 사용자가 양식 데이터 입력과 같은 다단계 프로세스를 완료하는 데 도움이 됩니다.

Google Chat API에 관한 자세한 내용은 참조 문서를 확인하세요.