Created
November 1, 2016 23:29
-
-
Save augustovictor/02d2d6b02828fe9d4cadb98181240533 to your computer and use it in GitHub Desktop.
This file contains 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
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