app.js 8.96 KB
'use strict'
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
var fs = require("fs");
app.use(express.static('images'));

app.use(bodyParser.json());
app.use(bodyParser.text());
app.use(bodyParser.urlencoded({
  extended: false
})); //post에서bodyparser로 받기 위함

var price;
var shape = [];
var kinds = [];

// 3번 단계에서 얻은 토큰을 넣어줍니다 . 개인 깃에 올릴 경우 이 부분은 절대 커밋하지 마세요.
var PAGE_ACCESS_TOKEN = 'EAATExQZAyiJ0BAAcfdgDOytqZCz6XZCCW05NRT7S2dpHbyxRw71m3RBm66Alu3BJLLU6hvLCMK5VYXSppy9BzDlpZB3BwNHgKJQrZAKfyKX5x2VYlYQApR3cGMl0Q27m8EJ7vZAIxEtKZAmSrNImbUmyyx5ZCiyqoTc9W63IYUg1dgZDZD';
//EAAIZBdEhUzlcBAAy7a21fSEuW76k1ABpld4ncE0XcrRv902dy56lZAZCAZANmKifUVah2H5j94xZBpmWAVGR9bhVlouzYyykVJ0XD447ju4Wco2G08jroUdF9hU1FZCILBSZAJxmgkoTYbCQ2FQ8xZByvsDGZAPVPvtBHL51ZCTfOiEgZDZD
app.set('port', (process.env.PORT || 5000));

app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(bodyParser.json());

app.get('/', (req, res) => {
  res.send('Hello world');
})

// 페이스북 연결
app.get('/webhook', (req, res) => {
  if (req.query['hub.verify_token'] === 'VERIFY_TOKEN') {
    res.send(req.query['hub.challenge']);
  }
  res.send('Error, wrong token');
})

app.post("/webhook", (req, res) => {
  console.log("WEBHOOK GET IT WORKS");
  var data = req.body;
  console.log(data);

  // Make sure this is a page subscription
  if (data.object == 'page') {
    // Iterate over each entry
    // There may be multiple if batched
    data.entry.forEach((pageEntry) => {
      var pageID = pageEntry.id;
      var timeOfEvent = pageEntry.time;

      // Iterate over each messaging event
      pageEntry.messaging.forEach((messagingEvent) => {
        if (messagingEvent.optin) {
          receivedAuthentication(messagingEvent);
        } else if (messagingEvent.message) {
          var quest = messagingEvent.message.text;
          var price = quest;
          if (((quest.search('음식') != -1) || (quest.search('추천') != -1)) || ((quest.search('뭐') != -1) && (quest.search('먹') != -1))) {
            receivedMessage_price(messagingEvent);
          } else if (price == Number(price)) {
            price = Number(price);
            sendTextMessage(messagingEvent.sender.id, '원하시는 음식 카테고리가 있나요?');
          } else if ((quest.search('한식') != -1) || (quest.search('중식') != -1) || (quest.search('일식') != -1) || (quest.search('양식') != -1)) {
            if ((quest.search('한식') != -1))
              kinds.push('한식');
            if ((quest.search('중식') != -1))
              kinds.push('중식');
            if (quest.search('일식') != -1)
              kinds.push('일식');
            if ((quest.search('양식') != -1))
              kinds.push('양식');
            sendTextMessage(messagingEvent.sender.id, '원하시는 음식 형태가 있나요?');
          } else if ((quest.search('밥') != -1) || (quest.search('면') != -1) || (quest.search('고기') != -1) || (quest.search('기타') != -1)) {
            if ((quest.search('밥') != -1))
              shape.push('밥');
            if ((quest.search('면') != -1))
              shape.push('면');
            if (quest.search('고기') != -1)
              shape.push('고기');
            if ((quest.search('기타') != -1))
              shape.push('기타');
            receivedMessage_recommend(messagingEvent);
          } else if ((quest.search('먹을까') != -1) || (quest.search('말까') != -1)) {
            receivedMessage_select(messagingEvent);
          } else {
            receivedMessage(messagingEvent);
          }
        } else if (messagingEvent.postback) {
          receivedPostback(messagingEvent);
        } else {
          console.log("Webhook received unknown messagingEvent: ", messagingEvent);
        }
      });
    });
    res.sendStatus(200);
  }
});

// 메세지 받고 내보내기
function receivedMessage_recommend(event) {
  var senderId = event.sender.id;
  var content = event.message.text;
  var bot_message = content;
  fs.readFile('data/food.json', 'utf8', function(err, food_data) {
    if (err) {
      console.log((err));
      res.status(500).send('Internal Server Error');
    } else {
      var users = JSON.parse(food_data);
      var set1 = new Set();
      var set2 = new Set();
      var set3 = new Set();

      function add(users, price, shape, kinds, callback) {
        for (var foods in users) {
          if (shape.length != 0) {
            for (var i = 0; i < shape.length; i++) {
              if (users[foods]['shape'] == shape[i]) {
                set1.add(foods);
              }
            }
          } else {
            set1.add(foods);
          }
          if (kinds.length != 0) {
            for (var j = 0; j < kinds.length; j++) {
              if (users[foods]['kinds'] == kinds[j]) {
                set2.add(foods);
              }
            }
          } else {
            set2.add(foods);
          }
          if (!price || (price && users[foods]['price'] <= Number(price) + 3000 && users[foods]['price'] >= Number(price) - 3000)) {
            set3.add(foods);
          }
        }
        callback(set1, set2, set3);
      }

      add(users, price, shape, kinds, function(set1, set2, set3) {
        let difference1 = new Set([...set1].filter(i => set2.has(i)));
        let difference2 = new Set([...difference1].filter(i => set3.has(i)));
        var food = [...difference2];
        var length = food.length;
        console.log('food 목록: ' + food);
        console.log('food 갯수: ' + length);
        var rand = Math.floor(Math.random() * length);
        var food_value = food[rand];
        console.log('랜덤 food 번호: ' + rand);
        price = '';
        shape = [];
        kinds = [];
        var food_address = 'https://map.naver.com/v5/search/'+food_value+'?c=14145162.8039144,4473559.4748438,14,0,0,0,dh';
        sendTextMessage(senderId, '제가 추천해드리는 음식이에욤:>');
        sendTextMessage(senderId, food_value);
        sendTextMessage(senderId, food_address);
        // sendTextMessage(senderId, /data/images/food_value.png);
      }); //add closed
    }
  }); //readFile closed

}

function receivedMessage(event) {
  var senderId = event.sender.id;
  var content = event.message.text;
  var bot_message = content;
  var happpy = ['오늘은 무엇을 드실건가요?:)', '뿌에에ㅔ엥', '헣', '저한테 왜그러시는거죠?', '뭐지', '그러쿤요!', '훌쩍', '쒸익쒸익', '뭐하시는거죠?', '눈물', '세상에', '이게무슨일이람', 'ㅋㅋㅋㅋㅋㅋㅋㅋ', '무야', '아니이ㅣㅣ', '네에ㅔㅔ', '찡긋', '(당근 흔드는 중)', '도와주세요', '살려줘'];
  var rand = Math.floor(Math.random() * happpy.length);
  sendTextMessage(senderId, happpy[rand]);
}

function receivedMessage_select(event) {
  var senderId = event.sender.id;
  var content = event.message.text;
  var answer = ['먹어', '먹지마'];
  var rand = Math.floor(Math.random() * answer.length);
  sendTextMessage(senderId, answer[rand]);
}

function receivedMessage_price(event) {
  var senderId = event.sender.id;
  var content = event.message.text;
  var bot_message = content;
  var recom = ['제가 추천해드릴까욤??', '에휴 결정장애시구먼요. 제가 추천해드릴게요', '밥먹어요!! 추천해줄게요', '뭐드시고 싶어요?? 추천해줄게욤'];
  var rand = Math.floor(Math.random() * recom.length);
  sendTextMessage(senderId, recom[rand]);
  sendTextMessage(senderId, "가격대를 입력하시겠어요? :)");
}

function receivedMessage_map(event) {
  var senderId = event.sender.id;
  var content = event.message.text;
  var bot_message = content;
  var recom = ['제가 추천해드릴까욤??', '에휴 결정장애시구먼요. 제가 추천해드릴게요', '밥먹어요!! 추천해줄게요', '뭐드시고 싶어요?? 추천해줄게욤'];
  var rand = Math.floor(Math.random() * recom.length);
  sendTextMessage(senderId, recom[rand]);
  sendTextMessage(senderId, "가격대를 입력하시겠어요? :)");
}

function receivedPostback(event) {
  console.log("RECEIVED POSTBACK IT WORKS");
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfPostback = event.timestamp;

  var payload = event.postback.payload;

  console.log("Received postback for user %d and page %d with payload '%s' " +
    "at %d", senderID, recipientID, payload, timeOfPostback);

  sendTextMessage(senderID, "Postback called");
}

function sendTextMessage(recipientId, message) {
  request({
    url: 'https://graph.facebook.com/v2.6/me/messages',
    qs: {
      access_token: PAGE_ACCESS_TOKEN
    },
    method: 'POST',
    json: {
      recipient: {
        id: recipientId
      },
      message: {
        text: message
      }
    }
  }, (error, response, body) => {
    if (error) {
      console.log('Error sending message: ' + response.error);
    }
  });
}

app.listen(app.get('port'), () => {
  console.log('running on port', app.get('port'));
})