Dialogflow와 Calendar를 통합하여 fulfillment 이해하기

1. 시작하기 전에

이 Codelab에서는 Dialogflow가 백엔드 시스템과 연결하여 사용자에게 풍부하고 동적인 응답을 제공하는 방법을 알아봅니다. 개의 질문이 있습니다.

기본 요건

계속하기 전에 다음 Codelab을 완료해야 합니다.

  1. Dialogflow로 약속 스케줄러 빌드하기
  2. Dialogflow와 Actions on Google 통합
  3. Dialogflow의 항목 이해

또한 Dialogflow의 기본 개념과 구성도 이해해야 합니다. Dialogflow의 기본 개념과 구성도 Dialogflow로 챗봇 빌드 과정에 있는 다음 동영상에서 얻을 수 있습니다.

학습할 내용

  • 처리란 무엇인가요?
  • Calendar용 서비스 계정을 설정하는 방법
  • Calendar 설정 방법
  • Dialogflow에서 fulfillment를 사용 설정하는 방법
  • 처리를 테스트하는 방법

빌드할 항목

  • Cloud Functions를 사용한 처리
  • Dialogflow와 Calendar 통합

필요한 항목

  • Dialogflow 콘솔에 로그인할 수 있는 웹브라우저 및 이메일 주소
  • Calendar에 액세스하기 위한 Google 계정

2. 처리란 무엇인가요?

처리는 Dialogflow 에이전트가 인텐트별로 비즈니스 로직을 호출할 수 있게 해주는 웹훅으로 배포되는 코드입니다. 대화 중에 처리를 통해 Dialogflow의 자연어 처리에서 추출된 정보를 사용하여 동적 응답을 생성하거나 백엔드에서 작업을 트리거할 수 있습니다. 대부분의 Dialogflow 에이전트는 fulfillment를 사용합니다.

다음은 처리를 사용하여 에이전트를 확장할 수 있는 경우를 보여주는 몇 가지 예입니다.

  • 데이터베이스에서 조회된 정보를 기반으로 동적 응답 생성
  • 고객이 요청한 제품을 기준으로 주문
  • 게임의 규칙과 승리 조건을 구현하기 위해

3. Calendar API 사용 설정

  1. Dialogflow 콘솔에서 d7d792687e597dd5.png를 클릭합니다.
  2. 일반 탭에서 프로젝트 ID로 스크롤한 다음 Google Cloud f2bffd4fcdb84fa9.png를 클릭합니다.

34be16fcd4c5aeff.png

  1. Google Cloud 콘솔에서 탐색 메뉴 ☰ >를 클릭합니다. API 및 서비스 > 라이브러리.
  2. 'Google Calendar API'를 검색합니다. 그런 다음 사용 설정을 클릭하여 Google Cloud 프로젝트에서 API를 사용합니다.

4. 서비스 계정 설정

  1. 탐색 메뉴 ❯를 클릭합니다. API 및 서비스 > 사용자 인증 정보.
  2. 사용자 인증 정보 만들기를 클릭합니다. 서비스 계정.

86f51af0e7886fdd.png

  1. 서비스 계정 세부정보에 'appointment-scheduler'를 입력합니다. 서비스 계정 이름으로 지정하고 만들기를 클릭합니다.

845d25f3e07ff770.png

  1. 이 서비스 계정에 프로젝트에 대한 액세스 권한 부여라고 표시된 부분에서 계속을 클릭하여 건너뜁니다.
  2. 사용자에게 이 서비스 계정에 대한 액세스 권한 부여 (선택사항)라고 표시된 부분에서 키 만들기를 클릭한 다음 JSON을 선택하고 만들기를 클릭합니다.

JSON 파일이 컴퓨터에 다운로드되며 다음 설정 섹션에서 필요합니다. a424cec60144d707.png

5. 캘린더 설정

  1. Calendar로 이동한 다음 기본 메뉴 ❯ >를 클릭합니다. 다른 캘린더 추가하기 fbc354048b0a2c6c.png> 새 캘린더 만들기

d6ec2fcf0bd2ae22.png

  1. '약속 캘린더'를 입력합니다. 을 캘린더 이름으로 설정하고 캘린더 만들기를 클릭합니다.
  2. 페이지를 새로고침하고 약속 캘린더를 클릭하고 특정 사용자와 공유까지 스크롤한 다음 사용자 추가를 클릭합니다.
  3. 서비스 계정 설정의 일부로 다운로드한 JSON 파일에서 client_email를 복사하여 대화상자에 붙여넣습니다.

7927f6fa675e3e87.png

  1. 권한 드롭다운 목록을 클릭한 다음 일정 변경 >을 클릭합니다. 보내기를 클릭합니다.

2ee99d3d15eed97b.png

  1. 설정에서 캘린더 통합으로 스크롤한 다음 캘린더 ID를 복사합니다.

df8a731f0713c52.png

6. Dialogflow에서 fulfillment 설정

처리에 서비스 계정 및 캘린더 ID 추가

  1. AppointmentScheduler Dialogflow 에이전트로 이동하여 Fulfillment를 클릭합니다.
  2. 인라인 편집기사용 설정합니다.

c8574c6ef899393f.png

  1. 다음 코드를 사용하여 index.js 파일을 업데이트합니다.
'use strict';

// Import the Dialogflow module from Google client libraries.
const functions = require('firebase-functions');
const {google} = require('googleapis');
const {WebhookClient} = require('dialogflow-fulfillment');

// Enter your calendar ID below and service account JSON below
const calendarId = "<INSERT YOUR CALENDAR ID>";
const serviceAccount = {<INSERT CONTENTS OF YOUr JSON FILE HERE>}; // Starts with {"type": "service_account",...

// Set up Google Calendar Service account credentials
const serviceAccountAuth = new google.auth.JWT({
 email: serviceAccount.client_email,
 key: serviceAccount.private_key,
 scopes: 'https://www.googleapis.com/auth/calendar'
});

const calendar = google.calendar('v3');
process.env.DEBUG = 'dialogflow:*'; // enables lib debugging statements

const timeZone = 'America/Los_Angeles';
const timeZoneOffset = '-07:00';

// Set the DialogflowApp object to handle the HTTPS POST request.
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
 const agent = new WebhookClient({ request, response });
 console.log("Parameters", agent.parameters);
 const appointment_type = agent.parameters.appointment_type;
 function makeAppointment (agent) {
   // Calculate appointment start and end datetimes (end = +1hr from start)
   const dateTimeStart = new Date(Date.parse(agent.parameters.date.split('T')[0] + 'T' + agent.parameters.time.split('T')[1].split('-')[0] + timeZoneOffset));
   const dateTimeEnd = new Date(new Date(dateTimeStart).setHours(dateTimeStart.getHours() + 1));
   const appointmentTimeString = dateTimeStart.toLocaleString(
     'en-US',
     { month: 'long', day: 'numeric', hour: 'numeric', timeZone: timeZone }
   );
    // Check the availability of the time, and make an appointment if there is time on the calendar
   return createCalendarEvent(dateTimeStart, dateTimeEnd, appointment_type).then(() => {
     agent.add(`Ok, let me see if we can fit you in. ${appointmentTimeString} is fine!.`);
   }).catch(() => {
     agent.add(`I'm sorry, there are no slots available for ${appointmentTimeString}.`);
   });
 }

// Handle the Dialogflow intent named 'Schedule Appointment'.
 let intentMap = new Map();
 intentMap.set('Schedule Appointment', makeAppointment);
 agent.handleRequest(intentMap);
});

//Creates calendar event in Google Calendar
function createCalendarEvent (dateTimeStart, dateTimeEnd, appointment_type) {
 return new Promise((resolve, reject) => {
   calendar.events.list({
     auth: serviceAccountAuth, // List events for time period
     calendarId: calendarId,
     timeMin: dateTimeStart.toISOString(),
     timeMax: dateTimeEnd.toISOString()
   }, (err, calendarResponse) => {
     // Check if there is a event already on the Calendar
     if (err || calendarResponse.data.items.length > 0) {
       reject(err || new Error('Requested time conflicts with another appointment'));
     } else {
       // Create event for the requested time period
       calendar.events.insert({ auth: serviceAccountAuth,
         calendarId: calendarId,
         resource: {summary: appointment_type +' Appointment', description: appointment_type,
           start: {dateTime: dateTimeStart},
           end: {dateTime: dateTimeEnd}}
       }, (err, event) => {
         err ? reject(err) : resolve(event);
       }
       );
     }
   });
 });
}
  1. <INSERT YOUR CALENDAR ID>를 이전 섹션에서 복사한 캘린더 ID로 바꿉니다.
  2. <INSERT CONTENTS OF YOUR JSON FILE HERE>를 JSON 파일의 콘텐츠로 바꿉니다.
  3. (선택사항) 약속 캘린더의 시간대에 따라 const timeZoneconst timeZoneOffset을 변경합니다.
  4. 배포를 클릭합니다.

fulfillment 응답 사용 설정

  1. Dialogflow 콘솔로 이동하여 인텐트를 클릭합니다.
  2. 일정 예약 인텐트를 클릭합니다.
  3. fulfillment까지 아래로 스크롤하고 인텐트의 웹훅 호출 사용 설정을 사용 설정합니다.

a5b41336b5249e44.png

  1. 저장을 클릭합니다.
  2. 배포를 클릭합니다.

7. 챗봇 테스트

Actions 시뮬레이터에서 챗봇을 테스트하거나 이전에 배운 웹 또는 Google Home 통합을 사용할 수 있습니다.

  1. 사용자: "내일 오후 2시에 차량 등록 일정 예약해 줘."
  2. 챗봇: "네, 연결해 드릴 수 있는지 알아보겠습니다. 4월 24일 오후 2시는 괜찮습니다."

96d3784c103daf5e.png

  1. Calendar에서 응답을 예약합니다.

b7da9da814271db8.png

8. 삭제

다른 Dialogflow Codelab을 완료할 계획이라면 지금은 이 섹션을 건너뛰고 나중에 다시 확인하세요.

Dialogflow 에이전트 삭제

  1. 기존 에이전트 옆에 있는 dc4ac6f9c0ae94e9.png를 클릭합니다.

520c1c6bb9f46ea6.png

  1. General 탭에서 하단으로 스크롤하여 Delete This Agent를 클릭합니다.
  2. 대화상자에 Delete를 입력하고 삭제를 클릭합니다.

9. 축하합니다

Dialogflow에서 챗봇을 만들어 Calendar와 통합해 보았습니다. 챗봇 개발자가 되셨습니다!

자세히 알아보기

자세한 내용은 Dialogflow GitHub 페이지의 코드 샘플을 확인하세요.