-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.mjs
More file actions
1352 lines (1081 loc) · 58.3 KB
/
index.mjs
File metadata and controls
1352 lines (1081 loc) · 58.3 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
// GNU GENERAL PUBLIC LICENSE
// Version 3, 29 June 2007
//
//Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
//Everyone is permitted to copy and distribute verbatim copies
//of this license document, but changing it is not allowed.
//
// Bot written by @thobi made to work with Arturo PTCG Bot for the PTCGP Rerollers community
// See here : https://github.com/Arturo-1212/PTCGPB
// Shoutout to @cjlj for Automated ids.txt modifications on the ahk side
//
// Documentation :
// https://github.com/TheThobi/PTCGPRerollManager
//
// Imports
import {
token,
guildID,
channelID_Commands,
channelID_UserStats,
channelID_GPVerificationForum,
channelID_2StarVerificationForum,
channelID_Webhook,
channelID_Heartbeat,
channelID_AntiCheat,
gitToken,
gitGistID,
gitGistGroupName,
gitGistGPName,
missBeforeDead,
missNotLikedMultiplier,
showPerPersonLive,
EnglishLanguage,
AntiCheat,
AutoKick,
refreshInterval,
inactiveTime,
inactiveInstanceCount,
inactivePackPerMinCount,
inactiveIfMainOffline,
heartbeatRate,
delayMsgDeleteState,
backupUserDatasTime,
min2Stars,
groupPacksType,
canPeopleAddOthers,
canPeopleRemoveOthers,
canPeopleLeech,
leechPermGPCount,
leechPermPackCount,
resetServerDataFrequently,
resetServerDataTime,
safeEligibleIDsFiltering,
forceSkipMin2Stars,
forceSkipMinPacks,
text_verifiedLogo,
text_likedLogo,
text_waitingLogo,
text_notLikedLogo,
text_deadLogo,
} from './config.js';
import {
formatMinutesToDays,
formatNumbertoK,
sumIntArray,
sumFloatArray,
roundToOneDecimal,
roundToTwoDecimals,
countDigits,
extractNumbers,
extractTwoStarAmount,
isNumbers,
convertMnToMs,
convertMsToMn,
splitMulti,
replaceLastOccurrence,
replaceMissCount,
replaceMissNeeded,
sendReceivedMessage,
sendChannelMessage,
bulkDeleteMessages,
colorText,
addTextBar,
formatNumberWithSpaces,
localize,
getRandomStringFromArray,
getOldestMessage,
wait,
replaceAnyLogoWith,
normalizeOCR,
getLastsAntiCheatMessages,
updateAverage,
} from './Dependencies/utils.js';
import {
getGuild,
getMemberByID,
getUsersStats,
sendStats,
sendIDs,
sendStatusHeader,
inactivityCheck,
extractGPInfo,
extractDoubleStarInfo,
createForumPost,
markAsDead,
updateEligibleIDs,
updateInactiveGPs,
setUserState,
updateServerData,
updateAntiCheat,
updateUserDataGPLive,
addUserDataGPLive,
} from './Dependencies/coreUtils.js';
import {
checkFileExists,
checkFileExistsOrCreate,
writeFile,
doesUserProfileExists,
setUserAttribValue,
getUserAttribValue,
setAllUsersAttribValue,
setUserSubsystemAttribValue,
getUserSubsystemAttribValue,
getActiveUsers,
getActiveIDs,
getAllUsers,
getUsernameFromUsers,
getUsernameFromUser,
getIDFromUsers,
getIDFromUser,
getTimeFromGP,
getAttribValueFromUsers,
getAttribValueFromUser,
getAttribValueFromUserSubsystems,
refreshUserActiveState,
refreshUserRealInstances,
cleanString,
addServerGP,
getServerDataGPs,
backupFile,
} from './Dependencies/xmlManager.js';
import {
attrib_PocketID,
attrib_Prefix,
attrib_UserState,
attrib_ActiveState,
attrib_AverageInstances,
attrib_HBInstances,
attrib_RealInstances,
attrib_SessionTime,
attrib_TotalPacksOpened,
attrib_TotalPacksFarm,
attrib_TotalAverageInstances,
attrib_TotalAveragePPM,
attrib_TotalHBTick,
attrib_SessionPacksOpened,
attrib_DiffPacksSinceLastHB,
attrib_DiffTimeSinceLastHB,
attrib_PacksPerMin,
attrib_GodPackFound,
attrib_GodPackLive,
attrib_LastActiveTime,
attrib_LastHeartbeatTime,
attrib_TotalTime,
attrib_TotalTimeFarm,
attrib_TotalMiss,
attrib_AntiCheatUserCount,
attrib_Subsystems,
attrib_Subsystem,
attrib_eligibleGPs,
attrib_eligibleGP,
attrib_liveGPs,
attrib_liveGP,
attrib_ineligibleGPs,
attrib_ineligibleGP,
attrib_SelectedPack,
attrib_RollingType,
attrib_DisplayName,
pathUsersData,
pathServerData,
} from './Dependencies/xmlConfig.js';
import {
text_lowTension,
text_mediumTension,
text_highTension,
} from './Dependencies/missSentences.js';
import {
Client,
Events,
GatewayIntentBits,
SlashCommandBuilder,
REST,
ButtonBuilder,
ButtonStyle,
ActionRowBuilder,
EmbedBuilder,
PermissionsBitField,
} from 'discord.js';
// Global Var
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
]
});
var startIntervalTime = Date.now();
var evenTurnShortInterval = false;
function getNexIntervalRemainingTime() {
const currentTime = Date.now();
const elapsedTime = currentTime - startIntervalTime;
const timeRemaining = (refreshInterval) - convertMsToMn(elapsedTime);
return timeRemaining;
}
// Events
client.once(Events.ClientReady, async c => {
console.log(`✅ Logged in as ${c.user.tag}`);
const guild = await getGuild(client);
// Every "refreshInterval/2" mn it will alternate from sendUserStat to inactivityCheck
setInterval(() =>{
startIntervalTime = Date.now();
evenTurnShortInterval = !evenTurnShortInterval;
if (evenTurnShortInterval) {
sendStats(client);
}
else if(AutoKick) {
inactivityCheck(client);
}
}, convertMnToMs(refreshInterval/2));
// Send back the messages with buttons so ppl can switch states easily
await sendStatusHeader(client)
setInterval(async() =>{
await sendStatusHeader(client)
}, convertMnToMs(60));
// Reset and Update ServerData every X hours (might disable the loop it if you have over 10k gp or it'll take a while)
await updateServerData(client, true);
setInterval(async() =>{
await updateServerData(client);
}, convertMnToMs(resetServerDataTime+1));
// Backup UserData.xml file
setInterval(async() =>{
await backupFile(pathUsersData);
}, convertMnToMs(backupUserDatasTime+1));
if(AntiCheat){
setInterval(async() =>{
await updateAntiCheat(client);
}, convertMnToMs(5));
await updateAntiCheat(client);
}
// Backup UserData.xml file
setInterval(async() =>{
await updateInactiveGPs(client);
}, convertMnToMs(60));
await updateInactiveGPs(client);
// Clear all guild commands (Warning : also clear channels restrictions set on discord)
// guild.commands.set([]);
// Clear a specific guild command
// const commandId = 'XXXXXXXXXXXXXXXXXXX';
// await guild.commands.delete(commandId);
// Commands Creation
const playeridDesc = localize("Lie votre code ami à votre pseudo discord unique", "Link your ID Code with you Discord unique username");
const playeridDescId = localize("Votre ID SANS TIRET", "Your ID without any dash");
const playeridSCB = new SlashCommandBuilder()
.setName(`setplayerid`)
.setDescription(`${playeridDesc}\n`)
.addStringOption(option =>
option
.setName("id")
.setDescription(`${playeridDescId}`)
.setRequired(true)
);
const instancesDesc = localize("Renseignez votre nombre d'instance moyen", "Set to your average number of instances");
const instancesDescAmount = localize("Nombres ronds (ex: pas 5.5 parce que vous etes a 6 et de fois 5)", "Round nombers (ex : not 5.5 if you're running 5 and sometimes 6)");
const instancesSCB = new SlashCommandBuilder()
.setName(`setaverageinstances`)
.setDescription(`${instancesDesc}\n`)
.addIntegerOption(option =>
option
.setName("amount")
.setDescription(`${instancesDescAmount}`)
.setRequired(true)
);
const prefixDesc = localize("Renseignez votre préfixe de votre liste de nom d'utilisateur", "Set your prefix from your username list");
const prefixDescPrefix = localize("Doit être composé de 4 lettres", "Needs to be 4 letters");
const prefixSCB = new SlashCommandBuilder()
.setName(`setprefix`)
.setDescription(`${prefixDesc}\n`)
.addStringOption(option =>
option
.setName("prefix")
.setDescription(`${prefixDescPrefix}`)
.setRequired(true)
);
const activeDesc = localize("Vous ajoute dans le doc d'ID", "Add yourself to the active rerollers list");
const activeDescUser = localize("ADMIN ONLY : pour forcer l'ajout de quelqu'un d'autre", "ADMIN ONLY : Only usefull so force add someone else than yourself");
const activeSCB = new SlashCommandBuilder()
.setName(`active`)
.setDescription(`${activeDesc}`)
.addUserOption(option =>
option
.setName("user")
.setDescription(`${activeDescUser}`)
.setRequired(false)
);
const inactiveDesc = localize("Vous retire du doc d'ID"," Withdraw yourself from the active rerollers list");
const inactiveDescUser = localize("ADMIN ONLY : pour forcer le retrait de quelqu'un d'autre", "ADMIN ONLY : Only usefull so force remove someone else than yourself");
const inactiveSCB = new SlashCommandBuilder()
.setName(`inactive`)
.setDescription(`${inactiveDesc}`)
.addUserOption(option =>
option
.setName("user")
.setDescription(`${inactiveDescUser}`)
.setRequired(false)
);
const farmDesc = localize("Vous ajoute dans le doc d'ID comme farmer (noMain)", "Add yourself to the active rerollers list as farmer (noMain)");
const farmDescUser = localize("ADMIN ONLY : pour forcer l'ajout' de quelqu'un d'autre", "ADMIN ONLY : Only usefull so force add someone else than yourself");
const farmSCB = new SlashCommandBuilder()
.setName(`farm`)
.setDescription(`${farmDesc}`)
.addUserOption(option =>
option
.setName("user")
.setDescription(`${farmDescUser}`)
.setRequired(false)
);
const leechDesc = localize("Vous ajoute dans le doc d'ID comme leecher (onlyMain)", "Add yourself to the active rerollers list as leecher (onlyMain)");
const leechDescUser = localize("ADMIN ONLY : pour forcer l'ajout' de quelqu'un d'autre", "ADMIN ONLY : Only usefull so force add someone else than yourself");
const leechSCB = new SlashCommandBuilder()
.setName(`leech`)
.setDescription(`${leechDesc}`)
.addUserOption(option =>
option
.setName("user")
.setDescription(`${leechDescUser}`)
.setRequired(false)
);
const refreshDesc = localize("Rafraichit la liste des Stats instantanément","Refresh the user stats instantly");
const refreshSCB = new SlashCommandBuilder()
.setName(`refresh`)
.setDescription(`${refreshDesc}`);
const forcerefreshDesc = localize("Rafraichit la liste des ids et les envois au server","Refresh the ids.txt and sent them to servers");
const forcerefreshSCB = new SlashCommandBuilder()
.setName(`forcerefresh`)
.setDescription(`${forcerefreshDesc}`);
const verifiedDesc = localize("Designe pack valide","Flag the post as valid");
const verifiedSCB = new SlashCommandBuilder()
.setName(`verified`)
.setDescription(`${verifiedDesc}`);
const deadDesc = localize("Designe pack invalide / dud","Flag the post as invalid / dud");
const deadSCB = new SlashCommandBuilder()
.setName(`dead`)
.setDescription(`${deadDesc}`);
const likedDesc = localize("Designe pack comme liké","Flag the post as liked");
const likedSCB = new SlashCommandBuilder()
.setName(`liked`)
.setDescription(`${likedDesc}`);
const notLikedDesc = localize("Designe pack comme non liké","Flag the post as not liked");
const notLikedSCB = new SlashCommandBuilder()
.setName(`notliked`)
.setDescription(`${notLikedDesc}`);
const missDesc = localize("Pour la verification GP, après X fois suivant le nombre de pack cela auto /dead", "For verification purposes, after X times based on pack amount it sends /dead");
const missSCB = new SlashCommandBuilder()
.setName(`miss`)
.setDescription(`${missDesc}`);
const misscountDesc = localize("Montre le rapport de miss par temps passé à roll", "Show how many miss rerollers have done while active");
const misscountSCB = new SlashCommandBuilder()
.setName(`misscount`)
.setDescription(`${misscountDesc}`);
const lastactivityDesc = localize("Montre à combien de temps remonte le dernier Heartbeat", "Show how long since the last Heartbeat was");
const lastactivitySCB = new SlashCommandBuilder()
.setName(`lastactivity`)
.setDescription(`${lastactivityDesc}`);
const generateusernamesDesc = localize("Génère liste basé sur préfixe et, facultatif, des mots","Generate a list based on a prefix and, if wanted, keywords");
const generateusernamesDescPrefix = localize("Les 4 premières lettres premières lettres de votre pseudo","The 4 firsts letter of your pseudonym");
const generateusernamesDescKeyword = localize("Des mots clés qui seront assemblés aléatoirement, espace/virgule = séparation","Some keywords that will be assembled randomly, space or comma are separations");
const generateusernamesSCB = new SlashCommandBuilder()
.setName(`generateusernames`)
.setDescription(`${generateusernamesDesc}`)
.addStringOption(option =>
option
.setName("prefix")
.setDescription(`${generateusernamesDescPrefix}`)
.setRequired(true)
).addStringOption(option2 =>
option2
.setName("keywords")
.setDescription(`${generateusernamesDescKeyword}`)
.setRequired(false)
);
const addGPFoundDesc = localize("ADMIN ONLY : Ajoute un GP trouvé à un utilisateur pour les stats","ADMIN ONLY : Add a GP Found to an user for the stats");
const addGPFoundDescUser = localize("seulement utile pour corriger des erreurs","Only usefull to fix bugs");
const addGPFoundSCB = new SlashCommandBuilder()
.setName(`addgpfound`)
.setDescription(`${addGPFoundDesc}`)
.addUserOption(option =>
option
.setName("user")
.setDescription(`${addGPFoundDescUser}`)
.setRequired(false)
);
const removeGPFoundDesc = localize("ADMIN ONLY : Retire un GP trouvé à un utilisateur pour les stats","ADMIN ONLY : Remove a GP Found to an user for the stats");
const removeGPFoundDescUser = localize("seulement utile pour corriger des erreurs","only usefull to fix bugs");
const removeGPFoundSCB = new SlashCommandBuilder()
.setName(`removegpfound`)
.setDescription(`${removeGPFoundDesc}`)
.addUserOption(option =>
option
.setName("user")
.setDescription(`${removeGPFoundDescUser}`)
.setRequired(false)
);
const playeridCommand = playeridSCB.toJSON();
client.application.commands.create(playeridCommand, guildID);
const instancesCommand = instancesSCB.toJSON();
client.application.commands.create(instancesCommand, guildID);
const prefixCommand = prefixSCB.toJSON();
client.application.commands.create(prefixCommand, guildID);
const activeCommand = activeSCB.toJSON();
client.application.commands.create(activeCommand, guildID);
const inactiveCommand = inactiveSCB.toJSON();
client.application.commands.create(inactiveCommand, guildID);
const farmCommand = farmSCB.toJSON();
client.application.commands.create(farmCommand, guildID);
const leechCommand = leechSCB.toJSON();
client.application.commands.create(leechCommand, guildID);
const refreshCommand = refreshSCB.toJSON();
client.application.commands.create(refreshCommand, guildID);
const forcerefreshCommand = forcerefreshSCB.toJSON();
client.application.commands.create(forcerefreshCommand, guildID);
const verifiedCommand = verifiedSCB.toJSON();
client.application.commands.create(verifiedCommand, guildID);
const deadCommand = deadSCB.toJSON();
client.application.commands.create(deadCommand, guildID);
const likedCommand = likedSCB.toJSON();
client.application.commands.create(likedCommand, guildID);
const notLikedCommand = notLikedSCB.toJSON();
client.application.commands.create(notLikedCommand, guildID);
const missCommand = missSCB.toJSON();
client.application.commands.create(missCommand, guildID);
const misscountCommand = misscountSCB.toJSON();
client.application.commands.create(misscountCommand, guildID);
const lastactivityCommand = lastactivitySCB.toJSON();
client.application.commands.create(lastactivityCommand, guildID);
const generateusernamesCommand = generateusernamesSCB.toJSON();
client.application.commands.create(generateusernamesCommand, guildID);
const addGPFoundCommand = addGPFoundSCB.toJSON();
client.application.commands.create(addGPFoundCommand, guildID);
const removeGPFoundCommand = removeGPFoundSCB.toJSON();
client.application.commands.create(removeGPFoundCommand, guildID);
});
client.on(Events.InteractionCreate, async interaction => {
var interactionUserName = interaction.user.username;
var interactionUserID = interaction.user.id;
var interactionDisplayName = interaction.user.displayName;
const guild = await getGuild(client);
// ======================= Buttons =======================
try{
if (interaction.customId === 'active') {
await interaction.deferReply();
setUserState(client, interaction.user, "active", interaction)
}
else if (interaction.customId === 'farm') {
await interaction.deferReply();
setUserState(client, interaction.user, "farm", interaction)
}
else if (interaction.customId === 'leech') {
await interaction.deferReply();
setUserState(client, interaction.user, "leech", interaction)
}
else if (interaction.customId === 'inactive') {
await interaction.deferReply();
setUserState(client, interaction.user, "inactive", interaction)
}
else if (interaction.customId === 'refreshUserStats') {
await interaction.deferReply();
const text_listForceRefreshed = localize(`**Stats des rerollers actifs rafraichies dans <#${channelID_UserStats}>**`, `**Active rerollers stats refreshed in <#${channelID_UserStats}>**`);
await sendReceivedMessage(client, text_listForceRefreshed, interaction, delayMsgDeleteState);
sendStats(client)
}
if(!interaction.isChatInputCommand()) return;
// SET PLAYER ID COMMAND
if(interaction.commandName === `setplayerid`){
await interaction.deferReply();
const id = interaction.options.getString(`id`);
const text_incorrectID = localize("ID Incorrect pour","ID Incorrect for");
const text_incorrectReason = localize("Votre code doit être composé de **16 chifres**","Your could should be **16 numbers length**");
const text_replace = localize("a été remplacé par","have been replaced by");
const text_for = localize("pour","for");
const text_set = localize("set pour","set for user");
if(id.length != 16 || !isNumbers(id)){
await sendReceivedMessage(client, text_incorrectID + ` **<@${interactionUserID}>**, ` + text_incorrectReason, interaction);
}
else{
const userPocketID = await getUserAttribValue( client, interactionUserID, attrib_PocketID);
if( userPocketID != undefined ){
await setUserAttribValue( interactionUserID, interactionUserName, attrib_PocketID, cleanString(id));
await sendReceivedMessage(client, `Code **${userPocketID}** ` + text_replace + ` **${id}** ` + text_for + ` **<@${interactionUserID}>**`, interaction);
}
else{
await setUserAttribValue( interactionUserID, interactionUserName, attrib_PocketID, cleanString(id));
await sendReceivedMessage(client, `Code **${id}** ` + text_set + ` **<@${interactionUserID}>**`, interaction);
}
}
}
// ACTIVE COMMAND
if(interaction.commandName === `active`){
await interaction.deferReply();
const text_missingPerm = localize("n\'a pas les permissions nécessaires pour changer l\'état de","do not have the permission to edit other user");
var user = interaction.user;
const userArg = interaction.options.getUser(`user`);
if( userArg != null ){
if(!canPeopleAddOthers) {
if (!interaction.member.permissions.has(PermissionsBitField.Flags.Administrator) && interactionUserID != user.id) {
return await sendReceivedMessage(client, `<@${interactionUserID}> ${text_missingPerm} <@${user.id}>`, interaction);
}
}
var user = userArg;
}
setUserState(client, user, "active", interaction)
}
// INACTIVE COMMAND
if(interaction.commandName === `inactive`){
await interaction.deferReply();
const text_missingPerm = localize("n\'a pas les permissions nécessaires pour changer l\'état de","do not have the permission to edit the other user");
var user = interaction.user;
const userArg = interaction.options.getUser(`user`);
if( userArg != null){
if(!canPeopleRemoveOthers) {
if (!interaction.member.permissions.has(PermissionsBitField.Flags.Administrator) && interactionUserID != user.id) {
return await sendReceivedMessage(client, `<@${interactionUserID}> ${text_missingPerm} <@${user.id}>`, interaction);
}
}
var user = userArg;
}
setUserState(client, user, "inactive", interaction)
}
// FARM COMMAND
if(interaction.commandName === `farm`){
await interaction.deferReply();
const text_missingPerm = localize("n\'a pas les permissions nécessaires pour changer l\'état de","do not have the permission to edit the other user");
var user = interaction.user;
const userArg = interaction.options.getUser(`user`);
if( userArg != null){
if(!canPeopleRemoveOthers) {
if (!interaction.member.permissions.has(PermissionsBitField.Flags.Administrator) && interactionUserID != user.id) {
return await sendReceivedMessage(client, `<@${interactionUserID}> ${text_missingPerm} <@${user.id}>`, interaction);
}
}
var user = userArg;
}
setUserState(client, user, "farm", interaction)
}
// LEECH COMMAND
if(interaction.commandName === `leech`){
await interaction.deferReply();
const text_missingPerm = localize("n\'a pas les permissions nécessaires pour changer l\'état de","do not have the permission to edit the other user");
var user = interaction.user;
const userArg = interaction.options.getUser(`user`);
if( userArg != null){
if(!canPeopleRemoveOthers) {
if (!interaction.member.permissions.has(PermissionsBitField.Flags.Administrator) && interactionUserID != user.id) {
return await sendReceivedMessage(client, `<@${interactionUserID}> ${text_missingPerm} <@${user.id}>`, interaction);
}
}
var user = userArg;
}
setUserState(client, user, "leech", interaction)
}
// REFRESH COMMAND
if(interaction.commandName === `refresh`){
await interaction.deferReply();
const text_listForceRefreshed = localize(`**Stats des rerollers actifs rafraichies dans <#${channelID_UserStats}>**`, `**Active rerollers stats refreshed in <#${channelID_UserStats}>**`);
await sendReceivedMessage(client, text_listForceRefreshed, interaction, delayMsgDeleteState);
sendStats(client)
}
// FORCE REFRESH COMMAND
if(interaction.commandName === `forcerefresh`){
await interaction.deferReply();
const refreshTime = roundToOneDecimal(getNexIntervalRemainingTime());
const text_IDsRefreshedIn = localize("**IDs rafraichis**, rafraichissment des **Stats dans","**IDs refreshed**, reshing the **Stats in");
const text_see = localize("voir","see");
const text_listRefreshed = `${text_IDsRefreshedIn} ${refreshTime}mn**, ${text_see} <#${channelID_UserStats}>`;
await sendReceivedMessage(client, text_listRefreshed, interaction, delayMsgDeleteState);
sendIDs(client);
}
// VERIFIED COMMAND
if(interaction.commandName === `verified`){
await interaction.deferReply();
const text_markAsVerified = localize("Godpack marqué comme live","Godpack marked as live");
const text_alreadyVerified = localize("C'est gentil de ta part mais il est déjà vérifié le GodPack","That's kind of you but this GP already is verified");
const thread = client.channels.cache.get(interaction.channelId);
if(thread.name.includes(text_verifiedLogo)){
await sendReceivedMessage(client, `${text_alreadyVerified}`, interaction);
}
else{
const newPostName = replaceAnyLogoWith(thread.name, text_verifiedLogo);
// Edit a thread
await thread.edit({ name: `${newPostName}` });
await addServerGP(attrib_liveGP, thread);
await addUserDataGPLive(client, thread);
await sendReceivedMessage(client, `${text_verifiedLogo} ${text_markAsVerified}`, interaction);
}
}
// DEAD COMMAND
if(interaction.commandName === `dead`){
await interaction.deferReply();
await markAsDead(client, interaction);
}
// LIKED COMMAND
if(interaction.commandName === `liked`){
await interaction.deferReply();
const text_markAsLiked = localize(`Godpack marqué comme **liké** ${text_likedLogo} beaucoup de chance d'être live`,`Godpack marked as **liked** ${text_likedLogo} likely to be live`);
const text_alreadyLiked = localize("C'est gentil de ta part mais il est déjà marqué comme liké","That's kind of you but this GP already is already marked as liked");
const thread = client.channels.cache.get(interaction.channelId);
if(thread.name.includes(text_likedLogo)){
await sendReceivedMessage(client, `${text_alreadyLiked}`, interaction);
}
else{
const newPostName = replaceAnyLogoWith(thread.name, text_likedLogo);
await thread.edit({ name: `${newPostName}` });
await sendReceivedMessage(client, `${text_markAsLiked}`, interaction);
}
}
// NOT LIKED COMMAND
if(interaction.commandName === `notliked`){
await interaction.deferReply();
const text_markAsNotLiked = localize(`Godpack marqué comme **non liké** ${text_notLikedLogo} Peu de chance d'être live\n**Nombre de miss total requis**`,`Godpack marked as **not liked** ${text_notLikedLogo} Unlikely to be live\n**Total amount of miss required**`);
const text_alreadyNotLiked = localize("C'est gentil de ta part mais il est déjà marqué comme non liké","That's kind of you but this GP already is already marked as not liked");
const thread = client.channels.cache.get(interaction.channelId);
if(thread.name.includes(text_notLikedLogo)){
await sendReceivedMessage(client, `${text_alreadyNotLiked}`, interaction);
}
else{
// Edit the initial message to divide multiplier miss required by missNotLikedMultiplier[numbersTwoStars]
const initialMessage = await getOldestMessage(thread);
const splitForumContent = splitMulti(initialMessage.content,['[',']']);
if (splitForumContent.length > 1){
const numbersMiss = extractNumbers(splitForumContent[1]);
const numbersTwoStars = extractTwoStarAmount(thread.name);
var missAmount = parseInt(numbersMiss[0]);
var missNeeded = numbersMiss[1];
var newMissNeeded = Math.round(parseInt(missNeeded)*missNotLikedMultiplier[numbersTwoStars]);
const text_finalNotLiked = text_markAsNotLiked + ` **x${missNotLikedMultiplier[numbersTwoStars]}\n[ ${missAmount} miss / ${newMissNeeded} ]**`
// Check if, once modified, the missAmount is greater or equal to the new newMissNeeded
if (missAmount>=newMissNeeded){
const text_failed = localize(`Po\n`,`Well rip,`) + ` **[ ${newMissAmount} miss / ${missNeeded} ]**\n`;
await markAsDead(client, interaction, text_finalNotLiked + localize(`\n\nCependant comportant deja suffisement de Miss pour être considéré comme\n`,`\n\nThought enough misses to be considered as\n`));
}
else{ // Else, the missAmount is lower to the new newMissNeeded
const newPostName = replaceAnyLogoWith(thread.name, text_notLikedLogo);
await thread.edit({ name: `${newPostName}` });
await initialMessage.edit(`${replaceMissNeeded(initialMessage.content, newMissNeeded)}`);
await sendReceivedMessage(client, `${text_finalNotLiked}`, interaction);
}
}
else{
await sendReceivedMessage(client, text_notCompatible, interaction);
}
}
}
// MISS COMMAND
if(interaction.commandName === `miss`){
await interaction.deferReply();
const text_notCompatible = localize("Le GP est dans **l'ancien format**, /miss incompatible","The GP is using the **old format**, /miss incompatible");
const text_scam = localize("Oh le petit malin il a essayé de scam un miss 🤡\nVenez voir tout le monde","Little sneaky boy tried to scam a miss 🤡\nCome see everyone");
const thread = client.channels.cache.get(interaction.channelId);
// Only add a miss for posts marked as notLiked, Waiting or Liked
if (thread.name.includes(text_notLikedLogo) || thread.name.includes(text_waitingLogo) || thread.name.includes(text_likedLogo)){
const initialMessage = await getOldestMessage(thread);
const splitForumContent = splitMulti(initialMessage.content,['[',']']);
if (splitForumContent.length > 1){
const numbersMiss = extractNumbers(splitForumContent[1]);
var missAmount = numbersMiss[0];
var newMissAmount = parseInt(missAmount)+1;
var missNeeded = numbersMiss[1];
var totalMiss = await getUserAttribValue( client, interactionUserID, attrib_TotalMiss, 0 );
await setUserAttribValue( interactionUserID, interactionUserName, attrib_TotalMiss, parseInt(totalMiss)+1);
if(newMissAmount >= missNeeded){
await initialMessage.edit( `${replaceMissCount(initialMessage.content, newMissAmount)}`);
const text_failed = localize(`C'est finito\n`,`Well rip,`) + ` **[ ${newMissAmount} miss / ${missNeeded} ]**\n`;
await markAsDead(client, interaction, text_failed);
}
else{
await initialMessage.edit( `${replaceMissCount(initialMessage.content, newMissAmount)}`);
// If miss is <= 50% the amount sentences are """encouraging""" then it gets worst and even more after 75%
const text_fitTension = newMissAmount <= missNeeded*0.5 ? text_lowTension(client) : newMissAmount <= missNeeded*0.75 ? text_mediumTension(client) : text_highTension(client);
await sendReceivedMessage(client, `${text_fitTension}\n**[ ${newMissAmount} miss / ${missNeeded} ]**`, interaction);
}
}
else{
await sendReceivedMessage(client, text_notCompatible, interaction);
}
}
else{
await sendReceivedMessage(client, text_scam, interaction);
}
}
// MISS COUNT COMMAND
if(interaction.commandName === `misscount`){
await interaction.deferReply();
// text_days = localize("jour","h");
var activityOutput = "\`\`\`\n";
const allUsers = await getAllUsers();
for( var i = 0; i < allUsers.length; i++ ) {
var user = allUsers[i];
var userID = getIDFromUser(user);
const member = await getMemberByID(client, userID);
// Skip if member do not exist
if (member == "") {
console.log(`❗️ User ${userID} is no registered on this server`)
continue;
}
var userDisplayName = member.displayName;
const totalMiss = getAttribValueFromUser(user, attrib_TotalMiss, 0);
const totalTime = getAttribValueFromUser(user, attrib_TotalTime, 0);
const totalTimeHour = parseFloat(totalTime)/60;
var missPer24Hour = roundToOneDecimal( (parseFloat(totalMiss) / totalTimeHour) * 24 );
missPer24Hour = isNaN(missPer24Hour) || missPer24Hour == Infinity ? 0 : missPer24Hour;
activityOutput += addTextBar(`${userDisplayName} `, 20, false) + ` ${missPer24Hour} miss / 24h - ${totalMiss} miss over ${roundToOneDecimal(totalTimeHour)}h\n`
};
activityOutput+="\`\`\`";
await sendReceivedMessage(client, activityOutput, interaction);
}
// LAST ACTIVITY COMMAND
if(interaction.commandName === `lastactivity`){
await interaction.deferReply();
// text_days = localize("jour","h");
var activityOutput = "\`\`\`\n";
const allUsers = await getAllUsers();
for( var i = 0; i < allUsers.length; i++ ) {
var userID = getIDFromUser(allUsers[i]);
const member = await getMemberByID(client, userID);
// Skip if member do not exist
if (member == "") {
console.log(`❗️ Heartbeat from ID ${userID} is no registered on this server`)
continue;
}
var userDisplayName = member.displayName;
const lastHBTime = new Date(getAttribValueFromUser(allUsers[i], attrib_LastHeartbeatTime));
var diffTime = (Date.now() - lastHBTime) / 60000 / 60;
diffTime = roundToOneDecimal(diffTime);
activityOutput += addTextBar(`${userDisplayName} `, 20, false) + ` ${diffTime} h since last hb\n`
};
activityOutput+="\`\`\`";
await sendReceivedMessage(client, activityOutput, interaction);
}
// GENERATE USERNAMES COMMAND
if(interaction.commandName === `generateusernames`){
await interaction.deferReply();
const text_incorrectPrefix = localize("Le préfixe doit être composé de 4 Lettres","The prefix needs to be 4 letters");
const text_incorrectParameters = localize("Paramètres incorrects, entre prefix ET keywords","Incorrect parameters, write prefix AND keyworks");
const text_listGenerated = localize("Nouvelle liste d'usernames generé :","New usernames.txt list generated :");
const prefix = interaction.options.getString(`prefix`).toUpperCase();
var keyWords = interaction.options.getString(`keywords`);
if(prefix.length != 4)
{
return await sendReceivedMessage(client, text_incorrectPrefix, interaction);
}
if(prefix == null || keyWords == null)
{
return await sendReceivedMessage(client, text_incorrectParameters, interaction);
}
keyWords = keyWords.replaceAll(`,`, ` `).split(' ');
const wordsGenerated = 1000;
const maxNameLength = 14;
const prefixLength = prefix.length + 1; // Include the underscore in the length calculation
const forbiddenWords = ["ass","sht","nazi","anus","nig","rape","pede","dic","bitte","hymen","pimp","shto","ugly","bch","nun","tara","wth","bastard","baka","cono","std","cox","chope"];
var content = "";
for (let i = 0; i < wordsGenerated; i++) {
var generatedWord = "";
for (let attempts = 0; attempts < 50; attempts++) {
// Break if maxNameLength-1 is hit
if (prefixLength + generatedWord.length >= maxNameLength-1) {break;}
const randomIndex = Math.floor(Math.random() * keyWords.length);
var keyWord = keyWords[randomIndex];
// Remove all special characters
keyWord = keyWord.replaceAll(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
if (prefixLength + (generatedWord + keyWord).length > maxNameLength) {
continue;
}
else {
generatedWord = generatedWord + keyWord;
}
}
const fullName = prefix + "O" + generatedWord; // I = separator as it seems adbShell.StdIn.WriteLine can't input special characters
if (!forbiddenWords.some(word => fullName.includes(word))) {
content = content + fullName + " \n";
}
}
await sendReceivedMessage(client, text_listGenerated, interaction);
await interaction.channel.send({
files: [{
attachment: Buffer.from(content),
name: 'usernames.txt'
}]
})
}
// SET AVERAGE INSTANCES COMMAND
if(interaction.commandName === `setaverageinstances`){
await interaction.deferReply();
const amount = interaction.options.getInteger(`amount`);
const text_instancesSetTo = localize("Nombre d'instance moyenne défini à","Average amount of instances set to");
const text_incorrectAmount = localize("Petit clown va, entre ton vrai nombre d'instances","You little clown, enter your real number of instances");
const text_for = localize("pour","for");