From 49ad83a71ab0661749697d3e32859d4f05cf4a02 Mon Sep 17 00:00:00 2001 From: IrPgFKS0 <2511445@gmail.com> Date: Sat, 9 Sep 2023 22:57:39 -0700 Subject: [PATCH] Partial refactoring/bug fix w/ session time correction --- commands/admin.js | 36 ++++++------ index.js | 10 ++-- structures/DayzRBot.js | 123 +++++++++++++++++++-------------------- util/AdminLogsHandler.js | 17 +++--- util/LogsHandler.js | 92 +++++++++++++++-------------- util/NitradoAPI.js | 6 +- 6 files changed, 141 insertions(+), 143 deletions(-) diff --git a/commands/admin.js b/commands/admin.js index 00b871d..e81f03f 100644 --- a/commands/admin.js +++ b/commands/admin.js @@ -185,7 +185,7 @@ module.exports = { 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?`) - + const opt = new ActionRowBuilder() .addComponents( new ButtonBuilder() @@ -202,7 +202,7 @@ module.exports = { } playerStat.discordID = args[0].options[0].value; - + let playerStatIndex = GuildDB.playerstats.indexOf(playerStat); GuildDB.playerstats[playerStatIndex] = playerStat; @@ -228,7 +228,7 @@ module.exports = { .setDescription(`Successfully connected \` ${playerStat.gamertag} \` as <@${args[0].options[0].value}>'s gamertag.`); return interaction.send({ embeds: [connectedEmbed] }) - + } else if (args[0].name == 'gamertag-unlink') { if (!client.exists(GuildDB.playerstats)) { @@ -248,7 +248,7 @@ module.exports = { const warnGTOverwrite = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription(`**Notice:**\n> This action will unlink the gamertag \` ${playerStat.gamertag} \` from the user <@${playerStat.discordID}>. Are you sure you would like to continue?`) - + const opt = new ActionRowBuilder() .addComponents( new ButtonBuilder() @@ -273,7 +273,7 @@ module.exports = { const warnArmbadChange = new EmbedBuilder() .setColor(client.config.Colors.Yellow) .setDescription(`**Notice:**\n> The faction <@&${args[0].options[0].value}> already has an armband selected. Are you sure you would like to change this?`) - + const opt = new ActionRowBuilder() .addComponents( new ButtonBuilder() @@ -289,13 +289,13 @@ module.exports = { return interaction.send({ embeds: [warnArmbadChange], components: [opt] }); } - // Any interaction for 'claim-armband' can be handled in + // Any interaction for 'claim-armband' can be handled in // 'commands/claim.js' Interaction handlers and does not require its own code in this file. let available = new StringSelectMenuBuilder() .setCustomId(`Claim-${args[0].options[0].value}-1-${interaction.member.user.id}`) .setPlaceholder('Select an armband from list 1 to claim') - + let availableNext = new StringSelectMenuBuilder() .setCustomId(`Claim-${args[0].options[0].value}-2-${interaction.member.user.id}`) .setPlaceholder('Select an armband from list 2 to claim') @@ -321,7 +321,7 @@ module.exports = { if (tracker > 25) { opt2 = new ActionRowBuilder().addComponents(availableNext); compList.push(opt2); - } + } return interaction.send({ components: compList }); @@ -340,7 +340,7 @@ module.exports = { } }, (err, res) => { if (err) return client.sendInternalError(interaction, err); - }); + }); const clearedBounty = new EmbedBuilder() .setColor(client.config.Colors.Green) @@ -399,13 +399,13 @@ module.exports = { } } - // Register bank for user + // 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; if (!client.exists(banking.guilds[GuildDB.serverID])) { @@ -416,11 +416,11 @@ module.exports = { let newBalance = args[0].name == 'add-money' ? banking.guilds[GuildDB.serverID].balance + args[0].options[0].value : banking.guilds[GuildDB.serverID].balance - args[0].options[0].value; - + client.dbo.collection("users").updateOne({"user.userID":targetUserID},{$set:{[`user.guilds.${GuildDB.serverID}.balance`]:newBalance}}, (err, res) => { if (err) return client.sendInternalError(interaction, err); }); - + const successEmbed = new EmbedBuilder() .setDescription(`Successfully ${args[0].name == 'add-money' ? 'added' : 'removed'} **$${args[0].options[0].value.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}** ${args[0].name == 'add' ? 'to' : 'from'} <@${targetUserID}>'s balance`) .setColor(client.config.Colors.Green); @@ -460,7 +460,7 @@ module.exports = { if (err) return client.sendInternalError(interaction, err); }); - return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(msg)] }); + return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(msg)], flags: (1 << 6) }); } } }, @@ -469,14 +469,14 @@ module.exports = { AdminOverwriteGamertag: { run: async(client, interaction, GuildDB) => { - if (!interaction.customId.endsWith(interaction.member.user.id)) + if (!interaction.customId.endsWith(interaction.member.user.id)) return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) }); if (interaction.customId.split('-')[1]=='yes') { let playerStat = GuildDB.playerstats.find(stat => stat.gamertag == interaction.customId.split('-')[2]); playerStat.discordID = interaction.customId.split('-')[3]; - + let playerStatIndex = GuildDB.playerstats.indexOf(playerStat); GuildDB.playerstats[playerStatIndex] = playerStat; @@ -515,14 +515,14 @@ module.exports = { AdminUnlinkGamertag: { run: async(client, interaction, GuildDB) => { - if (!interaction.customId.endsWith(interaction.member.user.id)) + if (!interaction.customId.endsWith(interaction.member.user.id)) return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) }); if (interaction.customId.split('-')[1]=='yes') { let playerStat = GuildDB.playerstats.find(stat => stat.discordID == interaction.customId.split('-')[2]); playerStat.discordID = ""; - + let playerStatIndex = GuildDB.playerstats.indexOf(playerStat); GuildDB.playerstats[playerStatIndex] = playerStat; diff --git a/index.js b/index.js index ade34fc..3af0c29 100644 --- a/index.js +++ b/index.js @@ -4,15 +4,14 @@ const { GatewayIntentBits } = require('discord.js'); const path = require("path"); const fs = require('fs'); - -let client = new DayzR({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMembers] }, config); -client.build() +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) { @@ -25,6 +24,9 @@ process.on('uncaughtException', async (error) => { }); }); - // Now, you can re-throw the error + // Now gracefully close the program process.exit() }); + +let client = new DayzR({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMembers] }, config); +client.build() diff --git a/structures/DayzRBot.js b/structures/DayzRBot.js index f628dff..e466d81 100644 --- a/structures/DayzRBot.js +++ b/structures/DayzRBot.js @@ -10,19 +10,18 @@ const { DownloadNitradoFile, CheckServerStatus } = require('../util/NitradoAPI') const { HandlePlayerLogs, HandleActivePlayersList } = require('../util/LogsHandler'); const { HandleKillfeed } = require('../util/KillfeedHandler'); const { HandleExpiredUAVs, HandleEvents } = require('../util/AlarmsHandler'); -const { SendConnectionLogs } = require('../util/AdminLogsHandler'); const path = require("path"); const fs = require('fs'); const readline = require('readline'); const minute = 60000; // 1 minute in milliseconds -const arInterval = 600000; // Set auto-restart interval 10mins (600,000ms) +const arInterval = 600000; // Set auto-restart interval 10 minutes (600,000ms) class DayzRBot extends Client { constructor(options, config) { - super(options) + super(options); this.config = config; this.commands = new Collection(); @@ -30,16 +29,17 @@ class DayzRBot extends Client { this.logger = new Logger(path.join(__dirname, "..", "logs/Logs.log")); this.timer = this.config.Dev == 'PROD.' ? minute * 5 : minute / 4; - if (this.config.Token === "" || this.config.GuildID === "") - throw new TypeError( - "The config.js is not filled out. Please make sure nothing is blank, otherwise the bot will not work properly." - ); + if (this.config.Token === "" || this.config.GuildID === "") { + throw new TypeError( + "The config.js is not filled out. Please make sure nothing is blank, otherwise the bot will not work properly." + ); + } this.db; this.dbo; this.databaseConnected = false; - this.arInterval = arInterval - this.arIntervalId; // Interval for auto-restart functions + this.arInterval = arInterval; + this.arIntervalId; // Interval for auto-restart functions this.autoRestartInit(); this.LoadCommandsAndInteractionHandlers(); this.LoadEvents(); @@ -49,7 +49,7 @@ class DayzRBot extends Client { this.ws.on("INTERACTION_CREATE", async (interaction) => { const start = new Date().getTime(); - if (interaction.type!=3) { + if (interaction.type != 3) { let GuildDB = await this.GetGuild(interaction.guild_id); for (const [factionID, data] of Object.entries(GuildDB.factionArmbands)) { @@ -60,21 +60,21 @@ class DayzRBot extends Client { $pull: { 'server.usedArmbands': data.armband }, $unset: { [`server.factionArmbands.${factionID}`]: "" }, }; - await this.dbo.collection("guilds").updateOne({'server.serverID': GuildDB.serverID}, query, (err, res) => { + await this.dbo.collection("guilds").updateOne({ 'server.serverID': GuildDB.serverID }, query, (err, res) => { if (err) return this.sendInternalError(interaction, err); }); } } - + const command = interaction.data.name.toLowerCase(); const args = interaction.data.options; - client.log(`Interaction - ${command}`); + this.log(`Interaction - ${command}`); - //Easy to send respnose so ;) + // Easy to send response so ;) interaction.guild = await this.guilds.fetch(interaction.guild_id); interaction.send = async (message) => { - const rest = new REST({ version: '10' }).setToken(client.config.Token); + const rest = new REST({ version: '10' }).setToken(this.config.Token); return await rest.post(Routes.interactionCallback(interaction.id, interaction.token), { body: { @@ -88,11 +88,11 @@ class DayzRBot extends Client { let dbFailedEmbed = new EmbedBuilder() .setDescription(`**Internal Error:**\nUh Oh D: Its not you, its me.\nThe bot has failed to connect to the database 5 times!\nContact the Developers\nhttps://discord.gg/YCXhvy9uZw`) .setColor(this.config.Colors.Red) - + return interaction.send({ embeds: [dbFailedEmbed] }); } - let cmd = client.commands.get(command); + let cmd = this.commands.get(command); try { cmd.SlashCommand.run(this, interaction, args, { GuildDB }, start); // start is only used in ping / stats command } catch (err) { @@ -100,24 +100,22 @@ class DayzRBot extends Client { } } }); - - const client = this; } log(Text) { this.logger.log(Text); } error(Text) { this.logger.error(Text); } async getDateEST(time) { - let timeArray = time.split(' ')[0].split(':') + let timeArray = time.split(' ')[0].split(':'); let t = new Date(); // Get current date & time (UTC) - let f = new Date(t.getTime() - 4 * 3600000) // Convert UTC into EST time to roll back the day as necessary + let f = new Date(t.getTime() - 4 * 3600000); // Convert UTC into EST time to roll back the day as necessary f.setUTCHours(timeArray[0], timeArray[1], timeArray[2]); // Apply the supplied EST time to the converted date (EST is the timezone produced from the Nitrado logs). return new Date(f.getTime() + 4 * 3600000); // Add EST time offset to return timestamp in UTC } async readLogs(guildId) { const fileStream = fs.createReadStream('./logs/server-logs.ADM'); - + let logHistoryDir = path.join(__dirname, '..', 'logs', 'history-logs.ADM.json'); let history; try { @@ -134,20 +132,20 @@ class DayzRBot extends Client { }); let lines = []; for await (const line of rl) { lines.push(line); } - + let logIndex = lines.indexOf(history.lastLog); - + let guild = await this.GetGuild(guildId); if (!this.exists(guild.playerstats)) guild.playerstats = []; let s = guild.playerstats; - s.map(p => p.connected = false) // assume all players not connected + s.map(p => p.connected = false); // assume all players not connected for (let i = logIndex + 1; i < lines.length; i++) { if (lines[i].includes('| ####')) continue; if (lines[i].includes("(id=Unknown") || lines[i].includes("Player \"Unknown Entity\"")) continue; - if ((i - 1) >= 0 && lines[i] == lines[i-1]) continue; // continue if this line is a duplicate of the last line - if (lines[i].includes('connected') || lines[i].includes('pos=<') || lines[1].includes('hit by Player')) s = await HandlePlayerLogs(this, guildId, s, lines[i]); + if ((i - 1) >= 0 && lines[i] == lines[i - 1]) continue; // continue if this line is a duplicate of the last line + if (lines[i].includes('connected') || lines[i].includes('pos=<') || lines[i].includes('hit by Player')) s = await HandlePlayerLogs(this, guildId, s, lines[i]); if (lines[i].includes('killed by with') || lines[i].includes('killed by LandMineTrap')) s = await HandleKillfeed(this, guildId, s, lines[i]); // Handles explosive deaths if (!(i + 1 >= lines.length) && lines[i + 1].includes('killed by') && lines[i].includes('TransportHit')) s = await HandleKillfeed(this, guildId, s, lines[i]) // Handles vehicle deaths if (!(i + 1 >= lines.length) && lines[i + 1].includes('killed by Player') && lines[i].includes('hit by Player')) s = await HandleKillfeed(this, guildId, s, lines[i]); // Handles regular deaths @@ -155,13 +153,14 @@ class DayzRBot extends Client { } const playerTemplate = /(.*) \| Player \"(.*)\" \(id=(.*) pos=<(.*)>\)/g; + const playerSessions = new Map(); let previouslyConnected = s.filter(p => p.connected); // All players with connection log captured above and no disconnect log let detectedAsConnected = []; let lastDetectedTime; for (let i = lines.length - 1; i > 0; i--) { if (lines[i].includes('PlayerList log:')) { - for (let j = i + 1; i < lines.length; j++) { + for (let j = i + 1; j < lines.length; j++) { let line = lines[j]; if (line.includes('| ####')) break; @@ -178,15 +177,29 @@ class DayzRBot extends Client { if (!this.exists(info.player) || !this.exists(info.playerID)) continue; + // Check if the player session exists in the map. + if (playerSessions.has(info.playerID)) { + // Player is already in a session, update the session's end time. + const session = playerSessions.get(info.playerID); + session.endTime = await this.getDateEST(info.time); // Update end time. + } else { + // Player is not in a session, create a new session. + const newSession = { + startTime: await this.getDateEST(info.time), + endTime: null, // Initialize end time as null. + }; + playerSessions.set(info.playerID, newSession); + } + let playerStat = s.find(stat => stat.playerID == info.playerID); let playerStatIndex = s.indexOf(playerStat); if (playerStat == undefined) playerStat = this.getDefaultPlayerStats(info.player, info.playerID); - if (!previouslyConnected.includes(playerStat)) { - // This player was not connected before, i.e missing connection log? + if (!previouslyConnected.includes(playerStat)) { + // Check if the player has been marked as connected before. playerStat.connected = true; - playerStat.lastConnectionDate = await this.getDateEST(info.time); // Assume connected now - detectedAsConnected.push() + playerStat.lastConnectionDate = await this.getDateEST(info.time); // Update last connection date. + detectedAsConnected.push(playerStat); } if (playerStatIndex == -1) s.push(playerStat); @@ -197,24 +210,6 @@ class DayzRBot extends Client { } } - for (let i = 0; i < previouslyConnected.length; i++) { - if (!detectedAsConnected.includes(previouslyConnected[i])) { - - let playerStat = previouslyConnected[i]; - let playerStatIndex = s.indexOf(playerStat); - - playerStat.connected = false; - s[playerStatIndex] = playerStat; - - SendConnectionLogs(this, guildId, { - time: lastDetectedTime, - player: playerStat.gamertag, - connected: false, - lastConnectionDate: playerStat.lastConnectionDate, - }); - } - } - await this.dbo.collection("guilds").updateOne({ "server.serverID": guildId }, { $set: { "server.playerstats": s @@ -223,7 +218,7 @@ class DayzRBot extends Client { if (err) this.sendError(this.GetChannel(guild.adminLogsChannel), err); }); - history.lastLog = lines[lines.length-1]; + history.lastLog = lines[lines.length - 1]; // write JSON string to a file fs.writeFileSync(logHistoryDir, JSON.stringify(history)); @@ -233,7 +228,7 @@ class DayzRBot extends Client { let t = new Date(); // c.log(`...Logs Tick - ${t.getHours()}:${t.getMinutes()}:${t.getSeconds()}...`); c.activePlayersTick++; - + await DownloadNitradoFile(c, `/games/${c.config.Nitrado.UserID}/noftp/dayzxb/config/DayZServer_X1_x64.ADM`, './logs/server-logs.ADM').then(async (status) => { if (status == 1) return c.error('...Failed to Download logs...'); // c.log('...Downloaded logs...'); @@ -267,14 +262,14 @@ class DayzRBot extends Client { try { // Connect to Mongo database. - this.db = await MongoClient.connect(mongoURI, {connectTimeoutMS: 1000}); + 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)); + useNewUrlParser: true, + }).catch(e => this.error(e)); this.log('Successfully connected to mongoDB'); databaselogs.connected = true; databaselogs.attempts = 0; // reset attempts @@ -296,7 +291,7 @@ class DayzRBot extends Client { await this.connectMongo(this.config.mongoURI, this.config.dbo); let is_enabled = undefined; - if (this.databaseConnected) is_enabled = await this.dbo.collection("guilds").findOne({"server.autoRestart":1}).then(is_enabled => is_enabled); + if (this.databaseConnected) is_enabled = await this.dbo.collection("guilds").findOne({ "server.autoRestart": 1 }).then(is_enabled => is_enabled); if (is_enabled) { this.log('Starting periodic Nitrado server status check.'); @@ -304,15 +299,15 @@ class DayzRBot extends Client { } } - exists(n) {return null != n && undefined != n && "" != n} + exists(n) { return null != n && undefined != n && "" != n } secondsToDhms(seconds) { seconds = Number(seconds); - const d = Math.floor(seconds / (3600*24)); - const h = Math.floor(seconds % (3600*24) / 3600); + const d = Math.floor(seconds / (3600 * 24)); + const h = Math.floor(seconds % (3600 * 24) / 3600); const m = Math.floor(seconds % 3600 / 60); const s = Math.floor(seconds % 60); - + const dDisplay = d > 0 ? d + (d == 1 ? " day, " : " days, ") : ""; const hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : ""; const mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : ""; @@ -330,8 +325,8 @@ class DayzRBot extends Client { if (!this.exists(cmd.name) || !this.exists(cmd.description)) return this.error( "Unable to load Command: " + - file.split(".")[0] + - ", Reason: File doesn't had name/desciption" + file.split(".")[0] + + ", Reason: File doesn't had name/desciption" ); this.commands.set(file.split(".")[0].toLowerCase(), cmd); if (this.exists(cmd.Interactions)) { @@ -351,7 +346,7 @@ class DayzRBot extends Client { else files.forEach((file) => { const event = require(EventsDir + "/" + file); - if (['interactionCreate','guildMemberAdd'].includes(file.split(".")[0])) this.on(file.split(".")[0], i => event(this, i)); + if (['interactionCreate', 'guildMemberAdd'].includes(file.split(".")[0])) this.on(file.split(".")[0], i => event(this, i)); else this.on(file.split(".")[0], event.bind(null, this)); this.log("Event Loaded: " + file.split(".")[0]); }); @@ -376,7 +371,7 @@ class DayzRBot extends Client { const embed = new EmbedBuilder() .setDescription(`**Internal Error:**\nUh Oh D: Its not you, its me.\nThis command has crashed\nContact the Developers\nhttps://discord.gg/YCXhvy9uZw`) .setColor(this.config.Colors.Red) - + try { Interaction.send({ embeds: [embed] }); } catch { diff --git a/util/AdminLogsHandler.js b/util/AdminLogsHandler.js index 0d39f8f..43cc0fb 100644 --- a/util/AdminLogsHandler.js +++ b/util/AdminLogsHandler.js @@ -1,15 +1,14 @@ const { EmbedBuilder } = require('discord.js'); module.exports = { - + SendConnectionLogs: async (client, guildId, data) => { - let guild = await client.GetGuild(guildId); if (!client.exists(guild.connectionLogsChannel)) return; const channel = client.GetChannel(guild.connectionLogsChannel); let newDt = await client.getDateEST(data.time); - let unixTime = Math.floor(newDt.getTime()/1000); + let unixTime = Math.floor(newDt.getTime() / 1000); let connectionLog = new EmbedBuilder() .setColor(data.connected ? client.config.Colors.Green : client.config.Colors.Red) @@ -17,7 +16,7 @@ module.exports = { if (!data.connected) { if (!(data.lastConnectionDate == null)) { - let oldUnixTime = Math.floor(data.lastConnectionDate.getTime()/1000); + let oldUnixTime = Math.floor(data.lastConnectionDate.getTime() / 1000); let sessionTime = client.secondsToDhms(unixTime - oldUnixTime); connectionLog.addFields({ name: '**Session Time**', value: `**${sessionTime}**`, inline: false }); } else connectionLog.addFields({ name: '**Session Time**', value: `**Unknown**`, inline: false }); @@ -28,7 +27,7 @@ module.exports = { DetectCombatLog: async (client, guildId, data) => { if (data.lastDamageDate == null) return; - + let newDt = await client.getDateEST(data.time); let diffSeconds = Math.round((newDt.getTime() - data.lastDamageDate.getTime()) / 1000); @@ -36,21 +35,21 @@ module.exports = { // If diff is greater than 5 minutes, not a combat log // or if death after last combat if (data.lastDamageDate <= data.lastDeathDate) return; - if (diffSeconds > (5 * 60)) return; + if (diffSeconds > 5 * 60) return; let guild = await client.GetGuild(guildId); if (!client.exists(guild.connectionLogsChannel)) return; const channel = client.GetChannel(guild.connectionLogsChannel); if (!channel) return; - let unixTime = Math.floor(newDt.getTime()/1000); + let unixTime = Math.floor(newDt.getTime() / 1000); let combatLog = new EmbedBuilder() .setColor(client.config.Colors.Red) .setDescription(`**NOTICE:**\n**${data.player}** has combat logged at when fighting **${data.lastHitBy}\nLocation [${data.pos[0]}, ${data.pos[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${data.pos[0]};${data.pos[1]})**`); - + if (client.exists(guild.adminRole)) channel.send({ content: `<@&${guild.adminRole}>` }); return channel.send({ embeds: [combatLog] }); } -} +}; diff --git a/util/LogsHandler.js b/util/LogsHandler.js index b8253d1..428c84d 100644 --- a/util/LogsHandler.js +++ b/util/LogsHandler.js @@ -18,10 +18,10 @@ module.exports = { const deadTemplate = /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\)\[HP\: (.*)\] hit by Player \"(.*)\" \(id=(.*) pos=<(.*)>\) into (.*) for (.*) damage \((.*)\) with (.*) from (.*) meters /g; if (line.includes(' connected')) { - let data = [...line.matchAll(connectTemplate)][0]; + const data = [...line.matchAll(connectTemplate)][0]; if (!data) return stats; - let info = { + const info = { time: data[1], player: data[2], playerID: data[3], @@ -29,17 +29,19 @@ module.exports = { if (!client.exists(info.player) || !client.exists(info.playerID)) return stats; - let playerStat = stats.find(stat => stat.playerID == info.playerID) + let playerStat = stats.find(stat => stat.playerID == info.playerID); let playerStatIndex = stats.indexOf(playerStat); - if (playerStat == undefined) playerStat = client.getDefaultPlayerStats(info.player, info.playerID); - - playerStat.lastConnectionDate = await client.getDateEST(info.time);; + if (playerStat === undefined) playerStat = client.getDefaultPlayerStats(info.player, info.playerID); + + const newDt = await client.getDateEST(info.time); + + playerStat.lastConnectionDate = newDt; playerStat.connected = true; - if (playerStatIndex == -1) stats.push(playerStat); + if (playerStatIndex === -1) stats.push(playerStat); else stats[playerStatIndex] = playerStat; - SendConnectionLogs(client, guildId, { + await SendConnectionLogs(client, guildId, { time: info.time, player: info.player, connected: true, @@ -48,25 +50,25 @@ module.exports = { } if (line.includes(' disconnected')) { - let data = [...line.matchAll(disconnectTemplate)][0]; + const data = [...line.matchAll(disconnectTemplate)][0]; if (!data) return stats; - let info = { + const info = { time: data[1], player: data[2], playerID: data[3], - } + }; if (!client.exists(info.player) || !client.exists(info.playerID)) return stats; - let playerStat = stats.find(stat => stat.playerID == info.playerID) + 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 = client.getDefaultPlayerStats(info.player, info.playerID); - let newDt = await client.getDateEST(info.time); - let unixTime = Math.round(newDt.getTime()/1000); // Seconds - let oldUnixTime = Math.round(playerStat.lastConnectionDate.getTime()/1000); // Seconds - let sessionTimeSeconds = unixTime - oldUnixTime; + const newDt = await client.getDateEST(info.time); + const unixTime = Math.round(newDt.getTime() / 1000); // Seconds + const oldUnixTime = Math.round(playerStat.lastConnectionDate.getTime() / 1000); // Seconds + const sessionTimeSeconds = unixTime - oldUnixTime; if (!client.exists(playerStat.longestSessionTime)) playerStat.longestSessionTime = 0; playerStat.totalSessionTime = playerStat.totalSessionTime + sessionTimeSeconds; @@ -74,10 +76,10 @@ module.exports = { playerStat.longestSessionTime = sessionTimeSeconds > playerStat.longestSessionTime ? sessionTimeSeconds : playerStat.longestSessionTime; playerStat.connected = false; - if (playerStatIndex == -1) stats.push(playerStat); + if (playerStatIndex === -1) stats.push(playerStat); else stats[playerStatIndex] = playerStat; - SendConnectionLogs(client, guildId, { + await SendConnectionLogs(client, guildId, { time: info.time, player: info.player, connected: false, @@ -95,10 +97,10 @@ module.exports = { } if (line.includes('pos=<') && !line.includes('hit by')) { - let data = [...line.matchAll(positionTemplate)][0]; + const data = [...line.matchAll(positionTemplate)][0]; if (!data) return stats; - let info = { + const info = { time: data[1], player: data[2], playerID: data[3], @@ -107,11 +109,11 @@ module.exports = { if (!client.exists(info.player) || !client.exists(info.playerID)) return stats; - let playerStat = stats.find(stat => stat.playerID == info.playerID) + 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 = client.getDefaultPlayerStats(info.player, info.playerID); if (!client.exists(playerStat.lastConnectionDate)) playerStat.lastConnectionDate = await client.getDateEST(info.time); - + playerStat.lastPos = playerStat.pos; playerStat.pos = info.pos; playerStat.lastTime = playerStat.time; @@ -119,7 +121,7 @@ module.exports = { playerStat.time = `${info.time} EST`; playerStat.date = await client.getDateEST(info.time); - if (playerStatIndex == -1) stats.push(playerStat); + if (playerStatIndex === -1) stats.push(playerStat); else stats[playerStatIndex] = playerStat; if (line.includes('hit by') || line.includes('killed by')) return stats; // prevent additional information from being fed to Alarms & UAVs @@ -130,33 +132,32 @@ module.exports = { playerID: info.playerID, pos: info.pos, }); - } if (line.includes('hit by Player')) { - let data = line.includes('(DEAD)') ? [...line.matchAll(deadTemplate)][0] : [...line.matchAll(damageTemplate)][0]; + const data = line.includes('(DEAD)') ? [...line.matchAll(deadTemplate)][0] : [...line.matchAll(damageTemplate)][0]; if (!data) return stats; - let info = { + const info = { time: data[1], player: data[2], playerID: data[3], attacker: data[6], attackerID: data[7] - } + }; if (!client.exists(info.player) || !client.exists(info.playerID)) return stats; - let playerStat = stats.find(stat => stat.playerID == info.playerID) + 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 = client.getDefaultPlayerStats(info.player, info.playerID); - let newDt = await client.getDateEST(info.time); + const newDt = await client.getDateEST(info.time); playerStat.lastDamageDate = newDt; playerStat.lastHitBy = info.attacker; - if (playerStatIndex == -1) stats.push(playerStat); + if (playerStatIndex === -1) stats.push(playerStat); else stats[playerStatIndex] = playerStat; } @@ -168,12 +169,13 @@ module.exports = { const data = await FetchServerSettings(client, 'HandleActivePlayersList'); // Fetch server status - if (data && data != 1) { + if (data && data !== 1) { let hostname = data.data.gameserver.settings.config.hostname; - let map = data.data.gameserver.settings.config.mission.slice(12); + let map = data.data.gameserver.settings.config.mission.slice(12); let status = data.data.gameserver.status; - let slots = data.data.gameserver.slots; - + let slots = data.data.gameserver.slots; + let playersOnline = data.data.gameserver.query.player_current; + let statusEmoji; let statusText; if (status === "started") { @@ -189,13 +191,13 @@ module.exports = { statusEmoji = "❓"; // Unknown status statusText = "Unknown Status"; } - + let guild = await client.GetGuild(guildId); if (!client.exists(guild.playerstats)) guild.playerstats = []; if (!client.exists(guild.activePlayersChannel)) return; const channel = client.GetChannel(guild.activePlayersChannel); - let activePlayers = guild.playerstats.filter(p => p.connected == true); + let activePlayers = guild.playerstats.filter(p => p.connected === true); let des = ``; for (let i = 0; i < activePlayers.length; i++) { @@ -204,11 +206,11 @@ module.exports = { const nodes = activePlayers.length === 0; const PlayersEmbed = new EmbedBuilder() .setColor(client.config.Colors.Default) - .setTitle(`Online List \` ${activePlayers.length} \` Player${activePlayers.length>1?'s':''} Online`) + .setTitle(`Online List \` ${playersOnline} \` Player${playersOnline > 1 ? 's' : ''} Online`) .addFields( - { name: 'Server:', value: `\` ${hostname} \``, inline: false }, + { name: 'Server:', value: `\` ${hostname} \``, inline: false }, { name: 'Map:', value: `\` ${map} \``, inline: true }, - { name: 'Status:', value: `\` ${statusEmoji} ${statusText} \``, inline: true }, + { name: 'Status:', value: `\` ${statusEmoji} ${statusText} \``, inline: true }, { name: 'Slots:', value: `\` ${slots} \``, inline: true } ); @@ -216,13 +218,13 @@ module.exports = { .setColor(client.config.Colors.Default) .setTimestamp() .setTitle(`Players Online:`) - .setDescription(des || (nodes ? "No Players Online :(" : "")) + .setDescription(des || (nodes ? "No Players Online :(" : "")); if (lastSendMessage) lastSendMessage.delete().catch(error => client.sendError(channel, `HandleActivePlayersList Error: \n${error}`)); // Remove previous message before reprinting - return channel.send({ embeds: [PlayersEmbed, activePlayersEmbed] }).then(sentMessage => + return channel.send({ embeds: [PlayersEmbed, activePlayersEmbed] }).then(sentMessage => lastSendMessage = sentMessage ); } } -} \ No newline at end of file +}; diff --git a/util/NitradoAPI.js b/util/NitradoAPI.js index b209011..ab5ac41 100644 --- a/util/NitradoAPI.js +++ b/util/NitradoAPI.js @@ -75,11 +75,11 @@ module.exports = { }).then(response => response.json().then(data => data) ).then(res => res); - + const stream = fs.createWriteStream(outputDir); if (!res.data || !res.data.token) { - client.error(`Error downloading File "${filename}":`); - client.error(res); + const errorText = await res.text(); + client.error(`Error downloading File "${filename}": message: ${errorText}: DownloadNitradoFile`); return 1; } const { body } = await fetch(res.data.token.url);