-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathserver.js
56 lines (49 loc) · 1.92 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"use strict";
var express = require('express'),
bodyParser = require('body-parser'),
processor = require('./modules/processor'),
handlers = require('./modules/handlers'),
postbacks = require('./modules/postbacks'),
FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN,
app = express();
app.set('port', process.env.PORT || 5000);
app.use(bodyParser.json());
app.get('/webhook', (req, res) => {
if (req.query['hub.verify_token'] === FB_VERIFY_TOKEN) {
res.send(req.query['hub.challenge']);
} else {
res.send('Error, wrong validation token');
}
});
app.post('/webhook', (req, res) => {
let events = req.body.entry[0].messaging;
for (let i = 0; i < events.length; i++) {
let event = events[i];
let sender = event.sender.id;
if (process.env.MAINTENANCE_MODE && ((event.message && event.message.text) || event.postback)) {
sendMessage({text: `Sorry I'm taking a break right now.`}, sender);
} else if (event.message && event.message.text) {
let result = processor.match(event.message.text);
if (result) {
let handler = handlers[result.handler];
if (handler && typeof handler === "function") {
handler(sender, result.match);
} else {
console.log("Handler " + result.handlerName + " is not defined");
}
}
} else if (event.postback) {
let payload = event.postback.payload.split(",");
let postback = postbacks[payload[0]];
if (postback && typeof postback === "function") {
postback(sender, payload);
} else {
console.log("Postback " + postback + " is not defined");
}
}
}
res.sendStatus(200);
});
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});