diff --git a/lib/Facebook.js b/lib/Facebook.js index 78cf8f208..9a4591abe 100644 --- a/lib/Facebook.js +++ b/lib/Facebook.js @@ -3,6 +3,7 @@ var request = require('request'); var express = require('express'); var bodyParser = require('body-parser'); var crypto = require('crypto'); +var fs = require('fs'); function Facebookbot(configuration) { @@ -77,6 +78,10 @@ function Facebookbot(configuration) { if (message.attachment) { facebook_message.message.attachment = message.attachment; + + if (message.filedata) { + facebook_message.filedata = message.filedata; + } } if (message.sticker_id) { @@ -129,31 +134,51 @@ function Facebookbot(configuration) { //Add Access Token to outgoing request facebook_message.access_token = configuration.access_token; - request({ - method: 'POST', - json: true, - headers: { - 'content-type': 'application/json', - }, - body: facebook_message, - uri: 'https://' + api_host + '/v2.6/me/messages' - }, - function(err, res, body) { + var requestObj = {}; + if ('filedata' in facebook_message) { + var prepareFormdata = {}; + for (key in facebook_message) { + if (key !== 'filedata' && typeof facebook_message[key] === 'object') { + prepareFormdata[key] = JSON.stringify(facebook_message[key]); + } else if (key === 'filedata') { + if (!fs.existsSync(facebook_message[key])) return cb(new Error('filedata not exist')); + prepareFormdata[key] = fs.createReadStream(facebook_message[key]); + } else { + prepareFormdata[key] = facebook_message[key]; + } + } + requestObj = { + method: 'POST', + formData: prepareFormdata, + uri: 'https://' + api_host + '/v2.6/me/messages' + }; + } else { + requestObj = { + method: 'POST', + json: true, + headers: { + 'content-type': 'application/json', + }, + body: facebook_message, + uri: 'https://' + api_host + '/v2.6/me/messages' + }; + } - if (err) { - botkit.debug('WEBHOOK ERROR', err); - return cb && cb(err); - } + request(requestObj, function(err, res, body) { + if (err) { + botkit.debug('WEBHOOK ERROR', err); + return cb && cb(err); + } - if (body.error) { - botkit.debug('API ERROR', body.error); - return cb && cb(body.error.message); - } + if (body.error) { + botkit.debug('API ERROR', body.error); + return cb && cb(body.error.message); + } - botkit.debug('WEBHOOK SUCCESS', body); - cb && cb(null, body); - }); + botkit.debug('WEBHOOK SUCCESS', body); + cb && cb(null, body); + }); }; bot.startTyping = function(src, cb) {