WhiskeySockets / Baileys

Lightweight full-featured typescript/javascript WhatsApp Web API
https://baileys.whiskeysockets.io/
MIT License
4.07k stars 1.38k forks source link

[BUG] getaddrinfo EAI_AGAIN web.whatsapp.com #1115

Closed Kepron closed 3 weeks ago

Kepron commented 3 weeks ago

Describe the bug When I start the nodejs server with yarn start, I get this error directly.

To Reproduce Steps to reproduce the behavior:

  1. Just start the nodejs server with yarn start

Environment (please complete the following information):

Additional context Here is my error message:

using WA v2.3000.1017531287, isLatest: false
connection update {
  connection: 'connecting',
  receivedPendingNotifications: false,
  qr: undefined
}
connection update {
  connection: 'close',
  lastDisconnect: {
    error: Error: WebSocket Error (getaddrinfo EAI_AGAIN web.whatsapp.com)
        at WebSocketClient.<anonymous> (/var/www/agencive-wp/node_modules/@whiskeysockets/baileys/lib/Socket/socket.js:612:17)
        at WebSocketClient.emit (node:events:515:28)
        at WebSocket.<anonymous> (/var/www/agencive-wp/node_modules/@whiskeysockets/baileys/lib/Socket/Client/websocket.js:46:100)
        at WebSocket.emit (node:events:515:28)
        at emitErrorAndClose (/var/www/agencive-wp/node_modules/ws/lib/websocket.js:1033:13)
        at ClientRequest.<anonymous> (/var/www/agencive-wp/node_modules/ws/lib/websocket.js:880:5)
        at ClientRequest.emit (node:events:515:28)
        at TLSSocket.socketErrorListener (node:_http_client:495:9)
        at TLSSocket.emit (node:events:515:28)
        at emitErrorNT (node:internal/streams/destroy:151:8) {
      data: [Error],
      isBoom: true,
      isServer: false,
      output: [Object]
    },
    date: 2024-11-01T14:10:57.160Z
  }
}

Here is my code:

import {
  makeWASocket,
  DisconnectReason,
  fetchLatestBaileysVersion,
  makeCacheableSignalKeyStore,
  makeInMemoryStore,
  useMultiFileAuthState,
} from "@whiskeysockets/baileys";
import pino from "pino";
import NodeCache from "node-cache";
import { createInterface } from "readline";
import bodyParser from "body-parser";
import cors from "cors";
import http from "http";
import express from "express";
import "dotenv/config";
import { jwtVerify } from "jose";

const app = express();
const usePairingCode = false;
const useMobile = false;
const useStore = false;
const msgRetryCounterCache = new NodeCache();
const MAIN_LOGGER = pino({
  timestamp: () => `,"time":"${new Date().toJSON()}"`,
});
const logger = MAIN_LOGGER.child({});
logger.level = "trace";

const store = useStore ? makeInMemoryStore({ logger }) : undefined;
store?.readFromFile("./baileys_store_multi.json");

setInterval(() => {
  store?.writeToFile("./baileys_store_multi.json");
}, 10000 * 6);

const rl = createInterface({
  input: process.stdin,
  output: process.stdout,
});

const question = (text) => new Promise((resolve) => rl.question(text, resolve));

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const server = http.createServer(app);
const port = 3002;

app.get("/", (req, res) => {
  res.send("server working");
});

let sock;

const startSock = async () => {
  let { state, saveCreds } = await useMultiFileAuthState("baileys_auth_info");
  let { version, isLatest } = await fetchLatestBaileysVersion();

  console.log(`using WA v${version.join(".")}, isLatest: ${isLatest}`);

  sock = makeWASocket({
    version,
    printQRInTerminal: !usePairingCode,
    auth: {
      creds: state.creds,
      keys: makeCacheableSignalKeyStore(
        state.keys,
        pino().child({ level: "fatal", stream: "store" })
      ),
    },
    mobile: useMobile,
    logger: pino({ level: "fatal" }),
    browser: ["Chrome (Linux)", "", ""],
    msgRetryCounterCache,
    connectTimeoutMs: 60000,
    defaultQueryTimeoutMs: undefined,
    generateHighQualityLinkPreview: true,
    syncFullHistory: false,
    markOnlineOnConnect: true,
  });
  store?.bind(sock.ev);

  sock.ev.on("creds.update", saveCreds);

  if (usePairingCode && !sock.authState.creds.registered) {
    if (useMobile) {
      throw new Error("Cannot use pairing code with mobile api");
    }

    const phoneNumber = await question(
      "Please enter your mobile phone number:\n"
    );
    const code = await sock.requestPairingCode(phoneNumber);
    console.log(`Pairing code: ${code}`);
  }
  sock.ev.process(async (events) => {
    if (events["connection.update"]) {
      const update = events["connection.update"];
      const { connection, lastDisconnect } = update;
      if (connection === "close") {
        if (
          lastDisconnect?.error?.output?.statusCode !==
          DisconnectReason.loggedOut
        ) {
          startSock();
        } else {
          console.log("Connection closed. You are logged out.");
        }
      }
      console.log("connection update", update);
    }

    if (events["creds.update"]) {
      await saveCreds();
    }
  });
  return sock;
};

app.use(async (req, res, next) => {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith("Bearer ")) {
    return res.status(401).json({
      message: "Unauthorized: Missing or invalid authorization header.",
    });
  }
  try {
    const token = authHeader.split(" ")[1];
    const secret = new TextEncoder().encode(process.env.JWT_SECRET);
    await jwtVerify(token, secret);
    next();
  } catch (error) {
    console.log(error);
    return res.status(401).json({ message: "Unauthorized: Invalid token." });
  }
});

app.post("/send-message", async (req, res) => {
  const tempMessage = req.body.message;
  const msgTo = req.body.to;
  console.log(req.body);
  try {
    await sock.sendMessage(msgTo, { text: tempMessage });
    res.status(200).json({
      status: "success",
      response: "ok",
    });
  } catch (error) {
    console.log(error);
    res.status(500).json({
      status: false,
      response: error,
    });
  }
});

app.get("/get-jid", async (req, res) => {
  const invCode = req.query.code;
  const response = await sock.groupGetInviteInfo(invCode);
  res.status(200).json(response);
});

startSock();
server.listen(port, () => {
  console.log("Server Run Port : " + port);
});
Kepron commented 3 weeks ago

Oh my bad. It was a DNS issue. I contacted my hosting provider and fixed the issue.