-
Notifications
You must be signed in to change notification settings - Fork 10
/
graphAPI.js
89 lines (78 loc) · 1.82 KB
/
graphAPI.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
'use strict';
const request = require('request-promise');
const config = require('./config')
const FB_PAGE_TOKEN = config.fbPageToken;
const Q = require('q');
const _ = require('lodash');
class GraphAPI {
constructor() {
this.api = request.defaults({
uri: 'https://graph.facebook.com/v2.6/me/messages',
method: 'POST',
json: true,
qs: { access_token: FB_PAGE_TOKEN },
headers: {'Content-Type': 'application/json'},
});
}
sendTemplateMessage(recipientId, data) {
const opts = {
form: {
recipient: {
id: recipientId,
},
message: data,
}
};
return this.api(opts);
}
sendPlainMessage(recipientId, msg) {
return this.sendTemplateMessage(recipientId, {text: msg});
}
sendBulkMessages(recipientId, messages) {
return messages.reduce((p, message) => {
return p.then(() => {
return this.sendTypingOn(recipientId)
.then(() => {
const delay = message.text && message.text.length * 20;
return Q.delay(delay || 500)
})
.then(() => {
if (_.isString(message)) {
return this.sendPlainMessage(recipientId, message);
} else {
return this.sendTemplateMessage(recipientId, message);
}
});
});
}, Q());
}
sendTypingOn(recipientId) {
return this._sendTyping(recipientId, 'typing_on');
}
sendTypingOff(recipientId) {
return this._sendTyping(recipientId, 'typing_off');
}
_sendTyping(recipientId, action) {
const opts = {
form: {
recipient: {
id: recipientId,
},
sender_action: action
}
};
return this.api(opts);
}
getUserProfile(recipientId) {
return request({
method:'GET',
url: 'https://graph.facebook.com/v2.6/' + recipientId,
json: true,
qs: {
fields: 'first_name,last_name,locale,timezone,gender',
access_token: FB_PAGE_TOKEN
}
})
}
}
module.exports = new GraphAPI();