Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
var express = require('express'); //express handles routes
var http = require('http'); //need http module to create a server
var app = express(); //starting express
var url = "MY_KEY" //replace with your page token
var request = require('request');
app.set('port', process.env.PORT || 3000); //set port to cloud9 specific port or 3000
app.use(express.bodyParser()); //body parser used to parse request data
app.use(app.router);
app.get('/', verificationHandler);
var dictionary = {
oi: 'oi, tudo bem?',
tudobem: 'Tudo sim, e com você?'
};
var formatUserText = function(text) {
return text.replace(/(\?|!| |,)/g, '');
};
function sendHelp(id, message) {
var options = {
uri: url,
method: 'POST',
json: {
"recipient": {
"id": id
},
"message": {
"text": message
}
}
}
request(options, function(error, response, body) {
if (error) {
console.log(error.message);
}
});
};
function verificationHandler(req, res) {
console.log(req);
if (req.query['hub.verify_token'] === 'verifycode') {
res.send(req.query['hub.challenge']);
}
res.send('Error, wrong validation token!');
}
function handleMessage(req, res) {
messaging_events = req.body.entry[0].messaging;
for (i = 0; i < messaging_events.length; i++) {
event = req.body.entry[0].messaging[i];
sender = event.sender.id;
if (event.message && event.message.text) {
text = event.message.text;
console.log('Event sender id' + sender + ' Message: ' + text);
sendHelp(sender, dictionary[formatUserText(text)]);
}
}
res.end('received!');
}
app.post('/', handleMessage);
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.