Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new items category #208

Merged
merged 12 commits into from
Jul 28, 2024
22 changes: 12 additions & 10 deletions commands/Bot Support/global-blacklist.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ class GlobalBlacklist extends Command {
name: 'global-blacklist',
description: 'Blacklist someone from using the bot',
usage: 'global-blacklist <Add | Remove | Check> <User> <Reason>',
requiredArgs: 1,
examples: ['global-blacklist check bunny', 'global-blacklist add bunny Being naughty'],
requiredArgs: 2,
category: 'Bot Support',
permLevel: 'Bot Support',
aliases: ['gbl', 'g-blacklist', 'gblacklist'],
Expand All @@ -26,6 +27,7 @@ class GlobalBlacklist extends Command {
return this.client.util.errorEmbed(msg, msg.settings.prefix + this.help.usage, 'Incorrect Usage');
} else {
type = args[0].toLowerCase();
mem = await this.client.util.getMember(msg, args[1]);
}
} else if (args[0]) {
// Check if the first argument is a user mention
Expand Down Expand Up @@ -59,13 +61,15 @@ class GlobalBlacklist extends Command {
if (!mem) {
return this.client.util.errorEmbed(msg, msg.settings.prefix + this.help.usage, 'User not found');
}
mem = mem.user ? mem.user : mem;

args.shift();
args.shift();
const reason = args.join(' ') || false;

const blacklist = await db.get(`users.${mem.id}.blacklist`);

console.log(mem);
const embed = new EmbedBuilder()
.setAuthor({ name: mem.tag, iconURL: mem.displayAvatarURL() })
.setColor(msg.settings.embedColor)
Expand All @@ -84,8 +88,8 @@ class GlobalBlacklist extends Command {
await db.set(`users.${mem.id}.blacklistReason`, reason);

embed.setTitle(`${mem.tag} has been added to the global blacklist.`).addFields([
{ name: 'Reason:', value: reason },
{ name: 'User:', value: `${mem.tag} \n(${mem.id})` },
{ name: 'Reason:', value: reason },
]);

msg.channel.send({ embeds: [embed] });
Expand All @@ -105,8 +109,8 @@ class GlobalBlacklist extends Command {
await db.set(`users.${mem.id}.blacklistReason`, reason);

embed.setTitle(`${mem.tag} has been removed from the global blacklist.`).addFields([
{ name: 'Reason:', value: reason },
{ name: 'User:', value: `${mem.tag} \n(${mem.id})` },
{ name: 'Reason:', value: reason },
]);

msg.channel.send({ embeds: [embed] });
Expand All @@ -117,13 +121,11 @@ class GlobalBlacklist extends Command {
case 'check': {
const reason = (await db.get(`users.${mem.id}.blacklistReason`)) || 'No reason specified';

embed
.setTitle(`${mem.tag} blacklist check`)
.addFields([
{ name: 'User:', value: `${mem.tag} (${mem.id})`, inline: true },
{ name: 'Is Blacklisted?', value: blacklist ? 'True' : 'False', inline: true },
])
.addField('Reason:', reason);
embed.setTitle(`${mem.tag} blacklist check`).addFields([
{ name: 'User:', value: `${mem.tag} (${mem.id})`, inline: true },
{ name: 'Is Blacklisted?', value: blacklist ? 'True' : 'False', inline: true },
{ name: 'Reason', value: reason, inline: true },
]);

msg.channel.send({ embeds: [embed] });
break;
Expand Down
6 changes: 3 additions & 3 deletions commands/Economy/rob.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class Rob extends Command {
} else {
const tLeft = moment
.duration(timeleft)
.format('y[ years][,] M[ Months]d[ days][,] h[ hours][,] m[ minutes][, and] s[ seconds]'); // format to any format
.format('y[ years][,] M[ Months][,] d[ days][,] h[ hours][,] m[ minutes][, and] s[ seconds]'); // format to any format

embed.setDescription(`You cannot rob for ${tLeft}`);
return msg.channel.send({ embeds: [embed] });
Expand Down 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
2 changes: 1 addition & 1 deletion commands/Economy/slut.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class Slut extends Command {
} else {
const tLeft = moment
.duration(timeleft)
.format('y[ years][,] M[ Months]d[ days][,] h[ hours][,] m[ minutes][, and] s[ seconds]'); // format to any format
.format('y[ years][,] M[ Months][,] d[ days][,] h[ hours][,] m[ minutes][, and] s[ seconds]'); // format to any format
embed.setDescription(`Please wait ${tLeft} to be a slut again.`);
return msg.channel.send({ embeds: [embed] });
}
Expand Down
2 changes: 1 addition & 1 deletion commands/Economy/work.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class Work extends Command {
} else {
const tLeft = moment
.duration(timeleft)
.format('y[ years][,] M[ Months]d[ days][,] h[ hours][,] m[ minutes][, and] s[ seconds]');
.format('y[ years][,] M[ Months][,] d[ days][,] h[ hours][,] m[ minutes][, and] s[ seconds]');
embed.setDescription(`You cannot work for ${tLeft}`);
return msg.channel.send({ embeds: [embed] });
}
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
191 changes: 191 additions & 0 deletions commands/Items/buy-item.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
const Command = require('../../base/Command.js');
const { EmbedBuilder } = require('discord.js');
const { QuickDB } = require('quick.db');
require('moment-duration-format');
const moment = require('moment');
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 [quantity] <item>',
examples: ['buy pizza'],
aliases: ['buy'],
requiredArgs: 1,
guildOnly: true,
});
}

async run(msg, args) {
let quantity = 1;
let itemName = args.join(' ').toLowerCase();
if (!isNaN(args[0])) {
quantity = parseInt(args[0]);
if (quantity <= 0) {
return msg.reply('Invalid `[quantity]` argument given. Cannot be less than 1');
}
args.shift();
itemName = args.join(' ').toLowerCase();
if (!itemName) {
return msg.reply('Invalid `<item name>` argument given');
}
}

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 * BigInt(quantity)) return msg.reply('You do not have enough money to buy this item.');

if (item.stock && item.stock < quantity) {
return msg.reply(`The store only has ${item.stock} stock remaining.`);
}
if (item.stock) {
item.stock -= quantity;
if (item.stock === 0) {
await db.delete(`servers.${msg.guild.id}.economy.store.${itemKey}`);
} else {
store[itemKey] = item;
await db.set(`servers.${msg.guild.id}.economy.store`, store);
}
}

if (item.roleRequired) {
const roleRequired = this.client.util.getRole(msg, item.roleRequired);
if (roleRequired) {
// Check if the member has the role
const hasRole = msg.member.roles.cache.has(roleRequired.id);
if (!hasRole) {
return msg.reply(`You do not have the required role **${roleRequired.name}** to purchase this item.`);
}
} else {
return msg.reply('The required role specified does not exist.');
}
}

if (item.roleGiven || item.roleRemoved) {
if (!msg.guild.members.me.permissions.has('ManageRoles'))
return this.client.util.errorEmbed(
msg,
'Manage Roles permission is required on the bot to buy this item.',
'Missing Permission',
);
}

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

if (!item.inventory) {
if (item.roleGiven) {
const role = this.client.util.getRole(msg, item.roleGiven);
await msg.member.roles.add(role).catch((error) => msg.channel.send(error));
}
if (item.roleRemoved) {
const role = this.client.util.getRole(msg, item.roleRemoved);
await msg.member.roles.remove(role).catch((error) => msg.channel.send(error));
}
if (!item.replyMessage) {
return msg.channel.send('👍');
}

// Replace Member
const memberCreatedAt = moment(msg.author.createdAt);
const memberCreated = memberCreatedAt.format('D MM YY');
const memberCreatedDuration = memberCreatedAt.from(moment(), true);
let replyMessage = item.replyMessage
.replace('{member.id}', msg.author.id)
.replace('{member.username}', msg.author.username)
.replace('{member.tag}', msg.author.tag)
.replace('{member.mention}', msg.author)
.replace('{member.created}', memberCreated)
.replace('{member.created.duration}', memberCreatedDuration);

// Replace Server
const guildCreatedAt = moment(msg.guild.createdAt);
const serverCreated = guildCreatedAt.format('D MM YY');
const serverCreatedDuration = guildCreatedAt.from(moment(), true);

replyMessage = replyMessage
.replace('{server.id}', msg.guild.id)
.replace('{server.name}', msg.guild.name)
.replace('{server.members}', msg.guild.memberCount.toLocaleString())
.replace('{server.created}', serverCreated)
.replace('{servers.created.duration', serverCreatedDuration);

const role =
(await this.client.util.getRole(msg, item.roleGiven)) ||
(await this.client.util.getRole(msg, item.roleRemoved)) ||
(await this.client.util.getRole(msg, item.roleRequired));

if (role) {
const roleCreatedAt = moment(role.createdAt);
const roleCreated = roleCreatedAt.format('D MM YY');
const roleCreatedDuration = roleCreatedAt.from(moment(), true);

replyMessage = replyMessage
.replace('{role.id}', role.id)
.replace('{role.name}', role.name)
.replace('{role.mention}', role)
.replace('{role.members}', role.members.size.toLocaleString())
.replace('{role.created}', roleCreated)
.replace('{role.created.duration}', roleCreatedDuration);
}
return msg.channel.send(replyMessage);
}

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

// Find the index of the item in the user's inventory
const itemIndex = userInventory.findIndex((inventoryItem) => inventoryItem?.name?.toLowerCase() === itemName);
if (itemIndex !== -1) {
// If the item is found, increment the quantity
userInventory[itemIndex].quantity += quantity;
userInventory[itemIndex] = {
...userInventory[itemIndex],
replyMessage: item.replyMessage,
roleRequired: item.roleRequired,
roleGiven: item.roleGiven,
roleRemoved: item.roleRemoved,
};
await db.set(`servers.${msg.guild.id}.users.${msg.member.id}.economy.inventory`, userInventory);
} else {
// Add the item to the user's inventory
item.quantity = quantity;
userInventory.push({ name: itemKey, ...item });

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 itemCostQuantity = (itemCost * BigInt(quantity)).toLocaleString();
const csCost =
itemCostQuantity.length > 700
? currencySymbol + itemCostQuantity.slice(0, 700) + '...'
: currencySymbol + itemCostQuantity;

const embed = new EmbedBuilder()
.setTitle('Purchase Successful')
.setDescription(
`You have bought ${quantity} ${itemKey}${
quantity > 1 ? 's' : ''
} for ${csCost}! This is now in your inventory. \nUse this item with the \`use-item\` command.`,
)
.setColor(msg.settings.embedColor)
.setTimestamp();

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

module.exports = BuyItem;
Loading
Loading