-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
71 lines (58 loc) · 2.1 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"use strict";
require('dotenv').config();
const express = require('express');
const app = express();
const request = require('superagent');
const bodyParser = require('body-parser');
const fbAccessToken = process.env.FB_ACCESS_TOKEN;
const engine = require('./src/engine/engine.js');
const fs = require('fs');
const handleMessageEvent = require('./messagingHandler.js');
const handlePostback = require('./postbackHandler.js');
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json());
app.get("/", (req, res) => {
res.send('howdie dreamin');
});
//verification
app.get("/webhook/", (req, res) => {
if (req.query["hub.mode"]==="subscribe" && req.query["hub.verify_token"]===process.env.VERIFY_TOKEN) {
res.send(req.query["hub.challenge"]);
}
});
app.post('/webhook', function (req, res) {
var data = req.body;
// Make sure this is a page subscription
if (data.object == 'page') {
// Iterate over each entry
// There may be multiple if batched
data.entry.forEach(function(pageEntry) {
var pageID = pageEntry.id;
var timeOfEvent = pageEntry.time;
// Iterate over each messaging event
pageEntry.messaging.forEach(function(messagingEvent) {
if (messagingEvent.optin) {
// receivedAuthentication(messagingEvent);
} else if (messagingEvent.message) {
handleMessageEvent(messagingEvent)
// receivedMessage(messagingEvent);
} else if (messagingEvent.delivery) {
// receivedDeliveryConfirmation(messagingEvent);
} else if (messagingEvent.postback) {
handlePostback(messagingEvent);
} else {
console.log("Webhook received unknown messagingEvent: ", messagingEvent);
}
});
});
// Assume all went well.
//
// You must send back a 200, within 20 seconds, to let us know you've
// successfully received the callback. Otherwise, the request will time out.
res.sendStatus(200);
}
});
// listen for requests :)
var listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});