diff --git a/src/DayZRBot.ts b/src/DayZRBot.ts index 22e3888..e2c6895 100644 --- a/src/DayZRBot.ts +++ b/src/DayZRBot.ts @@ -32,7 +32,7 @@ import { MongoClient } from "mongodb"; import { Colors, Config } from "./config/config"; // Utilities -import Logger from "./util/Logger"; +import Logger from "./services/Logger"; import { decrypt } from "./util/Cryptic"; import { DownloadNitradoFile, @@ -40,12 +40,13 @@ import { FetchServerSettings, PostServerSettings, NitradoCredentialStatus, -} from "./util/NitradoAPI"; -import { RegisterGlobalCommands, RegisterGuildCommands } from "./util/RegisterSlashCommands"; -import { HandlePlayerLogs, HandleActivePlayersList } from "./util/LogsHandler"; -import { HandleKillfeed, UpdateLastDeathDate } from "./util/KillfeedHandler"; -import { HandleExpiredUAVs, HandleEvents, PlaceFireplaceInAlarm } from "./util/AlarmsHandler"; -import { GetWebhook, WebhookSend } from "./util/WebhookHandler"; +} from "./services/NitradoAPI"; +import { RegisterGlobalCommands, RegisterGuildCommands } from "./services/RegisterSlashCommands"; +import { HandlePlayerLogs, HandleActivePlayersList } from "./handlers/LogsHandler"; +import { HandleKillfeed, UpdateLastDeathDate } from "./handlers/KillfeedHandler"; +import { HandleExpiredUAVs, HandleEvents, PlaceFireplaceInAlarm } from "./handlers/AlarmsHandler"; +import { GetWebhook, WebhookSend } from "./services/WebhookService"; +import isDefined from "./util/Validation"; // Database import { Player, UpdatePlayer, getDefaultPlayer } from "./database/player"; @@ -223,7 +224,7 @@ export default class DayZR extends Client let GuildDB: GuildConfig = await GetGuild(this, interaction.guildId); - if (this.exists(GuildDB.Nitrado) && this.exists(GuildDB.Nitrado.Auth)) + if (isDefined(GuildDB.Nitrado) && isDefined(GuildDB.Nitrado.Auth)) { GuildDB.Nitrado.Auth = decrypt( GuildDB.Nitrado.Auth, @@ -545,16 +546,16 @@ export default class DayZR extends Client }; // Skip this player if the player does not exist. - if (!this.exists(info.player) || !this.exists(info.playerID)) continue; + if (!isDefined(info.player) || !isDefined(info.playerID)) continue; lastDetectedTime = this.getDateEST(info.time); let playerStat: Player = await this.dbo.collection("players").findOne({ "playerID": info.playerID }); - if (!this.exists(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, guild.Nitrado.ServerID); + if (!isDefined(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, guild.Nitrado.ServerID); // Skip this player if the lastDisconnectionDate time is later than the player log entry. if (!previouslyConnected.includes(playerStat) && - this.exists(playerStat.lastDisconnectionDate) && + isDefined(playerStat.lastDisconnectionDate) && playerStat.lastDisconnectionDate !== null && playerStat.lastDisconnectionDate.getTime() > lastDetectedTime.getTime() ) continue; @@ -649,7 +650,7 @@ export default class DayZR extends Client */ // Continue if no nitrado credentials - if (!c.exists(GuildDB.Nitrado)) return; + if (!isDefined(GuildDB.Nitrado)) return; // Continue if these credentials are marked as failed if (GuildDB.Nitrado.Status == NitradoCredentialStatus.FAILED) return; @@ -858,7 +859,7 @@ export default class DayZR extends Client for (let i = 0; i < guilds.length; i++) { // // Ignore guilds with no Nitrado configuration - if (!this.exists(guilds[i].Nitrado)) continue; + if (!isDefined(guilds[i].Nitrado)) continue; if (guilds[i].server.autoRestart) { @@ -909,18 +910,6 @@ export default class DayZR extends Client this.log(`[${guildId}] Initialized new Nitrado`); } - /** - * exists simply ensures a given input is not - * null, undefined, an empty string or NaN. - * - * @param n to validate - * @returns if this object exists (boolean) - */ - public exists (n: T | null | undefined | "" | number): n is T - { - return typeof n === "number" ? !isNaN(n) : n !== null && n !== undefined && n !== ""; - } - /** * secondsToDhms converts a given number of seconds * to its equivilent in days, hours, minutes and seconds. @@ -967,7 +956,7 @@ export default class DayZR extends Client files.forEach((file) => { let cmd: Command = require(CommandsDir + "/" + file); - if (!this.exists(cmd.name) || !this.exists(cmd.description)) + if (!isDefined(cmd.name) || !isDefined(cmd.description)) { return this.error( "Unable to load Command: " + @@ -978,7 +967,7 @@ export default class DayZR extends Client this.commands.set(file.split(".")[0].toLowerCase(), cmd); - if (this.exists(cmd.Interactions)) + if (isDefined(cmd.Interactions)) { for (let [interaction, handler] of Object.entries(cmd.Interactions)) { diff --git a/src/commands/admin.js b/src/commands/admin.js index 7f24cbf..ebd51f7 100644 --- a/src/commands/admin.js +++ b/src/commands/admin.js @@ -4,6 +4,7 @@ const bitfieldCalculator = require("discord-bitfield-calculator"); const { Armbands } = require("../database/armbands.js"); const { createUser, addUser } = require("../database/user"); const { UpdatePlayer } = require("../database/player"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "admin", @@ -134,7 +135,7 @@ module.exports = { if (args[0].name == "gamertag-link") { - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID) || !isDefined(GuildDB.Nitrado.UserID) || !isDefined(GuildDB.Nitrado.Auth)) { const warnNitradoNotInitialized = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription("**WARNING:** The DayZ Nitrado Server has not been configured for this guild yet. This command or feature is currently unavailable."); @@ -143,9 +144,9 @@ module.exports = { } let playerStat = await client.dbo.collection("players").findOne({ "gamertag": args[0].options[1].value }); - if (!client.exists(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** This gamertag \` ${args[0].options[1].value} \` cannot be found, the gamertag may be incorrect or this player has not logged onto the server before for at least \` 5 minutes \`.`)] }); + if (!isDefined(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** This gamertag \` ${args[0].options[1].value} \` cannot be found, the gamertag may be incorrect or this player has not logged onto the server before for at least \` 5 minutes \`.`)] }); - if (client.exists(playerStat.discordID)) { + if (isDefined(playerStat.discordID)) { const warnGTOverwrite = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription(`**Notice:**\n> The gamertag has previously been linked to <@${playerStat.discordID}>. Are you sure you would like to change this?`) @@ -170,12 +171,12 @@ module.exports = { await UpdatePlayer(client, playerStat, interaction); let member = interaction.guild.members.cache.get(args[0].options[0].value); - if (client.exists(GuildDB.linkedGamertagRole)) { + if (isDefined(GuildDB.linkedGamertagRole)) { let role = interaction.guild.roles.cache.get(GuildDB.linkedGamertagRole); member.roles.add(role); } - if (client.exists(GuildDB.memberRole)) { + if (isDefined(GuildDB.memberRole)) { let role = interaction.guild.roles.cache.get(GuildDB.memberRole); member.roles.add(role); } @@ -188,7 +189,7 @@ module.exports = { } else if (args[0].name == "gamertag-unlink") { - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID) || !isDefined(GuildDB.Nitrado.UserID) || !isDefined(GuildDB.Nitrado.Auth)) { const warnNitradoNotInitialized = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription("**WARNING:** The DayZ Nitrado Server has not been configured for this guild yet. This command or feature is currently unavailable."); @@ -197,7 +198,7 @@ module.exports = { } let playerStat = await client.dbo.collection("players").findOne({ "discordID": args[0].options[0].value }); - if (!client.exists(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** <@${args[0].options[0].value}> has no gamertag linked.`)] }); + if (!isDefined(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** <@${args[0].options[0].value}> has no gamertag linked.`)] }); const warnGTOverwrite = new EmbedBuilder() .setColor(client.config.Colors.Yellow) @@ -281,7 +282,7 @@ module.exports = { } else if (args[0].name == "bounty-clear") { - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID) || !isDefined(GuildDB.Nitrado.UserID) || !isDefined(GuildDB.Nitrado.Auth)) { const warnNitradoNotInitialized = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription("**WARNING:** The DayZ Nitrado Server has not been configured for this guild yet. This command or feature is currently unavailable."); @@ -290,7 +291,7 @@ module.exports = { } let playerStat = await client.dbo.collection("players").findOne({ "gamertag": args[0].options[0].value }); - if (!client.exists(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription("**Not Found** This player cannot be found, the gamertag may be incorrect or this player has not logged onto the server before for at least ` 5 minutes `.")] }); + if (!isDefined(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription("**Not Found** This player cannot be found, the gamertag may be incorrect or this player has not logged onto the server before for at least ` 5 minutes `.")] }); playerStat.bounties = []; @@ -309,16 +310,16 @@ module.exports = { if (!banking) { banking = await createUser(targetUserID, GuildDB.serverID, GuildDB.startingBalance, client) - if (!client.exists(banking)) return client.sendInternalError(interaction, err); + if (!isDefined(banking)) return client.sendInternalError(interaction, err); } banking = banking.user; - if (!client.exists(banking.guilds[GuildDB.serverID])) { + if (!isDefined(banking.guilds[GuildDB.serverID])) { const success = addUser(banking.guilds, GuildDB.serverID, targetUserID, client, GuildDB.startingBalance); if (!success) return client.sendInternalError(interaction, "Failed to add bank"); } - if (!client.exists(banking.guilds[GuildDB.serverID].balance)) banking.guilds[GuildDB.serverID].balance = GuildDB.startingBalance; + if (!isDefined(banking.guilds[GuildDB.serverID].balance)) banking.guilds[GuildDB.serverID].balance = GuildDB.startingBalance; const add = args[0].options[0].name == "add"; let newBalance = add @@ -354,12 +355,12 @@ module.exports = { await UpdatePlayer(client, playerStat); let member = interaction.guild.members.cache.get(interaction.member.user.id); - if (client.exists(GuildDB.linkedGamertagRole)) { + if (isDefined(GuildDB.linkedGamertagRole)) { let role = interaction.guild.roles.cache.get(GuildDB.linkedGamertagRole); member.roles.add(role); } - if (client.exists(GuildDB.memberRole)) { + if (isDefined(GuildDB.memberRole)) { let role = interaction.guild.roles.cache.get(GuildDB.memberRole); member.roles.add(role); } diff --git a/src/commands/alarm.js b/src/commands/alarm.js index 90ff882..f8fce64 100644 --- a/src/commands/alarm.js +++ b/src/commands/alarm.js @@ -1,6 +1,7 @@ const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder } = require("discord.js"); const { ApplicationCommandOptionType } = require("discord.js"); const bitfieldCalculator = require("discord-bitfield-calculator"); +const isDefined = require("../util/Validation.js"); const generateAlarmMenus = (alarms, customId, placeholder, description) => { let alarmComponents = []; @@ -237,7 +238,7 @@ module.exports = { if (GuildDB.hasBotAdmin && interaction.member.roles.filter(e => GuildDB.botAdminRoles.indexOf(e) !== -1).length > 0) canUseCommand = true; if (!canUseCommand) return interaction.send({ content: "You don\"t have the permissions to use this command." }); - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID) || !isDefined(GuildDB.Nitrado.UserID) || !isDefined(GuildDB.Nitrado.Auth)) { const warnNitradoNotInitialized = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription("**WARNING:** The DayZ Nitrado Server has not been configured for this guild yet. This command or feature is currently unavailable."); @@ -259,8 +260,8 @@ module.exports = { role: args[0].options[5].value, ignoredPlayers: [], rules: [], - empExempt: client.exists(args[0].options[6]) ? args[0].options[6].value : false, - showPlayerCoord: client.exists(args[0].options[7]) ? args[0].options[7].value : true, + empExempt: isDefined(args[0].options[6]) ? args[0].options[6].value : false, + showPlayerCoord: isDefined(args[0].options[7]) ? args[0].options[7].value : true, disabled: false, empExpire: null, }; @@ -451,7 +452,7 @@ module.exports = { let alarmIndex = GuildDB.alarms.indexOf(alarm); let playerStat = await client.dbo.collection("players").findOne({ "gamertag": interaction.customId.split("-")[2] }); - if (!client.exists(playerStat)) return interaction.update({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription("**Not Found** This player cannot be found, the gamertag may be incorrect or this player has not logged onto the server before.")], components: [] }); + if (!isDefined(playerStat)) return interaction.update({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription("**Not Found** This player cannot be found, the gamertag may be incorrect or this player has not logged onto the server before.")], components: [] }); let add = interaction.customId.split("-")[1] == "add"; diff --git a/src/commands/bank.js b/src/commands/bank.js index 28ceec1..e3b17db 100644 --- a/src/commands/bank.js +++ b/src/commands/bank.js @@ -1,6 +1,7 @@ const { EmbedBuilder } = require("discord.js"); const { ApplicationCommandOptionType } = require("discord.js"); const { createUser, addUser } = require("../database/user"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "bank", @@ -67,11 +68,11 @@ module.exports = { if (!banking) { banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client) - if (!client.exists(banking)) return client.sendInternalError(interaction, err); + if (!isDefined(banking)) return client.sendInternalError(interaction, err); } banking = banking.user; - if (!client.exists(banking.guilds[GuildDB.serverID])) { + if (!isDefined(banking.guilds[GuildDB.serverID])) { const success = addUser(banking.guilds, GuildDB.serverID, interaction.member.user.id, client, GuildDB.startingBalance); if (!success) return client.sendInternalError(interaction, "Failed to add bank"); } @@ -88,11 +89,11 @@ module.exports = { if (!targetUserBanking) { targetUserBanking = await createUser(targetUserID, GuildDB.serverID, GuildDB.startingBalance, client) - if (!client.exists(banking)) return client.sendInternalError(interaction, err); + if (!isDefined(banking)) return client.sendInternalError(interaction, err); } targetUserBanking = targetUserBanking.user; - if (!client.exists(targetUserBanking.guilds[GuildDB.serverID])) { + if (!isDefined(targetUserBanking.guilds[GuildDB.serverID])) { const success = addUser(banking.guilds, GuildDB.serverID, targetUserID, client, GuildDB.startingBalance); if (!success) return client.sendInternalError(interaction, "Failed to add bank"); } @@ -138,11 +139,11 @@ module.exports = { if (!targetUserBanking) { targetUserBanking = await createUser(targetUserID, GuildDB.serverID, GuildDB.startingBalance, client) - if (!client.exists(banking)) return client.sendInternalError(interaction, err); + if (!isDefined(banking)) return client.sendInternalError(interaction, err); } targetUserBanking = targetUserBanking.user; - if (!client.exists(targetUserBanking.guilds[GuildDB.serverID])) { + if (!isDefined(targetUserBanking.guilds[GuildDB.serverID])) { const success = addUser(banking.guilds, GuildDB.serverID, targetUserID, client, GuildDB.startingBalance); if (!success) return client.sendInternalError(interaction, "Failed to add bank"); } diff --git a/src/commands/bounty.js b/src/commands/bounty.js index 115574d..53bb854 100644 --- a/src/commands/bounty.js +++ b/src/commands/bounty.js @@ -2,6 +2,7 @@ const { EmbedBuilder } = require("discord.js"); const { ApplicationCommandOptionType } = require("discord.js"); const { createUser, addUser } = require("../database/user"); const { UpdatePlayer } = require("../database/player"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "bounty", @@ -59,7 +60,7 @@ module.exports = { */ run: async (client, interaction, args, { GuildDB }) => { - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID) || !isDefined(GuildDB.Nitrado.UserID) || !isDefined(GuildDB.Nitrado.Auth)) { const warnNitradoNotInitialized = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription("**WARNING:** The DayZ Nitrado Server has not been configured for this guild yet. This command or feature is currently unavailable."); @@ -73,11 +74,11 @@ module.exports = { if (!banking) { banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client) - if (!client.exists(banking)) return client.sendInternalError(interaction, err); + if (!isDefined(banking)) return client.sendInternalError(interaction, err); } banking = banking.user; - if (!client.exists(banking.guilds[GuildDB.serverID])) { + if (!isDefined(banking.guilds[GuildDB.serverID])) { const success = addUser(banking.guilds, GuildDB.serverID, interaction.member.user.id, client, GuildDB.startingBalance); if (!success) return client.sendInternalError(interaction, "Failed to add bank"); } @@ -86,7 +87,7 @@ module.exports = { if (args[0].name == "set") { let playerStat = await client.dbo.collection("players").findOne({ "gamertag": args[0].options[0].value }); - if (!client.exists(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription("**Not Found** This player cannot be found, the gamertag may be incorrect or this player has not logged onto the server before for at least ` 5 minutes `.")] }); + if (!isDefined(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription("**Not Found** This player cannot be found, the gamertag may be incorrect or this player has not logged onto the server before for at least ` 5 minutes `.")] }); if (args[0].options[1].value > banking.guilds[GuildDB.serverID].balance) { let nsf = new EmbedBuilder() @@ -126,7 +127,7 @@ module.exports = { } else if (args[0].name == "pay") { let playerStat = await client.dbo.collection("players").findOne({ "discordID": interaction.member.user.id }); - if (!client.exists(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription("**Not Found** Your user ID could not be found, contact an Admin.")] }); + if (!isDefined(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription("**Not Found** Your user ID could not be found, contact an Admin.")] }); if (playerStat.bounties.length == 0) { const noBounty = new EmbedBuilder() diff --git a/src/commands/collect-income.js b/src/commands/collect-income.js index f41b883..01976ce 100644 --- a/src/commands/collect-income.js +++ b/src/commands/collect-income.js @@ -1,5 +1,6 @@ const { EmbedBuilder, } = require("discord.js"); const { createUser, addUser } = require("../database/user"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "collect-income", @@ -44,16 +45,16 @@ module.exports = { if (!banking) { banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client) - if (!client.exists(banking)) return client.sendInternalError(interaction, err); + if (!isDefined(banking)) return client.sendInternalError(interaction, err); } banking = banking.user; - if (!client.exists(banking.guilds[GuildDB.serverID])) { + if (!isDefined(banking.guilds[GuildDB.serverID])) { const success = addUser(banking.guilds, GuildDB.serverID, interaction.member.user.id, client, GuildDB.startingBalance); if (!success) return client.sendInternalError(interaction, "Failed to add bank"); } - if (!client.exists(banking.guilds[GuildDB.serverID].lastIncome)) banking.guilds[GuildDB.serverID].lastIncome = new Date("2000-01-01T00:00:00"); + if (!isDefined(banking.guilds[GuildDB.serverID].lastIncome)) banking.guilds[GuildDB.serverID].lastIncome = new Date("2000-01-01T00:00:00"); let now = new Date(); let diff = (now - banking.guilds[GuildDB.serverID].lastIncome) / 1000; diff --git a/src/commands/compare-rating.js b/src/commands/compare-rating.js index 8c4d077..d19b46e 100644 --- a/src/commands/compare-rating.js +++ b/src/commands/compare-rating.js @@ -1,6 +1,7 @@ const { EmbedBuilder } = require("discord.js"); const { ApplicationCommandOptionType } = require("discord.js"); const { insertPVPstats } = require("../database/player"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "compare-rating", @@ -34,7 +35,7 @@ module.exports = { */ run: async (client, interaction, args, { GuildDB }) => { - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID) || !isDefined(GuildDB.Nitrado.UserID) || !isDefined(GuildDB.Nitrado.Auth)) { const warnNitradoNotInitialized = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription("**WARNING:** The DayZ Nitrado Server has not been configured for this guild yet. This command or feature is currently unavailable."); @@ -56,8 +57,8 @@ module.exports = { if (gamertag) comp = leaderboard.find(s => s.gamertag == gamertag); let self = leaderboard.find(s => s.discordID == interaction.member.user.id); - if (!client.exists(comp)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** Unable to find any records with the gamertag or user provided.`)] }); - if (!client.exists(self)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** You haven"t linked your gamertag and your stats cannot be found.`)] }); + if (!isDefined(comp)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** Unable to find any records with the gamertag or user provided.`)] }); + if (!isDefined(self)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** You haven"t linked your gamertag and your stats cannot be found.`)] }); let lbPosSelf = leaderboard.indexOf(self) + 1; let lbPosComp = leaderboard.indexOf(comp) + 1; @@ -69,8 +70,8 @@ module.exports = { let selfDataMax = Math.max(...selfData); let compDataMax = Math.max(...compData); - if (!client.exists(self.highestCombatRating) || self.highestCombatRating < selfDataMax) self.highestCombatRating = selfDataMax; - if (!client.exists(comp.highestCombatRating) || comp.highestCombatRating < compDataMax) comp.highestCombatRating = compDataMax; + if (!isDefined(self.highestCombatRating) || self.highestCombatRating < selfDataMax) self.highestCombatRating = selfDataMax; + if (!isDefined(comp.highestCombatRating) || comp.highestCombatRating < compDataMax) comp.highestCombatRating = compDataMax; let tag = comp.discordID != "" ? `<@${comp.discordID}>` : comp.gamertag; diff --git a/src/commands/config.js b/src/commands/config.js index 3388647..7d010c2 100644 --- a/src/commands/config.js +++ b/src/commands/config.js @@ -2,6 +2,7 @@ const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require(" const { ApplicationCommandOptionType } = require("discord.js"); const bitfieldCalculator = require("discord-bitfield-calculator"); const { getDefaultSettings } = require("../database/guild"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "config", @@ -712,12 +713,12 @@ module.exports = { // Role / channel display const NONE = `${w}${m}none${w}`; const channelsInfo = GuildDB.customChannelStatus ? "\`\` to view" : NONE; - const killfeedChannel = client.exists(GuildDB.killfeedChannel) ? `<#${GuildDB.killfeedChannel}>` : NONE; - const connectionLogs = client.exists(GuildDB.connectionLogsChannel) ? `<#${GuildDB.connectionLogsChannel}>` : NONE; - const activePlayers = client.exists(GuildDB.activePlayersChannel) ? `<#${GuildDB.activePlayersChannel}>` : NONE; - const welcomeChannel = client.exists(GuildDB.welcomeChannel) ? `<#${GuildDB.welcomeChannel}>` : NONE; - const linkedGTRole = client.exists(GuildDB.linkedGamertagRole) ? `<@&${GuildDB.linkedGamertagRole}>` : NONE; - const memberRole = client.exists(GuildDB.memberRole) ? `<@&${GuildDB.memberRole}>` : NONE; + const killfeedChannel = isDefined(GuildDB.killfeedChannel) ? `<#${GuildDB.killfeedChannel}>` : NONE; + const connectionLogs = isDefined(GuildDB.connectionLogsChannel) ? `<#${GuildDB.connectionLogsChannel}>` : NONE; + const activePlayers = isDefined(GuildDB.activePlayersChannel) ? `<#${GuildDB.activePlayersChannel}>` : NONE; + const welcomeChannel = isDefined(GuildDB.welcomeChannel) ? `<#${GuildDB.welcomeChannel}>` : NONE; + const linkedGTRole = isDefined(GuildDB.linkedGamertagRole) ? `<@&${GuildDB.linkedGamertagRole}>` : NONE; + const memberRole = isDefined(GuildDB.memberRole) ? `<@&${GuildDB.memberRole}>` : NONE; // value display const incomeLimiter = `${GuildDB.incomeLimiter} hours`; diff --git a/src/commands/event.js b/src/commands/event.js index a1c581f..7965d4a 100644 --- a/src/commands/event.js +++ b/src/commands/event.js @@ -1,6 +1,7 @@ const { EmbedBuilder, ActionRowBuilder, StringSelectMenuBuilder } = require("discord.js"); const { ApplicationCommandOptionType } = require("discord.js"); const bitfieldCalculator = require("discord-bitfield-calculator"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "event", @@ -72,7 +73,7 @@ module.exports = { */ run: async (client, interaction, args, { GuildDB }) => { - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID) || !isDefined(GuildDB.Nitrado.UserID) || !isDefined(GuildDB.Nitrado.Auth)) { const warnNitradoNotInitialized = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription("**WARNING:** The DayZ Nitrado Server has not been configured for this guild yet. This command or feature is currently unavailable."); @@ -92,7 +93,7 @@ module.exports = { if (args[0].name == "player-track") { let playerStat = await client.dbo.collection("players").findOne({ "gamertag": args[0].options[0].value }); - if (!client.exists(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** This gamertag \` ${args[0].options[0].value} \` cannot be found, the gamertag may be incorrect or this player has not logged onto the server before for at least \` 5 minutes \`.`)] }); + if (!isDefined(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** This gamertag \` ${args[0].options[0].value} \` cannot be found, the gamertag may be incorrect or this player has not logged onto the server before for at least \` 5 minutes \`.`)] }); let event = { type: args[0].name, diff --git a/src/commands/gamertag-link.js b/src/commands/gamertag-link.js index 9753995..87b074a 100644 --- a/src/commands/gamertag-link.js +++ b/src/commands/gamertag-link.js @@ -1,6 +1,7 @@ const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require("discord.js"); const { ApplicationCommandOptionType } = require("discord.js"); const { UpdatePlayer } = require("../database/player"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "gamertag-link", @@ -29,7 +30,7 @@ module.exports = { */ run: async (client, interaction, args, { GuildDB }) => { - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID) || !isDefined(GuildDB.Nitrado.UserID) || !isDefined(GuildDB.Nitrado.Auth)) { const warnNitradoNotInitialized = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription("**WARNING:** The DayZ Nitrado Server has not been configured for this guild yet. This command or feature is currently unavailable."); @@ -38,9 +39,9 @@ module.exports = { } let playerStat = await client.dbo.collection("players").findOne({ "gamertag": args[0].value }); - if (!client.exists(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** This gamertag \` ${args[0].value} \` cannot be found, the gamertag may be incorrect or this player has not logged onto the server before for at least \` 5 minutes \`.`)] }); + if (!isDefined(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** This gamertag \` ${args[0].value} \` cannot be found, the gamertag may be incorrect or this player has not logged onto the server before for at least \` 5 minutes \`.`)] }); - if (client.exists(playerStat.discordID)) { + if (isDefined(playerStat.discordID)) { const warnGTOverwrite = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription(`**Notice:**\n> The gamertag has previously been linked to <@${playerStat.discordID}>. Are you sure you would like to change this?`) @@ -65,12 +66,12 @@ module.exports = { await UpdatePlayer(client, playerStat, interaction); let member = interaction.guild.members.cache.get(interaction.member.user.id); - if (client.exists(GuildDB.linkedGamertagRole)) { + if (isDefined(GuildDB.linkedGamertagRole)) { let role = interaction.guild.roles.cache.get(GuildDB.linkedGamertagRole); member.roles.add(role); } - if (client.exists(GuildDB.memberRole)) { + if (isDefined(GuildDB.memberRole)) { let role = interaction.guild.roles.cache.get(GuildDB.memberRole); member.roles.add(role); } @@ -98,12 +99,12 @@ module.exports = { await UpdatePlayer(client, playerStat, interaction); let member = interaction.guild.members.cache.get(interaction.member.user.id); - if (client.exists(GuildDB.linkedGamertagRole)) { + if (isDefined(GuildDB.linkedGamertagRole)) { let role = interaction.guild.roles.cache.get(GuildDB.linkedGamertagRole); member.roles.add(role); } - if (client.exists(GuildDB.memberRole)) { + if (isDefined(GuildDB.memberRole)) { let role = interaction.guild.roles.cache.get(GuildDB.memberRole); member.roles.add(role); } diff --git a/src/commands/gamertag-unlink.js b/src/commands/gamertag-unlink.js index 80ab4c0..41fd99a 100644 --- a/src/commands/gamertag-unlink.js +++ b/src/commands/gamertag-unlink.js @@ -1,5 +1,6 @@ const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require("discord.js"); const { UpdatePlayer } = require("../database/player"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "gamertag-unlink", @@ -21,7 +22,7 @@ module.exports = { */ run: async (client, interaction, args, { GuildDB }) => { - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID) || !isDefined(GuildDB.Nitrado.UserID) || !isDefined(GuildDB.Nitrado.Auth)) { const warnNitradoNotInitialized = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription("**WARNING:** The DayZ Nitrado Server has not been configured for this guild yet. This command or feature is currently unavailable."); @@ -30,7 +31,7 @@ module.exports = { } let playerStat = await client.dbo.collection("players").findOne({ "discordID": interaction.member.user.id }); - if (!client.exists(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**No Gamertag Linked** It Appears your don"t have a gamertag linked to your account.`)] }); + if (!isDefined(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**No Gamertag Linked** It Appears your don"t have a gamertag linked to your account.`)] }); const warnGTOverwrite = new EmbedBuilder() .setColor(client.config.Colors.Yellow) diff --git a/src/commands/leaderboard.js b/src/commands/leaderboard.js index 0d60417..61bf430 100644 --- a/src/commands/leaderboard.js +++ b/src/commands/leaderboard.js @@ -1,5 +1,6 @@ const { EmbedBuilder } = require("discord.js"); const { ApplicationCommandOptionType } = require("discord.js"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "leaderboard", @@ -53,7 +54,7 @@ module.exports = { */ run: async (client, interaction, args, { GuildDB }) => { - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID) || !isDefined(GuildDB.Nitrado.UserID) || !isDefined(GuildDB.Nitrado.Auth)) { const warnNitradoNotInitialized = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription("**WARNING:** The DayZ Nitrado Server has not been configured for this guild yet. This command or feature is currently unavailable."); diff --git a/src/commands/location.js b/src/commands/location.js index dc2bec6..ad483b5 100644 --- a/src/commands/location.js +++ b/src/commands/location.js @@ -1,5 +1,6 @@ const { EmbedBuilder } = require("discord.js"); const { nearest } = require("../database/destinations"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "location", @@ -21,7 +22,7 @@ module.exports = { */ run: async (client, interaction, args, { GuildDB }) => { - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth) || !client.exists(GuildDB.Nitrado.Mission)) { + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID) || !isDefined(GuildDB.Nitrado.UserID) || !isDefined(GuildDB.Nitrado.Auth) || !isDefined(GuildDB.Nitrado.Mission)) { const warnNitradoNotInitialized = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription("**WARNING:** The DayZ Nitrado Server has not been configured for this guild yet. This command or feature is currently unavailable."); @@ -30,8 +31,8 @@ module.exports = { } let playerStat = await client.dbo.collection("players").findOne({ "discordID": interaction.member.user.id }); - if (!client.exists(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** You haven"t linked your gamertag and are unable to use this command.`)], flags: (1 << 6) }); - if (!client.exists(playerStat.time)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** There is no location saved to your gamertag yet. Make sure you"ve logged into the server for more than **5 minutes.**`)], flags: (1 << 6) }); + if (!isDefined(playerStat)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** You haven"t linked your gamertag and are unable to use this command.`)], flags: (1 << 6) }); + if (!isDefined(playerStat.time)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** There is no location saved to your gamertag yet. Make sure you"ve logged into the server for more than **5 minutes.**`)], flags: (1 << 6) }); console.log(true); diff --git a/src/commands/lookup.js b/src/commands/lookup.js index 4da0f07..c3ad359 100644 --- a/src/commands/lookup.js +++ b/src/commands/lookup.js @@ -1,5 +1,6 @@ const { EmbedBuilder } = require("discord.js"); const { ApplicationCommandOptionType } = require("discord.js"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "lookup", @@ -46,7 +47,7 @@ module.exports = { */ run: async (client, interaction, args, { GuildDB }) => { - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID) || !isDefined(GuildDB.Nitrado.UserID) || !isDefined(GuildDB.Nitrado.Auth)) { const warnNitradoNotInitialized = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription("**WARNING:** The DayZ Nitrado Server has not been configured for this guild yet. This command or feature is currently unavailable."); @@ -59,7 +60,7 @@ module.exports = { let playerStat = await client.dbo.collection("players").findOne({ "gamertag": args[0].options[0].value }); if (playerStat == undefined) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** This gamertag \` ${args[0].options[0].value} \` cannot be found, the gamertag may be incorrect or this player has not logged onto the server before for at least \` 5 minutes \`.`)] }); - if (client.exists(playerStat.discordID)) { + if (isDefined(playerStat.discordID)) { const found = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription(`**Record Found**\n> The gamertag \` ${playerStat.gamertag} \` is currently linked to <@${playerStat.discordID}>.`) diff --git a/src/commands/player-list.js b/src/commands/player-list.js index de0b2af..700da90 100644 --- a/src/commands/player-list.js +++ b/src/commands/player-list.js @@ -1,6 +1,7 @@ -const { FetchServerSettings } = require("../util/NitradoAPI"); +const { FetchServerSettings } = require("../services/NitradoAPI"); const { Missions } = require("../database/destinations"); const { EmbedBuilder } = require("discord.js"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "player-list", @@ -23,7 +24,7 @@ module.exports = { */ run: async (client, interaction, args, { GuildDB }, start) => { - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID) || !isDefined(GuildDB.Nitrado.UserID) || !isDefined(GuildDB.Nitrado.Auth)) { const warnNitradoNotInitialized = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription("**WARNING:** The DayZ Nitrado Server has not been configured for this guild yet. This command or feature is currently unavailable."); diff --git a/src/commands/player-stats.js b/src/commands/player-stats.js index c0a1119..d027d57 100644 --- a/src/commands/player-stats.js +++ b/src/commands/player-stats.js @@ -1,6 +1,7 @@ const { EmbedBuilder } = require("discord.js"); const { ApplicationCommandOptionType } = require("discord.js"); const { insertPVPstats } = require("../database/player"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "player-stats", @@ -57,7 +58,7 @@ module.exports = { */ run: async (client, interaction, args, { GuildDB }, start) => { - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID) || !isDefined(GuildDB.Nitrado.UserID) || !isDefined(GuildDB.Nitrado.Auth)) { const warnNitradoNotInitialized = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription("**WARNING:** The DayZ Nitrado Server has not been configured for this guild yet. This command or feature is currently unavailable."); @@ -84,7 +85,7 @@ module.exports = { if (gamertag) query = leaderboard.find(u => u.user.userID == playerStat.discordID); // Searching by gamertag if (self) query = leaderboard.find(u => u.user.userID == interaction.member.user.id); // Searching for self - if (!client.exists(query)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** Unable to find any records with the gamertag or user provided.`)] }); + if (!isDefined(query)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** Unable to find any records with the gamertag or user provided.`)] }); leaderboardPos = leaderboard.indexOf(query); } else { @@ -97,7 +98,7 @@ module.exports = { if (gamertag) query = leaderboard.find(s => s.gamertag == gamertag); // Searching by gamertag if (self) query = leaderboard.find(s => s.discordID == interaction.member.user.id); // Searching for self - if (!client.exists(query)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** Unable to find any records with the gamertag or user provided.`)] }); + if (!isDefined(query)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** Unable to find any records with the gamertag or user provided.`)] }); leaderboardPos = leaderboard.indexOf(query); } @@ -142,7 +143,7 @@ module.exports = { statsEmbed.addFields({ name: "Leaderboard Position", value: `# ${leaderboardPos}`, inline: true }); - if ((category == "shotsLanded" || category == "timesShot") && !client.exists(query.shotsLanded)) query = insertPVPstats(query); + if ((category == "shotsLanded" || category == "timesShot") && !isDefined(query.shotsLanded)) query = insertPVPstats(query); if (category == "totalSessionTime") { statsEmbed.addFields( @@ -242,8 +243,8 @@ module.exports = { let dataMax = Math.max(...query.combatRatingHistory); let dataMin = Math.min(...query.combatRatingHistory); - if (!client.exists(query.highestCombatRating) || query.highestCombatRating < dataMax) query.highestCombatRating = dataMax; - if (!client.exists(query.lowestCombatRating) || query.lowestCombatRating > dataMin) query.lowestCombatRating = dataMin; + if (!isDefined(query.highestCombatRating) || query.highestCombatRating < dataMax) query.highestCombatRating = dataMax; + if (!isDefined(query.lowestCombatRating) || query.lowestCombatRating > dataMin) query.lowestCombatRating = dataMin; statsEmbed.addFields( { name: "Combat Rating", value: `${query.combatRating}`, inline: true }, diff --git a/src/commands/purchase-emp.js b/src/commands/purchase-emp.js index 319292f..8fe0994 100644 --- a/src/commands/purchase-emp.js +++ b/src/commands/purchase-emp.js @@ -1,6 +1,7 @@ const { EmbedBuilder, ActionRowBuilder, StringSelectMenuBuilder } = require("discord.js"); const { createUser, addUser } = require("../database/user"); const { ApplicationCommandOptionType } = require("discord.js"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "purchase-emp", @@ -33,7 +34,7 @@ module.exports = { */ run: async (client, interaction, args, { GuildDB }) => { - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID) || !isDefined(GuildDB.Nitrado.UserID) || !isDefined(GuildDB.Nitrado.Auth)) { const warnNitradoNotInitialized = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription("**WARNING:** The DayZ Nitrado Server has not been configured for this guild yet. This command or feature is currently unavailable."); @@ -41,18 +42,18 @@ module.exports = { return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); } - if (client.exists(GuildDB.purchaseEMP) && !GuildDB.purchaseEMP) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription("**Notice:** The admins have disabled this feature")] }); + if (isDefined(GuildDB.purchaseEMP) && !GuildDB.purchaseEMP) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription("**Notice:** The admins have disabled this feature")] }); const duration = args[0].value; let banking = await client.dbo.collection("users").findOne({ "user.userID": interaction.member.user.id }).then(banking => banking); if (!banking) { banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client) - if (!client.exists(banking)) return client.sendInternalError(interaction, err); + if (!isDefined(banking)) return client.sendInternalError(interaction, err); } banking = banking.user; - if (!client.exists(banking.guilds[GuildDB.serverID])) { + if (!isDefined(banking.guilds[GuildDB.serverID])) { const success = addUser(banking.guilds, GuildDB.serverID, interaction.member.user.id, client, GuildDB.startingBalance); if (!success) return client.sendInternalError(interaction, "Failed to add bank"); } diff --git a/src/commands/purchase-uav.js b/src/commands/purchase-uav.js index 344c53c..77d64db 100644 --- a/src/commands/purchase-uav.js +++ b/src/commands/purchase-uav.js @@ -1,6 +1,7 @@ const { EmbedBuilder } = require("discord.js"); const { ApplicationCommandOptionType } = require("discord.js"); -const { createUser, addUser } = require("../database/user") +const { createUser, addUser } = require("../database/user"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "purchase-uav", @@ -40,7 +41,7 @@ module.exports = { */ run: async (client, interaction, args, { GuildDB }) => { - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID) || !isDefined(GuildDB.Nitrado.UserID) || !isDefined(GuildDB.Nitrado.Auth)) { const warnNitradoNotInitialized = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription("**WARNING:** The DayZ Nitrado Server has not been configured for this guild yet. This command or feature is currently unavailable."); @@ -48,17 +49,17 @@ module.exports = { return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); } - if (client.exists(GuildDB.purchaseUAV) && !GuildDB.purchaseUAV) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription("**Notice:** The admins have disabled this feature")] }); + if (isDefined(GuildDB.purchaseUAV) && !GuildDB.purchaseUAV) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription("**Notice:** The admins have disabled this feature")] }); let banking = await client.dbo.collection("users").findOne({ "user.userID": interaction.member.user.id }).then(banking => banking); if (!banking) { banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client) - if (!client.exists(banking)) return client.sendInternalError(interaction, err); + if (!isDefined(banking)) return client.sendInternalError(interaction, err); } banking = banking.user; - if (!client.exists(banking.guilds[GuildDB.serverID])) { + if (!isDefined(banking.guilds[GuildDB.serverID])) { const success = addUser(banking.guilds, GuildDB.serverID, interaction.member.user.id, client, GuildDB.startingBalance); if (!success) return client.sendInternalError(interaction, "Failed to add bank"); } diff --git a/src/commands/reset.js b/src/commands/reset.js index dc5a1c4..b717fb2 100644 --- a/src/commands/reset.js +++ b/src/commands/reset.js @@ -2,6 +2,7 @@ const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require(" const { ApplicationCommandOptionType } = require("discord.js"); const { addUser } = require("../database/user"); const bitfieldCalculator = require("discord-bitfield-calculator"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "reset", @@ -33,7 +34,7 @@ module.exports = { let canUseCommand = false; if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; - if (client.exists(GuildDB.botAdmin) && interaction.member.roles.includes(GuildDB.botAdmin)) canUseCommand = true; + if (isDefined(GuildDB.botAdmin) && interaction.member.roles.includes(GuildDB.botAdmin)) canUseCommand = true; if (!canUseCommand) return interaction.send({ content: "You don\"t have the permissions to use this command." }); const targetUserID = args[0].value.replace("<@!", "").replace(">", ""); diff --git a/src/commands/server.js b/src/commands/server.js index 614b3b7..1e401f6 100644 --- a/src/commands/server.js +++ b/src/commands/server.js @@ -1,8 +1,9 @@ const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, ModalBuilder, TextInputBuilder, TextInputStyle } = require("discord.js"); const { ApplicationCommandOptionType } = require("discord.js"); const bitfieldCalculator = require("discord-bitfield-calculator"); -const { BanPlayer, UnbanPlayer, RestartServer, CheckServerStatus, DisableBaseDamage, DisableContainerDamage, NitradoCredentialStatus } = require("../util/NitradoAPI"); +const { BanPlayer, UnbanPlayer, RestartServer, CheckServerStatus, DisableBaseDamage, DisableContainerDamage, NitradoCredentialStatus } = require("../services/NitradoAPI"); const { encrypt, decrypt } = require("../util/Cryptic"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "server", @@ -117,7 +118,7 @@ module.exports = { if (args[0].name == "initialize") { - if (client.exists(GuildDB.Nitrado)) { + if (isDefined(GuildDB.Nitrado)) { const prompt = new EmbedBuilder() .setTitle(`Nitrado Server Information Already Configured!`) .setDescription("**Notice:** This will overwrite your previously configured Nitrado Server Information") @@ -190,7 +191,7 @@ module.exports = { return interaction.send({ embeds: [prompt], components: [opt], flags: (1 << 6) }); } - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Red).setDescription(`**Notice:**\nThis Discord guild has not been configured with a Nitrado DayZ server. To configure your guild, use `)] }); + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Red).setDescription(`**Notice:**\nThis Discord guild has not been configured with a Nitrado DayZ server. To configure your guild, use `)] }); if (args[0].name == "credentials-status") { diff --git a/src/commands/weapon-stats.js b/src/commands/weapon-stats.js index 24dcdbb..313dd1b 100644 --- a/src/commands/weapon-stats.js +++ b/src/commands/weapon-stats.js @@ -2,6 +2,7 @@ const { EmbedBuilder, ActionRowBuilder, StringSelectMenuBuilder } = require("dis const { ApplicationCommandOptionType } = require("discord.js"); const { weapons } = require("../database/weapons"); const { insertPVPstats, createWeaponStats } = require("../database/player"); +const isDefined = require("../util/Validation.js"); module.exports = { name: "weapon-stats", @@ -54,7 +55,7 @@ module.exports = { */ run: async (client, interaction, args, { GuildDB }) => { - if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { + if (!isDefined(GuildDB.Nitrado) || !isDefined(GuildDB.Nitrado.ServerID) || !isDefined(GuildDB.Nitrado.UserID) || !isDefined(GuildDB.Nitrado.Auth)) { const warnNitradoNotInitialized = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription("**WARNING:** The DayZ Nitrado Server has not been configured for this guild yet. This command or feature is currently unavailable."); @@ -78,7 +79,7 @@ module.exports = { // Searching for self if (self) query = await client.dbo.collection("players").findOne({ "discordID": interaction.member.user.id }); - if (!client.exists(query)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** Unable to find any records with the gamertag or user provided.`)] }); + if (!isDefined(query)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** Unable to find any records with the gamertag or user provided.`)] }); let weaponSelect = new StringSelectMenuBuilder() .setCustomId(`ViewWeaponStats-${query.playerID}-${interaction.member.user.id}`) @@ -110,8 +111,8 @@ module.exports = { let player = await client.dbo.collection("players").findOne({ "playerID": playerID }); const tag = player.discordID != "" ? `<@${player.discordID}>"s` : `**${player.gamertag}"s**`; - if (!client.exists(player.shotsLanded)) player = insertPVPstats(player); - if (!client.exists(player.weaponStats[weapon])) player = createWeaponStats(player, weapon); + if (!isDefined(player.shotsLanded)) player = insertPVPstats(player); + if (!isDefined(player.weaponStats[weapon])) player = createWeaponStats(player, weapon); let stats = new EmbedBuilder() .setColor(client.config.Colors.Default) diff --git a/src/database/guild.ts b/src/database/guild.ts index d391469..2174958 100644 --- a/src/database/guild.ts +++ b/src/database/guild.ts @@ -1,6 +1,6 @@ import { Snowflake } from "discord.js"; import DayZR from "../DayZRBot"; -import { NitradoCredentialStatus } from "../util/NitradoAPI"; +import { NitradoCredentialStatus } from "../services/NitradoAPI"; import { ArmbandName } from "./armbands"; import { MissionName } from "./destinations"; diff --git a/src/events/guildCreate.js b/src/events/guildCreate.js index 1e97d97..164834e 100644 --- a/src/events/guildCreate.js +++ b/src/events/guildCreate.js @@ -1,3 +1,3 @@ module.exports = (client, guild) => { - require("../util/RegisterSlashCommands").RegisterGuildCommands(client, guild.id); + require("../services/RegisterSlashCommands").RegisterGuildCommands(client, guild.id); }; \ No newline at end of file diff --git a/src/events/guildMemberAdd.js b/src/events/guildMemberAdd.js index 574c6bb..45873eb 100644 --- a/src/events/guildMemberAdd.js +++ b/src/events/guildMemberAdd.js @@ -4,7 +4,7 @@ const { GetGuild } = require("../database/guild"); module.exports = async (client, member) => { let GuildDB = await GetGuild(client, member.guild.id); - if (!client.exists(GuildDB.welcomeChannel)) return; + if (!isDefined(GuildDB.welcomeChannel)) return; const channel = client.GetChannel(GuildDB.welcomeChannel); if (GuildDB.serverName == "") GuildDB.serverName = "our server!" diff --git a/src/util/AdminLogsHandler.js b/src/handlers/AdminLogsHandler.js similarity index 86% rename from src/util/AdminLogsHandler.js rename to src/handlers/AdminLogsHandler.js index 83d4bfd..7868e61 100644 --- a/src/util/AdminLogsHandler.js +++ b/src/handlers/AdminLogsHandler.js @@ -1,11 +1,12 @@ const { EmbedBuilder } = require("discord.js"); const { nearest } = require("../database/destinations"); -const { GetWebhook, WebhookSend } = require("./WebhookHandler"); +const { GetWebhook, WebhookSend } = require("../services/WebhookService"); +const isDefined = require("../util/Validation.js"); module.exports = { SendConnectionLogs: async (client, guild, data) => { - if (!client.exists(guild.connectionLogsChannel)) return; + if (!isDefined(guild.connectionLogsChannel)) return; const channel = client.GetChannel(guild.connectionLogsChannel); if (!channel) return; @@ -27,13 +28,13 @@ module.exports = { } else connectionLog.addFields({ name: "**Session Time**", value: `**Unknown**`, inline: false }); } - // if (client.exists(channel)) await channel.send({ embeds: [connectionLog] }); + // if (isDefined(channel)) await channel.send({ embeds: [connectionLog] }); await WebhookSend(client, webhook, { embeds: [connectionLog] }); }, DetectCombatLog: async (client, guild, data) => { - if (!client.exists(data.lastDamageDate)) return; - if (!client.exists(guild.connectionLogsChannel)) return; + if (!isDefined(data.lastDamageDate)) return; + if (!isDefined(guild.connectionLogsChannel)) return; const channel = client.GetChannel(guild.connectionLogsChannel); if (!channel) return; // Ensure channel exists @@ -61,7 +62,7 @@ module.exports = { const webhook = await GetWebhook(client, NAME, guild.connectionLogsChannel); let content = { embeds: [combatLog] }; - if (client.exists(guild.adminRole)) content.content = `<@&${guild.adminRole}>`; + if (isDefined(guild.adminRole)) content.content = `<@&${guild.adminRole}>`; WebhookSend(client, webhook, content); // return channel.send({ embeds: [combatLog] }); } diff --git a/src/util/AlarmsHandler.js b/src/handlers/AlarmsHandler.js similarity index 95% rename from src/util/AlarmsHandler.js rename to src/handlers/AlarmsHandler.js index f4e0700..c15488a 100644 --- a/src/util/AlarmsHandler.js +++ b/src/handlers/AlarmsHandler.js @@ -2,14 +2,15 @@ const { BanPlayer, UnbanPlayer } = require("./NitradoAPI"); const { EmbedBuilder } = require("discord.js"); const { nearest } = require("../database/destinations"); const { GetGuild } = require("../database/guild"); -const { GetWebhook, WebhookSend } = require("./WebhookHandler"); +const { GetWebhook, WebhookSend } = require("../services/WebhookService"); +const isDefined = require("../util/Validation.js"); // Private functions (only called locally) const ExpireEvent = async (client, guild, e) => { let hasMR = (guild.memberRole != ""); const channel = client.GetChannel(e.channel); - if (client.exists(e.channel)) channel.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription(`${hasMR ? `<@&${guild.memberRole}>\n` : ""}**The ${e.name} Event has ended!**`)] }); + if (isDefined(e.channel)) channel.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription(`${hasMR ? `<@&${guild.memberRole}>\n` : ""}**The ${e.name} Event has ended!**`)] }); client.dbo.collection("guilds").updateOne({ "server.serverID": guild.serverID }, { $pull: { @@ -21,7 +22,7 @@ const ExpireEvent = async (client, guild, e) => { } const HandlePlayerTrackEvent = async (client, guild, e) => { - if (!client.exists(e.channel)) return ExpireEvent(client, guild, e); // Expire event since it has invalid channel. + if (!isDefined(e.channel)) return ExpireEvent(client, guild, e); // Expire event since it has invalid channel. const channel = client.GetChannel(e.channel); if (!channel) return; @@ -40,7 +41,7 @@ const HandlePlayerTrackEvent = async (client, guild, e) => { const webhook = await GetWebhook(client, NAME, e.channel); let content = { embeds: [trackEvent] }; - if (client.exists(guild.adminRole)) content.content = `<@&${e.role}>`; + if (isDefined(guild.adminRole)) content.content = `<@&${e.role}>`; WebhookSend(client, webhook, content); // if (e.role) channel.send({ content: `<@&${e.role}>`, embeds: [trackEvent] }); diff --git a/src/util/KillfeedHandler.js b/src/handlers/KillfeedHandler.js similarity index 83% rename from src/util/KillfeedHandler.js rename to src/handlers/KillfeedHandler.js index b9c53a9..4879b40 100644 --- a/src/util/KillfeedHandler.js +++ b/src/handlers/KillfeedHandler.js @@ -3,9 +3,10 @@ const { createUser, addUser } = require("../database/user"); const { KillInAlarm } = require("./AlarmsHandler"); const { nearest } = require("../database/destinations"); const { getDefaultPlayer, UpdatePlayer } = require("../database/player"); -const { calculateNewCombatRating } = require("./CombatRatingHandler"); +const { calculateNewCombatRating } = require("../util/CombatRating"); const { weapons, weaponClassOf } = require("../database/weapons"); const { GetWebhook, WebhookSend } = require("../util/WebhookHandler"); +const isDefined = require("../util/Validation.js"); const Templates = { Killed: 1, @@ -71,7 +72,7 @@ module.exports = { const newDt = await client.getDateEST(info.time); let victimStat = await client.dbo.collection("players").findOne({ "playerID": info.playerID }); - if (!client.exists(victimStat)) victimStat = getDefaultPlayer(info.player, info.playerID, NitradoServerID); + if (!isDefined(victimStat)) victimStat = getDefaultPlayer(info.player, info.playerID, NitradoServerID); victimStat.lastDeathDate = newDt; @@ -126,15 +127,15 @@ module.exports = { const newDt = await client.getDateEST(info.time); const unixTime = Math.floor(newDt.getTime() / 1000); - const showCoords = client.exists(guild.showKillfeedCoords) ? guild.showKillfeedCoords : false; // default to false if no record of configuration. - const showWeapon = client.exists(guild.showKillfeedWeapon) ? guild.showKillfeedWeapon : false; // default to false if no record of configuration. + const showCoords = isDefined(guild.showKillfeedCoords) ? guild.showKillfeedCoords : false; // default to false if no record of configuration. + const showWeapon = isDefined(guild.showKillfeedWeapon) ? guild.showKillfeedWeapon : false; // default to false if no record of configuration. const destination = nearest(info.victimPOS, guild.Nitrado.Mission); if ([Templates.LandMine, Templates.Explosion, Templates.Vehicle].includes(killedBy)) if (killedBy == Templates.LandMine || killedBy == Templates.Explosion || killedBy == Templates.Vehicle) { let victimStat = await client.dbo.collection("players").findOne({ "playerID": info.victimID }); - if (!client.exists(victimStat)) victimStat = getDefaultPlayer(info.victim, info.victimID, NitradoServerID); + if (!isDefined(victimStat)) victimStat = getDefaultPlayer(info.victim, info.victimID, NitradoServerID); victimStat.deaths++; victimStat.deathStreak++; victimStat.worstDeathStreak = victimStat.deathStreak > victimStat.worstDeathStreak ? victimStat.deathStreak : victimStat.worstDeathStreak; @@ -157,18 +158,18 @@ module.exports = { const webhook = await GetWebhook(client, NAME, guild.killfeedChannel); WebhookSend(client, webhook, { embeds: [killEvent] }); - // if (client.exists(channel)) await channel.send({ embeds: [killEvent] }); + // if (isDefined(channel)) await channel.send({ embeds: [killEvent] }); return; } KillInAlarm(client, guild.serverID, info); // check if kill happened in a no kill zone - if (!client.exists(info.victim) || !client.exists(info.victimID) || !client.exists(info.killer) || !client.exists(info.killerID)) return; + if (!isDefined(info.victim) || !isDefined(info.victimID) || !isDefined(info.killer) || !isDefined(info.killerID)) return; let victimStat = await client.dbo.collection("players").findOne({ "playerID": info.victimID }); let killerStat = await client.dbo.collection("players").findOne({ "playerID": info.killerID }); - if (!client.exists(victimStat)) victimStat = getDefaultPlayer(info.victim, info.victimID, NitradoServerID); - if (!client.exists(killerStat)) killerStat = getDefaultPlayer(info.killer, info.killerID, NitradoServerID); + if (!isDefined(victimStat)) victimStat = getDefaultPlayer(info.victim, info.victimID, NitradoServerID); + if (!isDefined(killerStat)) killerStat = getDefaultPlayer(info.killer, info.killerID, NitradoServerID); let weapon = info.weapon.includes("Engraved") ? info.weapon.split("Engraved ")[1] : info.weapon.includes("Sawed-off") ? info.weapon.split("Sawed-off ")[1] : @@ -181,7 +182,7 @@ module.exports = { killerStat.KDR = killerStat.kills / (killerStat.deaths == 0 ? 1 : killerStat.deaths); // prevent division by 0 killerStat.longestKill = info.distance > killerStat.longestKill ? info.distance : killerStat.longestKill; killerStat.deathStreak = 0; - if (!client.exists(killerStat.weaponStats[weapon].kills)) killerStat.weaponStats[weapon].kills = 0; + if (!isDefined(killerStat.weaponStats[weapon].kills)) killerStat.weaponStats[weapon].kills = 0; killerStat.weaponStats[weapon].kills++; // Update victim stats @@ -191,21 +192,21 @@ module.exports = { victimStat.KDR = victimStat.kills / (victimStat.deaths == 0 ? 1 : victimStat.deaths); // prevent division by 0 victimStat.killStreak = 0; victimStat.lastDeathDate = newDt; - if (!client.exists(victimStat.weaponStats[weapon].deaths)) victimStat.weaponStats[weapon].death = 0; + if (!isDefined(victimStat.weaponStats[weapon].deaths)) victimStat.weaponStats[weapon].death = 0; victimStat.weaponStats[weapon].deaths++; // Create defaults for non-existing ratings - if (!client.exists(killerStat.combatRating)) killerStat.combatRating = 800; - if (!client.exists(victimStat.combatRating)) victimStat.combatRating = 800; - if (!client.exists(killerStat.combatRatingHistory)) killerStat.combatRatingHistory = [800]; - if (!client.exists(victimStat.combatRatingHistory)) victimStat.combatRatingHistory = [800]; - if (!client.exists(killerStat.highestCombatRating)) killerStat.highestCombatRating = Math.max(...killerStat.combatRatingHistory); - if (!client.exists(victimStat.lowestCombatRating)) victimStat.lowestCombatRating = Math.min(...victimStat.combatRatingHistory); + if (!isDefined(killerStat.combatRating)) killerStat.combatRating = 800; + if (!isDefined(victimStat.combatRating)) victimStat.combatRating = 800; + if (!isDefined(killerStat.combatRatingHistory)) killerStat.combatRatingHistory = [800]; + if (!isDefined(victimStat.combatRatingHistory)) victimStat.combatRatingHistory = [800]; + if (!isDefined(killerStat.highestCombatRating)) killerStat.highestCombatRating = Math.max(...killerStat.combatRatingHistory); + if (!isDefined(victimStat.lowestCombatRating)) victimStat.lowestCombatRating = Math.min(...victimStat.combatRatingHistory); // Calculate new ratings let killerOldRating = killerStat.combatRating; let victimOldRating = victimStat.combatRating; - killerStat.combatRating = calculateNewCombatRating(killerStat.combatRating, victimStat.combatRating, client.exists(info.bodyPart) && info.bodyPart.includes("Head") ? 1.25 : 1); + killerStat.combatRating = calculateNewCombatRating(killerStat.combatRating, victimStat.combatRating, isDefined(info.bodyPart) && info.bodyPart.includes("Head") ? 1.25 : 1); victimStat.combatRating = calculateNewCombatRating(victimStat.combatRating, killerStat.combatRating, 0); // Update combat rating records @@ -230,11 +231,11 @@ module.exports = { if (!banking) { banking = await createUser(interaction.member.user.id, guild.serverID, guild.startingBalance, client) - if (!client.exists(banking)) return client.sendInternalError(interaction, err); + if (!isDefined(banking)) return client.sendInternalError(interaction, err); } banking = banking.user; - if (!client.exists(banking.guilds[guild.serverID])) { + if (!isDefined(banking.guilds[guild.serverID])) { const success = addUser(banking.guilds, guild.serverID, interaction.member.user.id, client, guild.startingBalance); if (!success) return client.sendInternalError(interaction, "Failed to add bank"); } @@ -280,10 +281,10 @@ module.exports = { const webhook = await GetWebhook(client, NAME, guild.killfeedChannel); WebhookSend(client, webhook, { embeds: [killEvent] }); - if (client.exists(receivedBounty) && client.exists(channel)) WebhookSend(client, webhook, { content: `<@${killerStat.discordID}>`, embeds: [receivedBounty] }); + if (isDefined(receivedBounty) && isDefined(channel)) WebhookSend(client, webhook, { content: `<@${killerStat.discordID}>`, embeds: [receivedBounty] }); - // if (client.exists(channel)) await channel.send({ embeds: [killEvent] }); - // if (client.exists(receivedBounty) && client.exists(channel)) await channel.send({ content: `<@${killerStat.discordID}>`, embeds: [receivedBounty] }); + // if (isDefined(channel)) await channel.send({ embeds: [killEvent] }); + // if (isDefined(receivedBounty) && isDefined(channel)) await channel.send({ content: `<@${killerStat.discordID}>`, embeds: [receivedBounty] }); return; } diff --git a/src/util/LogsHandler.js b/src/handlers/LogsHandler.js similarity index 85% rename from src/util/LogsHandler.js rename to src/handlers/LogsHandler.js index 25fc86c..150af1c 100644 --- a/src/util/LogsHandler.js +++ b/src/handlers/LogsHandler.js @@ -5,7 +5,8 @@ const { getDefaultPlayer } = require("../database/player"); const { FetchServerSettings } = require("./NitradoAPI"); const { UpdatePlayer, insertPVPstats, createWeaponStats } = require("../database/player") const { Missions } = require("../database/destinations"); -const { GetWebhook, WebhookSend, WebhookMessageEdit } = require("./WebhookHandler"); +const { GetWebhook, WebhookSend, WebhookMessageEdit } = require("../services/WebhookService"); +const isDefined = require("../util/Validation.js"); module.exports = { @@ -27,15 +28,15 @@ module.exports = { playerID: data[3], }; - if (!client.exists(info.player) || !client.exists(info.playerID)) return; + if (!isDefined(info.player) || !isDefined(info.playerID)) return; let playerStat = await client.dbo.collection("players").findOne({ "playerID": info.playerID }); - if (!client.exists(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, NitradoServerID); + if (!isDefined(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, NitradoServerID); const newDt = await client.getDateEST(info.time); playerStat.lastConnectionDate = newDt; playerStat.connected = true; - if (!client.exists(playerStat.connections)) playerStat.connections = 0; + if (!isDefined(playerStat.connections)) playerStat.connections = 0; playerStat.connections++; // Track adjusted sessions this instance has handled (e.g. no bot crashes or restarts). @@ -72,10 +73,10 @@ module.exports = { playerID: data[3], }; - if (!client.exists(info.player) || !client.exists(info.playerID)) return; + if (!isDefined(info.player) || !isDefined(info.playerID)) return; let playerStat = await client.dbo.collection("players").findOne({ "playerID": info.playerID }); - if (!client.exists(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, NitradoServerID); + if (!isDefined(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, NitradoServerID); let oldUnixTime; let sessionTimeSeconds; @@ -85,7 +86,7 @@ module.exports = { oldUnixTime = Math.round(playerStat.lastConnectionDate.getTime() / 1000); // Seconds sessionTimeSeconds = unixTime - oldUnixTime; } else sessionTimeSeconds = 0; - if (!client.exists(playerStat.longestSessionTime)) playerStat.longestSessionTime = 0; + if (!isDefined(playerStat.longestSessionTime)) playerStat.longestSessionTime = 0; playerStat.totalSessionTime = playerStat.totalSessionTime + sessionTimeSeconds; playerStat.lastSessionTime = sessionTimeSeconds; @@ -126,11 +127,11 @@ module.exports = { pos: data[4].split(", ").map(v => parseFloat(v)) }; - if (!client.exists(info.player) || !client.exists(info.playerID)) return; + if (!isDefined(info.player) || !isDefined(info.playerID)) return; let playerStat = await client.dbo.collection("players").findOne({ "playerID": info.playerID }); - if (!client.exists(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, NitradoServerID); - if (!client.exists(playerStat.lastConnectionDate)) playerStat.lastConnectionDate = await client.getDateEST(info.time); + if (!isDefined(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, NitradoServerID); + if (!isDefined(playerStat.lastConnectionDate)) playerStat.lastConnectionDate = await client.getDateEST(info.time); playerStat.lastPos = playerStat.pos; playerStat.pos = info.pos; @@ -165,18 +166,18 @@ module.exports = { weapon: data[12], }; - if (!client.exists(info.player) || !client.exists(info.playerID) || !client.exists(info.attacker) || !client.exists(info.attackerID)) return; + if (!isDefined(info.player) || !isDefined(info.playerID) || !isDefined(info.attacker) || !isDefined(info.attackerID)) return; let playerStat = await client.dbo.collection("players").findOne({ "playerID": info.playerID }); let attackerStat = await client.dbo.collection("players").findOne({ "playerID": info.attackerID }); - if (!client.exists(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, NitradoServerID); - if (!client.exists(attackerStat)) attackerStat = getDefaultPlayer(info.attacker, info.attackerID, NitradoServerID); + if (!isDefined(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, NitradoServerID); + if (!isDefined(attackerStat)) attackerStat = getDefaultPlayer(info.attacker, info.attackerID, NitradoServerID); playerStat.lastDamageDate = await client.getDateEST(info.time); playerStat.lastHitBy = info.attacker; - if (!client.exists(playerStat.shotsLanded)) playerStat = insertPVPstats(playerStat); - if (!client.exists(attackerStat.shotsLanded)) attackerStat = insertPVPstats(attackerStat); + if (!isDefined(playerStat.shotsLanded)) playerStat = insertPVPstats(playerStat); + if (!isDefined(attackerStat.shotsLanded)) attackerStat = insertPVPstats(attackerStat); // Update in depth PVP stats if non Melee weapon if (info.weapon.includes("Engraved")) info.weapon = info.weapon.split("Engraved ")[1]; @@ -184,13 +185,13 @@ module.exports = { if (info.weapon in playerStat.weaponStats) { playerStat.timesShot++; playerStat.timesShotPerBodyPart[info.bodyPart]++; - if (!client.exists(playerStat.weaponStats[info.weapon])) playerStat = createWeaponStats(playerStat, info.weapon); + if (!isDefined(playerStat.weaponStats[info.weapon])) playerStat = createWeaponStats(playerStat, info.weapon); playerStat.weaponStats[info.weapon].timesShot++; playerStat.weaponStats[info.weapon].timesShotPerBodyPart[info.bodyPart]++; attackerStat.shotsLanded++; attackerStat.shotsLandedPerBodyPart[info.bodyPart]++; - if (!client.exists(attackerStat.weaponStats[info.weapon])) attackerStat = createWeaponStats(attackerStat, info.weapon); + if (!isDefined(attackerStat.weaponStats[info.weapon])) attackerStat = createWeaponStats(attackerStat, info.weapon); attackerStat.weaponStats[info.weapon].shotsLanded++; attackerStat.weaponStats[info.weapon].shotsLandedPerBodyPart[info.bodyPart]++; } @@ -205,7 +206,7 @@ module.exports = { HandleActivePlayersList: async (nitrado_cred, client, guild) => { client.activePlayersTick = 0; // reset hour tick - if (!client.exists(guild.activePlayersChannel)) return; + if (!isDefined(guild.activePlayersChannel)) return; const channel = client.GetChannel(guild.activePlayersChannel); if (!channel) return; diff --git a/src/util/Logger.ts b/src/services/Logger.ts similarity index 100% rename from src/util/Logger.ts rename to src/services/Logger.ts diff --git a/src/util/NitradoAPI.ts b/src/services/NitradoAPI.ts similarity index 99% rename from src/util/NitradoAPI.ts rename to src/services/NitradoAPI.ts index 073906d..1e284ad 100644 --- a/src/util/NitradoAPI.ts +++ b/src/services/NitradoAPI.ts @@ -3,6 +3,7 @@ const concat = require("concat-stream"); // convert to import ? import { Readable } from "stream"; import FormData from "form-data"; import * as fs from "fs"; +import isDefined from "../util/Validation"; const MAX_RETRIES = 5; const RETRY_DELAY_MS = 5000; // 5 seconds @@ -73,7 +74,7 @@ const HandlePlayerBan = async (nitrado_cred: any, client: any, gamertag: any, ba } const GetRemoteDir = async (nitrado_cred: any, client: any, dir = "") => { - const dirParam = client.exists(dir) ? `?dir=${dir}` : ""; + const dirParam = isDefined(dir) ? `?dir=${dir}` : ""; for (let retries = 0; retries <= MAX_RETRIES; retries++) { try { const res = await fetch(`https://api.nitrado.net/services/${nitrado_cred.ServerID}/gameservers/file_server/list${dirParam}`, { diff --git a/src/util/RegisterSlashCommands.js b/src/services/RegisterSlashCommands.js similarity index 100% rename from src/util/RegisterSlashCommands.js rename to src/services/RegisterSlashCommands.js diff --git a/src/util/WebhookHandler.js b/src/services/WebhookService.js similarity index 100% rename from src/util/WebhookHandler.js rename to src/services/WebhookService.js diff --git a/src/services/index.ts b/src/services/index.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/util/CombatRatingHandler.js b/src/util/CombatRating.js similarity index 100% rename from src/util/CombatRatingHandler.js rename to src/util/CombatRating.js diff --git a/src/util/Validation.ts b/src/util/Validation.ts new file mode 100644 index 0000000..8ce251e --- /dev/null +++ b/src/util/Validation.ts @@ -0,0 +1,11 @@ +/** + * isDefined simply ensures a given input is not + * null, undefined, an empty string or NaN. + * + * @param n to validate + * @returns if this object exists (boolean) + */ +export default function isDefined(n: T | null | undefined | "" | number): n is T +{ + return typeof n === "number" ? !isNaN(n) : n !== null && n !== undefined && n !== ""; +}