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

// Views - handle Message, handle Postback

// Handles message events
exports.handleMessage = (sender_psid, received_message) => {
  let response;

  if(received_message.text){
    response = template.messageTemplate();
  }

  // Sends the reponse 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 === 'CHOICE_BY_PROF'){
	  response = template.choicebyprofTemplate();
	  callSendAPI(sender_psid, response);
  }else if(payload === 'CHOICE_BY_LECT'){
	  response = template.choicebylectTemplate();
	  callSendAPI(sender_psid, response);
  }else if(payload === 'HELP'){
	  response = template.help();
	  callSendAPI(sender_psid, response);
  }else if(payload.match('rate')){
	  response = template.rate(payload);
	  callSendAPI(sender_psid, response);
  }
}


// Sends response messages via the Send API
const callSendAPI = (sender_psid, response, cb = null) => {

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