From 14ea5a56c4eb6492c88fc9b5ec0607eddb98ab07 Mon Sep 17 00:00:00 2001 From: Braeden Sowinski Date: Mon, 23 Jan 2023 08:50:22 -0800 Subject: [PATCH] 3.1.5 Improved Interaction / Error Handling --- commands/updateLicense.js | 2 +- config/config.js | 6 ++- package.json | 2 +- structures/LinesPoliceCadBot.js | 91 +++++++++++++++++++++++---------- util/Logger.js | 16 ++++++ 5 files changed, 86 insertions(+), 31 deletions(-) diff --git a/commands/updateLicense.js b/commands/updateLicense.js index a8d42ed..8835592 100644 --- a/commands/updateLicense.js +++ b/commands/updateLicense.js @@ -104,7 +104,7 @@ module.exports = { ) } - return interaction.send({ embeds: [nameResult], components: [row] }); + return interaction.send({ embeds: [nameResult], components: [row], flags: (1 << 6) }); }); }, }, diff --git a/config/config.js b/config/config.js index fadfa63..361ba8d 100644 --- a/config/config.js +++ b/config/config.js @@ -2,7 +2,7 @@ require('dotenv').config() module.exports = { Dev: "PRODUCTION", - Version: "3.1.4", + Version: "3.1.5", Admins: ["362791661274660874"], // Admins of the bot DefaultPrefix: "?", socket: "https://www.linespolice-cad.com/", @@ -17,7 +17,9 @@ module.exports = { api_token: process.env.API_TOKEN || "", mongoURI: process.env.mongoURI || "mongodb://localhost:27017", dbo: process.env.dbo || "knoldus", - + Colors: { + Red: "#ba0f0f" + }, Presence: { status: "online", // You can show online, idle, and dnd name: "Grand Theft Auto V", // The message shown diff --git a/package.json b/package.json index c6e5497..6be88b6 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "license": "ISC", "dependencies": { "colors": "^1.4.0", - "discord.js": "^14.5.0", + "discord.js": "^14.3.0", "dotenv": "^16.0.3", "express": "^4.17.1", "moment-duration-format": "^2.3.2", diff --git a/structures/LinesPoliceCadBot.js b/structures/LinesPoliceCadBot.js index c3d0467..7c03ee4 100644 --- a/structures/LinesPoliceCadBot.js +++ b/structures/LinesPoliceCadBot.js @@ -24,6 +24,7 @@ class LinesPoliceCadBot extends Client { this.db; this.dbo; this.connectMongo(this.config.mongoURI, this.config.dbo); + this.databaseConnected = false; this.LoadCommandsAndInteractionHandlers(); this.LoadEvents(); @@ -31,11 +32,12 @@ class LinesPoliceCadBot extends Client { this.ws.on("INTERACTION_CREATE", async (interaction) => { if (interaction.type!=3) { - client.log("Interaction") let GuildDB = await this.GetGuild(interaction.guild_id); - + const command = interaction.data.name.toLowerCase(); const args = interaction.data.options; + + client.log(`Interaction - ${command}`) //Easy to send respnose so ;) interaction.guild = await this.guilds.fetch(interaction.guild_id); @@ -49,15 +51,20 @@ class LinesPoliceCadBot extends Client { } }); }; + + if (!this.databaseConnected) { + let dbFailedEmbed = new EmbedBuilder() + .setDescription(`**Internal Error:**\nUh Oh D: Its not you, its me.\nThe bot has failed to connect to the database 5 times!\nContact the Developers`) + .setColor(client.config.Colors.Red); + + return interaction.send({ embeds: [dbFailedEmbed] }); + } + let cmd = client.commands.get(command); try { cmd.SlashCommand.run(this, interaction, args, { GuildDB }); } catch (err) { - const embed = new EmbedBuilder() - .setDescription(`**Internal Error:**\nUh Oh D: Its not you, its me.\nThis command has crashed\nContact the Developers`) - .setColor(client.config.Colors.Red) - - return interaction.send({ embeds: [embed] }); + this.sendInternalError(interaction, err); } } }); @@ -66,9 +73,42 @@ class LinesPoliceCadBot extends Client { } async connectMongo(mongoURI, dbo) { - this.db = await MongoClient.connect(mongoURI,{useUnifiedTopology:true}); - this.dbo = this.db.db(dbo); - this.log('Successfully connected to mongoDB'); + let failed = false; + + let dbLogDir = path.join(__dirname, '..', 'logs', 'database-logs.json'); + let databaselogs; + try { + databaselogs = JSON.parse(fs.readFileSync(dbLogDir)); + } catch (err) { + databaselogs = { + attempts: 0, + connected: false, + } + } + + if (databaselogslogs.attempts >= 5) { + this.error('Failed to connect to mongodb after multiple attempts'); + return; // prevent further attempts + } + + try { + // Connect to MongoDB + this.db = await MongoClient.connect(mongoURI,{useUnifiedTopology:true}); + this.dbo = this.db.db(dbo); + this.log('Successfully connected to mongoDB'); + databaselogs.connected = true; + databaselogs.attempts = 0; + this.databaseConnected = true; + } catch (err) { + databaselogs.attempts++; + this.error(`Failed to connect to mongodb: attempt ${databaselogs.attempts}`); + failed = true; + } + + // write JSON string to a file + await fs.writeFileSync(dbLogDir, JSON.stringify(databaselogs)); + + if (failed) process.exit(-1); } // This is for the 'panic' command when enabling panic @@ -125,7 +165,7 @@ class LinesPoliceCadBot extends Client { LoadCommandsAndInteractionHandlers() { let CommandsDir = path.join(__dirname, '..', 'commands'); fs.readdir(CommandsDir, (err, files) => { - if (err) this.log(err); + if (err) this.error(err); else files.forEach((file) => { let cmd = require(CommandsDir + "/" + file); @@ -153,12 +193,22 @@ class LinesPoliceCadBot extends Client { else files.forEach((file) => { const event = require(EventsDir + "/" + file); - this.on(file.split(".")[0], event.bind(null, this)); + if (file.split(".")[0] == 'interactionCreate') this.on(file.split(".")[0], i => event(this, i)); + else this.on(file.split(".")[0], event.bind(null, this)); this.logger.log("Event Loaded: " + file.split(".")[0]); }); }); } + sendInternalError(Interaction, Error) { + this.error(Error); + const embed = new EmbedBuilder() + .setDescription(`**Internal Error:**\nUh Oh D: Its not you, its me.\nThis command has crashed\nCOntact the Developers`) + .setColor(this.config.Colors.Red) + + Interaction.send({ embeds: [embed] }); + } + sendTime(Channel, Error) { let embed = new EmbedBuilder() .setColor(this.config.EmbedColor) @@ -232,21 +282,8 @@ class LinesPoliceCadBot extends Client { } else return true // There is no role limits } - log(Text) { - this.logger.log(Text); - } - - sendError(Channel, Error) { - let embed = new EmbedBuilder() - .setTitle("An error occured") - .setColor("RED") - .setDescription(Error) - .setFooter({ - text: "If you think this as a bug, please report it in the support server!" - }); - - Channel.send(embed); - } + log(Text) { this.logger.log(Text); } + error(Text) { this.logger.error(Text); } build() { this.login(this.config.Token); diff --git a/util/Logger.js b/util/Logger.js index 68c24b4..84965d0 100644 --- a/util/Logger.js +++ b/util/Logger.js @@ -23,6 +23,22 @@ class Logger { ) + colors.yellow(" | Info: " + Text) ); } + + error(Text) { + let d = new Date(); + this.logger.log({ + level: "error", + message: + `${d.getHours()}:${ + d.getMInutes + } - ${d.getData()}:${d.getMonth()}:${d.getFullYear()} | Error: ` + Text, + }); + console.log( + colors.green( + `${d.getDate()}:${d.getMonth()}:${d.getFullYear()} - ${d.getHours}:${d.getMinutes()}` + ) + colors.yellow(" | Error: ") + colors.red(Text) + ); + } } module.exports = Logger; \ No newline at end of file