Created
July 29, 2016 13:18
-
-
Save ishanbakshi/c62f53a96c8c7390adfafdbf123c93ca to your computer and use it in GitHub Desktop.
A lambda function that acts like an fb messenger bot which pings back what you typed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
console.log('Loading function'); | |
var https = require('https'); | |
var PAGE_TOKEN = "EAASI6Z**********<fb tokenKey>"; | |
var VERIFY_TOKEN = "my_awesome_token"; | |
/** | |
* Provide an event that contains the following keys: | |
* | |
* - operation: one of the operations in the switch statement below | |
* - tableName: required for operations that interact with DynamoDB | |
* - payload: a parameter to pass to the operation being performed | |
*/ | |
exports.handler = (event, context, callback) => { | |
// process GET request | |
if(event.params && event.params.querystring){ | |
var queryParams = event.params.querystring; | |
var rVerifyToken = queryParams['hub.verify_token'] | |
if (rVerifyToken === VERIFY_TOKEN) { | |
var challenge = queryParams['hub.challenge'] | |
callback(null, parseInt(challenge)) | |
}else{ | |
callback(null, 'Error, wrong validation token'); | |
} | |
// process POST request | |
}else{ | |
var messagingEvents = event.entry[0].messaging; | |
for (var i = 0; i < messagingEvents.length; i++) { | |
var messagingEvent = messagingEvents[i]; | |
var sender = messagingEvent.sender.id; | |
if (messagingEvent.message && messagingEvent.message.text) { | |
var text = messagingEvent.message.text; | |
console.log("Receive a message: " + text); | |
//sendTextMessage(sender, "Text received, echo: "+ text.substring(0, 200)); | |
sendTextMessage(sender,"You just typed "+text.substring(0, 200)+" (echoed By the awesome parrot bot)") | |
callback(null, "Done") | |
} | |
} | |
callback(null, event); | |
} | |
}; | |
function sendTextMessage(senderFbId, text) { | |
var json = { | |
recipient: {id: senderFbId}, | |
message: {text: text}, | |
}; | |
var body = JSON.stringify(json); | |
var path = '/v2.6/me/messages?access_token=' + PAGE_TOKEN; | |
var options = { | |
host: "graph.facebook.com", | |
path: path, | |
method: 'POST', | |
headers: {'Content-Type': 'application/json'} | |
}; | |
var callback = function(response) { | |
var str = '' | |
response.on('data', function (chunk) { | |
str += chunk; | |
}); | |
response.on('end', function () { | |
}); | |
} | |
var req = https.request(options, callback); | |
req.on('error', function(e) { | |
console.log('problem with request: '+ e); | |
}); | |
req.write(body); | |
req.end(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment