From 27e7cb1121b7952d8736891f151457e5867dba25 Mon Sep 17 00:00:00 2001 From: canove Date: Fri, 21 Aug 2020 06:02:29 -0300 Subject: [PATCH] feat: starting handling messages sent from phone --- backend/src/services/wbotMessageListener.js | 30 +++++++++++++++------ 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/backend/src/services/wbotMessageListener.js b/backend/src/services/wbotMessageListener.js index ce6ff26..9c3dbb3 100644 --- a/backend/src/services/wbotMessageListener.js +++ b/backend/src/services/wbotMessageListener.js @@ -9,7 +9,7 @@ const Ticket = require("../models/Ticket"); const Message = require("../models/Message"); const { getIO } = require("../libs/socket"); -const { getWbot, init } = require("../libs/wbot"); +const { getWbot } = require("../libs/wbot"); const verifyContact = async (msgContact, profilePicUrl) => { let contact = await Contact.findOne({ @@ -136,8 +136,8 @@ const wbotMessageListener = () => { const wbot = getWbot(); const io = getIO(); - wbot.on("message", async msg => { - // console.log(msg); + wbot.on("message_create", async msg => { + console.log(msg); if ( msg.from === "status@broadcast" || msg.type === "location" || @@ -147,7 +147,22 @@ const wbotMessageListener = () => { } try { - const msgContact = await msg.getContact(); + let msgContact; + + if (msg.fromMe) { + const alreadyExists = await Message.findOne({ + where: { id: msg.id.id }, + }); + // return if message was already created by messagesController + if (alreadyExists) { + return; + } + + msgContact = await wbot.getContactById(msg.to); + } else { + msgContact = await msg.getContact(); + } + const profilePicUrl = await msgContact.getProfilePicUrl(); const contact = await verifyContact(msgContact, profilePicUrl); const ticket = await verifyTicket(contact); @@ -164,12 +179,11 @@ const wbotMessageListener = () => { const messageToUpdate = await Message.findOne({ where: { id: msg.id.id }, }); + if (!messageToUpdate) { - // will throw an error if msg was sent from cellphone - const error = new Error("No message with this ID found in database"); - error.statusCode = 404; - throw error; + return; } + await messageToUpdate.update({ ack: ack }); io.to(messageToUpdate.ticketId).emit("appMessage", {