feat: started multiple whatsapps support

This commit is contained in:
canove
2020-09-04 20:18:11 -03:00
parent f7fe3286b8
commit 8786c7ca5e
6 changed files with 72 additions and 36 deletions

View File

@@ -3,28 +3,24 @@ const { Client } = require("whatsapp-web.js");
const Whatsapp = require("../models/Whatsapp");
const { getIO } = require("../libs/socket");
let wbot;
let sessions = [];
module.exports = {
init: async () => {
init: async dbSession => {
const sessionName = dbSession.name;
let sessionCfg;
const [dbSession] = await Whatsapp.findOrCreate({
where: { id: 1 },
defaults: {
id: 1,
},
});
if (dbSession && dbSession.session) {
sessionCfg = JSON.parse(dbSession.session);
}
wbot = new Client({
const wbot = new Client({
session: sessionCfg,
restartOnAuthFail: true,
});
wbot.initialize();
wbot.on("qr", async qr => {
console.log("Session:", sessionName);
qrCode.generate(qr, { small: true });
await dbSession.update({ id: 1, qrcode: qr, status: "disconnected" });
getIO().emit("session", {
@@ -34,9 +30,8 @@ module.exports = {
});
});
wbot.on("authenticated", async session => {
console.log("AUTHENTICATED");
console.log("Session:", sessionName, "AUTHENTICATED");
await dbSession.update({
id: 1,
session: JSON.stringify(session),
status: "authenticated",
});
@@ -46,15 +41,16 @@ module.exports = {
});
});
wbot.on("auth_failure", async msg => {
console.error("AUTHENTICATION FAILURE", msg);
await Whatsapp.update({ session: "" }, { where: { id: 1 } });
console.error("Session:", sessionName, "AUTHENTICATION FAILURE", msg);
await dbSession.update({ session: "" });
});
wbot.on("ready", async () => {
console.log("READY");
await dbSession.update(
{ status: "CONNECTED", qrcode: "" },
{ where: { id: 1 } }
);
console.log("Session:", sessionName, "READY");
await dbSession.update({
status: "CONNECTED",
qrcode: "",
});
// const chats = await wbot.getChats(); // pega as mensagens nao lidas (recebidas quando o bot estava offline)
// let unreadMessages; // todo > salvar isso no DB pra mostrar no frontend
// for (let chat of chats) {
@@ -66,15 +62,20 @@ module.exports = {
// }
// console.log(unreadMessages);
wbot.sendPresenceAvailable();
// wbot.sendPresenceAvailable();
});
return { wbot, dbSession };
wbot.name = sessionName;
sessions.push(wbot);
return null;
},
getWbot: () => {
if (!wbot) {
throw new Error("Wbot not initialized");
getWbot: sessionName => {
const sessionIndex = sessions.findIndex(s => s.name === sessionName);
if (sessionIndex === -1) {
throw new Error("This Wbot session is not initialized");
}
return wbot;
return sessions[sessionIndex];
},
};