-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
1370 lines (1144 loc) · 42.9 KB
/
index.js
File metadata and controls
1370 lines (1144 loc) · 42.9 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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require('v8').setFlagsFromString('--max-old-space-size=7168');
process.on("uncaughtException", (err) => console.error("Erreur non geree:", err));
process.on("unhandledRejection", (reason) => console.error("Rejection:", reason));
const Discord = require("discord.js");
const fs = require('fs').promises;
const path = require('path');
const { Client, Collection } = require('safeness-sb-new');
const mysql = require('mysql2');
const { WebhookClient, REST, Routes, InteractionType, SlashCommandBuilder } = require('discord.js');
const yaml = require('js-yaml');
const { performance } = require('perf_hooks');
const sqlDb = require('./sqlDb');
const { setDbConfig } = require('./config/dbConfig');
const multistatus = require('./commands/Rpc/multistatus');
const afkCommand = require('./commands/Afk/afk.js');
const bl = require('./commands/Mod/bl.js');
const messageCmd = require('./commands/Utility2/message');
const rainbowModule = require('./commands/Tools2/rainbowrole');
require('events').EventEmitter.defaultMaxListeners = 100;
process.setMaxListeners(100);
const clients = [];
let config = { user: {}, discord: {} };
let users = {};
let globalDb = {};
let managerBot = null;
const RECONNECT_INTERVAL = 6 * 60 * 60 * 1000;
const SAVE_DEBOUNCE_DELAY = 30000;
const BATCH_DELAY = 100;
const ROTATION_DELAY = 5000;
let globalCommandsMap = null;
let dbConfig = {};
const connectionState = new Map();
class ExponentialBackoff {
constructor(maxRetries = 5, baseDelay = 1000, maxDelay = 60000) {
this.maxRetries = maxRetries;
this.baseDelay = baseDelay;
this.maxDelay = maxDelay;
}
async executeWithRetry(operation, context = '') {
let lastError;
for (let attempt = 0; attempt < this.maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
lastError = error;
if (error.message === 'TOKEN_INVALID' || error.noRetry) {
console.log(`🚫 ${context}: Token invalide, pas de nouvelle tentative`);
throw error;
}
if (attempt === this.maxRetries - 1) break;
const delay = Math.min(
this.baseDelay * Math.pow(2, attempt),
this.maxDelay
);
console.log(`↻ ${context}: Tentative ${attempt + 1}/${this.maxRetries}, nouvelle tentative dans ${delay}ms`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
throw lastError;
}
}
class AdvancedMonitor {
constructor() {
this.metrics = {
cpu: { values: [], threshold: 70, consecutive: 5 },
memory: { values: [], threshold: 85, consecutive: 3 }
};
this.lastCpuUsage = process.cpuUsage();
this.lastMeasureTime = performance.now();
this.alertCooldown = new Map();
this.measurementCount = 0;
}
collectMetrics() {
const now = performance.now();
const cpuUsage = process.cpuUsage(this.lastCpuUsage);
const timeDiff = (now - this.lastMeasureTime) / 1000;
if (timeDiff < 0.001 || timeDiff > 10) {
this.lastMeasureTime = now;
this.lastCpuUsage = process.cpuUsage();
return;
}
const totalCpuTime = cpuUsage.user + cpuUsage.system;
let cpuPercent = (totalCpuTime / 1000000 / timeDiff) * 100;
cpuPercent = Math.min(Math.max(cpuPercent, 0), 1000);
this.metrics.cpu.values.push(cpuPercent);
if (this.metrics.cpu.values.length > 10) {
this.metrics.cpu.values.shift();
}
const memUsage = process.memoryUsage();
const memoryPercent = (memUsage.heapUsed / memUsage.heapTotal) * 100;
this.metrics.memory.values.push(memoryPercent);
if (this.metrics.memory.values.length > 10) {
this.metrics.memory.values.shift();
}
this.lastCpuUsage = process.cpuUsage();
this.lastMeasureTime = now;
this.measurementCount++;
if (this.measurementCount % 10 === 0) {
this.checkThresholds();
}
}
checkThresholds() {
for (const [metric, data] of Object.entries(this.metrics)) {
if (data.values.length >= data.consecutive) {
const recentValues = data.values.slice(-data.consecutive);
const average = recentValues.reduce((a, b) => a + b, 0) / recentValues.length;
if (average > data.threshold && !this.isOnCooldown(metric)) {
this.triggerAlert(metric, average);
this.setCooldown(metric, 300000);
}
}
}
}
triggerAlert(metric, value) {
const stack = new Error().stack;
if (metric === 'memory') {
const mem = process.memoryUsage();
}
this.takeCorrectiveAction(metric);
}
takeCorrectiveAction(metric) {
switch(metric) {
case 'memory':
if (global.gc) {
global.gc();
}
break;
case 'cpu':
break;
}
}
isOnCooldown(metric) {
return this.alertCooldown.has(metric) &&
Date.now() < this.alertCooldown.get(metric);
}
setCooldown(metric, duration) {
this.alertCooldown.set(metric, Date.now() + duration);
}
startMonitoring(interval = 5000) {
setInterval(() => this.collectMetrics(), interval);
}
}
class DatabaseManager {
constructor() {
this.saveTimeouts = new Map();
this.isSaving = new Map();
this.pendingWrites = new Map();
this.initialized = false;
this.connection = null;
this.batchQueue = new Map();
this.batchTimeouts = new Map();
}
async initialize() {
if (this.initialized) return;
try {
await this.loadConfigFromYaml();
await this.connectToDatabase();
await this.createTables();
await this.loadManualConfig();
await sqlDb.connect();
this.initialized = true;
} catch (error) {
console.error('Initialisation echouee:', error);
config = { user: {} };
globalDb = {};
this.initialized = true;
}
}
async loadManualConfig() {
config = { ...config, user: {} };
users = {};
globalDb = {};
const USER_ID = ''; // Ton user id
const USER_TOKEN = ''; // ton token lié a ton user id
users[USER_ID] = { token: USER_TOKEN };
config.user[USER_ID] = { token: USER_TOKEN };
globalDb[USER_ID] = {};
connectionState.set(USER_ID, 'pending');
}
async removeInvalidUser(userId) {
try {
await this.query('DELETE FROM user_data WHERE user_id = ?', [userId]);
console.log(`✅ Utilisateur ${userId} supprimé de la base de données (token invalide)`);
return true;
} catch (error) {
console.error(`❌ Erreur suppression utilisateur ${userId}:`, error);
return false;
}
}
async loadConfigFromYaml() {
try {
const configPath = path.join(__dirname, 'config', 'config.yml');
const configFile = await fs.readFile(configPath, 'utf8');
const yamlConfig = yaml.load(configFile);
dbConfig = {
host: yamlConfig.db.host,
port: yamlConfig.db.port,
user: yamlConfig.db.user,
password: yamlConfig.db.password,
database: yamlConfig.db.database,
charset: yamlConfig.db.charset,
connectTimeout: yamlConfig.db.connectTimeout
};
setDbConfig(dbConfig);
config = { ...config, ...yamlConfig };
return yamlConfig;
} catch (error) {
console.error('Erreur chargement config.yml:', error);
throw error;
}
}
async connectToDatabase() {
const backoff = new ExponentialBackoff(3, 500, 5000);
return backoff.executeWithRetry(async () => {
return new Promise((resolve, reject) => {
this.connection = mysql.createConnection(dbConfig);
this.connection.connect((err) => {
if (err) {
console.error('Erreur connexion MySQL:', err);
reject(err);
} else {
this.connection.on('error', (err) => {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Connexion MySQL perdue');
this.connection = null;
}
});
resolve();
}
});
});
}, 'Connexion MySQL');
}
async query(sql, params = []) {
const backoff = new ExponentialBackoff(3, 500, 5000);
return backoff.executeWithRetry(async () => {
if (!this.connection || this.connection.state === 'disconnected') {
await this.connectToDatabase();
}
return new Promise((resolve, reject) => {
this.connection.query(sql, params, (err, results) => {
if (err) {
if (err.code === 'ECONNRESET' || err.code === 'PROTOCOL_CONNECTION_LOST') {
this.connection = null;
throw err;
}
reject(err);
} else {
resolve(results);
}
});
});
}, `SQL: ${sql.substring(0, 50)}...`);
}
async createTables() {
const tables = [
`CREATE TABLE IF NOT EXISTS user_data (
user_id VARCHAR(255) PRIMARY KEY,
user_data JSON,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)`,
`CREATE TABLE IF NOT EXISTS user_settings (
user_id VARCHAR(255) PRIMARY KEY,
prefix VARCHAR(100) DEFAULT '&',
langue VARCHAR(10) DEFAULT 'fr',
rpconoff ENUM('on', 'off') DEFAULT 'off',
rpctitle VARCHAR(255),
rpcdetails VARCHAR(255),
rpcstate VARCHAR(255),
rpctype VARCHAR(50),
appid VARCHAR(100),
rpcminparty INT,
rpcmaxparty INT,
rpctime BIGINT,
rpclargeimage VARCHAR(500),
rpclargeimagetext VARCHAR(255),
rpcsmallimage VARCHAR(500),
rpcsmallimagetext VARCHAR(255),
rpcplatform VARCHAR(50),
buttontext1 VARCHAR(255),
buttonlink1 VARCHAR(500),
buttontext2 VARCHAR(255),
buttonlink2 VARCHAR(500),
rpcemoji VARCHAR(255),
rpctextstatus VARCHAR(255),
streaming ENUM('on', 'off') DEFAULT 'off',
twitch VARCHAR(500),
spotifyonoff ENUM('on', 'off') DEFAULT 'off',
spotifysongname VARCHAR(255),
spotifyartists VARCHAR(255),
spotifyendtimestamp BIGINT,
spotifylargeimage VARCHAR(500),
spotifyalbumname VARCHAR(255),
spotifysmallimage VARCHAR(500),
voiceconnect VARCHAR(255),
voicemute BOOLEAN DEFAULT FALSE,
voicedeaf BOOLEAN DEFAULT FALSE,
voicewebcam BOOLEAN DEFAULT FALSE,
voicestream BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)`
];
for (const tableQuery of tables) {
await this.query(tableQuery);
}
}
async loadConfig() {
console.log('⚠️ loadConfig() non utilisée (configuration manuelle activée)');
}
async batchQuery(table, operations) {
const inserts = [];
const params = [];
for (const op of operations) {
inserts.push(`(?, ?)`);
params.push(op.userId, JSON.stringify(op.data));
}
if (inserts.length > 0) {
const insertQuery = `
INSERT INTO ${table} (user_id, user_data)
VALUES ${inserts.join(',')}
ON DUPLICATE KEY UPDATE user_data = VALUES(user_data)
`;
await this.query(insertQuery, params);
}
}
async debouncedBatchSave(key, operation) {
if (!this.batchQueue.has(key)) {
this.batchQueue.set(key, []);
}
this.batchQueue.get(key).push(operation);
if (this.batchTimeouts.has(key)) {
clearTimeout(this.batchTimeouts.get(key));
}
this.batchTimeouts.set(key, setTimeout(async () => {
const queue = this.batchQueue.get(key);
if (!queue || queue.length === 0) return;
try {
await this.batchQuery('user_data', queue);
} catch (error) {
console.error('Erreur batch SQL:', error);
for (const op of queue) {
try {
await this.query(
`INSERT INTO user_data (user_id, user_data)
VALUES (?, ?)
ON DUPLICATE KEY UPDATE user_data = ?`,
[op.userId, JSON.stringify(op.data), JSON.stringify(op.data)]
);
} catch (err) {
console.error(`Erreur sauvegarde ${op.userId}:`, err);
}
}
} finally {
this.batchQueue.delete(key);
this.batchTimeouts.delete(key);
}
}, BATCH_DELAY));
}
async saveConfigToDB() {
const operations = [];
for (const [userId, userConfig] of Object.entries(config.user || {})) {
const userData = globalDb[userId] || {};
userData.token = userConfig.token;
operations.push({
type: 'update',
userId,
data: userData
});
}
if (operations.length > 0) {
for (const op of operations) {
await this.debouncedBatchSave('config', op);
}
}
}
async saveGlobalDbToDB() {
const operations = Object.entries(globalDb).map(([userId, data]) => ({
type: 'update',
userId,
data
}));
if (operations.length > 0) {
await this.debouncedBatchSave('globaldb', operations[0]);
}
}
async debouncedSave(key, data, saveMethod) {
if (this.isSaving.get(key)) {
this.pendingWrites.set(key, { data, saveMethod });
return;
}
if (this.saveTimeouts.has(key)) {
clearTimeout(this.saveTimeouts.get(key));
}
this.saveTimeouts.set(key, setTimeout(async () => {
this.isSaving.set(key, true);
try {
await this[saveMethod]();
} catch (error) {
console.error('Erreur sauvegarde ' + key + ':', error);
} finally {
this.isSaving.set(key, false);
const pending = this.pendingWrites.get(key);
if (pending) {
this.pendingWrites.delete(key);
await this.debouncedSave(key, pending.data, pending.saveMethod);
}
}
}, SAVE_DEBOUNCE_DELAY));
}
async saveConfig() {
return await this.debouncedSave('config', config, 'saveConfigToDB');
}
async saveGlobalDb() {
return await this.debouncedSave('globaldb', globalDb, 'saveGlobalDbToDB');
}
getUserData(userId) {
if (!globalDb[userId]) globalDb[userId] = {};
return globalDb[userId];
}
updateUserData(userId, updates) {
if (!globalDb[userId]) globalDb[userId] = {};
Object.assign(globalDb[userId], updates);
return this.saveGlobalDb();
}
}
const dbManager = new DatabaseManager();
const monitor = new AdvancedMonitor();
async function saveConfig() {
try {
return await dbManager.saveConfig();
} catch (error) {
console.error('Erreur saveConfig:', error);
}
}
async function saveGlobalDb() {
try {
return await dbManager.saveGlobalDb();
} catch (error) {
console.error('Erreur saveGlobalDb:', error);
}
}
async function initConfig() {
await dbManager.initialize();
}
Client.prototype.refreshVoice = async function(channelId, userId) {
try {
const channel = this.channels.cache.get(channelId);
if (!channel || channel.type !== 'GUILD_VOICE') {
throw new Error('Salon vocal introuvable');
}
const userDb = await sqlDb.getUserData(userId);
const selfMute = userDb?.voicemute == 1 || userDb?.voicemute === true;
const selfDeaf = userDb?.voicedeaf == 1 || userDb?.voicedeaf === true;
const selfVideo = userDb?.voicewebcam == 1 || userDb?.voicewebcam === true;
const selfStream = userDb?.voicestream == 1 || userDb?.voicestream === true;
this.ws.broadcast({
op: 4,
d: {
guild_id: channel.guildId ?? null,
channel_id: channel.id,
self_mute: selfMute,
self_deaf: selfDeaf,
self_video: selfVideo,
flags: 2,
},
});
if (selfStream) {
this.ws.broadcast({
op: 18,
d: {
type: channel.guild ? 'guild' : 'dm',
guild_id: channel.guildId ?? null,
channel_id: channel.id,
preferred_region: "japan"
}
});
} else {
this.ws.broadcast({
op: 19,
d: {
stream_key: `${channel.guildId ? `guild:${channel.guildId}` : 'call'}:${channel.id}:${this.user.id}`
}
});
}
} catch (error) {
console.error('[AUTOVOC] Erreur refreshVoice:', error);
throw error;
}
};
async function cleanupAllClients() {
console.log('Deconnexion de tous les utilisateurs...');
for (const client of clients) {
try {
if (client.user?.setActivity) {
client.user.setActivity(null);
}
if (client.reconnectInterval) {
clearInterval(client.reconnectInterval);
}
client.ws.broadcast({
op: 4,
d: {
guild_id: null,
channel_id: null,
self_mute: false,
self_deaf: false,
self_video: false,
flags: 2,
},
});
client.removeAllListeners();
await client.destroy();
console.log('Utilisateur ' + client.userId + ' deconnecte');
} catch (error) {
console.error('Erreur deconnexion ' + client.userId + ':', error);
}
}
clients.length = 0;
}
async function createNewClient(userId, userData) {
const db = await sqlDb.getUserData(userId);
const platformSettings = {
mobile: {
os: 'Android',
browser: 'Discord Android',
release_channel: 'stable',
getClientVersion: function() {
return "218.15";
},
getClientBuildNumber: function() {
return 218150;
},
getNativeBuildNumber: function() {
return 218150;
},
os_version: '14',
os_arch: 'arm64',
system_locale: 'fr-FR',
client_event_source: null,
design_id: 0
},
desktop: {
os: 'Windows',
browser: 'Discord Client',
release_channel: 'stable',
getClientVersion: function() {
return "1.0.9225";
},
getClientBuildNumber: function() {
return 500334;
},
getNativeBuildNumber: function() {
return 75673;
},
os_version: '10.0.22621',
os_arch: 'x64',
system_locale: 'fr-FR',
client_event_source: null,
design_id: 0
},
web: {
os: 'Linux',
browser: 'Discord Web',
release_channel: 'stable',
getClientVersion: function() {
return "1.0.9011";
},
getClientBuildNumber: function() {
return 175517;
},
getNativeBuildNumber: function() {
return 29584;
},
os_version: '',
os_arch: 'x64',
system_locale: 'fr-FR',
client_event_source: null,
design_id: 0
},
canary: {
os: 'Windows',
browser: 'Discord Canary',
release_channel: 'canary',
getClientVersion: function() {
return "1.0.9230";
},
getClientBuildNumber: function() {
return 501234;
},
getNativeBuildNumber: function() {
return 76000;
},
os_version: '10.0.22621',
os_arch: 'x64',
system_locale: 'fr-FR',
client_event_source: null,
design_id: 0
}
};
const userPlatform = db.platform || "desktop";
const wsProps = platformSettings[userPlatform];
const user = new Client({
checkUpdate: false,
autoRedeemNitro: false,
messageCacheMaxSize: 0,
messageCacheLifetime: 0,
messageSweepInterval: 0,
restRequestTimeout: 45000,
ws: {
properties: wsProps,
compress: false
}
});
user.userId = userId;
user.commands = globalCommandsMap;
user.snipes = new Map();
user.setMaxListeners(50);
return user;
}
function isInvalidTokenError(error) {
const errorMessage = error.message?.toLowerCase() || '';
const errorCode = error.code?.toString() || '';
const isInvalid = errorMessage.includes('incorrect login details') ||
errorMessage.includes('invalid token') ||
errorMessage.includes('bad token') ||
errorMessage.includes('an invalid token was provided') ||
errorCode === '400' ||
errorCode === '401' ||
errorCode === '403';
return isInvalid;
}
const eventCache = require('./eventCache');
async function verifyTokenBeforeConnect(userId, token) {
try {
if (!token || token.length < 50) {
return { valid: false, reason: 'Format invalide' };
}
const https = require('https');
return new Promise((resolve) => {
const options = {
hostname: 'discord.com',
port: 443,
path: '/api/v10/users/@me',
method: 'GET',
headers: {
'Authorization': token.trim(),
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
},
timeout: 10000
};
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => {
if (res.statusCode === 200) {
try {
const userData = JSON.parse(data);
resolve({ valid: true, userData, tokenId: userData.id });
} catch {
resolve({ valid: false, reason: 'Réponse invalide' });
}
} else if (res.statusCode === 401) {
resolve({ valid: false, reason: 'Token invalide ou expiré (401)' });
} else {
resolve({ valid: false, reason: `Erreur API Discord (HTTP ${res.statusCode})` });
}
});
});
req.on('error', (err) => resolve({ valid: false, reason: 'Erreur réseau: ' + err.message }));
req.on('timeout', () => {
req.destroy();
resolve({ valid: false, reason: 'Timeout' });
});
req.end();
});
} catch (error) {
return { valid: false, reason: error.message };
}
}
async function initializeSingleClient(userId, userData) {
const token = userData.token?.trim();
if (!token) {
console.log(`❌ ${userId}: Pas de token`);
await removeUserFromConfig(userId);
return null;
}
if (connectionState.get(userId) === 'connecting' || connectionState.get(userId) === 'connected') {
console.log(`⚠️ ${userId}: Déjà en cours de connexion ou connecté`);
return null;
}
connectionState.set(userId, 'connecting');
try {
const verification = await verifyTokenBeforeConnect(userId, token);
if (!verification.valid) {
console.log(`❌ ${userId}: Token invalide - ${verification.reason}`);
await removeUserFromConfig(userId);
connectionState.set(userId, 'failed');
return null;
}
const user = await createNewClient(userId, userData);
await eventCache.attachEventsToClient(user);
attachSnipeEvent(user);
user.on('ready', async () => {
connectionState.set(userId, 'connected');
try {
await bl.init(user);
await messageCmd.init(user);
await rainbowModule.initializeRainbowRoles(user);
setTimeout(async () => {
try {
await multistatus.startMultiStatus(user);
afkCommand.initializeAfkListener(user);
} catch (err) {
console.error(`⚠️ ${userId}: Erreur démarrage multistatus différé:`, err.message);
}
}, 15000);
} catch (err) {
console.error(`⚠️ ${userId}: Erreur initialisation modules:`, err.message);
}
});
user.on('disconnect', () => {
console.log(`🔌 ${userId}: Déconnecté`);
connectionState.set(userId, 'disconnected');
});
user.on('error', (error) => {
console.error(`⚠️ ${userId}: Erreur client:`, error.message);
if (isInvalidTokenError(error)) {
connectionState.set(userId, 'invalid_token');
}
});
const maxAttempts = 2;
let lastError = null;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
await user.login(token);
if (user.user) {
clients.push(user);
return user;
}
} catch (error) {
lastError = error;
console.log(`⚠️ ${userId}: Échec tentative ${attempt}: ${error.message}`);
if (isInvalidTokenError(error)) {
console.log(`❌ ${userId}: Token invalide détecté`);
await removeUserFromConfig(userId);
connectionState.set(userId, 'invalid_token');
throw new Error('TOKEN_INVALID');
}
if (attempt < maxAttempts) {
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
}
throw lastError || new Error('Échec de connexion après plusieurs tentatives');
} catch (error) {
console.error(`❌ ${userId}: Échec connexion finale:`, error.message);
if (error.message === 'TOKEN_INVALID') {
await removeUserFromConfig(userId);
connectionState.set(userId, 'invalid_token');
} else {
connectionState.set(userId, 'failed');
}
return null;
}
}
async function rotateClientConnection(client) {
const userId = client.userId;
const token = config.user[userId]?.token;
if (!token) {
console.log(`❌ ${userId}: Pas de token pour la rotation`);
return false;
}
try {
connectionState.set(userId, 'rotating');
if (client.user?.setActivity) {
client.user.setActivity(null);
}
client.ws.broadcast({
op: 4,
d: {
guild_id: null,
channel_id: null,
self_mute: false,
self_deaf: false,
self_video: false,
flags: 2,
},
});
if (client.reconnectInterval) {
clearInterval(client.reconnectInterval);
}
client.removeAllListeners();
await client.destroy();
const clientIndex = clients.findIndex(c => c.userId === userId);
if (clientIndex !== -1) {
clients.splice(clientIndex, 1);
}
await new Promise(resolve => setTimeout(resolve, ROTATION_DELAY));
const verification = await verifyTokenBeforeConnect(userId, token);
if (!verification.valid) {
console.log(`❌ ${userId}: Token invalide pendant rotation`);
await removeUserFromConfig(userId);
connectionState.set(userId, 'invalid_token');
return false;
}
const newClient = await createNewClient(userId, { token });
await newClient.login(token);
if (newClient.user) {
await eventCache.attachEventsToClient(newClient);
attachSnipeEvent(newClient);
await bl.init(newClient);
clients.push(newClient);
console.log(`✅ ${userId}: Rotation terminée avec succès`);
connectionState.set(userId, 'connected');
return true;
}
return false;
} catch (error) {
console.error(`❌ ${userId}: Erreur rotation:`, error.message);
connectionState.set(userId, 'failed');
return false;
}
}
function startClientRotationSchedule() {
setInterval(async () => {
const clientsCopy = [...clients];
for (const client of clientsCopy) {
if (client && client.userId) {
await rotateClientConnection(client);
if (clientsCopy.length > 1) {
await new Promise(resolve => setTimeout(resolve, ROTATION_DELAY));
}
}
}
}, RECONNECT_INTERVAL);
}
async function reconnectUser(user, token) {