From 2f9d80f430e72fcd0281e510a14e800f9efd12f9 Mon Sep 17 00:00:00 2001 From: Ethan Lane Date: Fri, 1 Mar 2024 20:02:11 +0000 Subject: [PATCH 1/5] Fix trade command (#177) # Description Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. - Fix the decline button not working for the initiating user - Update labels on embed to follow "I Receive" and "You Receive" #165 ## Type of change Please delete options that are not relevant. - [x] Bug fix (non-breaking change which fixes an issue) # How Has This Been Tested? Please describe the tests that you ran to verify the changes. Provide instructions so we can reproduce. Please also list any relevant details to your test configuration. # Checklist - [ ] My code follows the style guidelines of this project - [ ] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that provde my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] Any dependent changes have been merged and published in downstream modules Reviewed-on: https://gitea.vylpes.xyz/External/card-drop/pulls/177 Reviewed-by: VylpesTester Co-authored-by: Ethan Lane Co-committed-by: Ethan Lane --- src/buttonEvents/Trade.ts | 18 +++++++++--------- src/commands/trade.ts | 18 +++++++++--------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/buttonEvents/Trade.ts b/src/buttonEvents/Trade.ts index 28b08ee..d272d9f 100644 --- a/src/buttonEvents/Trade.ts +++ b/src/buttonEvents/Trade.ts @@ -100,13 +100,13 @@ export default class Trade extends ButtonEvent { .setImage("https://i.imgur.com/9w5f1ls.gif") .addFields([ { - name: `${receiveUser.username} is giving`, - value: `${giveItem.id}: ${giveItem.name}`, + name: "I receieve", + value: `${receiveItem.id}: ${receiveItem.name}`, inline: true, }, { - name: `${giveUser.username} is giving`, - value: `${receiveItem.id}: ${receiveItem.name}`, + name: "You receieve", + value: `${giveItem.id}: ${giveItem.name}`, inline: true, }, { @@ -140,7 +140,7 @@ export default class Trade extends ButtonEvent { // No need to get expiry date const timeoutId = interaction.customId.split(" ")[7]; - if (interaction.user.id !== receiveUserId || interaction.user.id !== giveUserId) { + if (interaction.user.id != receiveUserId && interaction.user.id !==giveUserId) { await interaction.reply("You are not the user who the trade is intended for"); return; } @@ -170,13 +170,13 @@ export default class Trade extends ButtonEvent { .setImage("https://i.imgur.com/9w5f1ls.gif") .addFields([ { - name: `${receiveUser.username} is giving`, - value: `${giveItem.id}: ${giveItem.name}`, + name: "I Receive", + value: `${receiveItem.id}: ${receiveItem.name}`, inline: true, }, { - name: `${giveUser.username} is giving`, - value: `${receiveItem.id}: ${receiveItem.name}`, + name: "You Receive", + value: `${giveItem.id}: ${giveItem.name}`, inline: true, }, { diff --git a/src/commands/trade.ts b/src/commands/trade.ts index 60e78d8..8414ae9 100644 --- a/src/commands/trade.ts +++ b/src/commands/trade.ts @@ -63,19 +63,19 @@ export default class Trade extends Command { const expiry = now.setMinutes(now.getMinutes() + 15); const tradeEmbed = new EmbedBuilder() - .setTitle("Trade Offer") + .setTitle("⚠️ Trade Offer ⚠️") .setDescription(`Trade initiated between ${interaction.user.username} and ${user.username}`) .setColor(EmbedColours.Grey) .setImage("https://media1.tenor.com/m/KkZwKl2AQ2QAAAAd/trade-offer.gif") .addFields([ { - name: `${interaction.user.username} is giving`, - value: `${giveItem.id}: ${giveItem.name}`, + name: "I Receive", + value: `${receiveItem.id}: ${receiveItem.name}`, inline: true, }, { - name: `${user.username} is giving`, - value: `${receiveItem.id}: ${receiveItem.name}`, + name: "You Receive", + value: `${giveItem.id}: ${giveItem.name}`, inline: true, }, { @@ -109,13 +109,13 @@ export default class Trade extends Command { .setImage("https://media1.tenor.com/m/KkZwKl2AQ2QAAAAd/trade-offer.gif") .addFields([ { - name: `${receiveUsername} is giving`, - value: `${giveCardNumber}: ${giveCardName}`, + name: "I Receive", + value: `${receiveCardNumber}: ${receiveCardName}`, inline: true, }, { - name: `${giveUsername} is giving`, - value: `${receiveCardNumber}: ${receiveCardName}`, + name: "You Receive", + value: `${giveCardNumber}: ${giveCardName}`, inline: true, }, { From 42883c3a99df0cd340a92ee7d6216e40c96e6b2b Mon Sep 17 00:00:00 2001 From: Ethan Lane Date: Fri, 1 Mar 2024 20:03:34 +0000 Subject: [PATCH 2/5] Fix give command using the wrong username (#178) # Description Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. - Fix the give command incorrectly using the username of the user who used the command instead of the user who it was actually given to #174 ## Type of change Please delete options that are not relevant. - [x] Bug fix (non-breaking change which fixes an issue) # How Has This Been Tested? Please describe the tests that you ran to verify the changes. Provide instructions so we can reproduce. Please also list any relevant details to your test configuration. # Checklist - [ ] My code follows the style guidelines of this project - [ ] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that provde my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] Any dependent changes have been merged and published in downstream modules Reviewed-on: https://gitea.vylpes.xyz/External/card-drop/pulls/178 Reviewed-by: VylpesTester Co-authored-by: Ethan Lane Co-committed-by: Ethan Lane --- src/commands/give.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/commands/give.ts b/src/commands/give.ts index ad360a9..7bc24be 100644 --- a/src/commands/give.ts +++ b/src/commands/give.ts @@ -63,6 +63,6 @@ export default class Give extends Command { await inventory.Save(Inventory, inventory); - await interaction.reply(`${card.name} given to ${interaction.user}, they now have ${inventory.Quantity}`); + await interaction.reply(`${card.name} given to ${user.username}, they now have ${inventory.Quantity}`); } } \ No newline at end of file From 0c94c5817f518321b78b3fd1bde43a9c691f990a Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Tue, 5 Mar 2024 18:38:18 +0000 Subject: [PATCH 3/5] Update dependency @types/node to v20.11.24 (#179) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR contains the following updates: | Package | Type | Update | Change | |---|---|---|---| | [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node) ([source](https://github.com/DefinitelyTyped/DefinitelyTyped)) | devDependencies | patch | [`20.11.20` -> `20.11.24`](https://renovatebot.com/diffs/npm/@types%2fnode/20.11.20/20.11.24) | --- ### Configuration 📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box --- This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate). Reviewed-on: https://gitea.vylpes.xyz/External/card-drop/pulls/179 Reviewed-by: Vylpes Co-authored-by: Renovate Bot Co-committed-by: Renovate Bot --- package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index ee09231..91e48a2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1881,9 +1881,9 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "20.11.20", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.20.tgz", - "integrity": "sha512-7/rR21OS+fq8IyHTgtLkDK949uzsa6n8BkziAKtPVpugIkO6D+/ooXMvzXxDnZrmtXVfjb1bKQafYpb8s89LOg==", + "version": "20.11.24", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.24.tgz", + "integrity": "sha512-Kza43ewS3xoLgCEpQrsT+xRo/EJej1y0kVYGiLFE1NEODXGzTfwiC6tXTLMQskn1X4/Rjlh0MQUvx9W+L9long==", "dependencies": { "undici-types": "~5.26.4" } From 2377397a2e77f7f264a634dfed876aeb2873e9d1 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Tue, 5 Mar 2024 18:39:23 +0000 Subject: [PATCH 4/5] Update dependency express to v4.18.3 (#180) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR contains the following updates: | Package | Type | Update | Change | |---|---|---|---| | [express](http://expressjs.com/) ([source](https://github.com/expressjs/express)) | dependencies | patch | [`4.18.2` -> `4.18.3`](https://renovatebot.com/diffs/npm/express/4.18.2/4.18.3) | --- ### Release Notes
expressjs/express (express) ### [`v4.18.3`](https://github.com/expressjs/express/blob/HEAD/History.md#4183--2024-02-26) [Compare Source](https://github.com/expressjs/express/compare/4.18.2...4.18.3) \========== - Fix routing requests without method - deps: body-parser@1.20.2 - Fix strict json error message on Node.js 19+ - deps: content-type@~1.0.5 - deps: raw-body@2.5.2
--- ### Configuration 📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box --- This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate). Reviewed-on: https://gitea.vylpes.xyz/External/card-drop/pulls/180 Co-authored-by: Renovate Bot Co-committed-by: Renovate Bot --- package-lock.json | 42 ++++-------------------------------------- 1 file changed, 4 insertions(+), 38 deletions(-) diff --git a/package-lock.json b/package-lock.json index 91e48a2..b7bee01 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4692,12 +4692,13 @@ } }, "node_modules/express": { - "version": "4.18.2", - "license": "MIT", + "version": "4.18.3", + "resolved": "https://registry.npmjs.org/express/-/express-4.18.3.tgz", + "integrity": "sha512-6VyCijWQ+9O7WuVMTRBTl+cjNNIzD5cY5mQ1WM8r/LEkI2u8EYpOotESNwzNlyCn3g+dmjKYI6BmNneSr/FSRw==", "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", - "body-parser": "1.20.1", + "body-parser": "1.20.2", "content-disposition": "0.5.4", "content-type": "~1.0.4", "cookie": "0.5.0", @@ -4731,41 +4732,6 @@ "node": ">= 0.10.0" } }, - "node_modules/express/node_modules/body-parser": { - "version": "1.20.1", - "license": "MIT", - "dependencies": { - "bytes": "3.1.2", - "content-type": "~1.0.4", - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "1.2.0", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "on-finished": "2.4.1", - "qs": "6.11.0", - "raw-body": "2.5.1", - "type-is": "~1.6.18", - "unpipe": "1.0.0" - }, - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/express/node_modules/raw-body": { - "version": "2.5.1", - "license": "MIT", - "dependencies": { - "bytes": "3.1.2", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "unpipe": "1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, "node_modules/external-editor": { "version": "3.1.0", "dev": true, From 4a0050eb7054feda43cc62c106f7f0a15d1a0e6f Mon Sep 17 00:00:00 2001 From: Ethan Lane Date: Tue, 12 Mar 2024 17:42:02 +0000 Subject: [PATCH 5/5] WIP: Start of logging --- src/buttonEvents/Claim.ts | 3 ++ src/buttonEvents/Inventory.ts | 8 +++- src/buttonEvents/Reroll.ts | 8 +++- src/buttonEvents/Trade.ts | 7 +++ src/client/appLogger.ts | 19 ++++---- src/client/client.ts | 46 ++++++++++++++++--- src/client/events.ts | 5 +- src/client/interactionCreate/Button.ts | 8 +++- .../interactionCreate/ChatInputCommand.ts | 8 +++- src/client/util.ts | 5 ++ src/commands/drop.ts | 5 +- src/commands/gdrivesync.ts | 10 ++++ src/commands/give.ts | 3 ++ src/commands/inventory.ts | 3 ++ src/commands/resync.ts | 5 ++ src/commands/trade.ts | 5 ++ src/commands/view.ts | 7 ++- 17 files changed, 131 insertions(+), 24 deletions(-) diff --git a/src/buttonEvents/Claim.ts b/src/buttonEvents/Claim.ts index a9f8c86..53538f4 100644 --- a/src/buttonEvents/Claim.ts +++ b/src/buttonEvents/Claim.ts @@ -3,6 +3,7 @@ import { ButtonEvent } from "../type/buttonEvent"; import Inventory from "../database/entities/app/Inventory"; import { CoreClient } from "../client/client"; import { default as eClaim } from "../database/entities/app/Claim"; +import AppLogger from "../client/appLogger"; export default class Claim extends ButtonEvent { public override async execute(interaction: ButtonInteraction) { @@ -13,6 +14,8 @@ export default class Claim extends ButtonEvent { const droppedBy = interaction.customId.split(" ")[3]; const userId = interaction.user.id; + AppLogger.LogSilly("Button/Claim", `Parameters: cardNumber=${cardNumber}, claimId=${claimId}, droppedBy=${droppedBy}, userId=${userId}`); + await interaction.deferReply(); const claimed = await eClaim.FetchOneByClaimId(claimId); diff --git a/src/buttonEvents/Inventory.ts b/src/buttonEvents/Inventory.ts index 4bfffc1..7dfb305 100644 --- a/src/buttonEvents/Inventory.ts +++ b/src/buttonEvents/Inventory.ts @@ -1,6 +1,7 @@ import { ButtonInteraction } from "discord.js"; import { ButtonEvent } from "../type/buttonEvent"; import InventoryHelper from "../helpers/InventoryHelper"; +import AppLogger from "../client/appLogger"; export default class Inventory extends ButtonEvent { public override async execute(interaction: ButtonInteraction) { @@ -9,6 +10,8 @@ export default class Inventory extends ButtonEvent { const userid = interaction.customId.split(" ")[1]; const page = interaction.customId.split(" ")[2]; + AppLogger.LogSilly("Button/Inventory", `Parameters: userid=${userid}, page=${page}`); + const member = interaction.guild.members.cache.find(x => x.id == userid) || await interaction.guild.members.fetch(userid); if (!member) { @@ -17,6 +20,8 @@ export default class Inventory extends ButtonEvent { } try { + AppLogger.LogVerbose("Button/Inventory", `Generating inventory page ${page} for ${member.user.username} with id ${member.user.id}`); + const embed = await InventoryHelper.GenerateInventoryPage(member.user.username, member.user.id, Number(page)); await interaction.update({ @@ -24,7 +29,8 @@ export default class Inventory extends ButtonEvent { components: [ embed.row ], }); } catch (e) { - console.error(e); + AppLogger.LogError("Button/Inventory", `Error generating inventory page for ${member.user.username} with id ${member.user.id}: ${e}`); + await interaction.reply("No page for user found."); } } diff --git a/src/buttonEvents/Reroll.ts b/src/buttonEvents/Reroll.ts index a265bcb..c271a3a 100644 --- a/src/buttonEvents/Reroll.ts +++ b/src/buttonEvents/Reroll.ts @@ -7,6 +7,7 @@ import Inventory from "../database/entities/app/Inventory"; import Config from "../database/entities/app/Config"; import CardDropHelperMetadata from "../helpers/CardDropHelperMetadata"; import path from "path"; +import AppLogger from "../client/appLogger"; export default class Reroll extends ButtonEvent { public override async execute(interaction: ButtonInteraction) { @@ -16,6 +17,8 @@ export default class Reroll extends ButtonEvent { } if (await Config.GetValue("safemode") == "true") { + AppLogger.LogWarn("Button/Reroll", "Safe Mode is active, refusing to send next drop."); + await interaction.reply("Safe Mode has been activated, please resync to continue."); return; } @@ -30,6 +33,8 @@ export default class Reroll extends ButtonEvent { await interaction.deferReply(); try { + AppLogger.LogVerbose("Button/Reroll", `Sending next drop: ${randomCard.card.id} (${randomCard.card.name})`); + const image = readFileSync(path.join(process.env.DATA_DIR!, "cards", randomCard.card.path)); const imageFileName = randomCard.card.path.split("/").pop()!; @@ -51,9 +56,8 @@ export default class Reroll extends ButtonEvent { }); CoreClient.ClaimId = claimId; - } catch (e) { - console.error(e); + AppLogger.LogError("Button/Reroll", `Error sending next drop for card ${randomCard.card.id}: ${e}`); await interaction.editReply(`Unable to send next drop. Please try again, and report this if it keeps happening. (${randomCard.card.id})`); } diff --git a/src/buttonEvents/Trade.ts b/src/buttonEvents/Trade.ts index d272d9f..9ce4e56 100644 --- a/src/buttonEvents/Trade.ts +++ b/src/buttonEvents/Trade.ts @@ -3,11 +3,14 @@ import { ButtonEvent } from "../type/buttonEvent"; import { CoreClient } from "../client/client"; import Inventory from "../database/entities/app/Inventory"; import EmbedColours from "../constants/EmbedColours"; +import AppLogger from "../client/appLogger"; export default class Trade extends ButtonEvent { public override async execute(interaction: ButtonInteraction) { const action = interaction.customId.split(" ")[1]; + AppLogger.LogSilly("Button/Trade", `Parameters: action=${action}`); + switch (action) { case "accept": await this.AcceptTrade(interaction); @@ -26,6 +29,8 @@ export default class Trade extends ButtonEvent { const expiry = interaction.customId.split(" ")[6]; const timeoutId = interaction.customId.split(" ")[7]; + AppLogger.LogSilly("Button/Trade/AcceptTrade", `Parameters: giveUserId=${giveUserId}, receiveUserId=${receiveUserId}, giveCardNumber=${giveCardNumber}, receiveCardNumber=${receiveCardNumber}, expiry=${expiry}, timeoutId=${timeoutId}`); + const expiryDate = new Date(expiry); if (expiryDate < new Date()) { @@ -140,6 +145,8 @@ export default class Trade extends ButtonEvent { // No need to get expiry date const timeoutId = interaction.customId.split(" ")[7]; + AppLogger.LogSilly("Button/Trade/DeclineTrade", `Parameters: giveUserId=${giveUserId}, receiveUserId=${receiveUserId}, giveCardNumber=${giveCardNumber}, receiveCardNumber=${receiveCardNumber}, timeoutId=${timeoutId}`); + if (interaction.user.id != receiveUserId && interaction.user.id !==giveUserId) { await interaction.reply("You are not the user who the trade is intended for"); return; diff --git a/src/client/appLogger.ts b/src/client/appLogger.ts index b06627b..e865e48 100644 --- a/src/client/appLogger.ts +++ b/src/client/appLogger.ts @@ -1,8 +1,9 @@ import { Logger, createLogger, format, transports } from "winston"; -import { CoreClient } from "./client"; export default class AppLogger { - public static InitialiseLogger(logLevel: string, outputToConsole: boolean): Logger { + public static Logger: Logger; + + public static InitialiseLogger(logLevel: string, outputToConsole: boolean) { const customFormat = format.printf(({ level, message, timestamp, label }) => { return `${timestamp} [${label}] ${level}: ${message}`; }); @@ -33,30 +34,30 @@ export default class AppLogger { )})); } - return logger; + AppLogger.Logger = logger; } public static LogError(label: string, message: string) { - CoreClient.Logger.error({ label, message }); + AppLogger.Logger.error({ label, message }); } public static LogWarn(label: string, message: string) { - CoreClient.Logger.warn({ label, message }); + AppLogger.Logger.warn({ label, message }); } public static LogInfo(label: string, message: string) { - CoreClient.Logger.info({ label, message }); + AppLogger.Logger.info({ label, message }); } public static LogVerbose(label: string, message: string) { - CoreClient.Logger.verbose({ label, message }); + AppLogger.Logger.verbose({ label, message }); } public static LogDebug(label: string, message: string) { - CoreClient.Logger.debug({ label, message }); + AppLogger.Logger.debug({ label, message }); } public static LogSilly(label: string, message: string) { - CoreClient.Logger.silly({ label, message }); + AppLogger.Logger.silly({ label, message }); } } \ No newline at end of file diff --git a/src/client/client.ts b/src/client/client.ts index b31cd3d..92fbc5e 100644 --- a/src/client/client.ts +++ b/src/client/client.ts @@ -13,7 +13,6 @@ import { Environment } from "../constants/Environment"; import Webhooks from "../webhooks"; import CardMetadataFunction from "../Functions/CardMetadataFunction"; import { SeriesMetadata } from "../contracts/SeriesMetadata"; -import { Logger } from "winston"; import AppLogger from "./appLogger"; export class CoreClient extends Client { @@ -29,7 +28,6 @@ export class CoreClient extends Client { public static Environment: Environment; public static AllowDrops: boolean; public static Cards: SeriesMetadata[]; - public static Logger: Logger; public static get commandItems(): ICommandItem[] { return this._commandItems; @@ -49,7 +47,9 @@ export class CoreClient extends Client { CoreClient.Environment = Number(process.env.BOT_ENV); - CoreClient.Logger = AppLogger.InitialiseLogger(process.env.BOT_VERBOSE == "true" ? "verbose" : "info", CoreClient.Environment == Environment.Local); + AppLogger.InitialiseLogger(process.env.BOT_VERBOSE == "true" ? "verbose" : "info", CoreClient.Environment == Environment.Local); + + AppLogger.LogInfo("Client", "Initialising Client"); CoreClient._commandItems = []; CoreClient._buttonEvents = []; @@ -58,20 +58,24 @@ export class CoreClient extends Client { this._util = new Util(); this._webhooks = new Webhooks(); - console.log(`Bot Environment: ${CoreClient.Environment}`); + AppLogger.LogInfo("Client", `Environment: ${CoreClient.Environment}`); CoreClient.AllowDrops = true; } public async start() { if (!process.env.BOT_TOKEN) { - console.error("BOT_TOKEN is not defined in .env"); + AppLogger.LogError("Client", "BOT_TOKEN is not defined in .env"); return; } await AppDataSource.initialize() - .then(() => console.log("App Data Source Initialised")) - .catch(err => console.error("Error initialising App Data Source", err)); + .then(() => AppLogger.LogInfo("Client", "App Data Source Initialised")) + .catch(err => { + AppLogger.LogError("Client", "App Data Source Initialisation Failed"); + AppLogger.LogError("Client", err); + throw err; + }); super.on("interactionCreate", this._events.onInteractionCreate); super.on("ready", this._events.onReady); @@ -96,6 +100,8 @@ export class CoreClient extends Client { if ((environment & CoreClient.Environment) == CoreClient.Environment) { CoreClient._commandItems.push(item); + + AppLogger.LogVerbose("Client", `Registered Command: ${name}`); } } @@ -118,6 +124,8 @@ export class CoreClient extends Client { MessageUpdate: [], }; } + + AppLogger.LogVerbose("Client", `Registered Channel Create Event`); } public static RegisterChannelDeleteEvent(fn: (channel: DMChannel | NonThreadGuildBasedChannel) => void) { @@ -139,6 +147,8 @@ export class CoreClient extends Client { MessageUpdate: [], }; } + + AppLogger.LogVerbose("Client", `Registered Channel Delete Event`); } public static RegisterChannelUpdateEvent(fn: (channel: DMChannel | NonThreadGuildBasedChannel) => void) { @@ -160,6 +170,8 @@ export class CoreClient extends Client { MessageUpdate: [], }; } + + AppLogger.LogVerbose("Client", `Registered Channel Update Event`); } public static RegisterGuildBanAddEvent(fn: (ban: GuildBan) => void) { @@ -181,6 +193,8 @@ export class CoreClient extends Client { MessageUpdate: [], }; } + + AppLogger.LogVerbose("Client", `Registered Guild Ban Add Event`); } public static RegisterGuildBanRemoveEvent(fn: (channel: GuildBan) => void) { @@ -202,6 +216,8 @@ export class CoreClient extends Client { MessageUpdate: [], }; } + + AppLogger.LogVerbose("Client", `Registered Guild Ban Remove Event`); } public static RegisterGuildCreateEvent(fn: (guild: Guild) => void) { @@ -223,6 +239,8 @@ export class CoreClient extends Client { MessageUpdate: [], }; } + + AppLogger.LogVerbose("Client", `Registered Guild Create Event`); } public static RegisterGuildMemberAddEvent(fn: (member: GuildMember) => void) { @@ -244,6 +262,8 @@ export class CoreClient extends Client { MessageUpdate: [], }; } + + AppLogger.LogVerbose("Client", `Registered Guild Member Add Event`); } public static RegisterGuildMemberRemoveEvent(fn: (member: GuildMember | PartialGuildMember) => void) { @@ -265,6 +285,8 @@ export class CoreClient extends Client { MessageUpdate: [], }; } + + AppLogger.LogVerbose("Client", `Registered Guild Member Remove Event`); } public static GuildMemebrUpdate(fn: (oldMember: GuildMember | PartialGuildMember, newMember: GuildMember) => void) { @@ -286,6 +308,8 @@ export class CoreClient extends Client { MessageUpdate: [], }; } + + AppLogger.LogVerbose("Client", `Registered Guild Member Update Event`); } public static RegisterMessageCreateEvent(fn: (message: Message) => void) { @@ -307,6 +331,8 @@ export class CoreClient extends Client { MessageUpdate: [], }; } + + AppLogger.LogVerbose("Client", `Registered Message Create Event`); } public static RegisterMessageDeleteEvent(fn: (message: Message | PartialMessage) => void) { @@ -328,6 +354,8 @@ export class CoreClient extends Client { MessageUpdate: [], }; } + + AppLogger.LogVerbose("Client", `Registered Message Delete Event`); } public static RegisterMessageUpdateEvent(fn: (oldMessage: Message | PartialMessage, newMessage: Message | PartialMessage) => void) { @@ -349,6 +377,8 @@ export class CoreClient extends Client { MessageUpdate: [ fn ], }; } + + AppLogger.LogVerbose("Client", `Registered Message Update Event`); } public static RegisterButtonEvent(buttonId: string, event: ButtonEvent, environment: Environment = Environment.All) { @@ -360,6 +390,8 @@ export class CoreClient extends Client { if ((environment & CoreClient.Environment) == CoreClient.Environment) { CoreClient._buttonEvents.push(item); + + AppLogger.LogVerbose("Client", `Registered Button Event: ${buttonId}`); } } } diff --git a/src/client/events.ts b/src/client/events.ts index db6cfc4..0b82cee 100644 --- a/src/client/events.ts +++ b/src/client/events.ts @@ -1,22 +1,25 @@ import { Interaction } from "discord.js"; import ChatInputCommand from "./interactionCreate/ChatInputCommand"; import Button from "./interactionCreate/Button"; +import AppLogger from "./appLogger"; export class Events { public async onInteractionCreate(interaction: Interaction) { if (!interaction.guildId) return; if (interaction.isChatInputCommand()) { + AppLogger.LogVerbose("Client", `ChatInputCommand: ${interaction.commandName}`); ChatInputCommand.onChatInput(interaction); } if (interaction.isButton()) { + AppLogger.LogVerbose("Client", `Button: ${interaction.customId}`); Button.onButtonClicked(interaction); } } // Emit when bot is logged in and ready to use public onReady() { - console.log("Ready"); + AppLogger.LogInfo("Client", "Ready"); } } diff --git a/src/client/interactionCreate/Button.ts b/src/client/interactionCreate/Button.ts index 6d6a926..b8abbfc 100644 --- a/src/client/interactionCreate/Button.ts +++ b/src/client/interactionCreate/Button.ts @@ -1,5 +1,6 @@ import { ButtonInteraction } from "discord.js"; import { CoreClient } from "../client"; +import AppLogger from "../appLogger"; export default class Button { public static async onButtonClicked(interaction: ButtonInteraction) { @@ -8,14 +9,19 @@ export default class Button { const item = CoreClient.buttonEvents.find(x => x.ButtonId == interaction.customId.split(" ")[0]); if (!item) { + AppLogger.LogVerbose("Button", `Event not found: ${interaction.customId}`); + await interaction.reply("Event not found"); return; } try { + AppLogger.LogDebug("Button", `Executing ${interaction.customId}`); + item.Event.execute(interaction); } catch (e) { - console.error(e); + AppLogger.LogError("Button", `Error occurred while executing event: ${interaction.customId}`); + AppLogger.LogError("Button", e as string); await interaction.reply("An error occurred while executing the event"); } diff --git a/src/client/interactionCreate/ChatInputCommand.ts b/src/client/interactionCreate/ChatInputCommand.ts index 784ce6e..47f7b37 100644 --- a/src/client/interactionCreate/ChatInputCommand.ts +++ b/src/client/interactionCreate/ChatInputCommand.ts @@ -1,6 +1,7 @@ import { Interaction } from "discord.js"; import { CoreClient } from "../client"; import ICommandItem from "../../contracts/ICommandItem"; +import AppLogger from "../appLogger"; export default class ChatInputCommand { public static async onChatInput(interaction: Interaction) { @@ -13,6 +14,8 @@ export default class ChatInputCommand { if (!itemForServer) { if (!item) { + AppLogger.LogVerbose("ChatInputCommand", `Command not found: ${interaction.commandName}`); + await interaction.reply("Command not found"); return; } @@ -23,9 +26,12 @@ export default class ChatInputCommand { } try { + AppLogger.LogDebug("Command", `Executing ${interaction.commandName}`); + itemToUse.Command.execute(interaction); } catch (e) { - console.error(e); + AppLogger.LogError("ChatInputCommand", `Error occurred while executing command: ${interaction.commandName}`); + AppLogger.LogError("ChatInputCommand", e as string); await interaction.reply("An error occurred while executing the command"); } diff --git a/src/client/util.ts b/src/client/util.ts index ddd84fc..47daa3d 100644 --- a/src/client/util.ts +++ b/src/client/util.ts @@ -1,6 +1,7 @@ import { Client, REST, Routes, SlashCommandBuilder } from "discord.js"; import EventExecutors from "../contracts/EventExecutors"; import { CoreClient } from "./client"; +import AppLogger from "./appLogger"; export class Util { public loadSlashCommands(client: Client) { @@ -29,6 +30,8 @@ export class Util { const rest = new REST({ version: "10" }).setToken(process.env.BOT_TOKEN!); + AppLogger.LogVerbose("Util", `REST PUT: ${globalCommandData.flatMap(x => x.name).join(", ")}`); + rest.put( Routes.applicationCommands(process.env.BOT_CLIENTID!), { @@ -49,6 +52,8 @@ export class Util { if (!client.guilds.cache.has(guild)) continue; + AppLogger.LogVerbose("Util", `REST PUT: ${guild} - ${guildCommandData.flatMap(x => x.name).join(", ")}`); + rest.put( Routes.applicationGuildCommands(process.env.BOT_CLIENTID!, guild), { diff --git a/src/commands/drop.ts b/src/commands/drop.ts index e671e76..65b2b3e 100644 --- a/src/commands/drop.ts +++ b/src/commands/drop.ts @@ -7,6 +7,7 @@ import Inventory from "../database/entities/app/Inventory"; import Config from "../database/entities/app/Config"; import CardDropHelperMetadata from "../helpers/CardDropHelperMetadata"; import path from "path"; +import AppLogger from "../client/appLogger"; export default class Drop extends Command { constructor() { @@ -24,6 +25,8 @@ export default class Drop extends Command { } if (await Config.GetValue("safemode") == "true") { + AppLogger.LogWarn("Commands/Drop", "Safe Mode is active, refusing to send next drop."); + await interaction.reply("Safe Mode has been activated, please resync to continue."); return; } @@ -61,7 +64,7 @@ export default class Drop extends Command { CoreClient.ClaimId = claimId; } catch (e) { - console.error(e); + AppLogger.LogError("Commands/Drop", `Error sending next drop for card ${randomCard.card.id}: ${e}`); await interaction.editReply(`Unable to send next drop. Please try again, and report this if it keeps happening. (${randomCard.card.id})`); } diff --git a/src/commands/gdrivesync.ts b/src/commands/gdrivesync.ts index c8a393c..b02c873 100644 --- a/src/commands/gdrivesync.ts +++ b/src/commands/gdrivesync.ts @@ -4,6 +4,7 @@ import { ExecException, exec } from "child_process"; import { CoreClient } from "../client/client"; import Config from "../database/entities/app/Config"; import CardMetadataFunction from "../Functions/CardMetadataFunction"; +import AppLogger from "../client/appLogger"; export default class Gdrivesync extends Command { constructor() { @@ -32,19 +33,28 @@ export default class Gdrivesync extends Command { CoreClient.AllowDrops = false; + AppLogger.LogInfo("Commands/GDriveSync", "Syncing google drive to the bot"); + exec(`rclone sync card-drop-gdrive: ${process.env.DATA_DIR}/cards`, async (error: ExecException | null) => { if (error) { + AppLogger.LogError("Commands/GDriveSync", `Error while running sync command: ${error.code}, ${error.message}`); + AppLogger.LogWarn("Commands/GDriveSync", "Safe mode activated"); + await interaction.editReply(`Error while running sync command. Safe Mode has been activated. Code: ${error.code}`); await Config.SetValue("safemode", "true"); } else { const result = await CardMetadataFunction.Execute(true); if (result.IsSuccess) { + AppLogger.LogInfo("Commands/GDriveSync", "Synced successfully"); + await interaction.editReply("Synced successfully."); CoreClient.AllowDrops = true; await Config.SetValue("safemode", "false"); } else { + AppLogger.LogError("Commands/GDriveSync", `Error while running sync command: ${result.ErrorMessage}`); + await interaction.editReply(`Sync failed \`\`\`${result.ErrorMessage}\`\`\``); } } diff --git a/src/commands/give.ts b/src/commands/give.ts index 7bc24be..5121dda 100644 --- a/src/commands/give.ts +++ b/src/commands/give.ts @@ -4,6 +4,7 @@ import { CoreClient } from "../client/client"; import Config from "../database/entities/app/Config"; import CardDropHelperMetadata from "../helpers/CardDropHelperMetadata"; import Inventory from "../database/entities/app/Inventory"; +import AppLogger from "../client/appLogger"; export default class Give extends Command { constructor() { @@ -46,6 +47,8 @@ export default class Give extends Command { const cardNumber = interaction.options.get("cardnumber", true); const user = interaction.options.getUser("user", true); + AppLogger.LogSilly("Commands/Give", `Parameters: cardNumber=${cardNumber.value}, user=${user.id}`); + const card = CardDropHelperMetadata.GetCardByCardNumber(cardNumber.value!.toString()); if (!card) { diff --git a/src/commands/inventory.ts b/src/commands/inventory.ts index 868b14d..6c5ee51 100644 --- a/src/commands/inventory.ts +++ b/src/commands/inventory.ts @@ -1,6 +1,7 @@ import { CommandInteraction, SlashCommandBuilder } from "discord.js"; import { Command } from "../type/command"; import InventoryHelper from "../helpers/InventoryHelper"; +import AppLogger from "../client/appLogger"; export default class Inventory extends Command { constructor() { @@ -23,6 +24,8 @@ export default class Inventory extends Command { const page = interaction.options.get("page"); const user = interaction.options.getUser("user") || interaction.user; + AppLogger.LogSilly("Commands/Inventory", `Parameters: page=${page?.value}, user=${user.id}`); + try { let pageNumber = 0; diff --git a/src/commands/resync.ts b/src/commands/resync.ts index 7040d52..887208f 100644 --- a/src/commands/resync.ts +++ b/src/commands/resync.ts @@ -2,6 +2,7 @@ import { CacheType, CommandInteraction, PermissionsBitField, SlashCommandBuilder import { Command } from "../type/command"; import Config from "../database/entities/app/Config"; import CardMetadataFunction from "../Functions/CardMetadataFunction"; +import AppLogger from "../client/appLogger"; export default class Resync extends Command { constructor() { @@ -23,6 +24,8 @@ export default class Resync extends Command { return; } + AppLogger.LogInfo("Commands/Resync", "Resyncing database"); + const result = await CardMetadataFunction.Execute(true); if (result) { @@ -34,6 +37,8 @@ export default class Resync extends Command { } await interaction.reply("Resynced database."); } else { + AppLogger.LogWarn("Commands/Resync", "Resync failed, safe mode activated"); + await interaction.reply("Resync failed, safe mode has been activated until successful resync."); } } diff --git a/src/commands/trade.ts b/src/commands/trade.ts index 8414ae9..60f9033 100644 --- a/src/commands/trade.ts +++ b/src/commands/trade.ts @@ -3,6 +3,7 @@ import { Command } from "../type/command"; import Inventory from "../database/entities/app/Inventory"; import { CoreClient } from "../client/client"; import EmbedColours from "../constants/EmbedColours"; +import AppLogger from "../client/appLogger"; export default class Trade extends Command { constructor() { @@ -33,6 +34,8 @@ export default class Trade extends Command { const give = interaction.options.get("give")!; const receive = interaction.options.get("receive")!; + AppLogger.LogSilly("Commands/Trade", `Parameters: user=${user.id}, give=${give.value}, receive=${receive.value}`); + const giveItemEntity = await Inventory.FetchOneByCardNumberAndUserId(interaction.user.id, give.value!.toString()); const receiveItemEntity = await Inventory.FetchOneByCardNumberAndUserId(user.id, receive.value!.toString()); @@ -102,6 +105,8 @@ export default class Trade extends Command { } private async autoDecline(interaction: CommandInteraction, giveUsername: string, receiveUsername: string, giveCardNumber: string, receiveCardNumber: string, giveCardName: string, receiveCardName: string) { + AppLogger.LogSilly("Commands/Trade/AutoDecline", `Auto declining trade between ${giveUsername} and ${receiveUsername}`); + const tradeEmbed = new EmbedBuilder() .setTitle("Trade Expired") .setDescription(`Trade initiated between ${receiveUsername} and ${giveUsername}`) diff --git a/src/commands/view.ts b/src/commands/view.ts index 8f89eb4..ce6f9cb 100644 --- a/src/commands/view.ts +++ b/src/commands/view.ts @@ -5,6 +5,7 @@ import { readFileSync } from "fs"; import path from "path"; import Inventory from "../database/entities/app/Inventory"; import CardDropHelperMetadata from "../helpers/CardDropHelperMetadata"; +import AppLogger from "../client/appLogger"; export default class View extends Command { constructor() { @@ -23,6 +24,8 @@ export default class View extends Command { public override async execute(interaction: CommandInteraction) { const cardNumber = interaction.options.get("cardnumber"); + AppLogger.LogSilly("Commands/View", `Parameters: cardNumber=${cardNumber?.value}`); + if (!cardNumber || !cardNumber.value) { await interaction.reply("Card number is required."); return; @@ -46,6 +49,8 @@ export default class View extends Command { try { image = readFileSync(path.join(process.env.DATA_DIR!, "cards", card.path)); } catch { + AppLogger.LogError("Commands/View", `Unable to fetch image for card ${card.id}.`); + await interaction.reply(`Unable to fetch image for card ${card.id}.`); return; } @@ -65,7 +70,7 @@ export default class View extends Command { files: [ attachment ], }); } catch (e) { - console.error(e); + AppLogger.LogError("Commands/View", `Error sending view for card ${card.id}: ${e}`); if (e instanceof DiscordAPIError) { await interaction.editReply(`Unable to send next drop. Please try again, and report this if it keeps happening. Code: ${e.code}.`);