router_message_sendPesan.js


const kei = require('../../lib/sendMessage');
const db = require('../../db/db');
const { Message, WAParser, WebhookServer } = require('wacloudapi');
const config = require('../../config.js');

const { KeiLog } = require('../../lib/Logger');
/**
 * Module for sending WhatsApp messages using the WhatsApp Cloud API.
 *@module sendWa
 * @param {object} app - The Express application object.
 * @param {object} io - The socket.io object for emitting webhooks.
 * @returns {Promise<void>} The result of the function.
 */

module.exports = async function (app,io) {
    app.get("/sendWa", async (req, res) => {
        // Parse the request body from the POST
        let body = req.query.message;
        let to = req.query.number;
        let phone_id = req.query.phone_id;
        if (!phone_id) {
            phone_id = config.phone_id;
        }

        try {
            const message = new Message(config.apiVersion, phone_id, config.token);
            const send = await message.sendTextMessage(to, body);
            io.emit('webhook', { message: {
                incomingMessage: send.messageId,
                recipientPhone : body,
                recipientName : to,
                typeOfMsg : send.whatsappId,
                message_id : send.whatsappId,
                data: send.whatsappId
            } });
            // console.log(send);
            // const insert = await db.insertChat(send.messageId, send.whatsappId, to , body);
            KeiLog("INFO", `Berhasil mengirim pesan ke ${to}  dengan pesan ${body} `);
            res.status(200).json({
                status: true,
                messages: send
            });
        } catch (error) {
            KeiLog("ERROR", `Gagal mengirim pesan ke ${to}  dengan pesan ${body} ${error}`);
            res.status(400).json({
                status: false,
                messages: error.message
            });
        }
    });


};