message.js 7.92 KB
var express = require('express');
var request = require('request');
var rssparser = require('rss-parser');
var bodyparser = require('body-parser')
var app = express.Router();
// Naver Auth Key // to do)) get a new Auth key
var client_id = 'is216aNtQ6QLNkWW03bc';
var client_secret = 'Ot0BMdWXOJ';

// Naver API URL
var translate_url = 'https://openapi.naver.com/v1/language/translate';
var trend_url = 'https://openapi.naver.com/v1/datalab/search';
var source = 'ko';
var target = 'en';
//일본어 ja , 중국어 간체 zh-CN , 중국어 번체 zh-TW

//what kind of task to do
var translate = false;
var trend = false;
var option = false;
// Kakao Message API
app.post('/', function(req, res) {
  var _obj = {
    user_key: req.body.user_key,
    type: req.body.type,
    content: req.body.content
  };

  if(_obj.content == '언어설정'){
    option = true;
    translate = false;
    trend = false;
    res.json({
      "message": {
        "text": "번역 언어를 설정합니다"
      },
      "keyboard": {
        "type": "buttons",
        "buttons":["한-영", "영-한","한-일","일-한","한-중국어간체","중국어간체-한","한-중국어번체",
      "중국어번체-한"]
      }
    });
  }else if (_obj.content == '번역'){
      translate = true;
      option = false;
      trend = false;
      res.json({
        "message": {
  		  "text": "입력한 텍스트를 번역해드리겠습니다. 자 시작!"
        },
        "keyboard": {
          "type": "text"
        }
      });
    }else if (_obj.content == '트랜드 검색'){
      trend = true;
      option = false;
      translate = false;
      res.json({
        "message":{
          "text": "검색어 트랜드를 시작합니다. 주제를 입력해주세요."
        },
        "keyboard": {
          "type": "text"
        }
      });
    }
    else if (translate)
    {
      // Naver Papago Translate
      var options = {
        url: translate_url,
        // (source : 번역할 대상), (target: 번역후 언어), 카톡에서 받는 메시지(text)
        form: {'source':source, 'target':target, 'text':req.body.content},
        headers: {'X-Naver-Client-Id': client_id, 'X-Naver-Client-Secret': client_secret}
      };
      // Naver Post API
      request.post(options, function(error, response, body){
        // Translate API Sucess
        if(!error && response.statusCode == 200){
          // JSON
          var objBody = JSON.parse(response.body);
          // Message 잘 찍히는지 확인
          console.log(objBody.message.result.translatedText);

          // Kakao Message API
          let message = {
            "message": {
              // Naver API Translate 결과를 Kakao Message
              "text": objBody.message.result.translatedText
            },"keyboard": {
              "type": "buttons",
              "buttons":["언어설정", "번역","트랜드 검색"]
            }
          };
          // Kakao Message API 전송
          res.set({
            'content-type': 'application/json'
          }).send(JSON.stringify(message));
        }
        else{
          // Naver Message Error 발생
          res.status(response.statusCode).end();
          console.log('error = ' + response.statusCode);

          let message = {
            "message": {
              "text": response.statusCode
            },
            "keyboard": {
              "type": "buttons",
              "buttons":["언어설정", "번역","트랜드 검색"]
            }
          };

          // Kakao에 Error Message
          res.set({
            'content-type': 'application/json'
          }).send(JSON.stringify(message));
        }
      });
    }else if (trend)
    {
      var request_body = {
      "startDate": "2018-09-01",
      "endDate": "2018-12-01",
      "timeUnit": "month",
      "keywordGroups": [
          {
              "groupName": req.body.content,
              "keywords": [
                  req.body.content
              ]
          }
      ],
      "device": "pc",
      "ages": [

      ],
      "gender": ""
  };

    request.post({
        url: trend_url,
        body: JSON.stringify(request_body),
        headers: {
            'X-Naver-Client-Id': client_id,
            'X-Naver-Client-Secret': client_secret,
            'Content-Type': 'application/json'
        }
    },
      function (error, response, body) {
          console.log(response.statusCode);
          console.log(body);

          if(!error && response.statusCode == 200){
            var objBody = JSON.parse(response.body);
            console.log(objBody);
            let message = {
              "message": {
                "text": response.body
              },"keyboard": {
                "type": "buttons",
                "buttons":["언어설정", "번역","트랜드 검색"]
              }
            };

            res.set({
              'content-type': 'application/json'
            }).send(JSON.stringify(message));
          }
          else{
            res.status(response.statusCode).end();
            console.log('error = ' + response.statusCode);
            let message = {
              "message": {
                "text": response.statusCode
              },"keyboard": {
                "type": "buttons",
                "buttons":["언어설정", "번역","트랜드 검색"]
              }
            };
            res.set({
              'content-type': 'application/json'
            }).send(JSON.stringify(message));
          }
        });
   }
    /*else if (dictionary)
    {
      var reqURL = 'https://openapi.naver.com/v1/search/encyc.json?query=' + encodeURI(req.query.query)
      + '&display=3&start=1';

      var options = {
        url: reqURL,
        headers: {'X-Naver-Client-Id': client_id, 'X-Naver-Client-Secret': client_secret}
      };
      request.get(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
          let parser = new rssparser();

          (async () => {

            let feed = await parser.parseURL(reqURL);
              var title = feed.items.channel.title;
              var description = feed.items.channel.items.description;
              var link = feed.items.channel.items.link;

          }) ();
          //var objBody = JSON.parse(response.body);
          let message = {
              "message": {
                "text": title + " : " + description
              },
              "message_button": {
                "label": "백과사전에서 직접보기",
                "url": link
              }
            };


        }
        else {
        res.status(response.statusCode).end();
        console.log('error = ' + response.statusCode);
        }
      });

    }*/
    else if (option)
    {
        if (_obj.content == "한-영")
        {
          source = 'ko';
          target = 'en';
        }
        else if (_obj.content == "영-한")
        {
          source = "en";
          target = "ko";
        }
        else if (_obj.content == "한-일")
        {
          source = "ko";
          target = "ja";
        }
        else if (_obj.content == "일-한")
        {
          source = "ja";
          target = "ko";
        }
        else if (_obj.content == "한-중국어간체")
        {
          source = "ko";
          target = "zh-CN";
        }
        else if (_obj.content == "중국어간체-한")
        {
          source = "zh-CN";
          target = "ko";
        }
        else if (_obj.content == "한-중국어번체")
        {
          source = "ko";
          target = "zh-TW";
        }
        else if (_obj.content == "중국어번체-한")
        {
          source = "zh-TW";
          target = "ko";
        }
        console.log(source, target);
        res.json({
          "message": {
            "text": source + "에서" + target + "으로 번역합니다."
          },
          "keyboard": {
            "type": "buttons",
            "buttons":["언어설정", "번역","트랜드 검색"]
          }
        });
    }
});

module.exports = app;