Skip to content

Commit

Permalink
Initial Commit of Items category
Browse files Browse the repository at this point in the history
  • Loading branch information
TheMonDon committed Jul 25, 2024
1 parent daf168f commit 2427cb1
Show file tree
Hide file tree
Showing 9 changed files with 611 additions and 2 deletions.
4 changes: 2 additions & 2 deletions commands/Economy/rob.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,12 @@ class Rob extends Command {

let totalAmount = Number(memCash + authNet);
if (!Number.isFinite(totalAmount)) {
totalAmount = Number.MAX_SAFE_INTEGER;
totalAmount = Number.MAX_VALUE;
}

let authNetAmount = Number(authNet);
if (!Number.isFinite(authNetAmount)) {
authNetAmount = Number.MAX_SAFE_INTEGER;
authNetAmount = Number.MAX_VALUE;
}

const failRate = Math.floor((authNetAmount / totalAmount) * (maxRate - minRate + 1) + minRate);
Expand Down
1 change: 1 addition & 0 deletions commands/General/help.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ class Help extends Command {
async run(msg, args, level) {
const baseCategories = [
'economy',
'items',
'fun',
'games',
'general',
Expand Down
66 changes: 66 additions & 0 deletions commands/Items/buy-item.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
const Command = require('../../base/Command.js');
const { EmbedBuilder } = require('discord.js');
const { QuickDB } = require('quick.db');
const db = new QuickDB();

class BuyItem extends Command {
constructor(client) {
super(client, {
name: 'buy-item',
category: 'Items',
description: 'Buy an item from the store.',
usage: 'buy-item <item>',
examples: ['buy pizza'],
aliases: ['buy'],
requiredArgs: 1,
guildOnly: true,
});
}

async run(msg, args) {
const itemName = args.join(' ').toLowerCase();
if (!itemName) return msg.reply('Please specify an item to buy.');

const store = (await db.get(`servers.${msg.guild.id}.economy.store`)) || {};

// Find the item in the store regardless of case
const itemKey = Object.keys(store).find((key) => key.toLowerCase() === itemName);

if (!itemKey) return msg.reply('That item does not exist in the store.');

const item = store[itemKey];
const itemCost = BigInt(item.cost);
let userCash = BigInt(await db.get(`servers.${msg.guild.id}.users.${msg.member.id}.economy.cash`));
if (userCash < itemCost) return msg.reply('You do not have enough money to buy this item.');

const userInventory = (await db.get(`servers.${msg.guild.id}.users.${msg.member.id}.economy.inventory`)) || [];

// Check if the user already owns the item
const alreadyOwned = userInventory.find((inventoryItem) => inventoryItem.name.toLowerCase() === itemName);
if (alreadyOwned) return msg.reply('You already own this item.');

// Add the item to the user's inventory
userInventory.push({ name: itemKey, ...item });

// Deduct the cost from the user's cash
userCash = userCash - itemCost;
await db.set(`servers.${msg.guild.id}.users.${msg.member.id}.economy.cash`, userCash.toString());
await db.set(`servers.${msg.guild.id}.users.${msg.member.id}.economy.inventory`, userInventory);

const currencySymbol = (await db.get(`servers.${msg.guild.id}.economy.symbol`)) || '$';
const csCost =
itemCost.toLocaleString().length > 700
? currencySymbol + itemCost.toLocaleString().slice(0, 700) + '...'
: currencySymbol + itemCost.toLocaleString();

const embed = new EmbedBuilder()
.setTitle('Purchase Successful')
.setDescription(`You have successfully bought **${itemKey}** for ${csCost}.`)
.setColor(msg.settings.embedColor)
.setTimestamp();

return msg.channel.send({ embeds: [embed] });
}
}

module.exports = BuyItem;
100 changes: 100 additions & 0 deletions commands/Items/create-item.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
const Command = require('../../base/Command.js');
const { EmbedBuilder } = require('discord.js');
const { QuickDB } = require('quick.db');
const db = new QuickDB();

class CreateItem extends Command {
constructor(client) {
super(client, {
name: 'create-item',
category: 'Items',
description: 'Create an item to be shown in the store.',
usage: 'create-item <item name>',
longDescription: 'Create an item to be shown in the store. The item name will be cut off at 200 characters',
aliases: ['createitem'],
permLevel: 'Administrator',
guildOnly: true,
requiredArgs: 1,
});
}

async run(msg, args) {
const name = args.join(' ').slice(0, 200);
const store = (await db.get(`servers.${msg.guild.id}.economy.store`)) || {};
const filter = (m) => m.author.id === msg.author.id;
const embed = new EmbedBuilder()
.setAuthor({ name: msg.author.tag, iconURL: msg.author.displayAvatarURL() })
.setColor(msg.settings.embedColor)
.addFields([{ name: 'Name', value: name, inline: true }])
.setFooter({ text: 'Type cancel to quit.' })
.setTimestamp();

// Find the item in the store regardless of case
const item = Object.keys(store).find((key) => key.toLowerCase() === name);
if (item) {
const noItemEmbed = new EmbedBuilder()
.setAuthor({ name: msg.author.tag, iconURL: msg.author.displayAvatarURL() })
.setColor(msg.settings.embedErrorColor)
.setDescription('There is already an item with that name.');

return msg.channel.send({ embeds: [noItemEmbed] });
}

const message = await msg.channel.send({ content: 'What would you like the price to be?', embeds: [embed] });

let collected = await msg.channel
.awaitMessages({
filter,
max: 1,
time: 60000,
errors: ['time'],
})
.catch(() => null);
if (!collected) return msg.reply('You did not reply in time, the command has been cancelled.');
if (collected.first().content.toLowerCase() === 'cancel') return msg.reply('The command has been cancelled.');

let cost = parseInt(
collected
.first()
.content.toLowerCase()
.replace(/[^0-9\\.]/g, ''),
);
if (isNaN(cost)) return msg.reply('The cost must be a number. Command has been cancelled.');
if (cost === Infinity) {
msg.reply(`The cost must be less than Infinity. The cost has been set to ${Number.MAX_VALUE.toLocaleString()}.`);
cost = Number.MAX_VALUE;
}
if (cost < 0) {
msg.reply('The cost must be at least zero, therefore the cost has been set to zero.');
cost = 0;
}

const currencySymbol = (await db.get(`servers.${msg.guild.id}.economy.symbol`)) || '$';
embed.addFields([{ name: 'Cost', value: currencySymbol + cost.toLocaleString(), inline: true }]);

await message.edit({ content: 'What would you like the description to be?', embeds: [embed] });
collected = await msg.channel
.awaitMessages({
filter,
max: 1,
time: 60000,
errors: ['time'],
})
.catch(() => null);
if (!collected) return msg.reply('You did not reply in time, the command has been cancelled.');
if (collected.first().content.toLowerCase() === 'cancel') return msg.reply('The command has been cancelled.');

const description = collected.first().content.slice(0, 1024);
embed.addFields([{ name: 'Description', value: description, inline: true }]);

store[name] = {
cost,
description,
};

await db.set(`servers.${msg.guild.id}.economy.store`, store);
return message.edit({ content: ':white_check_mark: Item created successfully!', embeds: [embed] });
}
}

module.exports = CreateItem;
46 changes: 46 additions & 0 deletions commands/Items/delete-item.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
const Command = require('../../base/Command.js');
const { EmbedBuilder } = require('discord.js');
const { QuickDB } = require('quick.db');
const db = new QuickDB();

class DeleteItem extends Command {
constructor(client) {
super(client, {
name: 'delete-item',
category: 'Items',
description: 'Delete an item from the store.',
usage: 'delete-item <item name>',
aliases: ['deleteitem', 'delitem'],
permLevel: 'Administrator',
guildOnly: true,
requiredArgs: 1,
});
}

async run(msg, args) {
const itemName = args.join(' ').toLowerCase();
const store = (await db.get(`servers.${msg.guild.id}.economy.store`)) || {};

// Find the item in the store regardless of case
const itemKey = Object.keys(store).find((key) => key.toLowerCase() === itemName);

const item = store[itemKey];
if (!item) {
const embed = new EmbedBuilder()
.setAuthor({ name: msg.author.tag, iconURL: msg.author.displayAvatarURL() })
.setColor(msg.settings.embedErrorColor)
.setDescription('There is not an item with that name.');

return msg.channel.send({ embeds: [embed] });
}

await db.delete(`servers.${msg.guild.id}.economy.store.${itemKey}`);
const embed = new EmbedBuilder()
.setColor(msg.settings.embedColor)
.setAuthor({ name: msg.author.tag, iconURL: msg.author.displayAvatarURL() })
.setDescription('Item has been removed from the store.');
return msg.channel.send({ embeds: [embed] });
}
}

module.exports = DeleteItem;
84 changes: 84 additions & 0 deletions commands/Items/edit-item.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/* eslint-disable no-case-declarations */
const Command = require('../../base/Command.js');
const { EmbedBuilder } = require('discord.js');
const { QuickDB } = require('quick.db');
const db = new QuickDB();

class EditItem extends Command {
constructor(client) {
super(client, {
name: 'edit-item',
category: 'Items',
description: 'Edit an item in the store.',
usage: 'edit-item <name|price|description> "<item name>" <new value>',
aliases: ['edititem'],
permLevel: 'Administrator',
guildOnly: true,
requiredArgs: 3,
});
}

async run(msg, args) {
const attribute = args.shift().toLowerCase();
const itemNameStartIndex = args.findIndex((arg) => arg.startsWith('"'));
const itemNameEndIndex = args.findIndex((arg) => arg.endsWith('"'));

if (itemNameStartIndex === -1 || itemNameEndIndex === -1) {
return msg.reply('Please enclose the item name in double quotes.');
}

const itemName = args
.slice(itemNameStartIndex, itemNameEndIndex + 1)
.join(' ')
.replace(/"/g, '');
const newValue = args.slice(itemNameEndIndex + 1).join(' ');

const store = (await db.get(`servers.${msg.guild.id}.economy.store`)) || {};

// Find the item in the store regardless of case
const itemKey = Object.keys(store).find((key) => key.toLowerCase() === itemName.toLowerCase());

if (!itemKey) return msg.reply('That item does not exist in the store.');

const item = store[itemKey];

switch (attribute) {
case 'name':
// Ensure the new name is not already taken
const newItemKey = newValue.toLowerCase();
if (Object.keys(store).find((key) => key.toLowerCase() === newItemKey)) {
return msg.reply('An item with that name already exists.');
}
// Update the item name
store[newValue] = item;
delete store[itemKey];
break;
case 'price':
const price = parseInt(newValue, 10);
if (isNaN(price) || price < 0) {
return msg.reply('Please provide a valid price.');
}
item.cost = price;
store[itemKey] = item;
break;
case 'description':
item.description = newValue;
store[itemKey] = item;
break;
default:
return msg.reply('Invalid attribute. You can only edit name, price, or description.');
}

await db.set(`servers.${msg.guild.id}.economy.store`, store);

const embed = new EmbedBuilder()
.setTitle('Item Edited')
.setDescription(`The **${attribute}** of **${itemKey}** has been updated to **${newValue}**.`)
.setColor(msg.settings.embedColor)
.setTimestamp();

return msg.channel.send({ embeds: [embed] });
}
}

module.exports = EditItem;
Loading

0 comments on commit 2427cb1

Please sign in to comment.