-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.js
56 lines (52 loc) · 1.85 KB
/
handler.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';
const nodeFetch = require('node-fetch');
/**
* Function to verify facebook webhook
*/
module.exports.fbVerify = (event, context, callback) => {
if (event.query['hub.mode'] === 'subscribe' &&
event.query['hub.verify_token'] === 'sometoken') {
console.log("Validating webhook");
return callback(null, parseInt(event.query['hub.challenge']));
} else {
console.error("Failed validation. Make sure the validation tokens match.");
return callback('Invalid token');
}
};
/**
* Function to reply to other messages
*/
module.exports.fbMessages = (event, context, callback) => {
event.body.entry.map((entry) => {
entry.messaging.map((messagingItem) => {
if (messagingItem.message && messagingItem.message.text) {
const url = `https://graph.facebook.com/v2.6/me/messages?access_token=<your access token here>`;
const responsePayload = {
recipient: {
id: messagingItem.sender.id
},
message: {
text: messagingItem.message.text
}
};
nodeFetch(
url,
{
method: 'POST',
body: JSON.stringify(responsePayload),
headers: {'Content-Type': 'application/json'}
}
)
.then(res => res.json())
.then(json => {
console.log("Json result ", json);
callback(null, json)
})
.catch(error => {
console.error("Call failed ", error);
callback(null, error)
});
}
});
});
};