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

// Handles message events
exports.handleMessage = (sender_psid, received_message) => {
}

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);
  }
}

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

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

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

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

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

  if(stat === 'stat_0'){
	  response = template.getLectNameTemplate(received);
  }else if(stat === 'stat_1'){
	  response = template.choiceLectTemplate(received);
  }else if(stat === 'stat_2'){
	  response = template.choiceProfOfLectTemplate(received);
  }else if(stat === 'stat_3'){
	  response = template.rateTemplate(received);
  }else if(stat === 'stat_4'){
	  response = template.goToChoiceByProfTemplate(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);
  }else if(stat === 'stat_1'){
	  response = template.goToGreetTemplate(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);
    }
  });
}