Node.js를 사용하는 Google Chat용 대화형 설문조사 앱 빌드하기

1. 소개

Google Chat 앱은 서비스와 리소스를 Google Chat으로 바로 이동하므로 사용자는 대화에서 나가지 않고도 정보를 얻고 신속하게 작업할 수 있습니다.

이 Codelab에서는 Node.js 및 Cloud Functions를 사용하여 설문조사 앱을 빌드하고 배포하는 방법을 알아봅니다.

실습 내용

  • Cloud Shell 사용
  • Cloud Functions에 배포
  • 슬래시 명령어와 대화상자를 사용하여 사용자 입력 가져오기
  • 양방향 카드 만들기

2 설정 및 요건

Google Cloud 프로젝트를 만든 다음 Chat 앱에서 사용할 API 및 서비스를 사용 설정합니다.

기본 요건

Google Chat 앱을 개발하려면 Google Chat 액세스 권한이 있는 Google Workspace 계정이 필요합니다. 아직 Google Workspace 계정이 없다면 계정을 만들고 로그인한 후 이 Codelab을 진행하세요.

자습형 환경 설정

  1. Google Cloud Console을 열고 프로젝트를 만듭니다.

    프로젝트 선택 메뉴새 프로젝트 버튼프로젝트 ID

    모든 Google Cloud 프로젝트에서 고유한 이름을 사용하는 프로젝트 ID를 기억해 두세요. 위의 이름은 이미 사용되었으므로 사용할 수 없습니다. 이 Codelab의 뒷부분에서 PROJECT_ID라고 합니다.
  1. 다음으로 Google Cloud 리소스를 사용하려면 Cloud Console에서 결제를 사용 설정합니다.

이 Codelab 실행에는 많은 비용이 들지 않습니다. 이 튜토리얼 끝부분에서 '정리' 섹션의 안내에 따라 리소스를 종료하지 않도록 리소스를 종료하는 방법을 안내합니다. Google Cloud 새 사용자에게는 $300USD 상당의 무료 체험판 프로그램 참여 자격이 부여됩니다.

Google Cloud Shell

노트북에서 원격으로 작동할 수 있는 상태이지만, 이 Codelab에서는 Google Cloud에서 실행되는 명령줄 환경인 Google Cloud Shell을 사용합니다.

Cloud Shell 활성화

  1. Cloud Console에서 Cloud Shell 활성화 Cloud Shell 아이콘를 클릭합니다.

    메뉴 바의 Cloud Shell 아이콘

    Cloud Shell을 처음 열면 설명 메시지가 표시됩니다. 환영 메시지가 표시되면 계속을 클릭합니다. 환영 메시지는 다시 표시되지 않습니다. 환영 메시지:

    Cloud Shell 시작 메시지

    Cloud Shell을 프로비저닝하고 연결하는 데 몇 분 정도만 소요됩니다. 연결되면 Cloud Shell 터미널이 표시됩니다.

    Cloud Shell 터미널

    이 가상 머신은 필요한 모든 개발 도구가 함께 로드되어 있습니다. 영구적인 5GB 홈 디렉터리를 제공하고 Google Cloud에서 실행되므로 네트워크 성능과 인증이 크게 개선됩니다. 이 Codelab의 모든 작업은 브라우저 또는 Chromebook을 통해 완료할 수 있습니다.Cloud Shell에 연결되면 인증이 이미 완료되어 있고 프로젝트가 이미 프로젝트 ID로 설정되어 있음을 확인할 수 있습니다.
  2. Cloud Shell에서 다음 명령어를 실행하여 인증되었는지 확인합니다.
    gcloud auth list
    
    Cloud Shell에서 GCP API를 호출할 수 있도록 승인하라는 메시지가 표시되면 승인을 클릭합니다.

    명령어 결과
    Credentialed Accounts
    ACTIVE  ACCOUNT
    *       <my_account>@<my_domain.com>
    
    계정이 기본적으로 선택되어 있지 않으면 다음을 실행합니다.
    $ gcloud config set account <ACCOUNT>
    
  1. 올바른 프로젝트를 선택했는지 확인합니다. Cloud Shell에서 다음을 실행합니다.
    gcloud config list project
    
    명령어 결과
    [core]
    project = <PROJECT_ID>
    
    올바른 프로젝트가 반환되지 않은 경우 다음 명령어로 설정할 수 있습니다.
    gcloud config set project <PROJECT_ID>
    
    명령어 결과
    Updated property [core/project].
    

이 Codelab을 완료하면 명령줄 작업을 사용하고 파일을 수정할 수 있습니다. 파일 수정을 위해 Cloud Shell에 내장된 코드 편집기로 작업할 수 있습니다.Cloud Shell 편집기 , 클릭 후편집기 열기 을 클릭합니다. Cloud Shell에서 Vim, Emacs 같은 인기 있는 편집기도 사용할 수 있습니다.

3. Cloud Functions, Cloud Build, Google Chat API 사용 설정

Cloud Shell에서 다음 API 및 서비스를 사용 설정합니다.

gcloud services enable \
  cloudfunctions \
  cloudbuild.googleapis.com \
  chat.googleapis.com

작업을 완료하는 데 몇 분 정도 걸릴 수 있습니다.

완료되면 다음과 유사한 성공 메시지가 표시됩니다.

Operation "operations/acf.cc11852d-40af-47ad-9d59-477a12847c9e" finished successfully.

4. 초기 Chat 앱 만들기

프로젝트 초기화

먼저 간단한 'Hello world' 앱을 만들고 배포합니다. 채팅 앱은 https 요청에 응답하고 JSON 페이로드로 응답하는 웹 서비스입니다. 이 앱의 경우 Node.js와 Cloud Functions를 사용합니다.

Cloud Shell에서 poll-app라는 새 디렉터리를 만들고 해당 디렉터리로 이동합니다.

mkdir ~/poll-app
cd ~/poll-app

Codelab의 나머지 작업과 만들 파일은 이 디렉터리에 있습니다.

Node.js 프로젝트를 초기화합니다.

npm init

NPM에서 프로젝트 구성(예: 이름, 버전)에 관해 몇 가지 질문을 합니다. 질문마다 ENTER를 눌러 기본값을 수락합니다. 기본 진입점은 index.js이라는 파일이며 다음에 만들 것입니다.

Chat 앱 백엔드 만들기

이제 앱을 만들어 보겠습니다. 다음 콘텐츠로 index.js라는 파일을 만듭니다.

/**
 * App entry point.
 */
exports.app = async (req, res) => {
  if (!(req.method === 'POST' && req.body)) {
      res.status(400).send('')
  }
  const event = req.body;
  let reply = {};
  if (event.type === 'MESSAGE') {
    reply = {
        text: `Hello ${event.user.displayName}`
    };
  }
  res.json(reply)
}

앱은 아직 별다른 작업을 하지 않지만 괜찮습니다. 나중에 더 많은 기능을 추가할 것입니다.

앱 배포

'Hello world' 앱을 배포하려면 Cloud 함수를 배포하고 Google Cloud Console에서 Chat 앱을 구성한 다음 앱에 테스트 메시지를 보내 배포를 확인합니다.

Cloud 함수 배포

'Hello world' 앱의 Cloud 함수를 배포하려면 다음 명령어를 입력합니다.

gcloud functions deploy app --trigger-http --security-level=secure-always --allow-unauthenticated --runtime nodejs14

완료된 출력은 다음과 같습니다.

availableMemoryMb: 256
buildId: 993b2ca9-2719-40af-86e4-42c8e4563a4b
buildName: projects/595241540133/locations/us-central1/builds/993b2ca9-2719-40af-86e4-42c8e4563a4b
entryPoint: app
httpsTrigger:
  securityLevel: SECURE_ALWAYS
  url: https://us-central1-poll-app-codelab.cloudfunctions.net/app
ingressSettings: ALLOW_ALL
labels:
  deployment-tool: cli-gcloud
name: projects/poll-app-codelab/locations/us-central1/functions/app
runtime: nodejs14
serviceAccountEmail: poll-app-codelab@appspot.gserviceaccount.com
sourceUploadUrl: https://storage.googleapis.com/gcf-upload-us-central1-66a01777-67f0-46d7-a941-079c24414822/94057943-2b7c-4b4c-9a21-bb3acffc84c6.zip
status: ACTIVE
timeout: 60s
updateTime: '2021-09-17T19:30:33.694Z'
versionId: '1'

httpsTrigger.url 속성에서 배포된 함수의 URL을 기록합니다. 다음 단계에서 이 주소를 사용합니다.

앱 구성

앱을 구성하려면Chat 구성 Cloud Console의 페이지API 및 서비스 >대시보드 >행아웃 채팅 API >구성 또는 저장용량 버킷).

  1. 앱 이름에 'PollCodelab'을 입력합니다.
  2. 아바타 URLhttps://raw.githubusercontent.com/google/material-design-icons/master/png/social/poll/materialicons/24dp/2x/baseline_poll_black_24dp.png를 입력합니다.
  3. 설명에 'Codelab용 설문조사 앱'을 입력합니다.
  4. 기능에서 앱에서 직접 메시지를 보낼 수 있음여러 사용자가 있는 스페이스에서 앱 작동을 선택합니다.
  5. 연결 설정에서 앱 URL을 선택하고 Cloud 함수의 URL (마지막 섹션의 httpsTrigger.url 속성)을 붙여넣습니다.
  6. 권한에서 도메인의 특정 사용자 및 그룹을 선택하고 이메일 주소를 입력합니다.
  7. 저장을 클릭합니다.

이제 앱에서 메시지를 보낼 준비가 되었습니다.

앱 테스트

계속하기 전에 Google Chat의 스페이스에 앱을 추가하여 작동하는지 확인합니다.

  1. Google Chat으로 이동합니다.
  2. Chat 옆의 + > 앱 찾기를 클릭합니다.
  3. 검색창에 'PollCodelab'을 입력합니다.
  4. Chat을 클릭합니다.
  5. 앱에 메시지를 보내려면 'Hello'를 입력하고 Enter 키를 누릅니다.

앱은 간단한 Hello 메시지로 응답해야 합니다.

기본 뼈대가 준비되었으니 이제 더 유용하게 사용할 차례입니다.

5 설문조사 기능 빌드

앱 작동 방식에 대한 간략한 개요

앱은 두 가지 주요 부분으로 구성됩니다.

  1. 설문조사 구성 대화상자를 표시하는 슬래시 명령어입니다.
  2. 투표와 결과 확인을 위한 양방향 카드입니다.

또한 앱은 설문조사 구성 및 결과를 저장하려면 몇 가지 상태가 필요합니다. 이 작업은 Firestore 또는 모든 데이터베이스를 사용하여 수행하거나 앱 메시지 자체에 저장할 수 있습니다. 이 앱은 팀의 간단한 비공식 설문조사를 위한 것이므로 앱 메시지에 상태를 저장하는 것이 이 사용 사례에 적합합니다.

앱의 데이터 모델 (Typescript로 표현됨)은 다음과 같습니다.

interface Poll {
  /* Question/topic of poll */
  topic: string;
  /** User that submitted the poll */
  author: {
    /** Unique resource name of user */
    name: string;
    /** Display name */
    displayName: string;
  };
  /** Available choices to present to users */
  choices: string[];
  /** Map of user ids to the index of their selected choice */
  votes: { [key: string]: number };
}

주제 또는 질문과 선택 항목 목록 외에도 상태는 작성자의 ID와 이름, 기록된 투표를 포함합니다. 사용자가 여러 번 투표하지 못하도록 하기 위해 투표는 선택한 선택 색인에 사용자 ID 맵으로 저장됩니다.

물론 물론 다양한 접근법이 있지만, 이는 공간 내에서 빠른 설문조사를 실행하기 위한 좋은 출발점입니다.

설문조사 구성 명령어 구현

사용자가 설문조사를 시작하고 구성할 수 있도록 대화상자를 여는 슬래시 명령어를 설정합니다. 이는 여러 단계로 이루어진 프로세스입니다.

  1. 설문조사를 시작하는 슬래시 명령어를 등록합니다.
  2. 설문조사를 설정하는 대화상자를 만드세요.
  3. 앱에서 슬래시 명령어를 인식하고 처리하도록 허용합니다.
  4. 설문조사 참여를 촉진하는 양방향 카드를 만들 수 있습니다.
  5. 앱에서 설문조사를 실행할 수 있는 코드를 구현합니다.
  6. Cloud 함수를 다시 배포합니다.

슬래시 명령어 등록

슬래시 명령어를 등록하려면Chat 구성 콘솔의 페이지 (API 및 서비스 >대시보드 >행아웃 채팅 API >구성 또는 저장용량 버킷).

  1. 슬래시 명령어에서 슬래시 명령어 추가를 클릭합니다.
  2. 이름에 '/poll'을 입력합니다.
  3. 명령어 ID에 '1'을 입력합니다.
  4. 설명에 '설문조사 시작'을 입력합니다.
  5. 대화상자 열기를 선택합니다.
  6. 완료를 클릭합니다.
  7. 저장을 클릭합니다.

이제 앱이 /poll 명령어를 인식하여 대화상자를 엽니다. 다음으로 대화상자를 구성해 보겠습니다.

구성 양식을 대화상자로 만들기

슬래시 명령어로 대화상자를 열면 설문조사 주제 및 가능한 선택 항목을 구성할 수 있습니다. 다음 콘텐츠로 config-form.js라는 새 파일을 만듭니다.

/** Upper bounds on number of choices to present. */
const MAX_NUM_OF_OPTIONS = 5;

/**
 * Build widget with instructions on how to use form.
 *
 * @returns {object} card widget
 */
function helpText() {
  return {
    textParagraph: {
      text: 'Enter the poll topic and up to 5 choices in the poll. Blank options will be omitted.',
    },
  };
}

/**
 * Build the text input for a choice.
 *
 * @param {number} index - Index to identify the choice
 * @param {string|undefined} value - Initial value to render (optional)
 * @returns {object} card widget
 */
function optionInput(index, value) {
  return {
    textInput: {
      label: `Option ${index + 1}`,
      type: 'SINGLE_LINE',
      name: `option${index}`,
      value: value || '',
    },
  };
}

/**
 * Build the text input for the poll topic.
 *
 * @param {string|undefined} topic - Initial value to render (optional)
 * @returns {object} card widget
 */
function topicInput(topic) {
  return {
    textInput: {
      label: 'Topic',
      type: 'MULTIPLE_LINE',
      name: 'topic',
      value: topic || '',
    },
  };
}

/**
 * Build the buttons/actions for the form.
 *
 * @returns {object} card widget
 */
function buttons() {
  return {
    buttonList: {
      buttons: [
        {
          text: 'Submit',
          onClick: {
            action: {
              function: 'start_poll',
            },
          },
        },
      ],
    },
  };
}

/**
 * Build the configuration form.
 *
 * @param {object} options - Initial state to render with form
 * @param {string|undefined} options.topic - Topic of poll (optional)
 * @param {string[]|undefined} options.choices - Text of choices to display to users (optional)
 * @returns {object} card
 */
function buildConfigurationForm(options) {
  const widgets = [];
  widgets.push(helpText());
  widgets.push(topicInput(options.topic));
  for (let i = 0; i < MAX_NUM_OF_OPTIONS; ++i) {
    const choice = options?.choices?.[i];
    widgets.push(optionInput(i, choice));
  }
  widgets.push(buttons());

  // Assemble the card
  return {
    sections: [
      {
        widgets,
      },
    ],
  };
}

exports.MAX_NUM_OF_OPTIONS = MAX_NUM_OF_OPTIONS;
exports.buildConfigurationForm = buildConfigurationForm;

이 코드를 사용하면 사용자가 설문조사를 설정할 수 있는 대화상자 양식이 생성됩니다. 질문에 대한 최대 선택 횟수에 대한 상수도 내보냅니다. 매개변수로 전달된 상태를 사용하여 스테이트리스(Stateless) 함수로 UI 마크업을 빌드하는 것이 좋습니다. 재사용에 도움이 되며, 이 카드는 나중에 다른 컨텍스트에서 렌더링됩니다.

이 구현은 카드를 더 작은 단위나 구성요소로 분할합니다. 기법은 필수는 아니지만, 복잡한 인터페이스를 빌드할 때 더 읽기 쉽고 유지관리가 쉬운 경향이 있으므로 권장됩니다.

빌드한 전체 JSON 샘플을 보려면 카드 빌더 도구에서 확인하세요.

슬래시 명령어 처리

슬래시 명령어는 앱으로 전송될 때 MESSAGE 이벤트로 표시됩니다. MESSAGE 이벤트를 통해 슬래시 명령어가 있는지 확인하고 대화상자를 응답하도록 index.js를 업데이트합니다. index.js를 다음으로 바꿉니다.

const { buildConfigurationForm, MAX_NUM_OF_OPTIONS } = require('./config-form');

/**
 * App entry point.
 */
exports.app = async (req, res) => {
  if (!(req.method === 'POST' && req.body)) {
      res.status(400).send('')
  }
  const event = req.body;
  let reply = {};
  // Dispatch slash and action events
  if (event.type === 'MESSAGE') {
    const message = event.message;
    if (message.slashCommand?.commandId === '1') {
      reply = showConfigurationForm(event);
    }
  } else if (event.type === 'CARD_CLICKED') {
    if (event.action?.actionMethodName === 'start_poll') {
      reply = await startPoll(event);
    }
  }
  res.json(reply);
}

/**
 * Handles the slash command to display the config form.
 *
 * @param {object} event - chat event
 * @returns {object} Response to send back to Chat
 */
function showConfigurationForm(event) {
  // Seed the topic with any text after the slash command
  const topic = event.message?.argumentText?.trim();
  const dialog = buildConfigurationForm({
    topic,
    choices: [],
  });
  return {
    actionResponse: {
      type: 'DIALOG',
      dialogAction: {
        dialog: {
          body: dialog,
        },
      },
    },
  };
}

/**
 * Handle the custom start_poll action.
 *
 * @param {object} event - chat event
 * @returns {object} Response to send back to Chat
 */
function startPoll(event) {
  // Not fully implemented yet -- just close the dialog
  return {
    actionResponse: {
      type: 'DIALOG',
      dialogAction: {
        actionStatus: {
          statusCode: 'OK',
          userFacingMessage: 'Poll started.',
        },
      },
    },
  }
}

이제 앱은 /poll 명령어가 호출될 때 대화상자를 표시합니다. Cloud Shell에서 Cloud 함수를 다시 실행하여 상호작용을 테스트합니다.

gcloud functions deploy app --trigger-http --security-level=secure-always

Cloud 함수가 배포되면 /poll 명령어로 앱에 메시지를 보내 슬래시 명령어와 대화상자를 테스트합니다. 대화상자에서 맞춤 작업 start_poll를 사용하여 CARD_CLICKED 이벤트를 전송합니다. 이벤트는 startPoll 메서드를 호출하는 업데이트된 진입점에서 처리됩니다. 현재 startPoll 메서드는 스텁 처리되어 대화상자를 닫습니다. 다음 섹션에서는 투표 기능을 구현하고 모든 부분을 함께 연결합니다.

투표 카드 구현하기

앱의 투표 부분을 구현하려면 먼저 사용자가 투표할 수 있는 인터페이스를 제공하는 대화형 카드를 정의합니다.

투표 인터페이스 구현하기

다음 콘텐츠로 vote-card.js이라는 파일을 만듭니다.

/**
 * Creates a small progress bar to show percent of votes for an option. Since
 * width is limited, the percentage is scaled to 20 steps (5% increments).
 *
 * @param {number} voteCount - Number of votes for this option
 * @param {number} totalVotes - Total votes cast in the poll
 * @returns {string} Text snippet with bar and vote totals
 */
function progressBarText(voteCount, totalVotes) {
  if (voteCount === 0 || totalVotes === 0) {
    return '';
  }

  // For progress bar, calculate share of votes and scale it
  const percentage = (voteCount * 100) / totalVotes;
  const progress = Math.round((percentage / 100) * 20);
  return '▀'.repeat(progress);
}

/**
 * Builds a line in the card for a single choice, including
 * the current totals and voting action.
 *
 * @param {number} index - Index to identify the choice
 * @param {string|undefined} value - Text of the choice
 * @param {number} voteCount - Current number of votes cast for this item
 * @param {number} totalVotes - Total votes cast in poll
 * @param {string} state - Serialized state to send in events
 * @returns {object} card widget
 */
function choice(index, text, voteCount, totalVotes, state) {
  const progressBar = progressBarText(voteCount, totalVotes);
  return {
    keyValue: {
      bottomLabel: `${progressBar} ${voteCount}`,
      content: text,
      button: {
        textButton: {
          text: 'vote',
          onClick: {
            action: {
              actionMethodName: 'vote',
              parameters: [
                {
                  key: 'state',
                  value: state,
                },
                {
                  key: 'index',
                  value: index.toString(10),
                },
              ],
            },
          },
        },
      },
    },
  };
}

/**
 * Builds the card header including the question and author details.
 *
 * @param {string} topic - Topic of the poll
 * @param {string} author - Display name of user that created the poll
 * @returns {object} card widget
 */
function header(topic, author) {
  return {
    title: topic,
    subtitle: `Posted by ${author}`,
    imageUrl:
      'https://raw.githubusercontent.com/google/material-design-icons/master/png/social/poll/materialicons/24dp/2x/baseline_poll_black_24dp.png',
    imageStyle: 'AVATAR',
  };
}

/**
 * Builds the configuration form.
 *
 * @param {object} poll - Current state of poll
 * @param {object} poll.author - User that submitted the poll
 * @param {string} poll.topic - Topic of poll
 * @param {string[]} poll.choices - Text of choices to display to users
 * @param {object} poll.votes - Map of cast votes keyed by user ids
 * @returns {object} card
 */
function buildVoteCard(poll) {
  const widgets = [];
  const state = JSON.stringify(poll);
  const totalVotes = Object.keys(poll.votes).length;

  for (let i = 0; i < poll.choices.length; ++i) {
    // Count votes for this choice
    const votes = Object.values(poll.votes).reduce((sum, vote) => {
      if (vote === i) {
        return sum + 1;
      }
      return sum;
    }, 0);
    widgets.push(choice(i, poll.choices[i], votes, totalVotes, state));
  }

  return {
    header: header(poll.topic, poll.author.displayName),
    sections: [
      {
        widgets,
      },
    ],
  };
}

exports.buildVoteCard = buildVoteCard;

구현은 대화상자에 사용된 접근 방식과 유사하지만 양방향 카드의 마크업은 대화상자와 약간 다릅니다. 앞에서와 같이 카드 빌더 도구에서 생성된 JSON 샘플을 볼 수 있습니다.

투표 작업 구현

투표 카드에는 각 선택 항목의 버튼이 포함되어 있습니다. 설문조사의 직렬화된 상태와 함께 선택한 항목의 색인이 버튼에 연결됩니다. 앱은 버튼에 연결된 모든 데이터와 함께 작업 vote가 포함된 CARD_CLICKED를 수신합니다.

index.js를 다음으로 업데이트:

const { buildConfigurationForm, MAX_NUM_OF_OPTIONS } = require('./config-form');
const { buildVoteCard } = require('./vote-card');

/**
 * App entry point.
 */
exports.app = async (req, res) => {
  if (!(req.method === 'POST' && req.body)) {
      res.status(400).send('')
  }
  const event = req.body;
  let reply = {};
  // Dispatch slash and action events
  if (event.type === 'MESSAGE') {
    const message = event.message;
    if (message.slashCommand?.commandId === '1') {
      reply = showConfigurationForm(event);
    }
  } else if (event.type === 'CARD_CLICKED') {
    if (event.action?.actionMethodName === 'start_poll') {
      reply = await startPoll(event);
    } else if (event.action?.actionMethodName === 'vote') {
        reply = recordVote(event);
    }
  }
  res.json(reply);
}

/**
 * Handles the slash command to display the config form.
 *
 * @param {object} event - chat event
 * @returns {object} Response to send back to Chat
 */
function showConfigurationForm(event) {
  // Seed the topic with any text after the slash command
  const topic = event.message?.argumentText?.trim();
  const dialog = buildConfigurationForm({
    topic,
    choices: [],
  });
  return {
    actionResponse: {
      type: 'DIALOG',
      dialogAction: {
        dialog: {
          body: dialog,
        },
      },
    },
  };
}

/**
 * Handle the custom start_poll action.
 *
 * @param {object} event - chat event
 * @returns {object} Response to send back to Chat
 */
function startPoll(event) {
  // Not fully implemented yet -- just close the dialog
  return {
    actionResponse: {
      type: 'DIALOG',
      dialogAction: {
        actionStatus: {
          statusCode: 'OK',
          userFacingMessage: 'Poll started.',
        },
      },
    },
  }
}

/**
 * Handle the custom vote action. Updates the state to record
 * the user's vote then rerenders the card.
 *
 * @param {object} event - chat event
 * @returns {object} Response to send back to Chat
 */
function recordVote(event) {
  const parameters = event.common?.parameters;

  const choice = parseInt(parameters['index']);
  const userId = event.user.name;
  const state = JSON.parse(parameters['state']);

  // Add or update the user's selected option
  state.votes[userId] = choice;

  const card = buildVoteCard(state);
  return {
    thread: event.message.thread,
    actionResponse: {
      type: 'UPDATE_MESSAGE',
    },
    cards: [card],
  }
}

recordVote 메서드는 저장된 상태를 파싱하고 사용자의 투표로 업데이트한 다음 카드를 다시 렌더링합니다. 설문조사 결과는 직렬화될 때마다 카드와 함께 직렬화되어 저장됩니다.

조각 연결

앱이 거의 완성되었습니다. 투표와 함께 슬래시 명령어를 구현하면 startPoll 메서드를 종료하기만 하면 됩니다.

하지만 여기에 주목할 점이 있습니다.

설문조사 구성이 제출되면 앱은 다음 두 가지 작업을 실행해야 합니다.

  1. 대화상자를 닫습니다.
  2. 투표 카드를 사용하여 스페이스에 새 메시지를 게시하세요.

안타깝게도 HTTP 요청에 직접 응답하는 것은 하나만 가능하며, 첫 번째 응답이어야 합니다. 투표 카드를 게시하려면 앱에서 Chat API를 사용하여 비동기적으로 새 메시지를 만들어야 합니다.

클라이언트 라이브러리 추가

다음 명령어를 실행하여 Node.js용 Google API 클라이언트를 포함하도록 앱의 종속 항목을 업데이트합니다.

npm install --save googleapis

설문조사 시작하기

index.js을 아래의 최종 버전으로 업데이트합니다.

const { buildConfigurationForm, MAX_NUM_OF_OPTIONS } = require('./config-form');
const { buildVoteCard } = require('./vote-card');
const {google} = require('googleapis');

/**
 * App entry point.
 */
exports.app = async (req, res) => {
  if (!(req.method === 'POST' && req.body)) {
      res.status(400).send('')
  }
  const event = req.body;
  let reply = {};
  // Dispatch slash and action events
  if (event.type === 'MESSAGE') {
    const message = event.message;
    if (message.slashCommand?.commandId === '1') {
      reply = showConfigurationForm(event);
    }
  } else if (event.type === 'CARD_CLICKED') {
    if (event.action?.actionMethodName === 'start_poll') {
      reply = await startPoll(event);
    } else if (event.action?.actionMethodName === 'vote') {
        reply = recordVote(event);
    }
  }
  res.json(reply);
}

/**
 * Handles the slash command to display the config form.
 *
 * @param {object} event - chat event
 * @returns {object} Response to send back to Chat
 */
function showConfigurationForm(event) {
  // Seed the topic with any text after the slash command
  const topic = event.message?.argumentText?.trim();
  const dialog = buildConfigurationForm({
    topic,
    choices: [],
  });
  return {
    actionResponse: {
      type: 'DIALOG',
      dialogAction: {
        dialog: {
          body: dialog,
        },
      },
    },
  };
}

/**
 * Handle the custom start_poll action.
 *
 * @param {object} event - chat event
 * @returns {object} Response to send back to Chat
 */
async function startPoll(event) {
  // Get the form values
  const formValues = event.common?.formInputs;
  const topic = formValues?.['topic']?.stringInputs.value[0]?.trim();
  const choices = [];
  for (let i = 0; i < MAX_NUM_OF_OPTIONS; ++i) {
    const choice = formValues?.[`option${i}`]?.stringInputs.value[0]?.trim();
    if (choice) {
      choices.push(choice);
    }
  }

  if (!topic || choices.length === 0) {
    // Incomplete form submitted, rerender
    const dialog = buildConfigurationForm({
      topic,
      choices,
    });
    return {
      actionResponse: {
        type: 'DIALOG',
        dialogAction: {
          dialog: {
            body: dialog,
          },
        },
      },
    };
  }

  // Valid configuration, build the voting card to display
  // in the space
  const pollCard = buildVoteCard({
    topic: topic,
    author: event.user,
    choices: choices,
    votes: {},
  });
  const message = {
    cards: [pollCard],
  };
  const request = {
    parent: event.space.name,
    requestBody: message,
  };
  // Use default credentials (service account)
  const credentials = new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/chat.bot'],
  });
  const chatApi = google.chat({
    version: 'v1',
    auth: credentials,
  });
  await chatApi.spaces.messages.create(request);

  // Close dialog
  return {
    actionResponse: {
      type: 'DIALOG',
      dialogAction: {
        actionStatus: {
          statusCode: 'OK',
          userFacingMessage: 'Poll started.',
        },
      },
    },
  };
}

/**
 * Handle the custom vote action. Updates the state to record
 * the user's vote then rerenders the card.
 *
 * @param {object} event - chat event
 * @returns {object} Response to send back to Chat
 */
function recordVote(event) {
  const parameters = event.common?.parameters;

  const choice = parseInt(parameters['index']);
  const userId = event.user.name;
  const state = JSON.parse(parameters['state']);

  // Add or update the user's selected option
  state.votes[userId] = choice;

  const card = buildVoteCard(state);
  return {
    thread: event.message.thread,
    actionResponse: {
      type: 'UPDATE_MESSAGE',
    },
    cards: [card],
  }
}

함수를 다시 배포합니다.

gcloud functions deploy app --trigger-http --security-level=secure-always

이제 앱을 완전히 실행할 수 있습니다. /poll 명령어를 호출하여 질문과 선택 항목을 제공해 보세요. 제출하면 설문조사 카드가 표시됩니다.

투표하여 어떤 일이 일어나는지 확인해 보세요.

물론 설문조사가 여기서 유용한 것은 아니므로 친구나 동료를 초대하여 사용해 보세요.

6. 축하합니다

축하합니다. Cloud Functions를 사용하여 Google Chat 앱을 빌드하고 배포했습니다. Codelab에서는 앱 빌드의 핵심 개념을 대부분 다뤘지만 더 자세히 살펴보겠습니다. 아래 리소스를 확인하고 추가 비용이 청구되지 않도록 프로젝트를 정리하는 것을 잊지 마세요.

추가 활동

Chat 플랫폼과 이 앱을 더 자세히 살펴보고 싶다면 다음의 몇 가지 방법을 직접 사용해 보세요.

  • 앱을 @ 멘션하면 어떻게 되나요? 앱을 업데이트하여 동작을 개선해 보세요.
  • 작은 설문조사의 경우 카드에서 설문조사 상태를 직렬화하는 것은 문제가 없지만 제한이 있습니다. 더 나은 옵션으로 전환해 보세요.
  • 작성자가 설문조사를 수정하거나 새 투표를 중단하려면 어떻게 해야 하나요? 이 기능을 어떻게 구현할 수 있을까요?
  • 앱 엔드포인트가 아직 안전하지 않습니다. 요청을 추가하여 Google Chat에서 요청이 들어오도록 하세요.

이는 앱을 개선하는 몇 가지 방법일 뿐입니다. 창의력을 발휘하고 상상력을 발휘해 보세요!

삭제

이 가이드에서 사용한 리소스 비용이 Google Cloud Platform 계정에 청구되지 않도록 하는 방법은 다음과 같습니다.

  • Cloud Console에서 리소스 관리 페이지로 이동합니다. 왼쪽 상단에서 메뉴메뉴 아이콘 > IAM 및 관리자 > 리소스 관리를 클릭합니다.
  1. 프로젝트 목록에서 프로젝트를 선택한 다음 삭제를 클릭합니다.
  2. 대화상자에서 프로젝트 ID를 입력한 다음 종료를 클릭하여 프로젝트를 삭제합니다.

자세히 알아보기

Chat 앱 개발에 관한 자세한 내용은 다음을 참고하세요.

Google Cloud Console에서의 개발에 관한 자세한 내용은 다음을 참고하세요.