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
683 lines (548 loc) · 26.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
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
] });
/* Node-fetch */
const fetch = require('node-fetch');
/** Chance.JS */
const Chance = require('chance');
const chance = new Chance();
// FILES ------------------------------------------------------------------------------
const config = require('./json/config.json');
const items = require('./json/items.json');
const attributes = require('./json/attributes.json');
// COMMANDS ---------------------------------------------------------------------------
const commands = [
{ // Help
name: 'help',
description: 'Get help on a particular subject',
options: [
{
name: 'store',
description: 'Find out how the Bruh United store works',
type: 1
}
]
},
{ // Store
name: 'store',
description: 'Open the Bruh United store'
},
{ // Trade
name: 'trade',
description: 'Trade your items with other players',
options: [
{ type: 4, name: 'price', description: 'The price of your item', required: true }
]
},
{ // Changelog
name: 'changelog',
description: 'See what\'s changed recently'
},
// { // Refresh
// name: 'refresh',
// description: 'REFRESH THE STORE'
// }
];
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}` } }
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;
}
/** Generates a random item with the provided category
* @param {"weapons"|"armour"|"food"|"potions"|"spells"} category the category to generate
*/
async function generateItem(category) {
// Get category
const categoryItems = items[category];
if (!categoryItems) { console.log('Invalid category provided'); return; }
// Pick random item
const itemToPick = getRandomArbitrary(0, categoryItems.length - 1)
const item = categoryItems.slice(itemToPick, itemToPick + 1)[0];
// Pick a random rarity
const rarityID = getRandomArbitrary(item.rarity.min, item.rarity.max);
const absRarity = rarityID + 6;
var response = await fetch(`${serverDomain}attributes/rarity/id/${rarityID}/${passKeySuffix}`);
if (response.status !== 200) { console.log('An error occurred'); return; }
const rarity = await response.json();
// Get the type
var response = await fetch(`${serverDomain}attributes/type/id/${item.type}/${passKeySuffix}`);
if (response.status !== 200) { console.log('An error occurred'); return; }
const type = await response.json();
// Generate attributes
const stats = attributes[category];
// Construct item
var itemInfo = null;
itemInfo = {
name: item.name,
price: Math.ceil(stats.price * (stats.rarityModifier * (absRarity * 2))),
stackAmount: getRandomArbitrary(stats.stackAmount, type.maxStackAmount),
description: item.description,
type: type,
rarity: rarity,
attributes: [...item.stats],
isSold: false
}
// Assemble attributes
for (const attribute of stats.stats) {
itemInfo.attributes.push({
name: attribute.name,
value: Math.ceil(attribute.value * (stats.rarityModifier * absRarity))
});
}
console.log(itemInfo.name, stats.stats, itemInfo.attributes);
return(itemInfo);
}
/** Generates all the values required to create or update the store embed & buttons */
async function generateStore(userInfo, botInfo) {
// Get the user's account
var response = await fetch(`${serverDomain}accounts/${userInfo.id}/${passKeySuffix}`);
if (response.status === 400) {
await returnEmbed(interaction, botInfo, `You don't have a Mingleton RPG account`, 'You can create one with `/account create`.', response.status); return;
} else if (response.status !== 200) {
await returnEmbed(interaction, botInfo, `An error occurred`, null, response.status); return;
}
const userAccountInfo = await response.json();
// Calculate when the store will refresh
const timeNow = Date.now();
const msDifference = new Date(storeRefresh - timeNow);
// Generate embed
const embed = {
title: `Today's Store`,
color: botInfo.displayColor,
fields: [],
footer: { text: `You have ඞ${userAccountInfo.dollars} | Store will refresh in ${normaliseNumber(msDifference.getMinutes())}:${normaliseNumber(msDifference.getSeconds())}`}
}
// Generate buttons
const messageButtons = [];
var i = 1;
for (const item of storeItems) {
// Assemble field
let field = {
name: `**#${normaliseNumber(i, 2)} | ${item.rarity.emojiName} ${item.type.emojiName} ${item.name}**`,
value: `*${item.description}* \n **ඞ${item.price}**`
}
if (item.stackAmount > 1) { field.name += ` **(${item.stackAmount})**`; }
if (item.isSold) { field.name = '~~' + field.name + '~~'; }
for (const attribute of item.attributes) {
if (attribute.value < 0) { field.value += ` | ${attribute.value} ${attribute.name}` }
else { field.value += ` | +${attribute.value} ${attribute.name}` }
}
embed.fields.push(field);
// Generate buttons
messageButtons.push({
type: 2,
label: `#${normaliseNumber(i, 2)} (ඞ${item.price})`,
style: 2,
custom_id: `store_purchase_${i}`,
disabled: userAccountInfo.dollars < item.price || item.isSold
});
i++;
}
console.log(messageButtons);
return ({
embeds: [ embed ],
components: [
{ type: 1, components: messageButtons }
]
});
}
/** Refresh the store's items */
async function refreshStore() {
/** Generate 5 random items & store them locally. These items will eventually be updated periodically.
* 2x weapons
* 1x armour
* 1x food
* 1x potion/spell
*/
storeItems = [];
storeItems.push(await generateItem('weapons'));
storeItems.push(await generateItem('weapons'));
storeItems.push(await generateItem('armour'));
storeItems.push(await generateItem('food'));
storeItems.push(await generateItem(getRandomArbitrary(0, 1) === 1 ? 'potions' : 'spells'));
return storeItems;
}
// VARIABLES ---------------------------------------------------------------------------
const isProduction = true;
const serverDomain = isProduction === true ? config.apiServer.productionServerDomain : config.apiServer.devServerDomain;
const passKeySuffix = '?passKey=joe_mama';
var storeItems = []
var storeRefresh = null;
// ASYNC - REFRESH STORE ---------------------------------------------------------------
(async () => {
// Generate items
storeItems = await refreshStore();
var time = Date.now();
storeRefresh = new Date(time + config.store.refreshMs);
// Set an interval
setInterval(async function () {
storeItems = null;
storeItems = await refreshStore();
var time = Date.now();
storeRefresh = new Date(time + config.store.refreshMs);
}, config.store.refreshMs);
})();
// CLIENT EVENTS -----------------------------------------------------------------------
client.on('ready', async () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setPresence({
activities: [{
name: 'you make bad decisions',
type: 'WATCHING'
}],
status: 'online'
});
});
client.on('interactionCreate', async interaction => {
// 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)
}
console.log('NEW INTERACTION --------------------------------------------------------');
if (interaction.isCommand()) { // COMMAND INTERACTIONS
console.log('COMMAND INTERACTION', interaction.commandName);
await interaction.deferReply();
if (interaction.commandName === 'store') {
const store = await generateStore(userInfo, botInfo);
await interaction.editReply(store);
} else if (interaction.commandName === 'trade') {
const tradePrice = interaction.options.getInteger('price', false);
if (!tradePrice) { await returnEmbed(interaction, botInfo, 'Missing required fields!'); return; }
if (tradePrice < 0) { await returnEmbed(interaction, botInfo, `Yes, I thought of this too 😩`); return; }
// Get the user's account
var response = await fetch(`${serverDomain}accounts/${userInfo.id}/${passKeySuffix}`);
if (response.status === 400) {
await returnEmbed(interaction, botInfo, `You don't have a Mingleton RPG account`, 'You can create one with `/account create`.', response.status); return;
} else if (response.status !== 200) {
await returnEmbed(interaction, botInfo, `An error occurred`, null, response.status); return;
}
const userAccountInfo = await response.json();
if (userAccountInfo.inventory.length === 0) { await returnEmbed(interaction, botInfo, `You have no items in your inventory!`, `You need to have something to trade!`); return; }
// Display an inventory embed
const embed = {
title: 'Choose an item',
color: botInfo.displayColor,
description: `Select an item from your inventory to trade for **ඞ${tradePrice}**.`
}
const selectOptions = [];
for (const item of userAccountInfo.inventory) {
console.log(item);
selectOptions.push({
emoji: { name: item.type.emojiName },
label: item.name,
value: item.id,
description: capitalize(item.rarity.name) + ' ' + item.type.name
});
}
await interaction.editReply({
embeds: [ embed ],
components: [{
type: 1,
components: [{
type: 3,
customId: 'trade_select_item_' + tradePrice,
options: selectOptions,
placeholder: 'Choose an item...'
}]
}]
});
} else if (interaction.commandName === 'help') {
const interactionSubCommand = interaction.options.getSubcommand(false);
// Calculate when the store will refresh
const timeNow = Date.now();
const msDifference = new Date(storeRefresh - timeNow);
if (interactionSubCommand === 'store') {
const embed = {
color: botInfo.displayColor,
title: '💈 About the store • Help',
description: `Bruh United is a premium item dealership for the Mingleton RPG.`,
fields: [
{
name: 'How it works',
value: 'You can use `/store` to browse the catalogue of 5 items. This catalogue will refresh every hour, so be sure to pick up what you want when you see it! \n',
inline: false
},
{
name: 'What\'s in the store?',
value: 'Every catalogue is comprised of **2 weapons**, **1 armour**, **1 food item** and **1 potion/spell**. Every item in each category is roughly equivalent (assuming the same rarity)',
inline: false
},
{
name: 'How\'s this different from Baunders & Sons?',
value: 'Baunders & Sons will feature a far wider selection of items, and each item is far more variable in the stats it may have. Bruh United is designed to sell a smaller, more focused range of generally less-powerful weapons and armour to get the economy started.',
inline: false
}
],
footer: { text: `Store will refresh in ${normaliseNumber(msDifference.getMinutes())}:${normaliseNumber(msDifference.getSeconds())}`}
}
await interaction.editReply({ embeds: [ embed ] });
}
} else if (interaction.commandName === 'changelog') {
let embeds = [];
embeds.push({
color: botInfo.displayColor,
title: 'Minor patch • 22w01b',
description: `
• Fixed the store duping item statistics when refreshing
• Balanced the store a lot
`,
footer: { text: 'Released 21/05/2022'}
});
embeds.push({
color: botInfo.displayColor,
title: 'Initial Release • 22w01a',
description: `The first official release of Bruh United, fitted a basic store & trading features.`,
fields: [
{
name: 'Store',
value: `Browse a catalogue of premium items!`,
inline: false
},
{
name: 'Trading',
value: 'Put a price on items you own & earn a profit!',
inline: false
},
],
footer: { text: 'Released 08/05/2022'}
});
await interaction.editReply({ embeds: embeds });
}
// else if (interaction.commandName === 'refresh') {
// storeItems = null;
// storeItems = await refreshStore();
// var time = Date.now();
// storeRefresh = new Date(time + config.store.refreshMs);
// await interaction.editReply('refreshed store!');
// }
} else if (interaction.isButton()) { // BUTTON INTERACTIONS
console.log('BUTTON INTERACTION');
if (interaction.customId.includes('store_purchase_')) { // Item purchase
// Check if the original user sent this message
if (interaction.message.interaction.user.id !== userInfo.id) { return; }
const interactionMessage = interaction.message;
interaction.deferReply();
// Extract item
const itemID = interaction.customId.split('_')[2];
const item = storeItems[itemID - 1];
console.log(item);
// Get the user's account
var response = await fetch(`${serverDomain}accounts/${userInfo.id}/${passKeySuffix}`);
if (response.status === 400) {
await returnEmbed(interaction, botInfo, `You don't have a Mingleton RPG account`, 'You can create one with `/account create`.', response.status); return;
} else if (response.status !== 200) {
await returnEmbed(interaction, botInfo, `An error occurred`, null, response.status); return;
}
const userAccountInfo = await response.json();
if (userAccountInfo.dollars < item.price) { await returnEmbed(interaction, botInfo, `You don't have enough ඞdollars!`, `You need another ඞ${item.price - userAccountInfo.dollars} to purchase this item`); return; }
// Generate this item
var response = await fetch(`${serverDomain}items/create/${passKeySuffix}`, {
method: 'POST',
body: JSON.stringify({
name: item.name,
description: item.description,
rarityID: item.rarity.id,
typeID: item.type.id,
amount: item.stackAmount,
ownerID: userInfo.id,
attributes: item.attributes
}),
headers: { 'Content-Type': 'application/json' }
});
if (response.status !== 200) { await returnEmbed(interaction, botInfo, 'Something went wrong', null, response.status); return; }
// Deduct from account
var response = await fetch(`${serverDomain}accounts/${userInfo.id}/add-dollars/${0 - item.price}/${passKeySuffix}`, { method: 'POST' });
if (response.status !== 200) { await returnEmbed(interaction, botInfo, 'Something went wrong', null, response.status); return; }
const newAccountBalance = await response.json();
// Mark the item as sold
item.isSold = true;
// Refresh the store
interaction.editReply({ embeds: [{
title: 'Item purchased!',
color: botInfo.displayColor,
description: `You've purchased ${item.rarity.emojiName} ${item.type.emojiName} **${item.name}** for **ඞ${item.price}**.`,
footer: { text: `Your new account balance is ${newAccountBalance.dollars}` }
}]});
await interactionMessage.edit(await generateStore(userInfo, botInfo));
} else if (interaction.customId.includes('trade_')) { // Trade items
if (interaction.customId.includes('trade_retract_')) {
// Check if the original user sent this message
if (interaction.message.interaction && interaction.message.interaction.user.id !== userInfo.id) { return; }
// Delete the original message
await interaction.message.delete();
} else if (interaction.customId.includes('trade_accept_')) {
// Check that the original user DIDN'T send this
if (interaction.message.interaction && interaction.message.interaction.user.id === userInfo.id) { return; }
interaction.deferReply();
// Extract information
const itemID = interaction.customId.split('_')[2];
const tradePrice = interaction.customId.split('_')[3];
// Get the user's account
var response = await fetch(`${serverDomain}accounts/${userInfo.id}/${passKeySuffix}`);
if (response.status === 400) {
await returnEmbed(interaction, botInfo, `You don't have a Mingleton RPG account`, 'You can create one with `/account create`.', response.status); return;
} else if (response.status !== 200) {
await returnEmbed(interaction, botInfo, `An error occurred`, null, response.status); return;
}
const userAccountInfo = await response.json();
// Get information about that item group
var response = await fetch(`${serverDomain}items/${itemID}/true/${passKeySuffix}`);
if (response.status === 404) {
await returnEmbed(interaction, botInfo, `This item doesn't exist`, response.status); return;
} else if (response.status !== 200) {
await returnEmbed(interaction, botInfo, `An error occurred`, null, response.status); return;
}
const itemStackInfo = (await response.json())[0];
// Check if they have enough money
if (userAccountInfo.dollars < tradePrice) { await returnEmbed(interaction, botInfo, `You don't have enough ඞ dollars!`, `You need another **ඞ${tradePrice - userAccountInfo.dollars}** to make that trade.`); return; }
// Transfer the item
var response = await fetch(`${serverDomain}items/${itemID}/transfer/${userInfo.id}/true/${passKeySuffix}`, { method: 'POST' });
if (response.status !== 200) {
await returnEmbed(interaction, botInfo, `An error occurred`, null, response.status); return;
}
// Take dollars from the receiver
var response = await fetch(`${serverDomain}accounts/${userInfo.id}/add-dollars/${0 - tradePrice}/${passKeySuffix}`, { method: 'POST' });
if (response.status !== 200) {
await returnEmbed(interaction, botInfo, `An error occurred`, null, response.status); return;
}
// Give to the owner
var response = await fetch(`${serverDomain}accounts/${itemStackInfo.ownerID}/add-dollars/${tradePrice}/${passKeySuffix}`, { method: 'POST' });
if (response.status !== 200) {
await returnEmbed(interaction, botInfo, `An error occurred`, null, response.status); return;
}
// Assemble the embed
const sellerMemberInfo = await userInfo.guild.members.fetch(itemStackInfo.ownerID);
const embed = {
title: `@${userInfo.displayName} purchased ${itemStackInfo.amount} ${itemStackInfo.type.emojiName} *${itemStackInfo.name}*`,
color: botInfo.displayColor,
description: `${itemStackInfo.rarity.emojiName} Purchased from **@${sellerMemberInfo.displayName}** for **ඞ${tradePrice}**.`
}
interaction.editReply({ embeds: [ embed ]});
// Delete the original message
await interaction.message.delete();
// DM the seller
const dmChannel = await sellerMemberInfo.createDM();
await dmChannel.send({
embeds: [ embed ]
});
}
}
} else if (interaction.isMessageComponent()) { // MESSAGE COMPONENT INTERACTIONS
console.log('MESSAGE COMPONENT INTERACTION');
if (interaction.customId.includes('trade_select_item_')) {
// Check if the original user sent this message
if (interaction.message.interaction.user.id !== userInfo.id) { return; }
const interactionMessage = interaction.message;
interaction.deferUpdate();
// Extract tradeprice
const tradePrice = interaction.customId.split('_')[3];
// Get the user's account
var response = await fetch(`${serverDomain}accounts/${userInfo.id}/${passKeySuffix}`);
if (response.status === 400) {
await returnEmbed(interaction, botInfo, `You don't have a Mingleton RPG account`, 'You can create one with `/account create`.', response.status); return;
} else if (response.status !== 200) {
await returnEmbed(interaction, botInfo, `An error occurred`, null, response.status); return;
}
const userAccountInfo = await response.json();
// Find that item
const selectedItem = userAccountInfo.inventory.find(x => x.id === interaction.values[0]);
console.log(selectedItem);
if (!selectedItem) { await returnEmbed(interaction, botInfo, `You no longer own this item`, `It may have been deleted or sold already!`); return; }
// Create an embed
let embed = {
title: `@${userInfo.displayName} is selling ${selectedItem.amount} ${selectedItem.type.emojiName} *${selectedItem.name}*`,
color: botInfo.displayColor,
description: `${selectedItem.rarity.emojiName} **ඞ${tradePrice}**`
}
for (const attribute of selectedItem.attributes) {
console.log(attribute);
if (attribute.value < 0) { embed.description += ` | ${attribute.value} ${attribute.name}` }
else { embed.description += ` | +${attribute.value} ${attribute.name}` }
}
if (selectedItem.description) { embed.description = `*${selectedItem.description}* \n` + embed.description; }
await interactionMessage.edit({
embeds: [ embed ],
components: [{
type: 1,
components: [
{
type: 2,
customId: `trade_accept_${selectedItem.id}_${tradePrice}`,
style: 1,
label: `Accept trade (ඞ${tradePrice})`
},
{
type: 2,
customId: `trade_retract_${selectedItem.id}`,
style: 2,
label: `Retract trade (owner only)`
},
]
}]
});
}
} else { // OTHER
console.log('Interaction of type ' + interaction.type + ' unaccounted for.');
}
});
// RUN BOT ----------------------------------------------------------------------------
client.login(process.env.DISCORD_API_KEY);