router_message_sendTemplateMedia.js
const axios = require("axios");
const konfig = require("../../config.js");
const { KeiLog } = require('../../lib/Logger');
module.exports = async function (app) {
/**
* Sets up an Express route for sending template media messages via WhatsApp.
*
* This function adds a GET route to the provided Express application. When this route is accessed,
* it constructs a WhatsApp message template with optional parameters and sends it using the WhatsApp
* Business API. The message may include media (like an image) and additional text parameters.
* The response of the API call is then returned to the client.
*
*@module sendtemplateMedia
* @param {Object} app - The Express application instance.
*/
app.get("/sendtemplateMedia", async (req, res) => {
let msg = req.query.parameter;
let template = req.query.template;
let nmbr = req.query.number;
let media = req.query.attachment;
let components = [{
"type": "header",
"parameters": [{
"type": "image",
"image": { "link": media }
}]
}];
// If 'msg' query parameter is not empty, add its value to the 'header' components
if (msg) {
const parameters = msg.split(',');
components.push({
"type": "body",
"parameters": parameters.map(parameter => ({ "type": "text", "text": parameter }))
});
}
const message = {
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": nmbr,
"type": "template",
"template": {
"name": template,
"language": { "code": "en_US" },
"components": components
}
};
const config = {
method: 'post',
maxBodyLength: Infinity,
url: `https://graph.facebook.com/v14.0/${konfig.phone_id}/messages`,
headers: {
'Content-Type': 'application/json',
'Authorization': "Bearer " + konfig.token
},
data: message
};
try {
const response = await axios(config);
res.status(200).json({
status : true,
messages :response.data.messages[0].id
});
} catch (error) {
//console.log(error);
res.send({
status : false,
messages : error.response.data.error.message ?? error.message
});
}
});
};