-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot-commands.js
1100 lines (1053 loc) · 43.8 KB
/
bot-commands.js
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
// Routines for handling bot commands like !ping and !ban.
const Artillery = require('./artillery');
const Ban = require('./ban');
const diff = require('diff');
const discordTranscripts = require('discord-html-transcripts');
const DiscordUtil = require('./discord-util');
const exile = require('./exile-cache');
const FilterUsername = require('./filter-username');
const friend = require('./friend');
const fs = require('fs');
const huddles = require('./huddles');
const moment = require('moment');
const RandomPin = require('./random-pin');
const RankMetadata = require('./rank-definitions');
const RoleID = require('./role-id');
const Sleep = require('./sleep');
const UserCache = require('./user-cache');
const yen = require('./yen');
// The given Discord message is already verified to start with the !ping prefix.
// This is an example bot command that has been left in for fun. Maybe it's
// also useful for teaching people how to use bot commands. It's a harmless
// practice command that does nothing.
async function HandlePingCommand(discordMessage) {
await discordMessage.channel.send('Pong!');
}
// Handles any command that ends with ing. It is a joke command for fun.
async function HandleIngCommand(discordMessage) {
const tokens = discordMessage.content.split(' ');
if (tokens.length !== 1) {
return;
}
const command = tokens[0].toLowerCase();
if (command.length > 9) {
// Don't work for long commands to avoid the worst abuses.
return;
}
if (command.endsWith('ing')) {
const prefix = command.substring(1, command.length - 3);
const ong = prefix + 'ong!';
await discordMessage.channel.send(ong);
}
}
// A message that starts with !code.
async function HandleCodeCommand(discordMessage) {
const discordId = discordMessage.author.id;
const cu = await UserCache.GetCachedUserByDiscordId(discordId);
if (!cu) {
return;
}
const name = cu.getNicknameOrTitleWithInsignia();
const pin = RandomPin();
await discordMessage.author.send(pin);
await discordMessage.channel.send(`Sent a random code to ${name}`);
}
// A message that starts with !gender.
async function HandleGenderCommand(discordMessage) {
const discordId = discordMessage.author.id;
const cu = await UserCache.GetCachedUserByDiscordId(discordId);
if (!cu) {
throw 'Message author not found in database.';
}
const tokens = discordMessage.content.split(' ');
if (tokens.length !== 2) {
await discordMessage.channel.send('Error: wrong number of parameters. Example: `!gender F`');
return;
}
const genderString = tokens[1].toUpperCase();
if (genderString.length !== 1 || !genderString.match(/[A-Z]/i)) {
await discordMessage.channel.send('Error: gender must be exactly one letter. Example: `!gender F`');
return;
}
await cu.setGender(genderString);
await discordMessage.channel.send(`Gender changed to ${genderString}.`);
}
async function MakeOneServerVoteOption(channel, serverName, battlemetricsLink, peakRank) {
//const text = `__**${serverName}**__\n${battlemetricsLink}\n_Peak rank #${peakRank} ★ ${playerDensity} players / sq km ★ ${bpWipe}_`;
const text = `__**${serverName}**__\n${battlemetricsLink}\n_Peak rank #${peakRank}_`;
const message = await channel.send(text);
await message.react('✅');
}
async function HandleServerVoteCommand(discordMessage) {
const author = await UserCache.GetCachedUserByDiscordId(discordMessage.author.id);
if (!author || author.commissar_id !== 7) {
// Auth: this command for developer use only.
return;
}
const guild = await DiscordUtil.GetMainDiscordGuild();
const channel = await guild.channels.create({ name: 'server-vote' });
const message = await channel.send('The Government will play on whichever server gets the most votes. This will be our home Rust server for January 2025.');
await message.react('❤️');
await MakeOneServerVoteOption(channel, 'Rustopia US Large', 'https://www.battlemetrics.com/servers/rust/14876729', 15);
await MakeOneServerVoteOption(channel, 'Rustafied.com - US Long III', 'https://www.battlemetrics.com/servers/rust/433754', 11);
await MakeOneServerVoteOption(channel, 'Rustafied.com - US Long II', 'https://www.battlemetrics.com/servers/rust/2036399', 144);
await MakeOneServerVoteOption(channel, 'Rustafied.com - US Long', 'https://www.battlemetrics.com/servers/rust/1477148', 88);
await MakeOneServerVoteOption(channel, 'Rusty Moose |US Monthly|', 'https://www.battlemetrics.com/servers/rust/9611162', 5);
await MakeOneServerVoteOption(channel, 'Reddit.com/r/PlayRust - US Monthly', 'https://www.battlemetrics.com/servers/rust/3345988', 26);
await MakeOneServerVoteOption(channel, 'Rusty Moose |US Small|', 'https://www.battlemetrics.com/servers/rust/2933470', 34);
await MakeOneServerVoteOption(channel, 'PICKLE VANILLA MONTHLY', 'https://www.battlemetrics.com/servers/rust/4403307', 91);
await MakeOneServerVoteOption(channel, 'Rustopia.gg - US Small', 'https://www.battlemetrics.com/servers/rust/14876730', 108);
await MakeOneServerVoteOption(channel, 'Rustoria.co - US Long', 'https://www.battlemetrics.com/servers/rust/9594576', 2);
}
async function MakeOnePresidentVoteOption(channel, playerName) {
const text = `**${playerName}**`;
const message = await channel.send(text);
await message.react('✅');
}
async function HandlePresidentVoteCommand(discordMessage) {
const author = await UserCache.GetCachedUserByDiscordId(discordMessage.author.id);
if (!author || author.commissar_id !== 7) {
// Auth: this command for developer use only.
return;
}
const guild = await DiscordUtil.GetMainDiscordGuild();
const channel = await guild.channels.create({
name: 'presidential-erection',
type: 0,
});
const message = await channel.send('Whoever gets the most votes will be Mr. or Madam President in October 2024.');
await message.react('❤️');
const generalRankUsers = await UserCache.GetTopRankedUsers(20);
const candidateNames = [];
for (const user of generalRankUsers) {
if (user.commissar_id === 7) {
continue;
}
const name = user.getNicknameOrTitleWithInsignia();
candidateNames.push(name);
}
for (const name of candidateNames) {
await MakeOnePresidentVoteOption(channel, name);
}
}
async function HandleHypeCommand(discordMessage) {
const author = await UserCache.GetCachedUserByDiscordId(discordMessage.author.id);
if (!author || author.commissar_id !== 7) {
// Auth: this command for developer use only.
return;
}
const guild = await DiscordUtil.GetMainDiscordGuild();
const channel = await guild.channels.create({ name: 'hype' });
let message;
message = await channel.send(
`__**Wipe Hype!**__\n` +
`Mr. President needs a show of hands for Wipe Day, for planning purposes. It's not a commitment. Try your best to guess and if you can't make it day-of that is OK.\n\n` +
`Click ⌛ if you think you'll be on the minute of the wipe`);
await message.react('⌛');
message = await channel.send(
`Click 🔆 if you think you will be there wipe day, but not the minute of the wipe`);
await message.react('🔆');
message = await channel.send(
`Click 📅 if you might get on wipe week, but not wipe day`);
await message.react('📅');
const voteSectionId = '1043778293612163133';
await channel.setParent(voteSectionId);
}
async function HandlePrivateRoomVoteCommand(discordMessage) {
const author = await UserCache.GetCachedUserByDiscordId(discordMessage.author.id);
if (!author || author.commissar_id !== 7) {
// Auth: this command for developer use only.
return;
}
const guild = await DiscordUtil.GetMainDiscordGuild();
const channel = await guild.channels.create({ name: 'vote-on-gov-future' });
const message = await channel.send(
`__**Vote on the Future of the Government Community**__\n` +
`Should we keep the microcommunities, the 3 digit barcodes, and the New Guy Demotion that slows down new recruits from ranking up too quickly?\n\n` +
`The hierarchical ranks are obsolete, but they were not in vain. We needed to explore that direction to discover the concept of microcommunities that we are voting on now.\n\n` +
`The ranks we have now are almost identical to the original ones that reigned from March 2021 to March 2024. This vote is not primarily about the ranks after all. This vote is about whether to keep the microcommunities, the 3 digit barcodes, and the New Guy Demotion that slows down new recruits from ranking up too quickly.\n\n` +
`Vote YES to keep things how they are now\n\n` +
`Vote NO to go back to how everything was in March\n\n` +
`The vote ends May 30, 2024. All Generals past & present can vote.`);
await message.react('✅');
await message.react('❌');
const voteSectionId = '1043778293612163133';
await channel.setParent(voteSectionId);
}
function GenerateAkaStringForUser(cu) {
const peakRank = cu.peak_rank || 24;
const peakRankInsignia = RankMetadata[peakRank].insignia;
const names = [
cu.steam_name,
cu.nick,
cu.nickname,
cu.steam_id,
cu.discord_id,
peakRankInsignia,
];
const filteredNames = [];
for (const name of names) {
if (name && name.length > 0) {
filteredNames.push(name);
}
}
const joined = filteredNames.join(' / ');
return joined;
}
async function HandleAmnestyCommand(discordMessage) {
const author = await UserCache.GetCachedUserByDiscordId(discordMessage.author.id);
if (!author || author.commissar_id !== 7) {
// Auth: this command for developer use only.
return;
}
await discordMessage.channel.send(`The Generals have voted to unban the following individuals from The Government:`);
let unbanCountForGov = 0;
await UserCache.ForEach(async (cu) => {
if (!cu.good_standing && !cu.ban_vote_start_time && !cu.ban_pardon_time) {
await cu.setGoodStanding(true);
await cu.setBanVoteStartTime(null);
await cu.setBanVoteChatroom(null);
await cu.setBanVoteMessage(null);
await cu.setBanConvictionTime(null);
await cu.setBanPardonTime(null);
const aka = GenerateAkaStringForUser(cu);
await discordMessage.channel.send(`Unbanned ${aka}`);
await Sleep(1000);
unbanCountForGov++;
}
});
const guild = await DiscordUtil.GetMainDiscordGuild();
const bans = await guild.bans.fetch();
let unbanCountForDiscord = 0;
for (const [banId, ban] of bans) {
const discordId = ban.user.id;
if (!discordId) {
continue;
}
const cu = await UserCache.GetCachedUserByDiscordId(discordId);
if (!cu) {
continue;
}
if (!cu.ban_pardon_time) {
await guild.bans.remove(discordId);
const aka = GenerateAkaStringForUser(cu);
await discordMessage.channel.send(`Unbanned ${aka}`);
await Sleep(1000);
unbanCountForDiscord++;
}
}
await discordMessage.channel.send(`${unbanCountForGov} gov users unbanned`);
await discordMessage.channel.send(`${unbanCountForDiscord} discord users unbanned`);
const total = unbanCountForGov + unbanCountForDiscord;
await discordMessage.channel.send(`These ${total} bans have been pardoned by order of the Generals`);
}
async function HandleVoiceActiveUsersCommand(discordMessage) {
const tokens = discordMessage.content.split(' ');
if (tokens.length != 2) {
await discordMessage.channel.send('Invalid arguments.\nUSAGE: !activeusers daysToLookback');
return;
}
const daysToLookbackAsText = tokens[1];
if (isNaN(daysToLookbackAsText)) {
await discordMessage.channel.send('Invalid arguments.\nUSAGE: !voiceactiveusers daysToLookback');
return;
}
const daysToLookback = parseInt(daysToLookbackAsText);
const voiceActiveUsers = UserCache.CountVoiceActiveUsers(daysToLookback);
await discordMessage.channel.send(`${voiceActiveUsers} users active in voice chat in the last ${daysToLookback} days.`);
}
async function SendOrdersToOneCommissarUser(user, discordMessage) {
const guild = await DiscordUtil.GetMainDiscordGuild();
const discordMember = await guild.members.fetch(user.discord_id);
if (discordMember.user.bot) {
return;
}
const name = user.getNicknameOrTitleWithInsignia();
await discordMessage.channel.send(`Sending orders to ${name}`);
const rankNameAndInsignia = user.getRankNameAndInsignia();
let content = `${rankNameAndInsignia},\n\n`;
content += `We are playing on Rustopia.gg - US Large\n\n`;
content += `client.connect USLarge.Rustopia.gg\n\n`;
if (user.rank <= 21) {
content += `The build spot is F24 - F26.\n\n`;
content += `**New in 2025**\n`;
content += `You have your own voice channel in The Government. Add your homies with\n\n`;
content += '```!friend @name```\n\n';
content += `Kick out whoever you want instantly\n\n`;
content += '```!unfriend @name```\n\n';
content += `You control who can join your private channel. The rest of the gov can see who's in there but cannot join unless you !friend them.\n\n`;
content += `Ever wanted to start your own gov? Now it's easy. Play a Trio server while gaining rank points. Use it to play other games. Host a D&D night. Kick back with your quad when the public channel gets too busy. Get some privacy for your raid. The private channels will help the gov to absorb new groups and retain groups of old members by offering them some peace and quiet when they need.\n\n`;
}
if (user.rank <= 19) {
content += `There will be an officers-only base at the build spot. This message is the only way to get the code. Many will choose to live in the officers base for the whole wipe. If you do make your own base, you can still come in and use the T3 but please no longer access the loot boxes. The loot in the base is owned by everyone who lives there and has no other base. When you build your own base you can take anything that you brought into the officers base with you. If you get raided and are homeless then you automatically regain access to the officers base loot. Please help spread the word about this new system which replaces the old community base system of take-anything-you-want. That old rule was easy to enforce because there's nothing to enforce, but it was a big mistake since there was no respect for loot. This new system of respecting the officers' shared loot has proven successful over the last 3 months so ignore the naysayers. The officers base will be stacked to the rafters all wipe long. We have a bag for so come join us!\n\n`;
content += `Officers code 0444\n\n`;
}
if (user.rank <= 15) {
content += `Generals code 7800\n\n`;
}
console.log('content.length', content.length);
try {
await discordMember.send({
content,
//files: [{
//attachment: 'president-vote.png',
//name: 'president-vote.png'
//}]
});
} catch (error) {
console.log('Failed to send orders to', name);
console.log(error);
}
}
async function SendOrdersToTheseCommissarUsers(users, discordMessage) {
await discordMessage.channel.send(`Sending orders to ${users.length} members. Restart the bot now if this is not right.`);
await Sleep(1 * 1000);
for (const user of users) {
if (!user) {
continue;
}
await SendOrdersToOneCommissarUser(user, discordMessage);
await Sleep(5 * 1000);
}
}
async function HandleOrdersTestCommand(discordMessage) {
const author = await UserCache.GetCachedUserByDiscordId(discordMessage.author.id);
if (!author || author.commissar_id !== 7) {
// Auth: this command for developer use only.
return;
}
const jeff = await UserCache.GetCachedUserByDiscordId('268593188137074688');
await SpamInactiveRetiredGeneral(jeff, discordMessage);
}
async function HandleOrdersCommand(discordMessage) {
const author = await UserCache.GetCachedUserByDiscordId(discordMessage.author.id);
if (!author || author.commissar_id !== 7) {
// Auth: this command for developer use only.
return;
}
const tokens = discordMessage.content.split(' ');
if (tokens.length != 2) {
await discordMessage.channel.send('Invalid arguments.\nUSAGE: !orders daysToLookback');
return;
}
const daysToLookbackAsText = tokens[1];
if (isNaN(daysToLookbackAsText)) {
await discordMessage.channel.send('Invalid arguments.\nUSAGE: !orders daysToLookback');
return;
}
const daysToLookback = parseFloat(daysToLookbackAsText);
const recentActiveUsers = UserCache.GetUsersSortedByLastSeen(daysToLookback);
await SendOrdersToTheseCommissarUsers(recentActiveUsers, discordMessage);
}
async function SpamInactiveRetiredGeneral(user, discordMessage) {
if (!user.citizen) {
return;
}
const guild = await DiscordUtil.GetMainDiscordGuild();
const discordMember = await guild.members.fetch(user.discord_id);
if (!discordMember) {
return;
}
if (discordMember.user.bot) {
return;
}
const name = user.getNicknameOrTitleWithInsignia();
await discordMessage.channel.send(`Sending spam to inactive retired General ${name}`);
let content = '**I need your help.**\n';
content += 'Please vote in the new https://discord.com/channels/305840605328703500/1299963218265116753 . You would be doing me a huge favor.\n\n';
content += 'Hello, old friend. I hope you are doing well wherever you are. I sent you this message because you were a General. I am reaching out to you with this one-time message to let you know about something truly special. Every statistic that I can see suggests that this Nov 7 wipe day may be the biggest in gov history. We are moving to a more relaxed Rust server (Pickle) after years playing exclusively on top-10 Vanilla servers. Pickle can fit 50 players on a green dot team, so there is always room for you. 20 Officers & Generals will be sharing one big base together to chain-raid 24/7 in shifts. The village will surround the big bases. All of these factors mean that if you were ever thinking of reactivating for a good ol gov wipe, this Nov 7 is the best opportunity in years.\n\n';
content += `Either way, please vote in the #president-vote. The whole cycle is now 100% automated. All ranks can vote. That's 1000 voters. The Government is the largest democracy on the internet. I want you to vote for one of the options to make the total vote count go up. Thank you, friend.\n\n`;
content += 'Jeff <3';
try {
await discordMember.send({
content,
files: [{
attachment: 'president-vote.png',
name: 'president-vote.png'
}]
});
} catch (error) {
console.log('Failed to send orders to', name);
}
}
async function HandleSpamInactiveRetiredGeneralsCommand(discordMessage) {
const author = await UserCache.GetCachedUserByDiscordId(discordMessage.author.id);
if (!author || author.commissar_id !== 7) {
// Auth: this command for developer use only.
return;
}
const users = UserCache.GetAllUsersAsFlatList();
const inactiveRetiredGenerals = [];
for (const user of users) {
if (user.peak_rank > 15) {
continue;
}
if (!user.last_seen) {
continue;
}
const lastSeen = moment(user.last_seen);
const recent = moment().subtract(14, 'days');
if (lastSeen.isAfter(recent)) {
continue;
}
inactiveRetiredGenerals.push(user);
}
console.log('Inactive retired generals:', inactiveRetiredGenerals.length);
for (const user of inactiveRetiredGenerals) {
await SpamInactiveRetiredGeneral(user, discordMessage);
await Sleep(5000);
}
}
async function HandleBadgeCommand(discordMessage) {
const authorMember = discordMessage.member;
const authorUser = await UserCache.GetCachedUserByDiscordId(authorMember.id);
if (!authorUser) {
return;
}
const authorName = authorUser.getNicknameOrTitleWithInsignia();
const tokens = discordMessage.content.split(' ');
if (tokens.length !== 4) {
await discordMessage.channel.send('Invalid arguments. USAGE: !badge give Berry @nickname');
return;
}
const roleName = tokens[2];
if (roleName.length <= 1) {
await discordMessage.channel.send('Invalid role name ' + roleName);
return;
}
const juniorRoleName = roleName + ' Badge';
const seniorRoleName = roleName + ' Committee';
const juniorRole = await DiscordUtil.GetRoleByName(discordMessage.guild, juniorRoleName);
if (!juniorRole) {
await discordMessage.channel.send('No such role ' + juniorRoleName);
return;
}
const seniorRole = await DiscordUtil.GetRoleByName(discordMessage.guild, seniorRoleName);
if (!seniorRole) {
await discordMessage.channel.send('No such role ' + seniorRoleName);
return;
}
const has = await DiscordUtil.GuildMemberHasRole(discordMessage.member, seniorRole);
if (!has) {
await discordMessage.channel.send(`Only ${seniorRoleName} members can do that.`);
return;
}
const mentionedMember = await DiscordUtil.ParseExactlyOneMentionedDiscordMember(discordMessage);
if (!mentionedMember) {
await discordMessage.channel.send(`Couldn't find that member. They might have left the Discord guild. Have them re-join then try again.`);
return;
}
if (tokens[1] === 'give') {
if (!mentionedMember) {
await discordMessage.channel.send('Invalid arguments. USAGE: !badge give Berry @nickname');
return;
}
const hasJunior = await DiscordUtil.GuildMemberHasRole(mentionedMember, juniorRole);
const hasSenior = await DiscordUtil.GuildMemberHasRole(mentionedMember, seniorRole);
if (hasJunior || hasSenior) {
await discordMessage.channel.send(`That person already has their ${juniorRoleName}.`);
return;
}
const mentionedCommissarUser = await UserCache.GetCachedUserByDiscordId(mentionedMember.id);
if (!mentionedCommissarUser) {
await discordMessage.channel.send('Cannot find mentioned member in the database. Something must be badly fucked up!');
return;
}
await DiscordUtil.AddRole(mentionedMember, juniorRole);
const name = mentionedCommissarUser.getNicknameOrTitleWithInsignia();
await discordMessage.channel.send(`${name} has been awarded the ${juniorRoleName} by ${authorName}`);
} else if (tokens[1] === 'remove') {
if (!mentionedMember) {
await discordMessage.channel.send('Invalid arguments. USAGE: !badge remove Berry @nickname');
return;
}
const hasJunior = await DiscordUtil.GuildMemberHasRole(mentionedMember, juniorRole);
if (!hasJunior) {
await discordMessage.channel.send(`That person does not have the ${juniorRoleName}. Cannot remove.`);
return;
}
const mentionedCommissarUser = await UserCache.GetCachedUserByDiscordId(mentionedMember.id);
if (!mentionedCommissarUser) {
await discordMessage.channel.send('Cannot find mentioned member in the database. Something must be badly fucked up!');
return;
}
await DiscordUtil.RemoveRole(mentionedMember, juniorRole);
const name = mentionedCommissarUser.getNicknameOrTitleWithInsignia();
await discordMessage.channel.send(`${juniorRoleName} has been removed from ${name} by ${authorName}`);
} else if (tokens[1] === 'color') {
const colorCode = tokens[3];
if (colorCode.length !== 6) {
await discordMessage.channel.send('Invalid arguments. USAGE: !badge color Berry AB0B23');
return;
}
await juniorRole.setColor(colorCode);
await seniorRole.setColor(colorCode);
await discordMessage.channel.send(`Badge color updated successfully.`);
}
}
async function HandleCommitteeCommand(discordMessage) {
console.log('!committee command detected.');
const authorMember = discordMessage.member;
const authorUser = await UserCache.GetCachedUserByDiscordId(authorMember.id);
if (!authorUser) {
return;
}
const authorName = authorUser.getNicknameOrTitleWithInsignia();
const tokens = discordMessage.content.split(' ');
if (tokens.length !== 4) {
await discordMessage.channel.send('Invalid arguments. USAGE: !committee give Berry @nickname');
return;
}
if (tokens[2].length <= 1) {
await discordMessage.channel.send('Invalid role name ' + tokens[2]);
return;
}
const roleName = tokens[2] + ' Committee';
console.log('roleName', roleName);
const role = await DiscordUtil.GetRoleByName(discordMessage.guild, roleName);
if (!role) {
console.log('No such role', roleName);
await discordMessage.channel.send('No such role ' + roleName);
return;
}
const has = await DiscordUtil.GuildMemberHasRole(authorMember, role);
if (!has) {
console.log(`Only ${roleName} members can do that.`);
await discordMessage.channel.send(`Only ${roleName} members can do that.`);
return;
}
const mentionedMember = await DiscordUtil.ParseExactlyOneMentionedDiscordMember(discordMessage);
console.log('tokens[1]', tokens[1]);
if (tokens[1] === 'give') {
console.log('give');
if (!mentionedMember) {
await discordMessage.channel.send('Invalid arguments. USAGE: !committee give Berry @nickname');
return;
}
const hasRole = await DiscordUtil.GuildMemberHasRole(mentionedMember, role);
if (hasRole) {
console.log(`That person is already on the ${roleName}.`);
await discordMessage.channel.send(`That person is already on the ${roleName}.`);
return;
}
const mentionedCommissarUser = await UserCache.GetCachedUserByDiscordId(mentionedMember.id);
if (!mentionedCommissarUser) {
await discordMessage.channel.send('Cannot find mentioned member in the database. Something must be badly fucked up!');
return;
}
await DiscordUtil.AddRole(mentionedMember, role);
const name = mentionedCommissarUser.getNicknameOrTitleWithInsignia();
await discordMessage.channel.send(`${name} has been added to the ${roleName} by ${authorName}`);
} else if (tokens[1] === 'remove') {
console.log('remove');
if (!mentionedMember) {
await discordMessage.channel.send('Invalid arguments. USAGE: !committee remove Berry @nickname');
return;
}
const hasRole = await DiscordUtil.GuildMemberHasRole(mentionedMember, role);
if (!hasRole) {
await discordMessage.channel.send(`That person is not on the ${roleName}. Cannot remove.`);
return;
}
const mentionedCommissarUser = await UserCache.GetCachedUserByDiscordId(mentionedMember.id);
if (!mentionedCommissarUser) {
await discordMessage.channel.send('Cannot find mentioned member in the database. Something must be badly fucked up!');
return;
}
await DiscordUtil.RemoveRole(mentionedMember, role);
const name = mentionedCommissarUser.getNicknameOrTitleWithInsignia();
await discordMessage.channel.send(`${roleName} has been removed from ${name} by ${authorName}`);
} else if (tokens[1] === 'color') {
const colorCode = tokens[3];
if (colorCode.length !== 6) {
await discordMessage.channel.send('Invalid arguments. USAGE: !committee color Berry AB0B23');
return;
}
await role.setColor(colorCode);
await discordMessage.channel.send(`Badge color updated successfully.`);
} else {
await discordMessage.channel.send(`Invalid command !committee`, tokens[1], '. Options are [give|remove|color].');
}
}
async function HandleNickCommand(discordMessage) {
const tokens = discordMessage.content.split(' ');
if (tokens.length < 2) {
await discordMessage.channel.send(`ERROR: wrong number of arguments. USAGE: !nick NewNicknam3`);
return;
}
const raw = discordMessage.content.substring(6);
const filtered = FilterUsername(raw);
if (filtered.length === 0) {
await discordMessage.channel.send(`ERROR: no weird nicknames.`);
return;
}
const discordId = discordMessage.author.id;
const cu = await UserCache.GetCachedUserByDiscordId(discordId);
await cu.setNick(filtered);
const newName = cu.getNicknameOrTitleWithInsignia();
await discordMessage.channel.send(`Changed name to ${newName}`);
}
// Do as if the user just joined the discord. For manually resolving people who
// occasionally fall through the cracks of the automated onboarding process.
async function HandleBoopCommand(discordMessage) {
const tokens = discordMessage.content.split(' ');
if (tokens.length < 2) {
await discordMessage.channel.send(`ERROR: wrong number of arguments. USAGE: !nick NewNicknam3`);
return;
}
const mentionedMember = await DiscordUtil.ParseExactlyOneMentionedDiscordMember(discordMessage);
if (!mentionedMember) {
await discordMessage.channel.send(`ERROR: must mention a member to boop. Example: !boop @Jeff`);
return;
}
const cu = await UserCache.GetCachedUserByDiscordId(mentionedMember.id);
if (cu) {
await cu.setCitizen(true);
await discordMessage.channel.send(`Member already exists.`);
} else {
// We have no record of this Discord user. Create a new record in the cache.
console.log('New Discord user detected.');
await UserCache.CreateNewDatabaseUser(mentionedMember);
await discordMessage.channel.send(`Successfully booped.`);
}
}
// Removes any office that the mentioned user has.
async function HandleImpeachCommand(discordMessage) {
const author = await UserCache.GetCachedUserByDiscordId(discordMessage.author.id);
if (!author || author.commissar_id !== 7) {
// Auth: this command for developer use only.
return;
}
const mentionedMember = await DiscordUtil.ParseExactlyOneMentionedDiscordMember(discordMessage);
if (!mentionedMember) {
await discordMessage.channel.send(`ERROR: who to impeach? Example: !impeach @Jeff`);
return;
}
const cu = await UserCache.GetCachedUserByDiscordId(mentionedMember.id);
if (!cu) {
await discordMessage.channel.send(`No user record for that discord member.`);
}
await cu.setOffice(null);
const name = cu.getNicknameOrTitleWithInsignia();
await discordMessage.channel.send(`Impeached ${name}`);
}
// Appoints the mentioned member as Mr. President
async function HandlePrezCommand(discordMessage) {
const author = await UserCache.GetCachedUserByDiscordId(discordMessage.author.id);
if (!author || author.commissar_id !== 7) {
// Auth: this command for developer use only.
return;
}
const mentionedMember = await DiscordUtil.ParseExactlyOneMentionedDiscordMember(discordMessage);
if (!mentionedMember) {
await discordMessage.channel.send(`ERROR: who to appoint? Example: !prez @Jeff`);
return;
}
const cu = await UserCache.GetCachedUserByDiscordId(mentionedMember.id);
if (!cu) {
await discordMessage.channel.send(`No user record for that discord member.`);
}
const name = cu.getNicknameOrTitleWithInsignia();
await cu.setOffice('PREZ');
await discordMessage.channel.send(`${name} is now President`);
}
// Appoints the mentioned member as Mr. Vice President
async function HandleVeepCommand(discordMessage) {
const author = await UserCache.GetCachedUserByDiscordId(discordMessage.author.id);
if (!author || author.commissar_id !== 7) {
// Auth: this command for developer use only.
return;
}
const mentionedMember = await DiscordUtil.ParseExactlyOneMentionedDiscordMember(discordMessage);
if (!mentionedMember) {
await discordMessage.channel.send(`ERROR: who to appoint? Example: !veep @Jeff`);
return;
}
const cu = await UserCache.GetCachedUserByDiscordId(mentionedMember.id);
if (!cu) {
await discordMessage.channel.send(`No user record for that discord member.`);
}
const name = cu.getNicknameOrTitleWithInsignia();
await cu.setOffice('VEEP');
await discordMessage.channel.send(`${name} is now Vice President`);
}
async function HandleTranscriptCommand(discordMessage) {
const author = await UserCache.GetCachedUserByDiscordId(discordMessage.author.id);
if (!author || author.commissar_id !== 7) {
// Auth: this command for developer use only.
return;
}
const fromChannel = discordMessage.channel;
const attachment = await discordTranscripts.createTranscript(fromChannel);
const toChannel = discordMessage.guild.channels.resolve('1110429964580433920');
await toChannel.send({
files: [attachment],
});
}
const sentToAFkTimes = {};
async function HandleAfkCommand(discordMessage) {
const authorId = discordMessage.author.id;
const author = await UserCache.GetCachedUserByDiscordId(authorId);
if (!author || author.rank > 15) {
await discordMessage.channel.send(
`Error: Only generals can do that.`
)
return
}
const mentionedMember = await DiscordUtil.ParseExactlyOneMentionedDiscordMember(discordMessage);
if (!mentionedMember) {
await discordMessage.channel.send(
'Error: `!afk` only one person can be sent to afk at a time.\n' +
'Example: `!afk @nickname`\n'
);
return;
}
const memberSentTime = sentToAFkTimes[mentionedMember.id] || 0;
const diff = Math.abs(new Date().getTime() - memberSentTime);
const minutesSinceSentToAfk = Math.floor((diff/1000)/60);
if (minutesSinceSentToAfk < 30) {
await discordMessage.channel.send(
`${mentionedMember.nickname} cannot be sent to idle lounge more than once every 30 minutes.`
);
return;
}
try {
await DiscordUtil.moveMemberToAfk(mentionedMember);
} catch(e) {
// Note: Error code for member not in voice channel.
if (e.code === 40032) {
await discordMessage.channel.send(
`${mentionedMember.nickname} is not in a voice channel, cannot be sent to idle lounge.`
);
return;
}
throw new Error(e);
} finally {
sentToAFkTimes[mentionedMember.id] = new Date().getTime();
}
}
function ChooseRandomTrumpCard() {
const n = 32;
const r = Math.floor(n * Math.random());
return `trump-cards/${r}.png`;
}
let trumpNftPrice = null;
const buyQueue = [];
const sellQueue = [];
function LoadPrice() {
if (trumpNftPrice === null) {
const trumpPriceAsString = fs.readFileSync('trump-price.csv');
trumpNftPrice = parseInt(trumpPriceAsString);
}
}
function SavePrice() {
LoadPrice();
fs.writeFileSync('trump-price.csv', trumpNftPrice.toString());
}
function IncreasePrice() {
LoadPrice();
if (trumpNftPrice < 99) {
trumpNftPrice++;
}
SavePrice();
}
function DecreasePrice() {
LoadPrice();
if (trumpNftPrice > 1) {
trumpNftPrice--;
}
SavePrice();
}
async function HandleBuyCommand(discordMessage) {
buyQueue.push(discordMessage);
}
async function FulfillBuyOrder(discordMessage) {
LoadPrice();
if (trumpNftPrice > 99) {
await discordMessage.channel.send('Cannot buy when the price is maxed out to 100. Wait for someone to sell then try again.');
return;
}
const author = await UserCache.GetCachedUserByDiscordId(discordMessage.author.id);
if (!author) {
return;
}
const oldYen = author.yen || 0;
const oldCards = author.trump_cards || 0;
console.log('oldCards', oldCards);
const tradePrice = trumpNftPrice;
const name = author.getNicknameOrTitleWithInsignia();
let actionMessage = `${name} purchased this one-of-a-kind Donald Trump NFT for ${tradePrice} yen`;
let newYen = oldYen - tradePrice;
if (oldCards < 0) {
newYen += 100;
actionMessage += ' and got back their 100 yen deposit';
}
const newCards = oldCards + 1;
if (newYen >= 0) {
IncreasePrice();
await author.setYen(newYen);
await author.setTrumpCards(newCards);
} else {
await discordMessage.channel.send('Not enough yen. Use !yen to check how much money you have.');
return;
}
const prefixes = [
'The probability that Donald Trump will win the 2024 US presidential election is',
'The odds that Trump will win are',
'The probability of a Trump win is',
];
const r = Math.floor(prefixes.length * Math.random());
const randomPrefix = prefixes[r];
const probabilityAnnouncement = `${randomPrefix} ${trumpNftPrice}%`;
let positionStatement;
const plural = Math.abs(newCards) !== 1 ? 's' : '';
if (newCards > 0) {
const positivePayout = newCards * 100;
positionStatement = `They have ${newCards} NFT${plural} that will pay out ${positivePayout} yen if Trump wins`;
} else if (newCards < 0) {
const negativePayout = -newCards * 100;
positionStatement = `They are short ${-newCards} more NFT${plural} that will pay out ${negativePayout} yen if Trump does not win`;
} else {
positionStatement = 'They have no NFTs left';
}
let content = '```' + `${actionMessage}. ${positionStatement}. ${probabilityAnnouncement}` + '```';
const trumpCard = ChooseRandomTrumpCard();
try {
await discordMessage.channel.send({
content,
files: [{
attachment: trumpCard,
name: trumpCard,
}]
});
} catch (error) {
console.log(error);
}
await UpdateTrumpChannel(trumpCard, probabilityAnnouncement);
await yen.UpdateYenChannel();
}
async function HandleSellCommand(discordMessage) {
sellQueue.push(discordMessage);
}
async function FulfillSellOrder(discordMessage) {
LoadPrice();
if (trumpNftPrice < 2) {
await discordMessage.channel.send('Cannot sell when the price is bottomed out to 1. Wait for someone to buy then try again.');
return;
}
const author = await UserCache.GetCachedUserByDiscordId(discordMessage.author.id);
if (!author) {
return;
}
const oldYen = author.yen || 0;
const oldCards = author.trump_cards || 0;
const tradePrice = trumpNftPrice - 1;
const name = author.getNicknameOrTitleWithInsignia();
let actionMessage = `${name} sold this Donald Trump NFT for ${tradePrice} yen`;
let newYen = oldYen + tradePrice;
const newCards = oldCards - 1;
if (newCards < 0) {
newYen -= 100;
actionMessage = `${name} deposited 100 yen to mint a new Donald Trump NFT then sold it for ${tradePrice} yen`;
}
if (newYen >= 0) {
DecreasePrice();
await author.setYen(newYen);
await author.setTrumpCards(newCards);
} else {
await discordMessage.channel.send('Not enough yen to short-sell. Use !yen to check how much money you have.');
return;
}
const prefixes = [
'The probability that Donald Trump will win the 2024 US presidential election is',
'The odds that Trump will win are',
'The probability of a Trump win is',
];
const r = Math.floor(prefixes.length * Math.random());
const randomPrefix = prefixes[r];
const probabilityAnnouncement = `${randomPrefix} ${trumpNftPrice}%`;
let positionStatement;
const plural = Math.abs(newCards) !== 1 ? 's' : '';
if (newCards > 0) {
const positivePayout = newCards * 100;
positionStatement = `They have ${newCards} NFT${plural} left that will pay out ${positivePayout} yen if Trump wins`;
} else if (newCards < 0) {
const negativePayout = -newCards * 100;
positionStatement = `They are short ${-newCards} NFT${plural} that will pay out ${negativePayout} yen if Trump does not win`;
} else {
positionStatement = 'They have no NFTs left';
}
let content = '```' + `${actionMessage}. ${positionStatement}. ${probabilityAnnouncement}` + '```';
const trumpCard = ChooseRandomTrumpCard();
try {
await discordMessage.channel.send({
content,
files: [{
attachment: trumpCard,
name: trumpCard,
}]
});
} catch (error) {
console.log(error);
}
await UpdateTrumpChannel(trumpCard, probabilityAnnouncement);
await yen.UpdateYenChannel();
}
async function UpdateTrumpChannel(trumpCard, probabilityAnnouncement) {
const guild = await DiscordUtil.GetMainDiscordGuild();
const channel = await guild.channels.fetch('1267202328243732480');
let message = '```' + probabilityAnnouncement + '\n\n';
if (trumpNftPrice < 100) {
message += `!buy a Donald Trump NFT for ${trumpNftPrice} yen\n`;
}
if (trumpNftPrice > 1) {
const sellPrice = trumpNftPrice - 1;
message += `!sell a Donald Trump NFT for ${sellPrice} yen\n`;
}
message += '\n';
message += 'Every Donald Trump NFT pays out 100 yen if Donald Trump is declared the winner of the 2024 US presidential election by the Associated Press. Short-selling is allowed. If you believe that Trump will win then !buy. If you believe that he will not win then !sell.\n\n';
message += '!buy low !sell high. It\'s just business. Personal politics aside, if the price does not reflect the true probability, then consider a !buy or !sell. See a news event that is not priced in yet? Quickly !buy or !sell to profit from being the first to bring new information to market.\n\n';
message += 'Do you believe that one or both sides suffer from bias? Here is your chance to fine a random idiot from the internet for disagreeing with you. Make them pay!';
message += '```';
await channel.bulkDelete(99);
await channel.send({
content: message,
files: [{
attachment: trumpCard,
name: trumpCard,
}]
});
const users = UserCache.GetAllUsersAsFlatList();
const long = [];
const short = [];
for (const user of users) {
if (!user.trump_cards) {
continue;
}
if (user.trump_cards > 0) {
long.push(user);
}
if (user.trump_cards < 0) {
short.push(user);
}
}
long.sort((a, b) => (b.trump_cards - a.trump_cards));
const longLines = [
'If Trump wins',
'-------------',
];
for (const user of long) {
const name = user.getNicknameOrTitleWithInsignia();
const payout = user.trump_cards * 100;
longLines.push(`${name} collects ${payout} yen`);
}
await DiscordUtil.SendLongList(longLines, channel);
short.sort((a, b) => (a.trump_cards - b.trump_cards));
const shortLines = [
'If Trump does not win',
'---------------------',
];
for (const user of short) {
const name = user.getNicknameOrTitleWithInsignia();
const payout = -user.trump_cards * 100;
shortLines.push(`${name} collects ${payout} yen`);
}
await DiscordUtil.SendLongList(shortLines, channel);
}