Session ID Generator (Updated) - Quizontal
A Session ID Generator is an essential tool for running WhatsApp Multi-Device bots like Danuwa-MD without repeatedly scanning a QR code. Instead of logging in every time the bot restarts, the session ID securely stores your WhatsApp authentication data and allows the bot to reconnect automatically. This makes deployment on VPS, Railway, Replit, or other hosting platforms much easier and more stable. In this post, we’ll explain what the Danuwa-MD session ID generator is, why it’s important, and how you can use it safely to keep your WhatsApp bot online 24/7.
1. index.js
import express from "express";
import bodyParser from "body-parser";
import { fileURLToPath } from "url";
import path from "path";
import pairRouter from "./pair.js";
import qrRouter from "./qr.js";
const app = express();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const PORT = process.env.PORT || 8000;
import("events").then((events) => {
events.EventEmitter.defaultMaxListeners = 500;
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "pair.html"));
});
app.use("/pair", pairRouter);
app.use("/qr", qrRouter);
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
export default app;
2. mega.js
import * as mega from "megajs"; import fs from "fs"; // Mega authentication credentials const auth = { email: "", // your mega account login email password: "", // your mega account login password userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246", }; export const upload = (filePath, fileName) => { return new Promise((resolve, reject) => { try { const storage = new mega.Storage(auth, (err) => { if (err) { reject(err); return; } const readStream = fs.createReadStream(filePath); const uploadStream = storage.upload({ name: fileName, allowUploadBuffering: true, }); readStream.pipe(uploadStream); uploadStream.on("complete", (file) => { file.link((err, url) => { if (err) { reject(err); } else { storage.close(); resolve(url); } }); }); uploadStream.on("error", (error) => { reject(error); }); readStream.on("error", (error) => { reject(error); }); }); storage.on("error", (error) => { reject(error); }); } catch (err) { reject(err); } }); }; export const download = (url) => { return new Promise((resolve, reject) => { try { const file = mega.File.fromURL(url); file.loadAttributes((err) => { if (err) { reject(err); return; } file.downloadBuffer((err, buffer) => { if (err) { reject(err); } else { resolve(buffer); } }); }); } catch (err) { reject(err); } }); };
3. pair.js
import express from "express";
import fs from "fs";
import pino from "pino";
import {
makeWASocket,
useMultiFileAuthState,
delay,
makeCacheableSignalKeyStore,
Browsers,
jidNormalizedUser,
fetchLatestBaileysVersion,
} from "@whiskeysockets/baileys";
import pn from "awesome-phonenumber";
import { upload } from "./mega.js";
const router = express.Router();
function removeFile(FilePath) {
try {
if (!fs.existsSync(FilePath)) return false;
fs.rmSync(FilePath, { recursive: true, force: true });
} catch (e) {
console.error("Error removing file:", e);
}
}
function getMegaFileId(url) {
try {
// Extract everything after /file/ including the key
const match = url.match(/\/file\/([^#]+#[^\/]+)/);
return match ? match[1] : null;
} catch (error) {
return null;
}
}
router.get("/", async (req, res) => {
let num = req.query.number;
let dirs = "./" + (num || `session`);
await removeFile(dirs);
num = num.replace(/[^0-9]/g, "");
const phone = pn("+" + num);
if (!phone.isValid()) {
if (!res.headersSent) {
return res.status(400).send({
code: "Invalid phone number. Please enter your full international number (e.g., 15551234567 for US, 447911123456 for UK, 84987654321 for Vietnam, etc.) without + or spaces.",
});
}
return;
}
num = phone.getNumber("e164").replace("+", "");
async function initiateSession() {
const { state, saveCreds } = await useMultiFileAuthState(dirs);
try {
const { version, isLatest } = await fetchLatestBaileysVersion();
let KnightBot = makeWASocket({
version,
auth: {
creds: state.creds,
keys: makeCacheableSignalKeyStore(
state.keys,
pino({ level: "fatal" }).child({ level: "fatal" }),
),
},
printQRInTerminal: false,
logger: pino({ level: "fatal" }).child({ level: "fatal" }),
browser: Browsers.windows("Chrome"),
markOnlineOnConnect: false,
generateHighQualityLinkPreview: false,
defaultQueryTimeoutMs: 60000,
connectTimeoutMs: 60000,
keepAliveIntervalMs: 30000,
retryRequestDelayMs: 250,
maxRetries: 5,
});
KnightBot.ev.on("connection.update", async (update) => {
const { connection, lastDisconnect, isNewLogin, isOnline } =
update;
if (connection === "open") {
console.log("✅ Connected successfully!");
console.log("📱 Uploading session to MEGA...");
try {
const credsPath = dirs + "/creds.json";
const megaUrl = await upload(
credsPath,
`creds_${num}_${Date.now()}.json`,
);
const megaFileId = getMegaFileId(megaUrl);
if (megaFileId) {
console.log(
"✅ Session uploaded to MEGA. File ID:",
megaFileId,
);
const userJid = jidNormalizedUser(
num + "@s.whatsapp.net",
);
await KnightBot.sendMessage(userJid, {
text: `${megaFileId}`,
});
console.log("📄 MEGA file ID sent successfully");
} else {
console.log("❌ Failed to upload to MEGA");
}
console.log("🧹 Cleaning up session...");
await delay(1000);
removeFile(dirs);
console.log("✅ Session cleaned up successfully");
console.log("🎉 Process completed successfully!");
console.log("🛑 Shutting down application...");
await delay(2000);
process.exit(0);
} catch (error) {
console.error("❌ Error uploading to MEGA:", error);
removeFile(dirs);
await delay(2000);
process.exit(1);
}
}
if (isNewLogin) {
console.log("🔐 New login via pair code");
}
if (isOnline) {
console.log("📶 Client is online");
}
if (connection === "close") {
const statusCode =
lastDisconnect?.error?.output?.statusCode;
if (statusCode === 401) {
console.log(
"❌ Logged out from WhatsApp. Need to generate new pair code.",
);
} else {
console.log("🔁 Connection closed — restarting...");
initiateSession();
}
}
});
if (!KnightBot.authState.creds.registered) {
await delay(3000); // Wait 3 seconds before requesting pairing code
num = num.replace(/[^\d+]/g, "");
if (num.startsWith("+")) num = num.substring(1);
try {
let code = await KnightBot.requestPairingCode(num);
code = code?.match(/.{1,4}/g)?.join("-") || code;
if (!res.headersSent) {
console.log({ num, code });
await res.send({ code });
}
} catch (error) {
console.error("Error requesting pairing code:", error);
if (!res.headersSent) {
res.status(503).send({
code: "Failed to get pairing code. Please check your phone number and try again.",
});
}
setTimeout(() => process.exit(1), 2000);
}
}
KnightBot.ev.on("creds.update", saveCreds);
} catch (err) {
console.error("Error initializing session:", err);
if (!res.headersSent) {
res.status(503).send({ code: "Service Unavailable" });
}
setTimeout(() => process.exit(1), 2000);
}
}
await initiateSession();
});
process.on("uncaughtException", (err) => {
let e = String(err);
if (e.includes("conflict")) return;
if (e.includes("not-authorized")) return;
if (e.includes("Socket connection timeout")) return;
if (e.includes("rate-overlimit")) return;
if (e.includes("Connection Closed")) return;
if (e.includes("Timed Out")) return;
if (e.includes("Value not found")) return;
if (
e.includes("Stream Errored") ||
e.includes("Stream Errored (restart required)")
)
return;
if (e.includes("statusCode: 515") || e.includes("statusCode: 503")) return;
console.log("Caught exception: ", err);
process.exit(1);
});
export default router;
4. qr.js
import express from "express";
import fs from "fs";
import pino from "pino";
import {
makeWASocket,
useMultiFileAuthState,
delay,
makeCacheableSignalKeyStore,
Browsers,
jidNormalizedUser,
fetchLatestBaileysVersion,
} from "@whiskeysockets/baileys";
import QRCode from "qrcode";
import { upload } from "./mega.js";
const router = express.Router();
function removeFile(FilePath) {
try {
if (!fs.existsSync(FilePath)) return false;
fs.rmSync(FilePath, { recursive: true, force: true });
} catch (e) {
console.error("Error removing file:", e);
}
}
function getMegaFileId(url) {
try {
const match = url.match(/\/file\/([^#]+#[^\/]+)/);
return match ? match[1] : null;
} catch (error) {
return null;
}
}
router.get("/", async (req, res) => {
const sessionId =
Date.now().toString() + Math.random().toString(36).substr(2, 9);
const dirs = `./qr_sessions/session_${sessionId}`;
if (!fs.existsSync("./qr_sessions")) {
fs.mkdirSync("./qr_sessions", { recursive: true });
}
await removeFile(dirs);
async function initiateSession() {
const { state, saveCreds } = await useMultiFileAuthState(dirs);
try {
const { version, isLatest } = await fetchLatestBaileysVersion();
let responseSent = false;
const KnightBot = makeWASocket({
version,
auth: {
creds: state.creds,
keys: makeCacheableSignalKeyStore(
state.keys,
pino({ level: "fatal" }).child({ level: "fatal" }),
),
},
printQRInTerminal: false,
logger: pino({ level: "fatal" }).child({ level: "fatal" }),
browser: Browsers.windows("Chrome"),
markOnlineOnConnect: false,
generateHighQualityLinkPreview: false,
defaultQueryTimeoutMs: 60000,
connectTimeoutMs: 60000,
keepAliveIntervalMs: 30000,
retryRequestDelayMs: 250,
maxRetries: 5,
});
KnightBot.ev.on("connection.update", async (update) => {
const { connection, lastDisconnect, isNewLogin, isOnline, qr } =
update;
if (qr && !responseSent) {
console.log(
"🟢 QR Code Generated! Scan it with your WhatsApp app.",
);
try {
const qrDataURL = await QRCode.toDataURL(qr, {
errorCorrectionLevel: "M",
type: "image/png",
quality: 0.92,
margin: 1,
color: {
dark: "#000000",
light: "#FFFFFF",
},
});
if (!responseSent) {
responseSent = true;
console.log("QR Code sent to client");
res.send({
qr: qrDataURL,
message:
"QR Code Generated! Scan it with your WhatsApp app.",
instructions: [
"1. Open WhatsApp on your phone",
"2. Go to Settings > Linked Devices",
'3. Tap "Link a Device"',
"4. Scan the QR code above",
],
});
}
} catch (qrError) {
console.error("Error generating QR code:", qrError);
if (!responseSent) {
responseSent = true;
res.status(500).send({
code: "Failed to generate QR code",
});
}
}
}
if (connection === "open") {
console.log("✅ Connected successfully!");
console.log("📱 Uploading session to MEGA...");
try {
const credsPath = dirs + "/creds.json";
const megaUrl = await upload(
credsPath,
`creds_qr_${sessionId}.json`,
);
const megaFileId = getMegaFileId(megaUrl);
if (megaFileId) {
console.log(
"✅ Session uploaded to MEGA. File ID:",
megaFileId,
);
const userJid = jidNormalizedUser(
KnightBot.authState.creds.me?.id || "",
);
if (userJid) {
await KnightBot.sendMessage(userJid, {
text: `${megaFileId}`,
});
console.log(
"📄 MEGA file ID sent successfully",
);
} else {
console.log("❌ Could not determine user JID");
}
} else {
console.log("❌ Failed to upload to MEGA");
}
console.log("🧹 Cleaning up session...");
await delay(1000);
removeFile(dirs);
console.log("✅ Session cleaned up successfully");
console.log("🎉 Process completed successfully!");
console.log("🛑 Shutting down application...");
await delay(2000);
process.exit(0);
} catch (error) {
console.error("❌ Error uploading to MEGA:", error);
removeFile(dirs);
await delay(2000);
process.exit(1);
}
}
if (isNewLogin) {
console.log("🔐 New login via QR code");
}
if (isOnline) {
console.log("📶 Client is online");
}
if (connection === "close") {
const statusCode =
lastDisconnect?.error?.output?.statusCode;
if (statusCode === 401) {
console.log(
"❌ Logged out from WhatsApp. Need to generate new QR code.",
);
} else {
console.log("🔁 Connection closed — restarting...");
initiateSession();
}
}
});
KnightBot.ev.on("creds.update", saveCreds);
setTimeout(() => {
if (!responseSent) {
responseSent = true;
res.status(408).send({ code: "QR generation timeout" });
removeFile(dirs);
setTimeout(() => process.exit(1), 2000);
}
}, 30000);
} catch (err) {
console.error("Error initializing session:", err);
if (!res.headersSent) {
res.status(503).send({ code: "Service Unavailable" });
}
removeFile(dirs);
setTimeout(() => process.exit(1), 2000);
}
}
await initiateSession();
});
process.on("uncaughtException", (err) => {
let e = String(err);
if (e.includes("conflict")) return;
if (e.includes("not-authorized")) return;
if (e.includes("Socket connection timeout")) return;
if (e.includes("rate-overlimit")) return;
if (e.includes("Connection Closed")) return;
if (e.includes("Timed Out")) return;
if (e.includes("Value not found")) return;
if (
e.includes("Stream Errored") ||
e.includes("Stream Errored (restart required)")
)
return;
if (e.includes("statusCode: 515") || e.includes("statusCode: 503")) return;
console.log("Caught exception: ", err);
process.exit(1);
});
export default router;
5. package.json
{
"name": "DANUWA-MD",
"version": "1.0.0",
"description": "DANUWA-MD - WhatsApp Pair Code Generator",
"main": "index.js",
"type": "module",
"engines": {
"node": ">=20.0.0"
},
"scripts": {
"start": "node index.js",
"build": "echo 'No build step required'"
},
"author": "MMT",
"license": "ISC",
"dependencies": {
"@whiskeysockets/baileys": "latest",
"awesome-phonenumber": "7.2.0",
"body-parser": "^1.20.3",
"express": "^4.21.2",
"megajs": "^1.3.9",
"path": "^0.12.7",
"phone": "3.1.55",
"pino": "9.5.0",
"qrcode": "^1.5.4",
"qrcode-terminal": "^0.12.0"
}
}
6. pair.html

0 Comments