-
Notifications
You must be signed in to change notification settings - Fork 1
/
facebook.js
132 lines (103 loc) · 2.92 KB
/
facebook.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
131
132
'use strict';
// See the Send API reference
// https://developers.facebook.com/docs/messenger-platform/send-api-reference
const request = require('request');
const Config = require('./const.js');
const fbMessage = (id, data) => {
var body = JSON.stringify({
recipient: { id },
message: data,
});
if (data.attachment) {
var body = JSON.stringify({
recipient: { id },
message: data.attachment,
});
}
const qs = 'access_token=' + encodeURIComponent(Config.FB_PAGE_TOKEN);
return fetch('https://graph.facebook.com/me/messages?' + qs, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
})
.then(rsp => rsp.json())
.then(json => {
if (json.error && json.error.message) {
throw new Error(json.error.message);
}
return json;
});
};
const fbReq = request.defaults({
uri: 'https://graph.facebook.com/me/messages',
method: 'POST',
json: true,
qs: {
access_token: Config.FB_PAGE_TOKEN
},
headers: {
'Content-Type': 'application/json'
},
});
// const fbMessage = (recipientId, msg, cb) => {
// console.log("=========================>", msg)
// if (IsJsonString(msg)) {
// const opts = {
// form: {
// recipient: {
// id: recipientId,
// },
// message: msg,
// },
// };
// fbReq(opts, (err, resp, data) => {
// if (cb) {
// cb(err || data.error && data.error.message, data);
// }
// });
// } else {
// const opts = {
// form: {
// recipient: {
// id: recipientId,
// },
// message: {
// text: msg,
// },
// },
// };
// fbReq(opts, (err, resp, data) => {
// if (cb) {
// cb(err || data.error && data.error.message, data);
// }
// });
// }
// };
// See the Webhook reference
// https://developers.facebook.com/docs/messenger-platform/webhook-reference
const getFirstMessagingEntry = (body) => {
const val = body.object === 'page' &&
body.entry &&
Array.isArray(body.entry) &&
body.entry.length > 0 &&
body.entry[0] &&
body.entry[0].messaging &&
Array.isArray(body.entry[0].messaging) &&
body.entry[0].messaging.length > 0 &&
body.entry[0].messaging[0];
return val || null;
};
/* To check String is IsJsonString*/
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
module.exports = {
getFirstMessagingEntry: getFirstMessagingEntry,
fbMessage: fbMessage,
fbReq: fbReq
};