This repository has been archived by the owner on Jun 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.js
2053 lines (1694 loc) · 96.9 KB
/
bot.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
require('dotenv').config();
// MODULES ----------------------------------------------------------------------------
/** Discord.JS */
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { Client, Permissions, Intents, ThreadChannel, DiscordAPIError, MessageEmbed } = require('discord.js');
const client = new Client({ intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_VOICE_STATES,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_PRESENCES
] });
/** Chance.JS */
const Chance = require('chance');
const chance = new Chance();
/* Node-fetch */
const fetch = require('node-fetch');
// FILES ------------------------------------------------------------------------------
const config = require('./json/config.json');
// COMMANDS ---------------------------------------------------------------------------
const commands = [
{ // Send
name: 'send',
description: 'Sends ඞmoney to the user you @. This action is irreversible.',
options: [
{ type: 6, name: 'recipient', description: 'The user to send your ඞmoney to.', required: true },
{ type: 4, name: 'amount', description: 'The amount to send', required: true }
]
},
{ // Leaderboard
name: 'leaderboard',
description: 'Displays a leaderboard of the top users in the server.',
},
{ // lb (same as leaderboard)
name: 'lb',
description: 'Displays a leaderboard of the top users in the server.',
},
{ // Inventory
name: 'inventory',
description: 'Check the items in your inventory'
},
{ // Account
name: 'account',
description: 'Create or check your account information',
options: [
{
name: 'create',
description: 'Create a new Mingleton RPG account with ඞ100.',
type: 1
},
{
name: 'view',
description: 'Take a look at someone\'s account!',
type: 1,
options: [
{ type: 6, name: 'player', description: 'The player to look up.', required: false }
]
}
]
},
{ // Factions
name: 'faction',
description: 'Create or join a faction',
options: [
{
name: 'create',
description: 'Creates a new faction',
type: 1,
options: [
{ type: 3, name: 'name', description: 'The name of your new faction.', required: true },
{ type: 3, name: 'emoji', description: 'Your faction\'s special emoji.', required: true }
]
},
{
name: 'view',
description: 'See information about a faction \'f-<faction name>\'',
type: 1,
options: [
{ type: 8, name: 'faction', description: 'The faction to view.', required: true }
]
},
{
name: 'invite',
description: 'Invite a new member to your faction',
type: 1,
options: [
{ type: 6, name: 'player', description: 'The player to invite.', required: true }
]
},
{
name: 'leave',
description: 'Leave the faction you\'re currently in',
type: 1,
}
]
},
{ // Help
name: 'help',
description: 'Get help on a particular subject',
options: [
{
name: 'rarity',
description: 'Find out what rarities are and how they affect your items',
type: 1
},
{
name: 'type',
description: 'Find out what item types are and how they work',
type: 1
},
{
name: 'faction',
description: 'Find out what factions are, how they work, and how to join one',
type: 1
},
{
name: 'airdrop',
description: 'Find out what Airdrops are & how they work',
type: 1
}
]
},
{ // Profile (same as /account view)
name: 'profile',
description: 'Take a look at someone\'s profile!',
options: [
{ type: 6, name: 'player', description: 'The player to look up.', required: false }
]
},
{ // Changelog
name: 'changelog',
description: 'See what\'s changed recently'
},
];
const rest = new REST({ version: '9' }).setToken(process.env.DISCORD_API_KEY);
// SETUP COMMANDS
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(config.bot.botID, config.bot.guildID),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
// ASSISTANT FUNCTIONS -----------------------------------------------------------------
/** Return an error message from the interaction */
async function returnEmbed(interaction, botInfo, title, description, errorCode) {
var embed = new MessageEmbed({
title: title,
description: description,
color: botInfo.displayColor
});
if (errorCode) { embed.footer = { text: `Error ${errorCode}` } }
try {
await interaction.reply({ embeds: [ embed ] });
} catch (err) {
console.log('Attempted to reply to message; failed');
await interaction.editReply({ embeds: [ embed ] });
}
}
/** Get a random number between the min & max */
function getRandomArbitrary(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
/** Capitalise the first letter of a string */
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
/** Normalises a number to at least n digits, prepending with 0s if necessary
* @param {Number} number - number to normalise.
* @param {Number} digits - number of digits to normalise, defaults to 2.
*/
function normaliseNumber(number, digits = 2) {
// Make a fixed-length number to the number of digits
// If a number has less digits, it will be padded with zeros
let string = number.toString();
let length = string.length;
if (length < digits) {
for (let i = 0; i < digits - length; i++) {
string = '0' + string;
}
}
return string;
}
/** Convert a value of seconds to hours minutes, etc. */
function convertHMS(value) {
const sec = parseInt(value, 10); // convert value to number if it's string
let hours = normaliseNumber(Math.floor(sec / 3600)); // get hours
let minutes = normaliseNumber(Math.floor((sec - (hours * 3600)) / 60)); // get minutes
let seconds = normaliseNumber(sec - (hours * 3600) - (minutes * 60)); // get seconds
if (hours === 0) { return `${minutes}:${seconds}`;}
else { return `${hours}:${minutes}:${seconds}`; }
}
// GENERATOR FUNCTIONS -----------------------------------------------------------------
/** Generate the Profile embed */
async function generateProfile(userInfo, botInfo) {
// Get that user's account
var response = await fetch(`${serverDomain}accounts/${userInfo.id}/${passKeySuffix}`);
if (response.status !== 200) { return [false, 'Internal server error']; }
// Get the inventory
const userAccountInfo = await response.json();
const inventory = userAccountInfo.inventory;
const userAvatar = await userInfo.member.avatarURL() || await userInfo.member.user.avatarURL();
// Create the profile embed
let profileEmbed = {
title: `**@${userInfo.displayName}**`,
color: botInfo.displayColor,
thumbnail: { url: userAvatar },
description: `ඞ${userAccountInfo.dollars} \n ${userAccountInfo.hp} HP`,
fields: []
}
if (userAccountInfo.faction) {
profileEmbed.footer = { text: `Part of ${userAccountInfo.faction.emojiName} ${userAccountInfo.faction.name}` }
}
// Show equipped items
const equippedItems = inventory.filter(item => item.isEquipped === true);
// console.log(equippedItems);
if (equippedItems.length === 0) {
profileEmbed.fields.push({
name: 'Equipped items!',
value: 'There are no items equipped!',
inline: false
});
} else {
const itemsText = equippedItems.reduce((acc, curr) => {
return acc + `${curr.rarity.emojiName} ${curr.type.emojiName} *${curr.name}* \n`
}, '');
profileEmbed.fields.push({
name: `**Equipped items**`,
value: itemsText,
inline: false
});
}
return profileEmbed;
}
/** Generate the Inventory embeds
* @param {UserInfo} userInfo Discord generated user information
* @param {BotInfo} botInfo standard bot information
* @param {UUID} itemID server-generated item ID
*/
async function generateInventory(userInfo, botInfo, itemID, actionTitle, actionDescription) {
// Get that user's account
var response = await fetch(`${serverDomain}accounts/${userInfo.id}/${passKeySuffix}`);
if (response.status !== 200) { return [false, 'Internal server error']; }
// Get the inventory
const userAccountInfo = await response.json();
const inventory = userAccountInfo.inventory;
// Assemble embeds
const embeds = [];
// Get the user's profile
embeds.push(await generateProfile(userInfo, botInfo));
// Get the selected item, if relevant
const selectedItem = inventory.find(x => x.id === itemID);
if (selectedItem) {
console.log(selectedItem);
// Generate item attributes text
let attributesText = '';
for (const attribute of selectedItem.attributes) {
if (attribute.value < 0) { attributesText += ` | ${attribute.value} ${attribute.name}` }
else { attributesText += ` | +${attribute.value} ${attribute.name}` }
if (attribute.duration && attribute.duration > 1) { attributesText += `, ${attribute.duration} duration`; }
}
// Add an embed for that item
let itemEmbed = {
title: `${selectedItem.type.emojiName} *${selectedItem.name}*`,
color: botInfo.displayColor,
description: '',
fields: [
{
name: '**Item stats**',
value: `${selectedItem.rarity.emojiName} **${capitalize(selectedItem.rarity.name)} ${selectedItem.type.name}** ${attributesText}`
}
]
};
embeds.push(itemEmbed);
// Add lore
if (selectedItem.description != '' && selectedItem.description != null) {
itemEmbed.description = `*${selectedItem.description}*`;
}
// Add title modifiers
if (selectedItem.amount > 1) { itemEmbed.title += ` (${selectedItem.amount})`; }
if (selectedItem.isEquipped) { itemEmbed.title += ` (equipped)`; }
}
// Action
if (actionTitle) {
let actionEmbed = {
title: actionTitle,
color: botInfo.displayColor,
timestamp: Date.now()
}
if (actionDescription) { actionEmbed.description = actionDescription; }
embeds.push(actionEmbed);
}
// Compose options & get other items
const selectOptions = [];
for (item of inventory) {
const option = {
emoji: { name: item.type.emojiName },
label: item.name,
value: item.id,
description: capitalize(item.rarity.name) + ' ' + item.type.name,
}
if (selectedItem && item.id === selectedItem.id) {
option.default = true;
}
selectOptions.push(option);
}
// Compile message components
const messageComponents = [];
if (selectOptions.length > 0) {
messageComponents.push({
type: 1,
components: [
{
type: 3,
customId: 'item_select',
options: selectOptions,
placeholder: 'Choose an item...'
}
]
});
}
// Add buttons
if (selectedItem) {
const buttonList = [{
type: 2,
style: 4,
label: 'Drop',
customId: 'item_drop_' + selectedItem.id,
}];
for (item of selectedItem.type.functions) {
let button = {
type: 2,
style: item.style,
label: capitalize(item.label),
customId: item.id + selectedItem.id,
disabled: false
}
// EQUIP/UNEQUIP ARMOUR
if (item.id === 'item_equip_') { button.disabled = selectedItem.isEquipped; }
else if (item.id === 'item_unequip_') { button.disabled = !selectedItem.isEquipped; }
// CONSUME button
if (item.id === 'item_consume_') {
// Calculate how much health this item might add
const hp = selectedItem.attributes.find(s => s.name == 'health');
if (hp) {
const healthAdd = Math.min(hp.value, 100 - userAccountInfo.hp);
if (healthAdd <= 0) { button.disabled = true; }
else { button.label += ` (+${healthAdd} HP)`}
} else {
button.disabled = true;
}
}
// SWING button
if (item.id === 'weapon_swing_') {
// If <=0, don't allow
const durability = selectedItem.attributes.find(s => s.name == 'durability');
if (!durability || durability.value <= 0) { button.disabled = true; }
}
buttonList.push(button);
}
messageComponents.push({
type: 1,
components: buttonList
})
}
// Return message content
return ({
embeds: embeds,
components: messageComponents
});
}
// VARIABLES ---------------------------------------------------------------------------
var currentAirdrop = {
typeID: 0,
dropDate: null,
payout: 0,
claimants: []
};
const isProduction = true;
const serverDomain = isProduction === true ? config.apiServer.productionServerDomain : config.apiServer.devServerDomain;
const passKeySuffix = '?passKey=joe_mama';
// ASYNC - SEND AN AIRDROP -------------------------------------------------------------
/*
Has a chance to drop a reward based on the number of users with the role online.
Equation is curently y = 0.00049x + 0.003. https://www.desmos.com/calculator/gtb2zddoe6
At the moment this just contains a random amount of cash, but will eventually include cards and other valuable items.
*/
(async () => {
const isDebuggingAirdrop = false; // CHANGE BEFORE PRODUCTION
// Set an interval
var intervalID = setInterval(async function () {
// DEBUG ONLY - CLEAR INTERVAL
if (isDebuggingAirdrop) { clearInterval(intervalID); }
// Find out how many people with the mingleton-rp role are online
const guild = client.guilds.cache.get(config.bot.guildID);
const role = await guild.roles.fetch('962205339728633876');
const roleMembers = role.members.toJSON();
const onlineRoleMembers = roleMembers.filter(member => {
return (member.presence && (member.presence.status === 'online' || member.presence.status === 'dnd'));
});
console.log(onlineRoleMembers.length, roleMembers.length)
// Calculate the weighting
// y = 0.00049x + 0.003
const weighting = (0.00049 * onlineRoleMembers.length) + 0.0013;
console.log(weighting);
// Run a chance check with the calculated weight
if(isDebuggingAirdrop === false && chance.weighted([true, false], [weighting, 1]) === false) { return; }
console.log('SENDING AIRDROP --------------------------------------------------------');
// Choose a random Airdrop to send
const airdropType = config.airdrop.types[chance.natural({min: 0, max: config.airdrop.types.length - 1})];
// const airdropType = config.airdrop.types[1];
console.log(airdropType);
currentAirdrop = {
typeID: airdropType.id,
dropDate: new Date().getTime(),
payout: chance.natural({ min: airdropType.payout.min, max: airdropType.payout.max }),
claimants: []
}
// Assemble the embed
let embed = {
title: `${airdropType.emoji} ${airdropType.name} Airdrop has appeared!`,
color: guild.me.displayColor,
footer: { text: `This will disappear in ${Math.round(airdropType.expirationMs / 60000)} minutes!` }
}
// Determine claimants
if (airdropType.maxClaimants === -1) {
embed.description = `**Anybody** can claim this Airdrop and receive **ඞ${currentAirdrop.payout}**!`
} else if (airdropType.maxClaimants === 1) {
embed.description = `The **first person** to claim this Airdrop will receive **ඞ${currentAirdrop.payout}**!`
} else {
embed.description = `The first **${airdropType.maxClaimants} people** to claim this Airdrop will and receive **ඞ${currentAirdrop.payout}**!`
}
// Send the message
const channel = await guild.channels.fetch(isDebuggingAirdrop ? config.airdrop.debugChannelID : config.airdrop.channelID);
const airdropMessage = await channel.send({
embeds: [ embed ],
components: [
{ type: 1, components: [
{ type: 2, label: 'Claim now!', style: 1, custom_id: 'claim_airdrop' }
]}
]
});
// Expire the airdrop
currentAirdrop.timeout = setTimeout(function () {
// Clear the prize money - no cheating!
currentAirdrop.payout = 0;
// Delete the message
if (airdropMessage) { airdropMessage.edit({ components: [], embeds: [{
title: `${airdropType.emoji} Time's up!`,
color: guild.me.displayColor,
content: `The time has come and gone to claim this Airdrop of **ඞ${currentAirdrop.payout}**`
}]}) }
}, config.airdrop.types[currentAirdrop.typeID].expirationMs);
}, isDebuggingAirdrop ? 3000 : config.airdrop.intervalMs);
})();
// CLIENT EVENTS -----------------------------------------------------------------------
client.on('ready', async () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setPresence({
activities: [{
name: 'with your finances',
type: 'PLAYING'
}],
status: 'online'
});
});
client.on('interactionCreate', async interaction => {
if (interaction.guild) {
// Assemble bot & user information
const botInfo = {
displayColor: interaction.guild.me.displayColor,
}
const userInfo = {
displayName: interaction.member.displayName,
id: interaction.member.id,
guild: interaction.guild,
isBot: (interaction.member.user.bot),
member: interaction.member
}
console.log('NEW COMMAND ------------------------------------------------------------');
if (interaction.isCommand()) { // COMMAND INTERACTIONS
console.log('COMMAND INTERACTION');
await interaction.deferReply();
if (interaction.commandName === 'send') {
const recipient = interaction.options.getMember('recipient', false);
const dollarAmount = interaction.options.getInteger('amount', false);
if (dollarAmount <= 0) {
await returnEmbed(interaction, botInfo, 'Not so fast', `You must send at least 1ඞ. And, no, you can't put someone else in a crippling financial crisis for your own gain.`);
return;
}
// Get the user's account & check their balance
var response = await fetch(`${serverDomain}accounts/${userInfo.id}/${passKeySuffix}`);
if (response.status === 404) {
await returnEmbed(interaction, botInfo, 'You don\'t have an account!', `You can create one with \`/account create\` (error: ${response.status}).`);
return;
} else if (response.status !== 200) {
await returnEmbed(interaction, botInfo, 'Something went wrong', `An internal server error occurred (error: ${response.status}).`);
return;
}
const userAccountInfo = await response.json();
console.log(userAccountInfo);
if (userAccountInfo.dollars < dollarAmount) {
await returnEmbed(interaction, botInfo, 'Cries in poor', `You only have **ඞ${userAccountInfo.dollars}**, but need **ඞ${dollarAmount - userAccountInfo.dollars}** more to make that transaction. Try again when you have money, loser.`);
return;
}
// Get the recipient's account
var response = await fetch(`${serverDomain}accounts/${recipient.id}/${passKeySuffix}`);
if (response.status === 404) {
await returnEmbed(interaction, botInfo, 'That person doesn\'t have an account!', `They can create one with \`/account create\` (error: ${response.status}).`);
return;
} else if (response.status !== 200) {
await returnEmbed(interaction, botInfo, 'Something went wrong', `An internal server error occurred (error: ${response.status}).`);
return;
}
const recipientAccountInfo = await response.json();
console.log(recipientAccountInfo);
// Update everyone's balance
var response = await fetch(`${serverDomain}accounts/${userInfo.id}/add-dollars/-${dollarAmount}/${passKeySuffix}`, {
method: 'POST'
});
if (response.status !== 200) {
await returnEmbed(interaction, botInfo, 'Something went wrong', `An internal server error occurred (error: ${response.status}).`);
return;
}
var response = await fetch(`${serverDomain}accounts/${recipient.id}/add-dollars/${dollarAmount}/${passKeySuffix}`, {
method: 'POST'
});
if (response.status !== 200) {
await returnEmbed(interaction, botInfo, 'Something went wrong', `An internal server error occurred (error: ${response.status}).`);
return;
}
await returnEmbed(interaction, botInfo, 'Sent ඞmoney!', `**ඞ${dollarAmount}** has been send to **@${recipient.displayName}**. Enjoy your new cash! \n \n @${userInfo.displayName}, your balance is now ඞ${userAccountInfo.dollars - dollarAmount}. \n @${recipient.displayName}, your balance is now ඞ${recipientAccountInfo.dollars + dollarAmount}!`);
} else if (interaction.commandName === 'leaderboard' || interaction.commandName === 'lb') {
var response = await fetch(`${serverDomain}accounts/leaderboard/?passKey=${config.apiServer.passKey}`);
if (response.status !== 200) { returnEmbed(interaction, botInfo, 'An error ocurred', `Something went wrong.`, response.status); return; }
const accountList = await response.json();
let description = '';
let index = 1;
for (member of accountList) {
const memberInfo = await userInfo.guild.members.fetch(member.id)
description += '**' + index + ')** ' + memberInfo.displayName + ', ඞ' + member.dollars + ' \n';
index += 1;
}
console.log(description);
let embed = {
title: `Current leaderboard`,
color: botInfo.displayColor,
description: description
}
await interaction.editReply({ embeds: [ embed ] });
} else if (interaction.commandName === 'inventory') {
await interaction.editReply(await generateInventory(userInfo, botInfo, null));
} else if (interaction.commandName === 'account') {
const interactionSubCommand = interaction.options.getSubcommand(false);
if (interactionSubCommand === 'create') {
// Create this user
var response = await fetch(`${serverDomain}accounts/create/${userInfo.id}/?passKey=${config.apiServer.passKey}`, { method: 'POST' });
if (response.status === 403) {
returnEmbed(interaction, botInfo, 'You already have an account', `You already have an account in the Mingleton RPG! Use \`/account view\` to see your stats.`, response.status); return;
} else if (response.status !== 200) {
returnEmbed(interaction, botInfo, 'An error ocurred', `Something went wrong.`, response.status); return;
}
// Add the mingleton-RPG Role to the user
const role = await userInfo.guild.roles.fetch(config.bot.roleID);
await interaction.member.roles.add([config.bot.roleID, role]);
// Create the embed
const embed = {
title: 'Account created! Welcome to Mingleton RPG!',
color: botInfo.displayColor,
description: 'Your account has been created. \n You have **ඞ100** (currency), **100 HP**.',
footer: { text: 'use /account view to get your account information' }
}
await interaction.editReply({ embeds: [ embed ] });
} else if (interactionSubCommand === 'view') {
const player = interaction.options.getMember('player', false);
let playerInfo = userInfo;
if (player) {
playerInfo = {
displayName: player.displayName,
id: player.id,
guild: userInfo.guild,
isBot: (player.user.bot),
member: player
}
}
await interaction.editReply({ embeds: [ await generateProfile(playerInfo, botInfo) ] });
}
} else if (interaction.commandName === 'help') {
const interactionSubCommand = interaction.options.getSubcommand(false);
if (interactionSubCommand === 'rarity') {
// Get item rarities
var response = await fetch(`${serverDomain}attributes/rarity/list/?passKey=${config.apiServer.passKey}`);
const rarityList = await response.json();
const rarityText = rarityList.reduce(function(acc, cur) {
return acc + ' ' + cur.emojiName + ' ' + capitalize(cur.name) + '\n';
}, '');
// Create the embed
const embed = {
title: '<:aldi:963312717542871081> About item rarities • Help',
color: botInfo.displayColor,
description: 'Every item is assigned a rarity, which can modify how much damage, durability, protection, etc. that item can deal. "Standard" rarity items are default; items lower than that have a reduced stat capacity, and conversely for those with a high rarity rating. The exact stats that rarity will affect on an item depends on the type of item.',
fields: [
{
name: 'Rarity ratings (lowest to highest)',
value: rarityText
}
]
}
await interaction.editReply({ embeds: [ embed ] });
} else if (interactionSubCommand === 'type') {
// Get item types
var response = await fetch(`${serverDomain}attributes/type/list/?passKey=${config.apiServer.passKey}`);
const typeList = await response.json();
const typeText = typeList.reduce(function(acc, cur) {
return acc + ' ' + cur.emojiName + ' ' + capitalize(cur.name) + '\n';
}, '');
// Create the embed
const embed = {
title: '🗡 About item types • Help',
color: botInfo.displayColor,
description: 'Items can be categorised into types, with each type affecting what that item can be used for and the stats it can have.',
fields: [
{
name: 'Item types',
value: typeText
}
]
}
await interaction.editReply({ embeds: [ embed ] });
} else if (interactionSubCommand === 'faction') {
// Create the embed
const embed = {
title: '🛡 About factions • Help',
color: botInfo.displayColor,
description: 'Factions are small, private groups that you and your close mates can join. When in a faction, you get a custom role that gives you access to a private channel in the "MRPG - FACTIONS" section. You can only be a part of one faction at a time, so pick wisely!',
fields: [
{
name: 'Creating a faction',
value: 'To create a new faction, use `/faction create` and follow the subsequent setup instructions! Once you have created a faction, you can invite more members with `/faction invite`.'
},
{
name: 'Joining a faction',
value: 'You can only join a faction via an invite from another member of that faction; keep an eye on your DMs to see if you get an invite!'
},
{
name: 'Leaving a faction',
value: 'You can leave a faction at anytime using `/faction leave`. Once you have left a faction, you must wait for an invite before you can join another (or you can create your own).'
}
]
}
await interaction.editReply({ embeds: [ embed ] });
} else if (interactionSubCommand === 'airdrop') {
const embedFields = []
for (const type of config.airdrop.types) {
embedFields.push({
name: `${type.emoji} ${type.name} Airdrop`,
value: `
**Payout:** ${type.payout.min} - ${type.payout.max}
**Maximum claimants:** ${type.maxClaimants === -1 ? '∞' : type.maxClaimants}
**Expiration:** ${Math.round(type.expirationMs / 60000)} minutes
`, inline: true
});
}
// Create the embeds
const embeds = [];
embeds.push({
title: '🪂 About Airdrops • Help',
color: botInfo.displayColor,
description: `Airdrops are an excellent and competitive way to earn income in the Mingleton world. At random times throughout the day, an Airdrop will appear in the **#🪂-airdrops** channel. Read on to find out about each type, and how often they appear`,
fields: [
{
name: '**Appearance rarity**',
value: `
Airdrops have a probability of appearing proportional to the number of people online. The equation is \`y = 0.00049x + 0.0031\`, where:
• \`y\` is the probability of an Airdrop appearing, and
• \`x\` is the number of people Online or DnD
This will be calculated once every ${Math.round(config.airdrop.intervalMs / 60000)} minute/s.
`
}
]
});
embeds.push({
title: 'Airdrop types',
color: botInfo.displayColor,
fields: [ embedFields ]
})
await interaction.editReply({ embeds: embeds });
}
} else if (interaction.commandName === 'faction') {
const interactionSubCommand = interaction.options.getSubcommand(false);
if (interactionSubCommand === 'create') {
// Collect variables
const name = interaction.options.getString('name', false).toLowerCase();
var emojiName = interaction.options.getString('emoji', false)
if (!name || !emojiName) { returnEmbed(interaction, botInfo, 'Your faction needs a name & emoji!'); return; }
// Test for emoji
var emoji_regex = /^(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff]|[\u0023-\u0039]\ufe0f?\u20e3|\u3299|\u3297|\u303d|\u3030|\u24c2|\ud83c[\udd70-\udd71]|\ud83c[\udd7e-\udd7f]|\ud83c\udd8e|\ud83c[\udd91-\udd9a]|\ud83c[\udde6-\uddff]|[\ud83c[\ude01-\ude02]|\ud83c\ude1a|\ud83c\ude2f|[\ud83c[\ude32-\ude3a]|[\ud83c[\ude50-\ude51]|\u203c|\u2049|[\u25aa-\u25ab]|\u25b6|\u25c0|[\u25fb-\u25fe]|\u00a9|\u00ae|\u2122|\u2139|\ud83c\udc04|[\u2600-\u26FF]|\u2b05|\u2b06|\u2b07|\u2b1b|\u2b1c|\u2b50|\u2b55|\u231a|\u231b|\u2328|\u23cf|[\u23e9-\u23f3]|[\u23f8-\u23fa]|\ud83c\udccf|\u2934|\u2935|[\u2190-\u21ff])+$/;
const emojiCheck = emoji_regex.test(emojiName);
console.log(emojiCheck);
if (!emojiCheck) {
returnEmbed(interaction, botInfo, 'That\'s an invalid emoji!'); return;
}
// Check if the player is in a faction
var response = await fetch(`${serverDomain}accounts/${userInfo.id}/${passKeySuffix}`);
if (response.status === 404) {
returnEmbed(interaction, botInfo, `You don't have a Mingleton RPG account!`, null, response.status); return;
} else if (response.status !== 200) {
returnEmbed(interaction, botInfo, `An error occurred`, null, response.status); return;
}
const userAccountInfo = await response.json();
console.log(userAccountInfo);
if (userAccountInfo.faction !== null) {
returnEmbed(interaction, botInfo, `You're already part of a faction!`); return;
}
// Send to server
var response = await fetch(`${serverDomain}factions/create/${name}/${emojiName}/${passKeySuffix}`, { method: 'POST' });
if (response.status === 403) {
returnEmbed(interaction, botInfo, 'A faction with that name already exists!', null, response.status); return;
} else if (response.status !== 200) {
returnEmbed(interaction, botInfo, 'An error occurred', null, response.status); return;
}
const factionID = await response.json();
// Add user to faction
var response = await fetch(`${serverDomain}factions/${factionID.factionID}/join/${userInfo.id}/${passKeySuffix}`, { method: 'POST'});
if (response.status !== 200) {
returnEmbed(interaction, botInfo, 'An error occurred', null, response.status); return;
}
// Create a new role
const factionRole = await interaction.guild.roles.create({
name: `f-${name}`,
reason: 'Faction creation'
});
// Give the role to the user
interaction.member.roles.add(factionRole);
// Create a new channel
const factionChannel = await interaction.guild.channels.create(`${emojiName}-${name}`, {
type: 'GUILD_TEXT'
});
// Set the parent
await factionChannel.setParent('970662777616236575', { lockPermissions: true });
await factionChannel.edit({
permissionOverwrites: [
{
id: factionRole.id,
allow: [ Permissions.FLAGS.VIEW_CHANNEL ],
},
{
id: '618748256028983326',
deny: [ Permissions.FLAGS.VIEW_CHANNEL ],
}
]
})
// Done!
await returnEmbed(interaction, botInfo, `Welcome to your new faction, ${emojiName} ${name}!`, `You can now view your faction's private channel!`);
} else if (interactionSubCommand === 'invite') {
const player = interaction.options.getMember('player', false);
if (!player) { returnEmbed(interaction, botInfo, 'That\'s not a valid user!'); return; }
// Check if the player is in a faction
var response = await fetch(`${serverDomain}accounts/${userInfo.id}/${passKeySuffix}`);
if (response.status === 404) {
returnEmbed(interaction, botInfo, `You don't have a Mingleton RPG account!`, null, response.status); return;
} else if (response.status !== 200) {
returnEmbed(interaction, botInfo, `An error occurred`, null, response.status); return;
}
const userAccountInfo = await response.json();
if (userAccountInfo.faction === null) {
returnEmbed(interaction, botInfo, `You're not part of a faction!`); return;
}
// Check if the other player is in a faction
var response = await fetch(`${serverDomain}accounts/${player.id}/${passKeySuffix}`);
if (response.status === 404) {
returnEmbed(interaction, botInfo, `That user doesn't have a Mingleton RPG account!`, null, response.status); return;
} else if (response.status !== 200) {
returnEmbed(interaction, botInfo, `An error occurred`, null, response.status); return;
}
const playerAccountInfo = await response.json();
if (playerAccountInfo.faction !== null) {
returnEmbed(interaction, botInfo, `They're already part of a faction!`); return;
}
// Create embed
const embed = {
title: `${userAccountInfo.faction.emojiName} You have an invite!`,
color: botInfo.displayColor,
description: `You've been invited by **@${userInfo.displayName}** to join ${userAccountInfo.faction.emojiName} **${userAccountInfo.faction.name}**!`
}
// Create a DM
const dmChannel = await player.createDM();
await dmChannel.send({
embeds: [ embed ],
components: [
{ type: 1, components: [
{ type: 2, label: 'Accept', style: 1, custom_id: 'join_faction_' + userAccountInfo.faction.id },
{ type: 2, label: 'Decline', style: 2, custom_id: 'decline_faction_' + userAccountInfo.faction.id }
]}
]
});
// Send an update to that faction's channel
const factionChannel = userInfo.guild.channels.cache.find(channel => channel.name.includes(userAccountInfo.faction.name.replace(/ /g, '-')));
if (factionChannel && factionChannel.id !== interaction.channel.id) {
await factionChannel.send({ embeds: [{
title: `@${player.displayName} has been invited to this faction!`,
description: `I'll let you know if they accept or decline the request!`,
footer: { text: `Invited by @${userInfo.displayName}`},
color: botInfo.displayColor
}]});
}
// Return to user
returnEmbed(interaction, botInfo, 'Invite sent!', `I'll let you know if they accept or decline your request!`);
} else if (interactionSubCommand === 'leave') {
// Get the player's current faction
var response = await fetch(`${serverDomain}accounts/${userInfo.id}/${passKeySuffix}`);
if (response.status === 404) {
returnEmbed(interaction, botInfo, `You don't have a Mingleton RPG account!`, null, response.status); return;
} else if (response.status !== 200) {