Added state monitor to wwebjs

This commit is contained in:
Cassio Santos
2020-06-16 15:09:18 -03:00
parent eaea17fb66
commit 794a217a4e
15 changed files with 198 additions and 79 deletions

View File

@@ -1 +0,0 @@
{"WABrowserId":"\"E9dnt9Mm/JiFDCMJQHkXBw==\"","WASecretBundle":"{\"key\":\"fHTKtoDcxidboASIs5WV5JKyRrF+SfMktqHXmq/KBJU=\",\"encKey\":\"FrM3OnnEbuEr1JrtKypw5CPSc6rSD5bjbOGstv8ijk4=\",\"macKey\":\"fHTKtoDcxidboASIs5WV5JKyRrF+SfMktqHXmq/KBJU=\"}","WAToken1":"\"tjwS2T/ux5P+nyxYcBEj+gRIUS/XqREEEPqap787yzg=\"","WAToken2":"\"1@781NE8OipW/PigfWCI6tiz8fEpUOVVhyNEePCZMuEyC7aXG0cy1I75liSVz8z6DxVjXiw4iGI7c4Hg==\""}

View File

@@ -1,39 +1,42 @@
const path = require("path");
const qrCode = require("qrcode-terminal");
const fs = require("fs");
const { Client } = require("whatsapp-web.js");
const Whatsapp = require("../models/Whatsapp");
let wbot;
module.exports = {
init: () => {
const SESSION_FILE_PATH = path.join(__dirname, "/session.json");
init: async () => {
let sessionCfg;
if (fs.existsSync(SESSION_FILE_PATH)) {
sessionCfg = require(SESSION_FILE_PATH);
const dbSession = await Whatsapp.findOne({ where: { id: 1 } });
if (dbSession && dbSession.session) {
sessionCfg = JSON.parse(dbSession.session);
}
wbot = new Client({
session: sessionCfg,
restartOnAuthFail: true,
});
wbot.initialize();
wbot.on("qr", qr => {
wbot.on("qr", async qr => {
qrCode.generate(qr, { small: true });
await Whatsapp.upsert({ id: 1, qrcode: qr, status: "pending" });
});
wbot.on("authenticated", session => {
wbot.on("authenticated", async session => {
console.log("AUTHENTICATED");
sessionCfg = session;
fs.writeFile(SESSION_FILE_PATH, JSON.stringify(sessionCfg), function (
err
) {
if (err) {
console.error(err);
}
await Whatsapp.upsert({
id: 1,
session: JSON.stringify(session),
status: "authenticated",
});
});
wbot.on("auth_failure", msg => {
wbot.on("auth_failure", async msg => {
console.error("AUTHENTICATION FAILURE", msg);
await Whatsapp.destroy({ where: { id: 1 } });
});
wbot.on("ready", async () => {
console.log("READY");
await Whatsapp.update({ status: "online" }, { where: { id: 1 } });
// 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) {
@@ -45,6 +48,7 @@ module.exports = {
// }
// console.log(unreadMessages);
wbot.sendPresenceAvailable();
});
return wbot;

View File

@@ -5,7 +5,7 @@ const path = require("path");
const fs = require("fs");
const { getIO } = require("../socket");
const { getWbot } = require("./wbot");
const { getWbot, init } = require("./wbot");
const wbotMessageListener = () => {
const io = getIO();
@@ -14,6 +14,9 @@ const wbotMessageListener = () => {
wbot.on("message", async msg => {
let newMessage;
console.log(msg);
if (msg.from === "status@broadcast") {
return;
}
const msgContact = await msg.getContact();
const imageUrl = await msgContact.getProfilePicUrl();
try {
@@ -21,6 +24,10 @@ const wbotMessageListener = () => {
where: { number: msgContact.number },
});
if (contact) {
await contact.update({ imageURL: imageUrl });
}
if (!contact) {
try {
contact = await Contact.create({
@@ -28,13 +35,6 @@ const wbotMessageListener = () => {
number: msgContact.number,
imageURL: imageUrl,
});
// contact.dataValues.unreadMessages = 1;
io.to("notification").emit("contact", {
action: "create",
contact: contact,
});
} catch (err) {
console.log(err);
}
@@ -45,8 +45,7 @@ const wbotMessageListener = () => {
if (media) {
if (!media.filename) {
let ext = media.mimetype.split("/")[1].split(";")[0];
let aux = Math.random(5).toString();
media.filename = aux.split(".")[1] + "." + ext;
media.filename = `${new Date().getTime()}.${ext}`;
}
fs.writeFile(
@@ -72,10 +71,19 @@ const wbotMessageListener = () => {
});
}
io.to(contact.id).to("notification").emit("appMessage", {
action: "create",
message: newMessage,
});
io.to(contact.id)
.to("notification")
.emit("appMessage", {
action: "create",
message: {
...newMessage.dataValues,
mediaUrl: `${
newMessage.mediaUrl
? `http://localhost:8080/public/${newMessage.mediaUrl}`
: ""
}`,
},
});
let chat = await msg.getChat();
chat.sendSeen();
@@ -90,6 +98,7 @@ const wbotMessageListener = () => {
where: { id: msg.id.id },
});
if (!messageToUpdate) {
// will throw an error is msg wasn't sent from app
const error = new Error(
"Erro ao alterar o ack da mensagem no banco de dados"
);

View File

@@ -0,0 +1,40 @@
const Contact = require("../models/Contact");
const Message = require("../models/Message");
const wbotMessageListener = require("./wbotMessageListener");
const path = require("path");
const fs = require("fs");
const { getIO } = require("../socket");
const { getWbot, init } = require("./wbot");
const wbotMonitor = () => {
const io = getIO();
const wbot = getWbot();
wbot.on("change_state", newState => {
console.log(newState);
});
wbot.on("change_battery", batteryInfo => {
// Battery percentage for attached device has changed
const { battery, plugged } = batteryInfo;
console.log(`Battery: ${battery}% - Charging? ${plugged}`);
});
wbot.on("disconnected", reason => {
console.log("disconnected", reason);
wbot.destroy();
setTimeout(() =>
init()
.then(res => wbotMessageListener(), 2000)
.catch(err => console.log(err))
);
});
// setInterval(() => {
// wbot.resetState();
// }, 20000);
};
module.exports = wbotMonitor;