IT/AI

Dialogflow - 4. 외부 사이트 연동

루벤초이 2021. 4. 16. 20:19

Dialogflow 웹앱 시리즈입니다.

★Sample Code


지난 편에서 fulfillment를 사용해봤습니다. 오늘은 fulfillment inline editor를 통해 외부 사이트를 연동해 봅니다.

 

외부 서버 연동

코딩에 앞서, 날씨 정보를 가져올 수 있는 외부 사이트가 필요한데, 실제 날씨 서버를 연결할 수 없으니 샘플 서버를 사용하겠습니다.

샘플 날씨 서버

위와 같이 https GET으로 json 날씨 정보를 받아올 수 있는 샘플 서버를 사용해서 날씨를 알려주는 코드를 짜 봅시다.

날씨 인텐트

우선 날씨를 물어보는 인텐트 ask-weather를 만들고 fulfillment를 enable합니다.

...생략...
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {

...중략...

  function getWeather(agent) {
    console.log("----------------getWeather");
    return weatherAPI()
        .then(result => agent.add(result))
        .catch((err) => agent.add(err));
  }

  function weatherAPI() {
      const url = "https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22";
      console.log("weatherAPI: url=", url);
      return new Promise((resolve, reject) => {
          https.get(url, function (res) {
              console.log("**************************");
              console.log(res.statusCode, res.headers);
              var json = "";
              res.on("data", function (chunk) {
                  console.log("received JSON response: " + chunk);
                  json += chunk;
              });

              res.on("end", function () {
                  let jsonData = JSON.parse(json);
                  let r = "The weather is " + jsonData.weather[0].description;
                  resolve(r);
              });
          });
      });
  }
  
...중략...
  intentMap.set('ask-weather', getWeather);
...생략...
});

Fulfillment에 가서 위와 같이 getWeather(), weatherAPI() 함수를 추가하고 intentMap에 ask-weather 처리구문을 추가한 뒤, DEPLOY합니다. 이 부분은 일반적인 Node.js 코드인데요, HTTPS GET으로 외부 서버로부터 정보를 가져오는 구문입니다.

 

혹시 Promise에 관한 문법을 잘 모르면 React 웹캠 - 1. Promise 비동기 함수의 이해편을 참고하세요.

이제 검증해 봅시다.

오늘 날씨를 묻자 ask-weather 인텐트가 작동하고 fulfillment에서 외부 서버로부터 받아 온 정보를 조합하여 응답하는 것을 확인할 수 있습니다.

 

확장

이쯤 되면, 날씨 샘플 서버 대신 우리가 만든 서버를 사용할 수 있겠죠. 그럴려면 우선 우리 서버가 public하게 즉 인터넷에서 접근 가능해야 하는데요, AWS EC2 같은 유료 호스팅 서비스를 사용하거나, 일시적으로는 localtunnel 같은 무료 오픈 소스를 사용해서 public 서버를 구축할 수 있습니다. 통신 방법은 위와 같이 HTTP GET 통신을 사용할 수도 있고 Restful이나 MQTT 등 Node.js에서 사용 가능한 통신 프로토콜이라면 뭐든지 사용할 수 있겠죠.

 

문제는 DEPLOY가 너무 오래 걸린다는 점과 만일 코드가 많이 늘어나면, Inline Editor로 관리하기 불편해진다는 점이죠. 그래서 나왔습니다. Webhook!

 

Webhook을 단번에 다루기엔 머리가 복잡하니 좀 쉬었다가 다음 편에서 다루도록 하겠습니다.

728x90
반응형

'IT > AI' 카테고리의 다른 글

Dialogflow - 6. 클라이언트  (0) 2021.04.20
Dialogflow - 5. Webhook  (0) 2021.04.19
Dialogflow - 3. Fulfillment  (2) 2021.04.16
Google Cloud Platform & Firebase  (0) 2021.04.15
Dialogflow - 2. Context  (0) 2021.04.15