-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathpair.js
More file actions
183 lines (158 loc) · 7.58 KB
/
pair.js
File metadata and controls
183 lines (158 loc) · 7.58 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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';
const router = express.Router();
// Ensure the session directory exists
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);
}
}
router.get('/', async (req, res) => {
let num = req.query.number;
let dirs = './' + (num || `session`);
// Remove existing session if present
await removeFile(dirs);
// Clean the phone number - remove any non-digit characters
num = num.replace(/[^0-9]/g, '');
// Validate the phone number using awesome-phonenumber
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;
}
// Use the international number format (E.164, without '+')
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("📱 Sending session file to user...");
try {
const sessionKnight = fs.readFileSync(dirs + '/creds.json');
// Send session file to user
const userJid = jidNormalizedUser(num + '@s.whatsapp.net');
await KnightBot.sendMessage(userJid, {
document: sessionKnight,
mimetype: 'application/json',
fileName: 'creds.json'
});
console.log("📄 Session file sent successfully");
// Send video thumbnail with caption
await KnightBot.sendMessage(userJid, {
image: { url: 'https://img.youtube.com/vi/-oz_u1iMgf8/maxresdefault.jpg' },
caption: `🎬 *KnightBot MD V2.0 Full Setup Guide!*\n\n🚀 Bug Fixes + New Commands + Fast AI Chat\n📺 Watch Now: https://youtu.be/NjOipI2AoMk`
});
console.log("🎬 Video guide sent successfully");
// Send warning message
await KnightBot.sendMessage(userJid, {
text: `⚠️Do not share this file with anybody⚠️\n
┌┤✑ Thanks for using Knight Bot
│└────────────┈ ⳹
│©2025 Mr Unique Hacker
└─────────────────┈ ⳹\n\n`
});
console.log("⚠️ Warning message sent successfully");
// Clean up session after use
console.log("🧹 Cleaning up session...");
await delay(1000);
removeFile(dirs);
console.log("✅ Session cleaned up successfully");
console.log("🎉 Process completed successfully!");
// Do not exit the process, just finish gracefully
} catch (error) {
console.error("❌ Error sending messages:", error);
// Still clean up session even if sending fails
removeFile(dirs);
// Do not exit the process, just finish gracefully
}
}
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.' });
}
}
}
KnightBot.ev.on('creds.update', saveCreds);
} catch (err) {
console.error('Error initializing session:', err);
if (!res.headersSent) {
res.status(503).send({ code: 'Service Unavailable' });
}
}
}
await initiateSession();
});
// Global uncaught exception handler
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")) return;
if (e.includes("Stream Errored (restart required)")) return;
if (e.includes("statusCode: 515")) return;
if (e.includes("statusCode: 503")) return;
console.log('Caught exception: ', err);
});
export default router;