@onboardmobility/whatsapp
Version:
Utility class to connect to WhatsApp APIs
89 lines (74 loc) • 2.46 kB
JavaScript
;
const request = require('request-promise');
/**
* Envs vars
*/
const { WA_BASE_URL, WA_TOKEN, } = process.env;
async function processIncomingMessages(data) {
if (data.event === 'message:in:new') {
const body = data.data.body;
const author = data.data.from;
const fromMe = data.data.fromNumber === data.data.toNumber;
const senderName = data.data.chat.name;
const type = data.data.type;
const attachments = [];
if (data.data.media) {
attachments.push({
contentUrl: WA_BASE_URL + data.data.media.links['download'].replace('/v1', '') + `?token=${WA_TOKEN}`,
name: `${data.data.media.message}.${data.data.media.extension}`,
contentType: data.data.media.mime
});
}
return { body, author, fromMe, senderName, type, result: true, attachments };
}
return { result: false };
}
async function sendMessage({ caption, text, url, to }) {
if (to && to.includes('@c.us')) {
const body = {
phone: to,
message: text,
};
return request.post({
url: `${WA_BASE_URL}/messages`,
headers: {
'Content-Type': 'application/json',
'token': WA_TOKEN,
},
body: JSON.stringify(body),
});
}
}
async function sendFile({ to, url }) {
if (to && to.includes('@c.us')) {
const body = {
phone: to,
url: url,
};
try {
const file = JSON.parse(await request.post({
url: `${WA_BASE_URL}/files`,
headers: {
'Content-Type': 'application/json',
'token': WA_TOKEN,
},
body: JSON.stringify(body),
}));
const newbody = {
phone: to,
media: { file: file[0].id, format: file[0].format, message: file[0].filename }
};
return await request.post({
url: `${WA_BASE_URL}/messages`,
headers: {
'Content-Type': 'application/json',
'token': WA_TOKEN,
},
body: JSON.stringify(newbody),
});
} catch (e) {
// Do nothing
}
}
}
module.exports = { processIncomingMessages, sendMessage, sendFile };