-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
130 lines (114 loc) · 3.71 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// init project
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();
// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));
app.use(bodyParser.json());
app.get('/', function(req, res) {
res.status(200).send('Ready');
});
// Webhook validation - just send back a validation token
app.get('/webhook', function(req, res) {
if (req.query['hub.mode'] === 'subscribe' &&
req.query['hub.verify_token'] === process.env.VALIDATION_TOKEN) {
console.log("Validating webhook");
res.status(200).send(req.query['hub.challenge']);
} else {
console.error("Failed validation. Make sure the validation tokens match.");
res.sendStatus(403);
}
});
// Webhook itself, will receive calls from messenger platform
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.message) {
receivedMessage(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);
}
});
// Implement the call to send a message to the user
function sendTextMessage(recipientId, messageText) {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText
}
};
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: process.env.PAGE_ACCESS_TOKEN },
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
console.log("Successfully sent generic message with id %s to recipient %s",
messageId, recipientId);
} else {
console.error("Unable to send message.");
console.error(response);
console.error(error);
}
});
}
// What to do when you receive a message from the user
function receivedMessage(event) {
var senderID = event.sender.id;
var messageText = event.message.text;
console.log(messageText);
var sessionId = (new Date()).toISOString();
witProcessMessage(sessionId, messageText, function (body) {
console.log(typeof(body));
if ((body.confidence > 0.3)
&& (body.entities.location !== undefined)
&& (body.entities.location.length > 0 )) {
sendTextMessage(senderID, 'Detected this location in the message: ' + body.entities.location[0].value)
} else {
sendTextMessage(senderID, messageText);
}
});
}
function witProcessMessage(sessionId, message, callback) {
var qs = 'session_id=' + encodeURIComponent(sessionId);
if (message) {
qs += '&q=' + encodeURIComponent(message);
}
request({
headers: {
'Authorization': 'Bearer ' + process.env.WIT_ACCESS_TOKEN,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
url: 'https://api.wit.ai/converse?' + qs,
method: 'POST',
json: {}
}, function(error, response, body) {
console.log("WIT RESPONSE: ", body);
callback(body);
});
}
// listen for requests :)
var listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});