All files / WbotServices wbotMonitor.ts

0% Statements 0/87
0% Branches 0/1
0% Functions 0/1
0% Lines 0/87

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88                                                                                                                                                                               
import * as Sentry from "@sentry/node";

import wbotMessageListener from "./wbotMessageListener";

import { getIO } from "../../libs/socket";
import { getWbot, initWbot } from "../../libs/wbot";
import Whatsapp from "../../models/Whatsapp";

const wbotMonitor = (whatsapp: Whatsapp): void => {
  const io = getIO();
  const sessionName = whatsapp.name;
  const wbot = getWbot(whatsapp.id);

  try {
    wbot.on("change_state", async newState => {
      console.log("Monitor session:", sessionName, newState);
      try {
        await whatsapp.update({ status: newState });
      } catch (err) {
        Sentry.captureException(err);
        console.log(err);
      }

      io.emit("whatsappSession", {
        action: "update",
        session: whatsapp
      });
    });

    wbot.on("change_battery", async batteryInfo => {
      const { battery, plugged } = batteryInfo;
      console.log(
        `Battery session: ${sessionName} ${battery}% - Charging? ${plugged}`
      );

      try {
        await whatsapp.update({ battery, plugged });
      } catch (err) {
        Sentry.captureException(err);
        console.log(err);
      }

      io.emit("whatsappSession", {
        action: "update",
        session: whatsapp
      });
    });

    wbot.on("disconnected", async reason => {
      console.log("Disconnected session:", sessionName, reason);
      try {
        await whatsapp.update({ status: "disconnected" });
      } catch (err) {
        Sentry.captureException(err);
        console.log(err);
      }

      io.emit("whatsappSession", {
        action: "update",
        session: whatsapp
      });

      setTimeout(
        () =>
          initWbot(whatsapp)
            .then(() => {
              wbotMessageListener(whatsapp);
              wbotMonitor(whatsapp);
            })
            .catch(err => {
              Sentry.captureException(err);
              console.log(err);
            }),
        2000
      );
    });

    // setInterval(() => {
    // 	wbot.resetState();
    // }, 20000);
  } catch (err) {
    Sentry.captureException(err);
    console.log(err);
  }
};

export default wbotMonitor;