controller.js 2.76 KB
let request = require('request'),
    template = require('./template');

// Handles message events
exports.handleMessage = (sender_psid, received_message) => {
  let response; 
  if(received_message.text === "처음으로"){
    response = template.goToGreetTemplate(received_message);
  }else{
    response = template.choiceLectProfTemplate(received_message);
  }
  callSendAPI(sender_psid, response);
}

exports.handlePostback = (sender_psid, received_postback) => {
  let response;

  // Get the payload for the postback
  let payload = received_postback.payload;

  // Set the response based on the postback payload
  if(payload === 'Greeting'){
	  response = template.greetingTemplate();
	  callSendAPI(sender_psid, response);
  }else if(payload.substr(0,14)=== 'CHOICE_BY_PROF'){
	  handlePostback_choiceByProf(sender_psid, received_postback);
  }else if(payload.substr(0,14)=== 'CHOICE_BY_LECT'){
	  handlePostback_choiceByLect(sender_psid, recieved_postback);
  }else if(payload.substr(0,14) ==='CHOICE_BY_HELP'){
	  handlePostback_help(sender_psid, recieved_postback);
  }else if(payload.substr(0,8) === 'MoreRate'){
    response = template.moreRateTemplate(received_postback);
    callSendAPI(sender_psid, response);
  }
}

const handlePostback_choiceByProf = (sender_psid, received) => {
  let response;

  let stat = received.payload.substr(14,6);

  if(stat === 'stat_0'){
	  response = template.getProfNameTemplate(received);
  }else if(stat === 'stat_2'){
    response = template.moreProfTemplate(received);
  }else if(stat === 'stat_3'){
    response = template.rateTemplate(received);
  }
  callSendAPI(sender_psid, response);
}

const handlePostback_choiceByLect = (sender_psid, recieved) => {
  let response;

  let stat = recieved.payload.substr(14,6);

  if(stat === 'stat_0'){
	  response = template.getLectNameTemplate(received);
  }else if(stat === 'stat_2'){
	  response = template.moreLectTemplate(received);
  }else if(stat === 'stat_3'){
	  response = template.rateTemplate(received);
  }
  callSendAPI(sender_psid, response);
}

const handlePostback_help = (sender_psid, received) => {
  let response;

  let stat = received.payload.substr(14);

  if(stat === 'stat_0'){
	  response = template.howToTemplate(received);
  }
  callSendAPI(sender_psid, response);
}

// Sends response messages via the Send API
const callSendAPI = (sender_psid, response, cb = null) => {
  console.log('response:'+response);
  // Send the HTTP request to the Messenger Platform
  request({
    "url": "https://graph.facebook.com/v2.6/me/messages",
    "qs": { "access_token": process.env.PAGE_ACCESS_TOKEN },
    "method": "POST",
    "json": {
	    recipient: {id: sender_psid},
	    message: response
    }
  }, (err, res, body) => {
    if (err) {
      console.error("Unable to send message:" + err);
    }
  });
}