From 37aff394909c1939edd265ff85dccfe8c5fde17a Mon Sep 17 00:00:00 2001 From: Braeden Sowinski Date: Sat, 21 Oct 2023 15:03:45 -0700 Subject: [PATCH] refactor/remove mongoose + quality of life --- commands/admin.js | 25 ++----- commands/armbands.js | 2 +- commands/bank.js | 79 ++++++-------------- commands/bounty.js | 24 ++---- commands/claim.js | 2 +- commands/collect-income.js | 25 ++----- commands/config.js | 3 +- commands/factions.js | 2 +- commands/location.js | 1 - commands/purchase-emp.js | 24 ++---- commands/purchase-uav.js | 24 ++---- commands/reset.js | 2 +- config/armbandsdb.js => database/armbands.js | 0 {config => database}/destinations.js | 0 database/guildSettings.js | 39 ++++++++++ database/playerStatistics.js | 36 +++++++++ database/user.js | 43 +++++++++++ index.js | 36 ++++----- package.json | 3 +- {structures => src}/DayzRBot.js | 77 ++----------------- structures/user.js | 41 ---------- util/AdminLogsHandler.js | 2 +- util/AlarmsHandler.js | 2 +- util/CommandOptionTypes.js | 20 ++--- util/KillfeedHandler.js | 41 ++++------ util/LogsHandler.js | 11 ++- 26 files changed, 235 insertions(+), 329 deletions(-) rename config/armbandsdb.js => database/armbands.js (100%) rename {config => database}/destinations.js (100%) create mode 100644 database/guildSettings.js create mode 100644 database/playerStatistics.js create mode 100644 database/user.js rename {structures => src}/DayzRBot.js (90%) delete mode 100644 structures/user.js diff --git a/commands/admin.js b/commands/admin.js index d97dbef..5f3083e 100644 --- a/commands/admin.js +++ b/commands/admin.js @@ -2,8 +2,8 @@ const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelect const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; const bitfieldCalculator = require('discord-bitfield-calculator'); const { BanPlayer, UnbanPlayer, RestartServer, CheckServerStatus, DisableBaseDamage } = require('../util/NitradoAPI'); -const { Armbands } = require('../config/armbandsdb.js'); -const { User, addUser } = require('../structures/user'); +const { Armbands } = require('../database/armbands.js'); +const { createUser, addUser } = require('../database/user') module.exports = { name: "admin", @@ -404,23 +404,10 @@ module.exports = { let banking = await client.dbo.collection("users").findOne({"user.userID": targetUserID}).then(banking => banking); if (!banking) { - banking = { - userID: targetUserID, - guilds: { - [GuildDB.serverID]: { - balance: GuildDB.startingBalance, - } - } - } - - // Register bank for user - let newBank = new User(); - newBank.createUser(targetUserID, GuildDB.serverID, GuildDB.startingBalance); - newBank.save().catch(err => { - if (err) return client.sendInternalError(interaction, err); - }); - - } else banking = banking.user; + banking = await createUser(targetUserID, GuildDB.serverID, GuildDB.startingBalance, client) + if (!client.exists(banking)) return client.sendInternalError(interaction, err); + } + banking = banking.user; if (!client.exists(banking.guilds[GuildDB.serverID])) { const success = addUser(banking.guilds, GuildDB.serverID, targetUserID, client, GuildDB.startingBalance); diff --git a/commands/armbands.js b/commands/armbands.js index e0d20a8..ceda096 100644 --- a/commands/armbands.js +++ b/commands/armbands.js @@ -1,5 +1,5 @@ const { StringSelectMenuBuilder, EmbedBuilder, ActionRowBuilder } = require('discord.js'); -const { Armbands } = require('../config/armbandsdb.js'); +const { Armbands } = require('../database/armbands.js'); module.exports = { name: "armbands", diff --git a/commands/bank.js b/commands/bank.js index 983d208..f6af2c5 100644 --- a/commands/bank.js +++ b/commands/bank.js @@ -1,6 +1,6 @@ const { EmbedBuilder } = require('discord.js'); const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const { User, addUser } = require('../structures/user'); +const { createUser, addUser } = require('../database/user'); module.exports = { name: "bank", @@ -64,25 +64,12 @@ module.exports = { } let banking = await client.dbo.collection("users").findOne({"user.userID": interaction.member.user.id}).then(banking => banking); - + if (!banking) { - banking = { - userID: interaction.member.user.id, - guilds: { - [GuildDB.serverID]: { - balance: GuildDB.startingBalance, - } - } - } - - // Register bank for user - let newBank = new User(); - newBank.createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance); - newBank.save().catch(err => { - if (err) return client.sendInternalError(interaction, err); - }); - - } else banking = banking.user; + banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client) + if (!client.exists(banking)) return client.sendInternalError(interaction, err); + } + banking = banking.user; if (!client.exists(banking.guilds[GuildDB.serverID])) { const success = addUser(banking.guilds, GuildDB.serverID, interaction.member.user.id, client, GuildDB.startingBalance); @@ -97,29 +84,16 @@ module.exports = { // Show target users balance let targetUserID = args[0].options[0].value.replace('<@!', '').replace('>', ''); - let targetUserBanking = await client.dbo.collection("users").findOne({"user.userID": targetUserID}).then(banking => banking); + let targetUserBanking = await client.dbo.collection("users").findOne({"user.userID": targetUserID}).then(targetUserBanking => targetUserBanking); if (!targetUserBanking) { - targetUserBanking = { - userID: targetUserID, - guilds: { - [GuildDB.serverID]: { - balance: GuildDB.startingBalance, - } - } - } - - // Register bank for user - let newBank = new User(); - newBank.createUser(targetUserID, GuildDB.serverID, GuildDB.startingBalance, 0); - newBank.save().catch(err => { - if (err) return client.sendInternalError(interaction, err); - }); - - } else targetUserBanking = targetUserBanking.user; - + targetUserBanking = await createUser(targetUserID, GuildDB.serverID, GuildDB.startingBalance, client) + if (!client.exists(banking)) return client.sendInternalError(interaction, err); + } + targetUserBanking = targetUserBanking.user; + if (!client.exists(targetUserBanking.guilds[GuildDB.serverID])) { - const success = addUser(targetUserBanking.guilds, GuildDB.serverID, targetUserID, client, GuildDB.startingBalance); + const success = addUser(banking.guilds, GuildDB.serverID, targetUserID, client, GuildDB.startingBalance); if (!success) return client.sendInternalError(interaction, 'Failed to add bank'); } @@ -160,25 +134,18 @@ module.exports = { if (err) return client.sendInternalError(interaction, err); }); - let targetUserBanking = await client.dbo.collection("users").findOne({"user.userID": targetUserID}).then(banking => banking); + let targetUserBanking = await client.dbo.collection("users").findOne({"user.userID": targetUserID}).then(targetUserBanking => targetUserBanking); if (!targetUserBanking) { - targetUserBanking = { - userID: targetUserID, - guilds: { - [GuildDB.serverID]: { - balance: (GuildDB.startingBalance + args[0].options[1].value), - } - } - } - - // Register bank for user - let newBank = new User(); - newBank.createUser(targetUserID, GuildDB.serverID, GuildDB.startingBalance, 0); - newBank.save().catch(err => { - if (err) return client.sendInternalError(interaction, err); - }); - } else targetUserBanking = targetUserBanking.user; + targetUserBanking = await createUser(targetUserID, GuildDB.serverID, GuildDB.startingBalance, client) + if (!client.exists(banking)) return client.sendInternalError(interaction, err); + } + targetUserBanking = targetUserBanking.user; + + if (!client.exists(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'); + } const newTargetBalance = targetUserBanking.guilds[GuildDB.serverID].balance + args[0].options[1].value; diff --git a/commands/bounty.js b/commands/bounty.js index 7c0bd68..bcf859e 100644 --- a/commands/bounty.js +++ b/commands/bounty.js @@ -1,5 +1,6 @@ const { EmbedBuilder } = require('discord.js'); const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; +const { createUser, addUser } = require('../database/user'); module.exports = { name: "bounty", @@ -60,25 +61,12 @@ module.exports = { let banking; if (args[0].name == 'set' || args[0].name == 'pay') { banking = await client.dbo.collection("users").findOne({"user.userID": interaction.member.user.id}).then(banking => banking); - + if (!banking) { - banking = { - userID: interaction.member.user.id, - guilds: { - [GuildDB.serverID]: { - balance: GuildDB.startingBalance, - } - } - } - - // Register bank for user - let newBank = new User(); - newBank.createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance); - newBank.save().catch(err => { - if (err) return client.sendInternalError(interaction, err); - }); - - } else banking = banking.user; + banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client) + if (!client.exists(banking)) return client.sendInternalError(interaction, err); + } + banking = banking.user; if (!client.exists(banking.guilds[GuildDB.serverID])) { const success = addUser(banking.guilds, GuildDB.serverID, interaction.member.user.id, client, GuildDB.startingBalance); diff --git a/commands/claim.js b/commands/claim.js index ca0d55f..d3006e5 100644 --- a/commands/claim.js +++ b/commands/claim.js @@ -1,6 +1,6 @@ const { ActionRowBuilder, EmbedBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder } = require('discord.js'); const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const { Armbands } = require('../config/armbandsdb.js'); +const { Armbands } = require('../database/armbands.js'); module.exports = { name: "claim", diff --git a/commands/collect-income.js b/commands/collect-income.js index b644ed2..02c9d41 100644 --- a/commands/collect-income.js +++ b/commands/collect-income.js @@ -1,5 +1,5 @@ const { EmbedBuilder, } = require('discord.js'); -const { User, addUser } = require('../structures/user'); +const { createUser, addUser } = require('../database/user'); module.exports = { name: "collect-income", @@ -41,25 +41,12 @@ module.exports = { let banking = await client.dbo.collection("users").findOne({"user.userID": interaction.member.user.id}).then(banking => banking); + if (!banking) { - banking = { - userID: interaction.member.user.id, - guilds: { - [GuildDB.serverID]: { - balance: GuildDB.startingBalance, - lastIncome: new Date('2000-01-01T00:00:00'), - } - } - } - - // Register bank for user - let newBank = new User(); - newBank.createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance); - newBank.save().catch(err => { - if (err) return client.sendInternalError(interaction, err); - }); - - } else banking = banking.user; + banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client) + if (!client.exists(banking)) return client.sendInternalError(interaction, err); + } + banking = banking.user; if (!client.exists(banking.guilds[GuildDB.serverID])) { const success = addUser(banking.guilds, GuildDB.serverID, interaction.member.user.id, client, GuildDB.startingBalance); diff --git a/commands/config.js b/commands/config.js index cac3ea5..be45099 100644 --- a/commands/config.js +++ b/commands/config.js @@ -1,6 +1,7 @@ const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js'); const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; const bitfieldCalculator = require('discord-bitfield-calculator'); +const { getDefaultSettings } = require('../database/guildSettings'); module.exports = { name: "config", @@ -832,7 +833,7 @@ module.exports = { let action = ''; if (interaction.customId.split('-')[1]=='yes') { action = 'reset'; - const defaultGuildConfig = client.getDefaultSettings(GuildDB.serverID); + const defaultGuildConfig = getDefaultSettings(GuildDB.serverID); client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID}, {$set: {"server": defaultGuildConfig}}, (err, res) => { if (err) return client.sendInternalError(interaction, err); }); diff --git a/commands/factions.js b/commands/factions.js index 94a10fd..11c7460 100644 --- a/commands/factions.js +++ b/commands/factions.js @@ -1,6 +1,6 @@ const { EmbedBuilder } = require('discord.js'); const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const { Armbands } = require('../config/armbandsdb.js'); +const { Armbands } = require('../database/armbands.js'); module.exports = { name: "factions", diff --git a/commands/location.js b/commands/location.js index bc93642..dea7f54 100644 --- a/commands/location.js +++ b/commands/location.js @@ -1,5 +1,4 @@ const { EmbedBuilder } = require('discord.js'); -const bitfieldCalculator = require('discord-bitfield-calculator'); module.exports = { name: "location", diff --git a/commands/purchase-emp.js b/commands/purchase-emp.js index cf7e352..7f85dd2 100644 --- a/commands/purchase-emp.js +++ b/commands/purchase-emp.js @@ -1,5 +1,5 @@ const { EmbedBuilder, ActionRowBuilder, StringSelectMenuBuilder } = require('discord.js'); -const { User, addUser } = require('../structures/user'); +const { createUser, addUser } = require('../database/user'); module.exports = { name: "purchase-emp", @@ -24,24 +24,12 @@ module.exports = { let banking = await client.dbo.collection("users").findOne({"user.userID": interaction.member.user.id}).then(banking => banking); + if (!banking) { - banking = { - userID: interaction.member.user.id, - guilds: { - [GuildDB.serverID]: { - balance: GuildDB.startingBalance, - } - } - } - - // Register bank for user - let newBank = new User(); - newBank.createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance); - newBank.save().catch(err => { - if (err) return client.sendInternalError(interaction, err); - }); - - } else banking = banking.user; + banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client) + if (!client.exists(banking)) return client.sendInternalError(interaction, err); + } + banking = banking.user; if (!client.exists(banking.guilds[GuildDB.serverID])) { const success = addUser(banking.guilds, GuildDB.serverID, interaction.member.user.id, client, GuildDB.startingBalance); diff --git a/commands/purchase-uav.js b/commands/purchase-uav.js index 8c325df..6032a04 100644 --- a/commands/purchase-uav.js +++ b/commands/purchase-uav.js @@ -1,6 +1,6 @@ const { EmbedBuilder } = require('discord.js'); const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const { User, addUser } = require('../structures/user') +const { createUser, addUser } = require('../database/user') module.exports = { name: "purchase-uav", @@ -42,24 +42,12 @@ module.exports = { let banking = await client.dbo.collection("users").findOne({"user.userID": interaction.member.user.id}).then(banking => banking); + if (!banking) { - banking = { - userID: interaction.member.user.id, - guilds: { - [GuildDB.serverID]: { - balance: GuildDB.startingBalance, - } - } - } - - // Register bank for user - let newBank = new User(); - newBank.createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, 0); - newBank.save().catch(err => { - if (err) return client.sendInternalError(interaction, err); - }); - - } else banking = banking.user; + banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client) + if (!client.exists(banking)) return client.sendInternalError(interaction, err); + } + banking = banking.user; if (!client.exists(banking.guilds[GuildDB.serverID])) { const success = addUser(banking.guilds, GuildDB.serverID, interaction.member.user.id, client, GuildDB.startingBalance); diff --git a/commands/reset.js b/commands/reset.js index a04ce07..b85e5c8 100644 --- a/commands/reset.js +++ b/commands/reset.js @@ -1,6 +1,6 @@ const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js'); const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const { addUser } = require('../structures/user'); +const { addUser } = require('../database/user'); const bitfieldCalculator = require('discord-bitfield-calculator'); module.exports = { diff --git a/config/armbandsdb.js b/database/armbands.js similarity index 100% rename from config/armbandsdb.js rename to database/armbands.js diff --git a/config/destinations.js b/database/destinations.js similarity index 100% rename from config/destinations.js rename to database/destinations.js diff --git a/database/guildSettings.js b/database/guildSettings.js new file mode 100644 index 0000000..bb0554b --- /dev/null +++ b/database/guildSettings.js @@ -0,0 +1,39 @@ +module.exports = { + getDefaultSettings(GuildId) { + return { + serverID: GuildId, + autoRestart: 0, + showKillfeedCoords: 0, + allowedChannels: [], + + killfeedChannel: "", + connectionLogsChannel: "", + activePlayersChannel: "", + welcomeChannel: "", + + factionArmbands: {}, + usedArmbands: [], + excludedRoles: [], + botAdminRoles: [], + + playerstats: [], // to be removed + + alarms: [], + events: [], + uavs: [], + + incomeRoles: [], + incomeLimiter: 168, // # of hours in 7 days + + startingBalance: 500, + uavPrice: 50000, + empPrice: 500000, + + linkedGamertagRole: "", + memberRole: "", + adminRole: "", + + combatLogTimer: 5, // minutes + } + } +} diff --git a/database/playerStatistics.js b/database/playerStatistics.js new file mode 100644 index 0000000..51c8170 --- /dev/null +++ b/database/playerStatistics.js @@ -0,0 +1,36 @@ +module.exports = { + getDefaultPlayerStats(gt, pID) { + return { + gamertag: gt, + playerID: pID, + discordID: "", + + KDR: 0.00, + kills: 0, + deaths: 0, + killStreak: 0, + bestKillStreak: 0, + longestKill: 0, + deathStreak: 0, + worstDeathStreak: 0, + + pos: [], + lastPos: [], + time: null, + lastTime: null, + + lastConnectionDate: null, + lastDisconnectionDate: null, + lastDamageDate: null, + lastDeathDate: null, + lastHitBy: null, + connected: false, + + totalSessionTime: 0, + lastSessionTime: 0, + longestSessionTime: 0, + + bounties: [], + } + } +} \ No newline at end of file diff --git a/database/user.js b/database/user.js new file mode 100644 index 0000000..05e57ac --- /dev/null +++ b/database/user.js @@ -0,0 +1,43 @@ +module.exports = { + createUser: async (userID, initialGuildID, startingBalance, client) => { + let User = { + user: { + userID: userID, + guilds: {} + } + }; + + User.user.guilds[initialGuildID] = { + balance: startingBalance, + lastIncome: new Date('2000-01-01T00:00:00'), + }; + + await client.dbo.collection("users").insertOne(User, (err, res) => { + if (err) { + client.error(`Failed to create user - ${err}`); + return undefined; + } + }); + + return User; + }, + + /* + This function is to add a new guild specific user to an already existing + user document + or + can be used to reset a data back to default + */ + addUser: async (guilds, newGuildID, userID, client, startingBalance) => { + let updatedGuilds = guilds; + updatedGuilds[newGuildID] = { + balance: startingBalance, + lastIncome: new Date('2000-01-01T00:00:00') + } + + await client.dbo.collection("users").updateOne({"user.userID":userID}, {$set: {"user.guilds": updatedGuilds}}, (err, res) => { + if (err) return false + }) + return true + } +} diff --git a/index.js b/index.js index 3af0c29..4a702e8 100644 --- a/index.js +++ b/index.js @@ -1,4 +1,4 @@ -const DayzR = require('./structures/DayzRBot'); +const DayzR = require('./src/DayzRBot'); const config = require('./config/config'); const { GatewayIntentBits } = require('discord.js'); @@ -8,24 +8,24 @@ const { HandleActivePlayersList } = require('./util/LogsHandler'); // Log all uncaught exceptions before killing process. process.on('uncaughtException', async (error) => { - let d = new Date(); - // Asynchronously write the error message to a log file using Promises - await new Promise((resolve, reject) => { - if (HandleActivePlayersList.lastSendMessage) HandleActivePlayersList.lastSendMessage.delete().catch(error => client.sendError(channel, `HandleActivePlayersList Error: \n${error}`)); // Remove previous embed message before closing - fs.appendFile(path.join(__dirname, "./logs/Logs.log"), - `{"level":"error","message":"${d.getHours()}:${d.getMinutes()} - ${d.getMonth()+1}:${d.getDate()}:${d.getFullYear()} | uncaughtException: ${error.stack}"}`, (logErr) => { - if (logErr) { - console.error('Error writing uncaughtException to log file:', logErr); - reject(logErr); - process.exit() - } else { - resolve(); - } - }); - }); + let d = new Date(); + // Asynchronously write the error message to a log file using Promises + await new Promise((resolve, reject) => { + if (HandleActivePlayersList.lastSendMessage) HandleActivePlayersList.lastSendMessage.delete().catch(error => client.sendError(channel, `HandleActivePlayersList Error: \n${error}`)); // Remove previous embed message before closing + fs.appendFile(path.join(__dirname, "./logs/Logs.log"), + `{"level":"error","message":"${d.getHours()}:${d.getMinutes()} - ${d.getMonth()+1}:${d.getDate()}:${d.getFullYear()} | uncaughtException: ${error.stack}"}`, (logErr) => { + if (logErr) { + console.error('Error writing uncaughtException to log file:', logErr); + reject(logErr); + process.exit() + } else { + resolve(); + } + }); + }); - // Now gracefully close the program - process.exit() + // Now gracefully close the program + process.exit() }); let client = new DayzR({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMembers] }, config); diff --git a/package.json b/package.json index 9dbfce3..22e89a1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dayzr-bot", - "version": "10.4.4", + "version": "11.0.0", "description": "A General Purpose Discord Bot for DayZ Nitrado Servers.", "main": "index.js", "nodemonConfig": { @@ -25,7 +25,6 @@ "dotenv": "^16.0.3", "form-data": "^4.0.0", "mongodb": "^4.12.1", - "mongoose": "^7.0.1", "winston": "^3.8.1" }, "devDependencies": { diff --git a/structures/DayzRBot.js b/src/DayzRBot.js similarity index 90% rename from structures/DayzRBot.js rename to src/DayzRBot.js index 7c6c44c..2420cb9 100644 --- a/structures/DayzRBot.js +++ b/src/DayzRBot.js @@ -3,7 +3,6 @@ const { Collection, Client, EmbedBuilder, Routes } = require('discord.js'); const MongoClient = require('mongodb').MongoClient; const { REST } = require('@discordjs/rest'); const Logger = require("../util/Logger"); -const mongoose = require('mongoose'); // custom util imports const { DownloadNitradoFile, CheckServerStatus } = require('../util/NitradoAPI'); @@ -11,6 +10,10 @@ const { HandlePlayerLogs, HandleActivePlayersList } = require('../util/LogsHandl const { HandleKillfeed, UpdateLastDeathDate } = require('../util/KillfeedHandler'); const { HandleExpiredUAVs, HandleEvents } = require('../util/AlarmsHandler'); +// Data structures imports +const { getDefaultPlayerStats } = require('../database/playerStatistics'); +const { getDefaultSettings } = require('../database/guildSettings'); + const path = require("path"); const fs = require('fs'); const readline = require('readline'); @@ -193,7 +196,7 @@ class DayzRBot extends Client { lastDetectedTime = await this.getDateEST(info.time); let playerStat = s.find(stat => stat.playerID == info.playerID); - if (playerStat == undefined) playerStat = this.getDefaultPlayerStats(info.player, info.playerID); + if (playerStat == undefined) playerStat = getDefaultPlayerStats(info.player, info.playerID); if (!previouslyConnected.includes(playerStat) && this.exists(playerStat.lastDisconnectionDate) && playerStat.lastDisconnectionDate !== null && playerStat.lastDisconnectionDate.getTime() > lastDetectedTime.getTime()) continue; // Skip this player if the lastDisconnectionDate time is later than the player log entry. @@ -283,19 +286,13 @@ class DayzRBot extends Client { // Connect to Mongo database. this.db = await MongoClient.connect(mongoURI, { connectTimeoutMS: 1000 }); this.dbo = this.db.db(dbo); - mongoose.connect(`mongodb://${mongoURI.split('@')[1]}/${dbo}`, { - authSource: "admin", - user: mongoURI.split('//')[1].split(':')[0], - pass: mongoURI.split('//')[1].split(':')[1].split('@')[0], - useNewUrlParser: true, - }).catch(e => this.error(e)); this.log('Successfully connected to mongoDB'); databaselogs.connected = true; databaselogs.attempts = 0; // reset attempts this.databaseConnected = true; } catch (err) { databaselogs.attempts++; - this.error(`Failed to connect to mongodb (mongodb://${mongoURI.split('@')[1]}/${dbo}): attempt ${databaselogs.attempts} - Error: ${err}`); + this.error(`Failed to connect to mongodb (mongodb://${mongoURI.split('@')[1]}/${dbo}): attempt ${databaselogs.attempts} - ${err}`); failed = true; } @@ -404,66 +401,6 @@ class DayzRBot extends Client { this.guilds.cache.forEach((guild) => RegisterGuildCommands(this, guild.id)); } - getDefaultSettings(GuildId) { - return { - serverID: GuildId, - autoRestart: 0, - allowedChannels: [], - killfeedChannel: "", - showKillfeedCoords: 0, - connectionLogsChannel: "", - activePlayersChannel: "", - welcomeChannel: "", - factionArmbands: {}, - usedArmbands: [], - excludedRoles: [], - botAdminRoles: [], - playerstats: [], - alarms: [], - events: [], - uavs: [], - incomeRoles: [], - incomeLimiter: 168, // # of hours in 7 days - linkedGamertagRole: "", - startingBalance: 500, - uavPrice: 50000, - empPrice: 500000, - memberRole: "", - adminRole: "", - combatLogTimer: 5, // minutes - } - } - - getDefaultPlayerStats(gt, pID) { - return { - gamertag: gt, - playerID: pID, - discordID: "", - KDR: 0.00, - kills: 0, - deaths: 0, - killStreak: 0, - bestKillStreak: 0, - longestKill: 0, - deathStreak: 0, - worstDeathStreak: 0, - pos: [], - lastPos: [], - time: null, - lastTime: null, - lastConnectionDate: null, - lastDisconnectionDate: null, - lastDamageDate: null, - lastDeathDate: null, - lastHitBy: null, - connected: false, - totalSessionTime: 0, - lastSessionTime: 0, - longestSessionTime: 0, - bounties: [], - } - } - async GetGuild(GuildId) { let guild = undefined; if (this.databaseConnected) guild = await this.dbo.collection("guilds").findOne({"server.serverID":GuildId}).then(guild => guild); @@ -471,7 +408,7 @@ class DayzRBot extends Client { // If guild not found, generate guild default if (!guild) { guild = {} - guild.server = this.getDefaultSettings(GuildId); + guild.server = getDefaultSettings(GuildId); if (this.databaseConnected) { this.dbo.collection("guilds").insertOne(guild, (err, res) => { if (err) throw err; diff --git a/structures/user.js b/structures/user.js deleted file mode 100644 index 0e51b54..0000000 --- a/structures/user.js +++ /dev/null @@ -1,41 +0,0 @@ -const mongoose = require('mongoose'); - -let userSchema = mongoose.Schema({ - user: { - userID: String, - guilds: {} - }, -}); - -userSchema.methods.createUser = function (userID, guildID, startingBalance) { - this.user.userID = userID; - this.user.guilds = {}; - this.user.guilds[guildID] = { - balance: startingBalance, - lastIncome: new Date('2000-01-01T00:00:00'), - }; -}; - -/* - This function is to add a new guild specific user to an already existing - user document - or - can be used to reset a data back to default -*/ -function addUser(guilds, guildID, userID, client, startingBalance) { - let updatedGuilds = guilds; - updatedGuilds[guildID] = { - balance: startingBalance, - lastIncome: new Date('2000-01-01T00:00:00') - } - - client.dbo.collection("users").updateOne({"user.userID":userID}, {$set: {"user.guilds": updatedGuilds}}, (err, res) => { - if (err) return false - }) - return true -} - -module.exports = { - User: mongoose.model('User', userSchema), - addUser: addUser, -}; diff --git a/util/AdminLogsHandler.js b/util/AdminLogsHandler.js index c04f06e..689b906 100644 --- a/util/AdminLogsHandler.js +++ b/util/AdminLogsHandler.js @@ -1,5 +1,5 @@ const { EmbedBuilder } = require('discord.js'); -const { destinations } = require('../config/destinations'); +const { destinations } = require('../database/destinations'); const { calculateVector } = require('./vector'); module.exports = { diff --git a/util/AlarmsHandler.js b/util/AlarmsHandler.js index d29d005..14238b2 100644 --- a/util/AlarmsHandler.js +++ b/util/AlarmsHandler.js @@ -1,7 +1,7 @@ const { BanPlayer, UnbanPlayer } = require('./NitradoAPI'); const { EmbedBuilder } = require('discord.js'); const { calculateVector } = require('./vector'); -const { destinations } = require('../config/destinations'); +const { destinations } = require('../database/destinations'); // Private functions (only called locally) diff --git a/util/CommandOptionTypes.js b/util/CommandOptionTypes.js index 716b2cb..d74fec1 100644 --- a/util/CommandOptionTypes.js +++ b/util/CommandOptionTypes.js @@ -1,15 +1,15 @@ module.exports = { CommandOptionTypes: { - SubCommand: 1, + SubCommand: 1, SubCommandGroup: 2, - String: 3, - Integer: 4, - Boolean: 5, - User: 6, - Channel: 7, - Role: 8, - Mentionable: 9, - Float: 10, // AKA Number in Discord's Documentation - Attachment: 11, + String: 3, + Integer: 4, + Boolean: 5, + User: 6, + Channel: 7, + Role: 8, + Mentionable: 9, + Float: 10, // AKA Number in Discord's Documentation + Attachment: 11, } }; \ No newline at end of file diff --git a/util/KillfeedHandler.js b/util/KillfeedHandler.js index a96e1bd..93c3c92 100644 --- a/util/KillfeedHandler.js +++ b/util/KillfeedHandler.js @@ -1,8 +1,9 @@ const { EmbedBuilder } = require('discord.js'); -const { User, addUser } = require('../structures/user'); +const { createUser, addUser } = require('../database/user'); const { KillInAlarm } = require('./AlarmsHandler'); -const { destinations } = require('../config/destinations'); +const { destinations } = require('../database/destinations'); const { calculateVector } = require('./vector'); +const { getDefaultPlayerStats } = require('../database/playerStatistics'); const Templates = { Killed: 1, @@ -59,7 +60,7 @@ module.exports = { let victimStat = stats.find(stat => stat.playerID == info.victimID); let victimStatIndex = stats.indexOf(victimStat); - if (victimStat == undefined) victimStat = client.getDefaultPlayerStats(info.victim, info.victimID); + if (victimStat == undefined) victimStat = getDefaultPlayerStats(info.victim, info.victimID); victimStat.lastDeathDate = newDt; if (victimStatIndex == -1) stats.push(victimStat); else stats[victimStatIndex] = victimStat; @@ -146,7 +147,7 @@ module.exports = { if (killedBy == Templates.LandMine || killedBy == Templates.Explosion || killedBy == Templates.Vehicle) { let victimStat = stats.find(stat => stat.playerID == info.victimID) let victimStatIndex = stats.indexOf(victimStat); - if (victimStat == undefined) victimStat = client.getDefaultPlayerStats(info.victim, info.victimID); + if (victimStat == undefined) victimStat = getDefaultPlayerStats(info.victim, info.victimID); victimStat.lastDeathDate = newDt; if (victimStatIndex == -1) stats.push(victimStat); else stats[victimStatIndex] = victimStat; @@ -172,8 +173,8 @@ module.exports = { let victimStat = stats.find(stat => stat.playerID == info.victimID) let killerStatIndex = stats.indexOf(killerStat); let victimStatIndex = stats.indexOf(victimStat); - if (killerStat == undefined) killerStat = client.getDefaultPlayerStats(info.killer, info.killerID); - if (victimStat == undefined) victimStat = client.getDefaultPlayerStats(info.victim, info.victimID); + if (killerStat == undefined) killerStat = getDefaultPlayerStats(info.killer, info.killerID); + if (victimStat == undefined) victimStat = getDefaultPlayerStats(info.victim, info.victimID); killerStat.kills++; killerStat.killStreak++; @@ -197,28 +198,16 @@ module.exports = { let banking = await client.dbo.collection("users").findOne({"user.userID": killerStat.discordID}).then(banking => banking); + if (!banking) { - banking = { - userID: killerStat.discordID, - guilds: { - [guildId]: { - balance: guild.startingBalance, - } - } - } + banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client) + if (!client.exists(banking)) return client.sendInternalError(interaction, err); + } + banking = banking.user; - // Register bank for user - let newBank = new User(); - newBank.createUser(killerStat.discordID, guildId, guild.startingBalance); - newBank.save().catch(err => { - if (err) return client.sendError(client.GetChannel(guild.killfeedChannel), err); - }); - - } else banking = banking.user; - - if (!client.exists(banking.guilds[guildId])) { - const success = addUser(banking.guilds, guildId, killer.discordID, this, guild.startingBalance); - if (!success) return client.sendError(client.GetChannel(guild.killfeedChannel), 'Automatic Bounty Payout: Failed to add bank to database.'); + if (!client.exists(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'); } const newBalance = banking.guilds[guildId].balance + totalBounty; diff --git a/util/LogsHandler.js b/util/LogsHandler.js index e9fbb44..baab5bf 100644 --- a/util/LogsHandler.js +++ b/util/LogsHandler.js @@ -1,8 +1,7 @@ const { EmbedBuilder } = require('discord.js'); const { HandleAlarmsAndUAVs } = require('./AlarmsHandler'); const { SendConnectionLogs, DetectCombatLog } = require('./AdminLogsHandler'); - -// custom util imports +const { getDefaultPlayerStats } = require('../database/playerStatistics'); const { FetchServerSettings } = require('../util/NitradoAPI'); let lastSendMessage; @@ -31,7 +30,7 @@ module.exports = { let playerStat = stats.find(stat => stat.playerID == info.playerID); let playerStatIndex = stats.indexOf(playerStat); - if (playerStat === undefined) playerStat = client.getDefaultPlayerStats(info.player, info.playerID); + if (playerStat === undefined) playerStat = getDefaultPlayerStats(info.player, info.playerID); const newDt = await client.getDateEST(info.time); @@ -77,7 +76,7 @@ module.exports = { let playerStat = stats.find(stat => stat.playerID == info.playerID); let playerStatIndex = stats.indexOf(playerStat); - if (playerStat === undefined) playerStat = client.getDefaultPlayerStats(info.player, info.playerID); + if (playerStat === undefined) playerStat = getDefaultPlayerStats(info.player, info.playerID); const newDt = await client.getDateEST(info.time); const unixTime = Math.round(newDt.getTime() / 1000); // Seconds @@ -129,7 +128,7 @@ module.exports = { let playerStat = stats.find(stat => stat.playerID == info.playerID); let playerStatIndex = stats.indexOf(playerStat); - if (playerStat === undefined) playerStat = client.getDefaultPlayerStats(info.player, info.playerID); + if (playerStat === undefined) playerStat = getDefaultPlayerStats(info.player, info.playerID); if (!client.exists(playerStat.lastConnectionDate)) playerStat.lastConnectionDate = await client.getDateEST(info.time); playerStat.lastPos = playerStat.pos; @@ -168,7 +167,7 @@ module.exports = { let playerStat = stats.find(stat => stat.playerID == info.playerID); let playerStatIndex = stats.indexOf(playerStat); - if (playerStat === undefined) playerStat = client.getDefaultPlayerStats(info.player, info.playerID); + if (playerStat === undefined) playerStat = getDefaultPlayerStats(info.player, info.playerID); playerStat.lastDamageDate = await client.getDateEST(info.time); playerStat.lastHitBy = info.attacker;