3.1.5 Improved Interaction / Error Handling

This commit is contained in:
SowinskiBraeden committed 2023-01-23 08:50:22 -08:00
1 parent 05930e8d33
commit 14ea5a56c4
5 files changed
+86 -31

No files matched your search

+1 -1
View File
@@ -104,7 +104,7 @@ module.exports = {
) )
} }
return interaction.send({ embeds: [nameResult], components: [row] }); return interaction.send({ embeds: [nameResult], components: [row], flags: (1 << 6) });
}); });
}, },
}, },
+4 -2
View File
@@ -2,7 +2,7 @@ require('dotenv').config()
module.exports = { module.exports = {
Dev: "PRODUCTION", Dev: "PRODUCTION",
Version: "3.1.4", Version: "3.1.5",
Admins: ["362791661274660874"], // Admins of the bot Admins: ["362791661274660874"], // Admins of the bot
DefaultPrefix: "?", DefaultPrefix: "?",
socket: "https://www.linespolice-cad.com/", socket: "https://www.linespolice-cad.com/",
@@ -17,7 +17,9 @@ module.exports = {
api_token: process.env.API_TOKEN || "", api_token: process.env.API_TOKEN || "",
mongoURI: process.env.mongoURI || "mongodb://localhost:27017", mongoURI: process.env.mongoURI || "mongodb://localhost:27017",
dbo: process.env.dbo || "knoldus", dbo: process.env.dbo || "knoldus",
Colors: {
Red: "#ba0f0f"
},
Presence: { Presence: {
status: "online", // You can show online, idle, and dnd status: "online", // You can show online, idle, and dnd
name: "Grand Theft Auto V", // The message shown name: "Grand Theft Auto V", // The message shown
+1 -1
View File
@@ -12,7 +12,7 @@
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"colors": "^1.4.0", "colors": "^1.4.0",
"discord.js": "^14.5.0", "discord.js": "^14.3.0",
"dotenv": "^16.0.3", "dotenv": "^16.0.3",
"express": "^4.17.1", "express": "^4.17.1",
"moment-duration-format": "^2.3.2", "moment-duration-format": "^2.3.2",
+64 -27
View File
@@ -24,6 +24,7 @@ class LinesPoliceCadBot extends Client {
this.db; this.db;
this.dbo; this.dbo;
this.connectMongo(this.config.mongoURI, this.config.dbo); this.connectMongo(this.config.mongoURI, this.config.dbo);
this.databaseConnected = false;
this.LoadCommandsAndInteractionHandlers(); this.LoadCommandsAndInteractionHandlers();
this.LoadEvents(); this.LoadEvents();
@@ -31,11 +32,12 @@ class LinesPoliceCadBot extends Client {
this.ws.on("INTERACTION_CREATE", async (interaction) => { this.ws.on("INTERACTION_CREATE", async (interaction) => {
if (interaction.type!=3) { if (interaction.type!=3) {
client.log("Interaction")
let GuildDB = await this.GetGuild(interaction.guild_id); let GuildDB = await this.GetGuild(interaction.guild_id);
const command = interaction.data.name.toLowerCase(); const command = interaction.data.name.toLowerCase();
const args = interaction.data.options; const args = interaction.data.options;
client.log(`Interaction - ${command}`)
//Easy to send respnose so ;) //Easy to send respnose so ;)
interaction.guild = await this.guilds.fetch(interaction.guild_id); 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); let cmd = client.commands.get(command);
try { try {
cmd.SlashCommand.run(this, interaction, args, { GuildDB }); cmd.SlashCommand.run(this, interaction, args, { GuildDB });
} catch (err) { } catch (err) {
const embed = new EmbedBuilder() this.sendInternalError(interaction, err);
.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] });
} }
} }
}); });
@@ -66,9 +73,42 @@ class LinesPoliceCadBot extends Client {
} }
async connectMongo(mongoURI, dbo) { async connectMongo(mongoURI, dbo) {
this.db = await MongoClient.connect(mongoURI,{useUnifiedTopology:true}); let failed = false;
this.dbo = this.db.db(dbo);
this.log('Successfully connected to mongoDB'); 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 // This is for the 'panic' command when enabling panic
@@ -125,7 +165,7 @@ class LinesPoliceCadBot extends Client {
LoadCommandsAndInteractionHandlers() { LoadCommandsAndInteractionHandlers() {
let CommandsDir = path.join(__dirname, '..', 'commands'); let CommandsDir = path.join(__dirname, '..', 'commands');
fs.readdir(CommandsDir, (err, files) => { fs.readdir(CommandsDir, (err, files) => {
if (err) this.log(err); if (err) this.error(err);
else else
files.forEach((file) => { files.forEach((file) => {
let cmd = require(CommandsDir + "/" + file); let cmd = require(CommandsDir + "/" + file);
@@ -153,12 +193,22 @@ class LinesPoliceCadBot extends Client {
else else
files.forEach((file) => { files.forEach((file) => {
const event = require(EventsDir + "/" + 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]); 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) { sendTime(Channel, Error) {
let embed = new EmbedBuilder() let embed = new EmbedBuilder()
.setColor(this.config.EmbedColor) .setColor(this.config.EmbedColor)
@@ -232,21 +282,8 @@ class LinesPoliceCadBot extends Client {
} else return true // There is no role limits } else return true // There is no role limits
} }
log(Text) { log(Text) { this.logger.log(Text); }
this.logger.log(Text); error(Text) { this.logger.error(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);
}
build() { build() {
this.login(this.config.Token); this.login(this.config.Token);
+16
View File
@@ -23,6 +23,22 @@ class Logger {
) + colors.yellow(" | Info: " + Text) ) + 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; module.exports = Logger;