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

// Views - handle Message, handle Postback

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

  if(received_message.text){

    // Create the payload for a basic text message
    response = template.askTemplate()
  }

  // Sends the reponse message
  callSendAPI(sender_psid, response);
}


// Handle postback(=button) events
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 === 'CAT_PICS') {
    response = template.imageTemplate('cats', sender_psid);
    callSendAPI(sender_psid, response, function(){
      callSendAPI(sender_psid, template.askTemplate('Show me more'));
    });
  } else if (payload === 'DOG_PICS') {
    response = template.imageTemplate('dogs', sender_psid);
    callSendAPI(sender_psid, response, function(){
      callSendAPI(sender_psid, template.askTemplate('Show me more'));
    });
  } else if(payload === 'GET_STARTED'){
    response = template.greetingTemplate();
    callSendAPI(sender_psid, response);
  }
  // Send the message to acknowledge the postback
}

// Sends response messages via the Send API
const callSendAPI = (sender_psid, response, cb = null) => {
  // Construct the message body
  let request_body = {
    "recipient": {
      "id": sender_psid
    },
    "message": response
  };

  // Send the HTTP request to the Messenger Platform
  request({
    "uri": "https://graph.facebook.com/v2.6/me/messages",
    "qs": { "access_token": config.get('facebook.page.access_token') },
    "method": "POST",
    "json": request_body
  }, (err, res, body) => {
    if (!err) {
      if(cb){
        cb();
      }
    } else {
      console.error("Unable to send message:" + err);
    }
  });
}