-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfbme.js
110 lines (100 loc) · 3.36 KB
/
fbme.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
const
log = require('loglevel').getLogger('fbme'),
crypto = require('crypto'),
request = require('request'),
HttpStatus = require('http-status-codes'),
utils = require('./utils'),
format = utils.format;
const
GRAPH_API_URL = 'https://graph.facebook.com/v2.6/me/messages';
class FbMe {
constructor(config) {
this.config = config;
this.appSecretPoof = crypto.createHmac('sha256', config.appSecret).update(config.accessToken).digest('hex');
}
attachment(senderPsid, buffer, contentType, filename) {
let assetType = contentType.split('/')[0];
let httpOptions = {
uri: GRAPH_API_URL,
qs: {
access_token: this.config.accessToken
},
method: 'POST'
};
var postRequest = request(httpOptions, (err, res, body) => {
if (err || res.statusCode != HttpStatus.OK) {
log.error('Unable to send message: %s', JSON.stringify(err));
log.error('Failed request: %s', JSON.stringify(httpOptions));
} else if (body) {
let attachment = JSON.parse(body);
log.trace('Sent attachment with id: %s', attachment.attachment_id);
}
});
var form = postRequest.form();
form.append('appsecret_proof', this.appSecretPoof);
form.append('recipient', format("{ \"id\": \"%s\"}", senderPsid));
form.append('message', format("{ \"attachment\": { \"type\": \"%s\", \"payload\": { \"is_reusable\": true}}}", assetType));
form.append('filedata', buffer, {
filename: filename,
contentType: contentType
});
}
genericTemplate(senderPsid, elements) {
let message = {
attachment: {
type: 'template',
payload: {
image_aspect_ratio: 'square',
template_type: 'generic',
elements: elements
}
}
};
this.callSendAPI(senderPsid, message);
}
textMessage(senderPsid, text) {
this.callSendAPI(senderPsid, {
text: text
});
}
typingOn(senderPsid) {
this.callSenderActionAPI(senderPsid, 'typing_on');
}
callSendAPI(senderPsid, message) {
let requestBody = {
appsecret_proof: this.appSecretPoof,
recipient: {
id: senderPsid
},
message: message
};
this.sendRequest(requestBody)
}
callSenderActionAPI(senderPsid, senderAction) {
let requestBody = {
appsecret_proof: this.appSecretPoof,
recipient: {
id: senderPsid
},
sender_action: senderAction
};
this.sendRequest(requestBody)
}
sendRequest(requestBody) {
let httpOptions = {
uri: GRAPH_API_URL,
qs: {
access_token: this.config.accessToken
},
method: 'POST',
json: requestBody
};
request(httpOptions, (err, res, body) => {
if (err || res.statusCode != HttpStatus.OK) {
log.error('Unable to send message: %s', JSON.stringify(err || res));
log.error('Failed request: %s', JSON.stringify(httpOptions));
}
});
}
}
module.exports = FbMe;