Skip to content

Commit

Permalink
Merge pull request #103 from vb2007/dev
Browse files Browse the repository at this point in the history
Merge Dev to Main
  • Loading branch information
vb2007 authored Dec 22, 2024
2 parents 53971ae + 0f8773c commit 158e611
Show file tree
Hide file tree
Showing 9 changed files with 270 additions and 205 deletions.
16 changes: 7 additions & 9 deletions commands/economy/deposit.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { ActionRowBuilder, ButtonBuilder, ButtonStyle, SlashCommandBuilder } = require("discord.js");
const { embedReplyFailureColor, embedReplySuccessColor } = require("../../helpers/embeds/embed-reply");
const { embedReplyFailureColor, embedReplySuccessColor, embedReplyWarningColor } = require("../../helpers/embeds/embed-reply");
const { logToFileAndDatabase } = require("../../helpers/logger");
const db = require("../../helpers/db");

Expand All @@ -10,7 +10,7 @@ const feePercentage = 0.3;
module.exports = {
data: new SlashCommandBuilder()
.setName("deposit")
.setDescription("Desposits a specified amount of money to your bank account.")
.setDescription("Deposits a specified amount of money to your bank account.")
.addIntegerOption(option =>
option
.setName("amount")
Expand Down Expand Up @@ -76,7 +76,7 @@ module.exports = {
isCommandReplied = true;

const filter = i => i.user.id === interaction.user.id;
const collector = message.createMessageComponentCollector({ filter, time: 30000 });
const collector = message.createMessageComponentCollector({ filter, time: 15000 });

collector.on("collect", async i => {
if (i.customId === "confirm") {
Expand All @@ -91,11 +91,12 @@ module.exports = {

var embedReply = embedReplySuccessColor(
"Deposit successful.",
`You've successfully deposited \`$${amount}\` for a fee of \`$${fee}\`.\Your balance decreased by total of \`$${totalAmount}\`.`,
`You've successfully deposited \`$${amount}\` for a fee of \`$${fee}\`.\nYour balance decreased by total of \`$${totalAmount}\`.`,
interaction
);

await i.update({ embeds: [embedReply], components: [] });
await logToFileAndDatabase(interaction, JSON.stringify(embedReply.toJSON()));
}
else if (i.customId === "cancel") {
var embedReply = embedReplyFailureColor(
Expand Down Expand Up @@ -140,10 +141,7 @@ module.exports = {

if (!isCommandReplied) {
await interaction.reply({ embeds: [embedReply] });
}

//logging
const response = JSON.stringify(embedReply.toJSON());
await logToFileAndDatabase(interaction, response);
await logToFileAndDatabase(interaction, JSON.stringify(embedReply.toJSON()));
}
}
}
43 changes: 21 additions & 22 deletions commands/economy/pay.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,25 @@ module.exports = {
}
else {
const amount = interaction.options.getInteger("amount");
const targetUserId = interaction.options.getUser("target").id;

const targetUser = interaction.options.getUser("target");
const targetUserId = targetUser.id;
const targetUserName = targetUser.username;
const interactionUserId = interaction.user.id;

if (targetUserId === interactionUserId) {
var embedReply = embedReplyFailureColor(
"Payment - Error",
"You cannot issue a payment to yourself.",
interaction
);
}

const interactionUserBalanceQuery = await db.query("SELECT balance FROM economy WHERE userId = ?", [interactionUserId]);
const userBalance = interactionUserBalanceQuery[0]?.balance || null;
const userBalance = interactionUserBalanceQuery[0]?.balance || 0;

const targetUserBalanceQuery = await db.query("SELECT balance FROM economy WHERE userId = ?", [targetUserId]);
const targetUserBalance = targetUserBalanceQuery[0]?.balance || null;
const targetUserQuery = await db.query("SELECT * FROM economy WHERE userId = ?", [targetUserId]);
const targetUserExists = targetUserQuery.length > 0;

if (amount > userBalance) {
var embedReply = embedReplyFailureColor(
Expand All @@ -53,26 +64,17 @@ module.exports = {
}
else {
await db.query("UPDATE economy SET balance = balance - ? WHERE userId = ?",
[
amount,
interactionUserId
]
[amount, interactionUserId]
);

if (!targetUserBalance) {
await db.query("INSERT INTO economy (userId, balance) VALUES (?, ?)",
[
targetUserId,
amount
]
if (!targetUserExists) {
await db.query("INSERT INTO economy (userName, userId, balance) VALUES (?, ?, ?)",
[targetUserName, targetUserId, amount]
);
}
else {
await db.query("UPDATE economy SET balance = balance + ? WHERE userId = ?",
[
amount,
targetUserId
]
[amount, targetUserId]
);
}

Expand All @@ -85,9 +87,6 @@ module.exports = {
}

await interaction.reply({ embeds: [embedReply] });

//logging
const response = JSON.stringify(embedReply.toJSON());
await logToFileAndDatabase(interaction, response);
await logToFileAndDatabase(interaction, JSON.stringify(embedReply.toJSON()));
}
}
209 changes: 87 additions & 122 deletions commands/utility/help.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const { SlashCommandBuilder } = require("discord.js");
const { embedReplyPrimaryColorWithFields, embedReplyErrorColorWithFields } = require("../../helpers/embeds/embed-reply");
const { embedReplyPrimaryColorWithFields, embedReplyErrorColorWithFields, embedReplyFailureColor } = require("../../helpers/embeds/embed-reply");
const { logToFileAndDatabase } = require("../../helpers/logger");
const db = require("../../helpers/db");

module.exports = {
data: new SlashCommandBuilder()
Expand All @@ -18,137 +19,101 @@ module.exports = {
{ name: "Administration", value: "administration" },
)
.setRequired(false))
.addStringOption(option =>
option
.setName("command")
.setDescription("Specify a command's name you would like to know more information about.")
.setRequired(false))
.setDMPermission(true),
async execute(interaction) {
const commandCategory = interaction.options.getString("category");

const utilityCommands =
{ name: "Utility", value:
"`/help` - Displays this message.\n" +
"`/ping` - Displays the discord API's current latency.\n" +
"`/ping-db` - Displays the current latency between the bot and it's database.\n" +
"`/server` - Provides information about the current server.\n" +
"`/user` - Provides information about a specified user.\n" +
"`/translate` - Translates a message from any language to any language.\n" +
"`/say` - Makes the bot say a specified message."
};

const funCommands =
{ name: "Fun", value:
"`/coinflip` - Flips a coin that has a 50/50 chance landing on heads or tails.\n" +
"`/randompic` - Send a random picture using the [picsum.photos](https://picsum.photos/) API.\n" +
"`/randomfeet` - I have nothing to say about my greatest shame...\n" +
"`/911-countdown` - Displays huw much time is left until Spetember 11th."
};

const economyCommands =
{ name: "Economy", value:
"`/work` - Lets you work for a random amount of money.\n" +
"`/beg` - Lets you beg for a random (or no) amount of money.\n" +
"`/rob` - Steals a random amount of money from the target user, and adds it to your balance.\n" +
"`/balance` - Displays the user's current bank and handheld balance.\n" +
"`/deposit` - Deposits money into the user's bank account. It has a daily limit for free deposits, but the users can choose to pay a small deposit fee if they exceed the limit.\n" +
"`/withdraw` - Withdraws money from the user's bank account.\n" +
"`/pay` - Transfers money from one user to another.\n" +
"`/roulette` - Lets you pick a color, then gives you a great price if you guess the color right.\n" +
"`/leaderboard` - Displays users with the most money on the server."
};

const moderationCommands =
{ name: "Moderation", value:
"**__NOTE__**: The following commands require relevant **moderation permissions** for both the bot and the command's executor to work.\n" +
"`/warn` - Warns a specified member on the server.\n" +
"`/timeout` - Times out a specified member for a specified time.\n" +
"`/kick` - Kicks a specified member from the server.\n" +
"`/ban` - Bans a specified member from the server.\n" +
"`/purge` - Purges (mass deletes) a specified amount of messages from the current channel."
};

const administrationCommands =
{ name: "Administration", value:
"**__NOTE__**: The following commands require relevant **administration permissions** for both the bot and the command's executor to work.\n" +
"`/autorole-configure` - Sets / modifies the autorole feature. When a new member joins the server, a specified role will get assigned to them automatically.\n" +
"`/autorole-disable` - Disables the autorole feature. New members won't get the specified role automatically on join anymore.\n" +
"`/welcome-configure` - Sets / modifies the welcome messages feature. When a new member joins the server, the bot send a specified welcome message.\n" +
"`/welcome-disable` - Disables the welcome messages feature. The bot won't send a welcome message on join anymore.\n" +
"`/logging-configure` - Sets / modifies the channel where event on the server will get logged.\n" +
"`/logging-disable` - Disables the logging feature. The bot won't log the events on the server anymore.\n" +
"`/bridge-configure` - Bridges all messages from one channel to another.\n" +
"`/bridge-disable` - Disables briding for a target channel.\n" +
"`/rename` - Renames a specified user to a specified nickname in the current server."
};

const tipField =
{ name: "Tip.", value:
"**Friendly reminder**: You can use `/help <category>` to get a list of commands from a specific category. :grin:"
const commandName = interaction.options.getString("command");

if (commandCategory && commandName) {
var embedReply = embedReplyFailureColor(
"Help: Error",
"Please only provide one parameter at a time for the command.",
interaction
);
}
else if (commandCategory) {
const commandsQuery = await db.query("SELECT name, category FROM commandData WHERE category = ? ORDER BY name", [commandCategory]);

if (commandsQuery.length === 0) {
var embedReply = embedReplyFailureColor(
"Help: Error",
"Invalid command category provided as parameter.\nPlease choose a valid category: `utility`, `fun`, `economy`, `moderation`, `administration`.",
interaction
);
}
else {
const commandsList = commandsQuery
.map(cmd => `\`/${cmd.name}\``)
.join(", ");

const errorField =
{ name: "Error", value:
"Invalid command category provided as parameter.\n" +
"Please choose a valid category: `utility`, `fun`, `economy`, `moderation`, `administration`."
var embedReply = embedReplyPrimaryColorWithFields(
`Help - ${commandCategory.charAt(0).toUpperCase() + commandCategory.slice(1)} Commands`,
`Here is a list of the bot's currently available **${commandCategory}** commands:`,
[{ name: "Commands", value: commandsList }],
interaction
);
}
}
else if (commandName) {
const commandQuery = await db.query("SELECT category, description FROM commandData WHERE name = ?", [commandName]);
const category = commandQuery[0]?.category || null;
const description = commandQuery[0]?.description || null;

if (!description) {
var embedReply = embedReplyFailureColor(
"Help - Error",
`There is no such command as \`/${commandName}\`.\nPlease provide a valid command name.`,
interaction
);
}
else {
var embedReply = embedReplyPrimaryColorWithFields(
`Help - /${commandName}`,
"You can check out all commands with descriptions on [the bot's wiki](https://github.com/vb2007/discordbot/wiki/Commands)",
[
{ name: "Category", value: category.charAt(0).toUpperCase() + category.slice(1) },
{ name: "Description", value: description }
],
interaction
);
}
}
else {
const allCommandsQuery = await db.query("SELECT name, category FROM commandData ORDER BY category, name");

let embedReply;
if (!commandCategory) {
embedReply = embedReplyPrimaryColorWithFields(
"Help - All Commands.",
"Here is a list of the bot's currently avaliable commands:",
[ utilityCommands, funCommands, economyCommands, moderationCommands, administrationCommands, tipField ],
//grouping commands by category
const commandsByCategory = allCommandsQuery.reduce((acc, cmd) => {
if (!acc[cmd.category]) {
acc[cmd.category] = [];
}
acc[cmd.category].push(cmd.name);
return acc;
}, {});

//fields for each category
const categoryFields = Object.entries(commandsByCategory).map(([category, commands]) => ({
name: category.charAt(0).toUpperCase() + category.slice(1),
value: commands.map(cmd => `\`/${cmd}\``).join(", ")
}));

var embedReply = embedReplyPrimaryColorWithFields(
"Help - All Commands",
"You can check out all commands with descriptions on [the bot's wiki](https://github.com/vb2007/discordbot/wiki/Commands)",
[
...categoryFields,
{
name: "Tip.",
value: "You can use `/help <category>` to get a list of commands from a specific category."
}
],
interaction
);
}
else {
switch (commandCategory) {
case "utility":
embedReply = embedReplyPrimaryColorWithFields(
"Help - Utility Commands.",
"Here is a list of the bot's currently avaliable **utility** commands:",
[ utilityCommands ],
interaction
);
break;
case "fun":
embedReply = embedReplyPrimaryColorWithFields(
"Help - Fun Commands.",
"Here is a list of the bot's currently avaliable **fun** commands:",
[ funCommands ],
interaction
);
break;
case "economy":
embedReply = embedReplyPrimaryColorWithFields(
"Help - Economy Commands.",
"Here is a list of the bot's currently avaliable **economy** commands:",
[ economyCommands ],
interaction
);
break;
case "moderation":
embedReply = embedReplyPrimaryColorWithFields(
"Help - Moderation Commands.",
"Here is a list of the bot's currently avaliable **moderation** commands:",
[ moderationCommands ],
interaction
);
break;
case "administration":
embedReply = embedReplyPrimaryColorWithFields(
"Help - Administration Commands.",
"Here is a list of the bot's currently avaliable **administration** commands:",
[ administrationCommands ],
interaction
);
break;
default:
embedReply = embedReplyErrorColorWithFields(
"Help - Utility Commands.",
"Here is a list of the bot's currently avaliable **utility** commands:",
[ errorField ],
interaction
);
}
}

await interaction.reply({ embeds: [embedReply] });

Expand Down
Loading

0 comments on commit 158e611

Please sign in to comment.