-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkaleyra.js
99 lines (84 loc) · 2.75 KB
/
kaleyra.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
const fetch = require("node-fetch");
require('url-search-params-polyfill');
const config = require('../env-variables');
var geturl = require("url");
const fs = require('fs');
const FormData = require('form-data');
const path = require("path");
class KaleyraWhatsAppProvider {
constructor() {
this.url = config.kaleyra.sendMessageUrl;
this.url = this.url.replace('{{sid}}', config.kaleyra.sid);
}
processMessageFromUser(req) {
try {
let requestBody = geturl.parse(req.url, true).query;
let reformattedMessage = {};
reformattedMessage.user = {
mobileNumber: requestBody.from.slice(2)
}
reformattedMessage.extraInfo = {
whatsAppBusinessNumber: requestBody.wanumber
}
let type = requestBody.type;
if(type == 'text') {
reformattedMessage.message = {
type: type,
input: requestBody.body
};
} else {
reformattedMessage.message = {
type: 'unknown',
input: ''
}
}
return reformattedMessage;
} catch(err) {
console.error('Error while processing message from user: ' + err);
return undefined;
}
}
async sendMessageToUser(user, outputMessages, extraInfo) {
for(let message of outputMessages) {
let phone = user.mobileNumber;
let headers = {
'api-key': config.kaleyra.apikey
}
let form = new FormData();
form.append("channel", "whatsapp");
form.append("from", extraInfo.whatsAppBusinessNumber);
form.append("to", '91' + phone);
if(typeof(message) == 'string') {
form.append("type", 'text');
form.append("body", message);
} else if (message.type == 'media') {
let buffer;
buffer = fs.readFileSync(path.resolve(__dirname, `../../${message.output}`));
form.append("caption", message.caption || '');
form.append("type", 'media');
form.append("media", buffer, {
contentType: 'text/plain',
name: 'file',
filename: message.output,
});
} else if(message.type == 'template') {
//TODO: Handle media template
form.append("type", message.type);
form.append("body", message.output);
} else {
form.append("type", message.type);
form.append("body", message.output);
}
var request = {
method: "POST",
headers: headers,
body: form
}
const response = await fetch(this.url, request).then(res => res.json());
if (response && message.type === 'media' && message.output.includes('dynamic-media')) {
fs.unlinkSync(path.resolve(__dirname, `../../${message.output}`));
}
}
}
}
module.exports = new KaleyraWhatsAppProvider();