-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
591 lines (485 loc) · 17.8 KB
/
Copy pathindex.js
File metadata and controls
591 lines (485 loc) · 17.8 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
import pkg from "discord.js-selfbot-v13";
const { Client } = pkg;
import chalk from "chalk";
import figlet from "figlet";
import gradient from "gradient-string";
import { readFileSync, writeFileSync, existsSync } from "fs";
import { resolve } from "path";
import readline from "readline";
import { loadEvents } from "./handlers/EventsHandler.js";
import { loadCommands } from "./handlers/CommandHandler.js";
import { setupAntiCrash } from "./handlers/anticrash.js";
import { setupRateLimit } from "./handlers/RateLimitHandler.js";
import { loadConfig, clearConsole, log, wait, style, loadJSONAsync, saveJSONAsync } from "./utils/functions.js";
import { getUserPrefix } from "./utils/userPrefixManager.js";
import TaskManager from "./utils/TaskManager.js";
import { initNitroSniper } from "./commands/general/nitrosniper.js";
let isShuttingDown = false;
let clients = [];
let isLoggedIn = false; // True if at least one client is connected
let logoutCooldownTimer = 0;
let logoutCooldownActive = false;
// ============================================
// STYLING & FORMATTING HELPERS
// ============================================
function displaySimpleMenu() {
console.log('\n' + style('Available Commands:', '0;36'));
console.log(style('login', '1;37') + ' | Start all bots');
console.log(style('logout', '1;37') + ' | Turn off all bots');
console.log(style('restart', '1;37') + ' | Restart all bots');
console.log(style('status', '1;37') + ' | Check the status of bots');
console.log(style('exit', '1;37') + ' | Exit the terminal\n');
}
// ============================================
// TRACKING HELPER FUNCTIONS
// ============================================
async function setupTracking(client) {
const PFP_PATH = resolve('./data/pfphistory.json');
const NAME_PATH = resolve('./data/namehistory.json');
const BANNER_PATH = resolve('./data/bannerhistory.json');
client.on('userUpdate', async (oldUser, newUser) => {
try {
let fullOldUser = oldUser;
let fullNewUser = newUser;
try {
fullNewUser = await client.users.fetch(newUser.id, { force: true });
} catch {
// Keep original
}
// ---- TRACK PFP CHANGE ----
if (oldUser.avatar !== newUser.avatar) {
const pfpData = await loadJSONAsync(PFP_PATH);
if (!pfpData[newUser.id]) pfpData[newUser.id] = [];
pfpData[newUser.id].push({
url: oldUser.displayAvatarURL({ dynamic: true, size: 1024 }),
changedAt: new Date().toISOString(),
});
if (pfpData[newUser.id].length > 20) {
pfpData[newUser.id] = pfpData[newUser.id].slice(-20);
}
await saveJSONAsync(PFP_PATH, pfpData);
log(`Tracked PFP change for ${newUser.username}`, 'debug', client.user?.username || 'Unknown');
}
// ---- TRACK USERNAME CHANGE ----
if (oldUser.username !== newUser.username) {
const nameData = await loadJSONAsync(NAME_PATH);
if (!nameData[newUser.id]) nameData[newUser.id] = [];
nameData[newUser.id].push({
name: oldUser.username,
changedAt: new Date().toISOString(),
});
if (nameData[newUser.id].length > 20) {
nameData[newUser.id] = nameData[newUser.id].slice(-20);
}
await saveJSONAsync(NAME_PATH, nameData);
log(`Tracked username change for ${newUser.username} (was ${oldUser.username})`, 'debug', client.user?.username || 'Unknown');
}
// ---- TRACK BANNER CHANGE ----
if (oldUser.banner !== newUser.banner) {
const bannerData = await loadJSONAsync(BANNER_PATH);
if (!bannerData[newUser.id]) bannerData[newUser.id] = [];
const oldBannerURL = oldUser.bannerURL?.({ dynamic: true, size: 1024 }) || null;
if (oldBannerURL) {
bannerData[newUser.id].push({
url: oldBannerURL,
changedAt: new Date().toISOString(),
});
if (bannerData[newUser.id].length > 20) {
bannerData[newUser.id] = bannerData[newUser.id].slice(-20);
}
await saveJSONAsync(BANNER_PATH, bannerData);
log(`Tracked banner change for ${newUser.username}`, 'debug', client.user?.username || 'Unknown');
}
}
} catch (err) {
log(`Error in tracking userUpdate: ${err.message}`, 'debug', client.user?.username || 'Unknown');
}
});
log('PFP, username and banner tracking initialized', 'debug');
}
// ============================================
// DISPLAY BANNER
// ============================================
function displayBanner() {
try {
const coolGradient = gradient(["#00FFFF", "#0099FF", "#0033FF", "#0000FF"]);
const asciiArt = figlet.textSync("Barro", {
font: "Standard",
horizontalLayout: "default",
verticalLayout: "default",
width: 80,
whitespaceBreak: true,
});
console.log(chalk.cyan("> ") + chalk.gray("Barro selfbot initialized"));
console.log(chalk.cyan("> ") + chalk.gray("Private build"));
console.log(chalk.cyan("> ") + chalk.gray("Use responsibly"));
console.log(chalk.cyan("> ") + chalk.gray("Developed by Barro"));
console.log("\n");
} catch (error) {
console.log("\n");
console.log(chalk.cyan("=".repeat(50)));
console.log(chalk.cyan(" Barro SELFBOT"));
console.log(chalk.cyan("=".repeat(50)));
console.log("\n");
}
}
// ============================================
// VALIDATE TOKEN
// ============================================
function validateToken(token) {
if (!token) {
return { isValid: false, error: "No token provided in config.yaml." };
}
if (typeof token !== "string") {
return { isValid: false, error: "Token must be a string." };
}
if (!token.trim()) {
return { isValid: false, error: "Token is empty." };
}
if (token.length < 50) {
return { isValid: false, error: "Token appears to be too short." };
}
const placeholders = [
"YOUR_TOKEN_HERE", "DISCORD_TOKEN", "TOKEN",
"your_token", "paste_token_here", "YOUR_DISCORD_TOKEN",
];
if (placeholders.some(p => token.toLowerCase().includes(p.toLowerCase()))) {
return { isValid: false, error: "Token appears to be a placeholder." };
}
if (!token.includes(".")) {
return { isValid: false, error: "Token format appears invalid." };
}
return { isValid: true, error: null };
}
// ============================================
// BOT CONTROL FUNCTIONS
// ============================================
function startLogoutCooldown() {
logoutCooldownActive = true;
logoutCooldownTimer = 60;
const countdownInterval = setInterval(() => {
logoutCooldownTimer--;
if (logoutCooldownTimer % 10 === 0 || logoutCooldownTimer <= 5) {
console.log(style(`Auto-login available in ${logoutCooldownTimer}s...`, '0;33'));
}
if (logoutCooldownTimer <= 0) {
clearInterval(countdownInterval);
logoutCooldownActive = false;
console.log(style('Ready to login again', '0;32'));
}
}, 1000);
}
function getLogoutStatus() {
if (!logoutCooldownActive) return null;
return logoutCooldownTimer;
}
async function loginBots(clients, config) {
if (isLoggedIn) {
console.log(style('At least one bot is already connected to Discord', '1;33'));
return;
}
if (logoutCooldownActive) {
console.log(style(`Login blocked for ${logoutCooldownTimer}s to avoid rate limiting...`, '1;33'));
console.log(style('Waiting before auto-login...', '0;36'));
while (logoutCooldownTimer > 0) {
await new Promise(r => setTimeout(r, 1000));
}
console.log(style('Cooldown expired, proceeding with login...', '0;32'));
}
try {
console.log(style('Connecting all accounts to Discord...', '0;36'));
for (let i = 0; i < clients.length; i++) {
const client = clients[i];
const account = config.selfbot.accounts ? config.selfbot.accounts[i] : null;
const token = account ? account.token : (config.selfbot.token);
const accLabel = `Acc ${i + 1}`;
try {
await client.login(token);
// Assign the correct prefix after login
const fallbackPrefix = account?.prefix || config.selfbot.prefix || ',';
client.prefix = getUserPrefix(client.user.id, fallbackPrefix, client.user.id);
log(`Connected successfully`, 'success', accLabel);
if (config.nitro_sniper?.enabled !== false) {
try {
initNitroSniper(client);
log("Nitro sniper initialized", "debug", accLabel);
} catch (err) {
log(`Warning: Failed to initialize Nitro sniper: ${err.message}`, "warn", accLabel);
}
}
} catch (err) {
log(`Connection failed: ${err.message}`, 'error', accLabel);
}
}
isLoggedIn = true;
} catch (err) {
isLoggedIn = false;
console.log(style(`Critical error during multi-login: ${err.message}`, '1;31'));
}
}
async function logoutBots(clients, config) {
if (!isLoggedIn && clients.length === 0) {
console.log(style('No bots connected to Discord', '1;33'));
return;
}
try {
console.log(style('Disconnecting all bots from Discord...', '0;36'));
for (let i = 0; i < clients.length; i++) {
const client = clients[i];
const accLabel = `Acc ${i + 1}`;
try {
await client.destroy();
log(`Disconnected successfully`, 'success', accLabel);
} catch (err) {
log(`Disconnect failed: ${err.message}`, 'error', accLabel);
}
}
isLoggedIn = false;
const shutdownTime = Math.random() * 10 + 5;
console.log(style(`Cleaning up (${Math.round(shutdownTime)}s)...`, '0;33'));
await new Promise(r => setTimeout(r, shutdownTime * 1000));
startLogoutCooldown();
// Re-initialize clients array
clients.length = 0;
const accounts = config.selfbot.accounts || (config.selfbot.token ? [{ token: config.selfbot.token }] : []);
for (const acc of accounts) {
const newClient = new Client({
checkUpdate: false,
autoRedeemNitro: true,
relationshipSweepInterval: 60,
restRequestTimeout: 60000,
partials: ['MESSAGE', 'CHANNEL', 'REACTION', 'USER', 'GUILD_MEMBER'],
ws: {
properties: {
$browser: config.client_properties?.browser || "Discord Client",
},
},
});
newClient.config = config;
newClient.noprefix = false;
newClient.commands = new Map();
newClient.cooldowns = new Map();
setupAntiCrash(newClient);
setupRateLimit(newClient);
clients.push(newClient);
}
} catch (err) {
console.log(style(`Critical logout error: ${err.message}`, '1;31'));
}
}
async function restartBots(clients, config) {
console.log(style('Restarting all bots...', '0;36'));
await logoutBots(clients, config);
while (logoutCooldownTimer > 0) {
await new Promise(r => setTimeout(r, 1000));
}
await loginBots(clients, config);
}
// ============================================
// TERMINAL INTERFACE SETUP
// ============================================
function setupTerminalInterface(clients, config) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
displaySimpleMenu();
const prompt = () => {
rl.question(style('> ', '0;36'), async (input) => {
const command = input.trim().toLowerCase();
switch (command) {
case 'login':
await loginBots(clients, config);
break;
case 'logout':
await logoutBots(clients, config);
break;
case 'restart':
await restartBots(clients, config);
break;
case 'status':
console.log('');
if (clients.length === 0) {
console.log(style('No bots configured', '1;31'));
} else {
clients.forEach((client, index) => {
const accLabel = `Acc ${index + 1}`;
const connected = client.user ? style('Connected', '0;32') : style('Disconnected', '1;31');
const prefix = client.prefix || 'None';
console.log(style(`${accLabel} Status: `, '0;36') + connected + style(` | Prefix: ${prefix}`, '0;37'));
if (client.user) {
console.log(style(`${accLabel} Account: `, '0;36') + client.user.username);
}
});
}
console.log('');
break;
case 'exit':
console.log(style('Exiting...', '0;33'));
await gracefulShutdown('USER_COMMAND', 0, rl);
return;
case 'help':
displaySimpleMenu();
prompt();
return;
case '':
prompt();
return;
default:
console.log(style('Unknown command. Type "help" for available commands.', '1;31'));
break;
}
prompt();
});
};
prompt();
}
async function gracefulShutdown(signal, exitCode = 0, rl = null) {
if (isShuttingDown) return;
isShuttingDown = true;
log(`\nReceived ${signal} signal, shutting down...`, "warn");
try {
if (rl) {
rl.close();
}
await TaskManager.cleanup();
for (const client of clients) {
if (client?.destroy) {
await client.destroy();
}
}
log("Shutdown completed", "success");
} catch (error) {
log(`Error during shutdown: ${error.message}`, "error");
exitCode = 1;
} finally {
setTimeout(() => process.exit(exitCode), 100);
}
}
// ============================================
// SIGNAL HANDLERS
// ============================================
function setupSignalHandlers() {
const handleSignal = async (signal, exitCode = 0) => {
await gracefulShutdown(signal, exitCode);
};
process.on("SIGINT", () => handleSignal("SIGINT", 0));
process.on("SIGTERM", () => handleSignal("SIGTERM", 0));
process.on("SIGQUIT", () => handleSignal("SIGQUIT", 0));
process.on("uncaughtException", (error) => {
log(`Uncaught Exception: ${error.message}`, "error");
handleSignal("UNCAUGHT_EXCEPTION", 1);
});
process.on("unhandledRejection", (reason) => {
log(`Unhandled Rejection: ${reason}`, "error");
handleSignal("UNHANDLED_REJECTION", 1);
});
}
// ============================================
// MAIN INIT
// ============================================
async function initializeSelfbot() {
try {
log("Loading configuration...", "info");
const config = loadConfig();
const accounts = config.selfbot.accounts || (config.selfbot.token ? [{ token: config.selfbot.token }] : []);
if (accounts.length === 0) {
console.error(chalk.red("\n[TOKEN ERROR] No accounts provided in config.yaml."));
process.exit(1);
}
log(`Validating accounts...`, "info");
const validAccounts = [];
for (let i = 0; i < accounts.length; i++) {
const acc = accounts[i];
const token = acc && typeof acc === 'object' ? acc.token : acc;
if (!token || (typeof token === 'string' && token.trim() === "")) {
log(`Skipping Account ${i + 1}: No token provided.`, 'debug');
continue;
}
const validation = validateToken(token);
if (!validation.isValid) {
log(`Skipping Account ${i + 1}: ${validation.error}`, 'warn');
continue;
}
validAccounts.push(accounts[i]);
}
if (validAccounts.length === 0) {
console.error(chalk.red("\n[TOKEN ERROR] No valid tokens found. Bot cannot start."));
process.exit(1);
}
log(`Initializing ${validAccounts.length} Discord clients...`, "info");
clients = validAccounts.map((acc, index) => {
const token = acc.token || acc;
const client = new Client({
checkUpdate: false,
autoRedeemNitro: true,
relationshipSweepInterval: 60,
restRequestTimeout: 60000,
partials: ['MESSAGE', 'CHANNEL', 'REACTION', 'USER', 'GUILD_MEMBER'],
ws: {
properties: {
$browser: config.client_properties?.browser || "Discord Client",
},
},
});
client.config = config;
client.prefix = acc.prefix || config.selfbot.prefix;
client.noprefix = false;
client.commands = new Map();
client.cooldowns = new Map();
setupAntiCrash(client);
setupRateLimit(client);
return client;
});
log("Commands", "info");
let totalCommands = 0;
for (const client of clients) {
const count = await loadCommands(client);
if (totalCommands === 0) totalCommands = count;
}
log(`Loaded ${totalCommands} unique commands for all ${clients.length} accounts`, "success");
log("Events", "info");
for (const client of clients) {
await loadEvents(client);
}
log(`Loaded events for all ${clients.length} accounts`, "success");
setupSignalHandlers();
await wait(1000);
try {
clearConsole();
} catch {
console.log("\n".repeat(10));
}
// displayBanner(); // Disabled to reduce terminal noise
console.log(style('\nBot initialized and ready', '0;36'));
isLoggedIn = false;
try {
if (config.nitro_sniper?.enabled !== false) {
log("Nitro sniper ready", "debug");
}
for (const client of clients) {
setupTracking(client);
}
} catch (featureError) {
log(`Warning: Failed to initialize some features: ${featureError.message}`, "warn");
}
log(`Multi-account initialization completed successfully! (${clients.length} accounts)`, "debug");
return config;
} catch (error) {
console.error(chalk.red("\n[INITIALIZATION ERROR] " + error.message));
if (error.stack) console.error(chalk.gray(error.stack));
if (clients.length > 0) {
try {
for (const c of clients) c.destroy();
} catch {}
}
process.exit(1);
}
}
log("Starting Barro Multi-Account Selfbot...", "info");
initializeSelfbot().then((config) => {
setupTerminalInterface(clients, config);
}).catch((error) => {
console.error(chalk.red("\n[FATAL ERROR] " + error.message));
process.exit(1);
});