optimize by minimizing database calls

This commit is contained in:
SowinskiBraeden committed 2023-03-30 14:07:45 -07:00
1 parent eafb6dc33c
commit 2ba187d88d
2 files changed
+54 -84

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "dayz-armbands", "name": "dayz-armbands",
"version": "5.10.0", "version": "5.11.0",
"description": "A General Purpose Discord Bot for DayZ Servers.", "description": "A General Purpose Discord Bot for DayZ Servers.",
"main": "index.js", "main": "index.js",
"nodemonConfig": { "nodemonConfig": {
+53 -83
View File
@@ -117,11 +117,11 @@ class DayzArmbands extends Client {
}); });
} }
async handleKillfeed(guildId, line) { async handleKillfeed(guildId, stats, line) {
let guild = await this.GetGuild(guildId); let guild = await this.GetGuild(guildId);
if (guild.playerstats == undefined) guild.playerstats = [];
const channel = this.channels.cache.get(guild.killfeedChannel); const channel = this.channels.cache.get(guild.killfeedChannel);
let template = /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\)\[HP\: 0\] hit by Player \"(.*)\" \(id=(.*) pos=<(.*)>\) into (.*) for (.*) damage \((.*)\) with (.*) from (.*) meters /g; let template = /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\)\[HP\: 0\] hit by Player \"(.*)\" \(id=(.*) pos=<(.*)>\) into (.*) for (.*) damage \((.*)\) with (.*) from (.*) meters /g;
let data = [...line.matchAll(template)][0]; let data = [...line.matchAll(template)][0];
@@ -142,10 +142,10 @@ class DayzArmbands extends Client {
if (!this.exists(info.victim) || !this.exists(info.victimID) || !this.exists(info.killer) || !this.exists(info.killerID)) return; if (!this.exists(info.victim) || !this.exists(info.victimID) || !this.exists(info.killer) || !this.exists(info.killerID)) return;
let killerStat = guild.playerstats.find(stat => stat.playerID == info.killerID) let killerStat = stats.find(stat => stat.playerID == info.killerID)
let victimStat = guild.playerstats.find(stat => stat.playerID == info.victimID) let victimStat = stats.find(stat => stat.playerID == info.victimID)
let killerStatIndex = guild.playerstats.indexOf(killerStat); let killerStatIndex = stats.indexOf(killerStat);
let victimStatIndex = guild.playerstats.indexOf(victimStat); let victimStatIndex = stats.indexOf(victimStat);
if (killerStat == undefined) killerStat = this.getDefaultPlayerStats(info.killer, info.killerID); if (killerStat == undefined) killerStat = this.getDefaultPlayerStats(info.killer, info.killerID);
if (victimStat == undefined) victimStat = this.getDefaultPlayerStats(info.victim, info.victimID); if (victimStat == undefined) victimStat = this.getDefaultPlayerStats(info.victim, info.victimID);
@@ -171,9 +171,9 @@ class DayzArmbands extends Client {
if (!banking) { if (!banking) {
banking = { banking = {
userID: interaction.member.user.id, userID: killerStat.discordID,
guilds: { guilds: {
[guild.serverID]: { [guildId]: {
bankAccount: { bankAccount: {
balance: guild.startingBalance, balance: guild.startingBalance,
cash: 0.00, cash: 0.00,
@@ -184,23 +184,23 @@ class DayzArmbands extends Client {
// Register inventory for user // Register inventory for user
let newBank = new User(); let newBank = new User();
newBank.createUser(interaction.member.user.id, guild.serverID, guild.startingBalance, 0); newBank.createUser(killerStat.discordID, guildId, guild.startingBalance, 0);
newBank.save().catch(err => { newBank.save().catch(err => {
if (err) return client.sendInternalError(interaction, err); if (err) return this.sendInternalError(interaction, err);
}); });
} else banking = banking.user; } else banking = banking.user;
if (!this.exists(banking.guilds[guild.serverID])) { if (!this.exists(banking.guilds[guildId])) {
const success = addUser(banking.guilds, guild.serverID, interaction.member.user.id, this, guild.startingBalance); const success = addUser(banking.guilds, guildId, killer.discordID, this, guild.startingBalance);
if (!success) return this.sendError(guild.connectionLogsChannel, 'Failed to add bank'); if (!success) return this.sendError(guild.connectionLogsChannel, 'Failed to add bank');
} }
const newBalance = banking.guilds[guild.serverID].bankAccount.balance + totalBounty; const newBalance = banking.guilds[guildId].bankAccount.balance + totalBounty;
await this.dbo.collection("users").updateOne({ "user.userID": killerStat.discordID }, { await this.dbo.collection("users").updateOne({ "user.userID": killerStat.discordID }, {
$set: { $set: {
[`banking.guilds.${guild.serverID}.bankAccount.balance`]: newBalance, [`banking.guilds.${guildId}.bankAccount.balance`]: newBalance,
} }
}, function(err, res) { }, function(err, res) {
if (err) return this.sendError(guild.connectionLogsChannel, err); if (err) return this.sendError(guild.connectionLogsChannel, err);
@@ -211,18 +211,10 @@ class DayzArmbands extends Client {
.setDescription(`<@${killerStat.discordID}> received **$${totalBounty.toFixed(2)}** in bounty rewards.`); .setDescription(`<@${killerStat.discordID}> received **$${totalBounty.toFixed(2)}** in bounty rewards.`);
} }
if (killerStatIndex == -1) guild.playerstats.push(killerStat); if (killerStatIndex == -1) stats.push(killerStat);
else guild.playerstats[killerStatIndex] = killerStat; else stats[killerStatIndex] = killerStat;
if (victimStatIndex == -1) guild.playerstats.push(victimStat); if (victimStatIndex == -1) stats.push(victimStat);
else guild.playerstats[victimStatIndex] = victimStat; else stats[victimStatIndex] = victimStat;
await this.dbo.collection("guilds").updateOne({ "server.serverID": guild.serverID }, {
$set: {
"server.playerstats": guild.playerstats
}
}, function (err, res) {
if (err && this.exists(channel)) return this.sendInternalError(channel, err);
});
let today = new Date(); let today = new Date();
let newDt = new Date(`${today.toLocaleDateString('default', { month: 'long' })} ${today.getDate()}, ${today.getFullYear()} ${info.time} EST`) let newDt = new Date(`${today.toLocaleDateString('default', { month: 'long' })} ${today.getDate()}, ${today.getFullYear()} ${info.time} EST`)
@@ -234,7 +226,8 @@ class DayzArmbands extends Client {
if (this.exists(channel)) channel.send({ embeds: [killEvent] }); if (this.exists(channel)) channel.send({ embeds: [killEvent] });
if (this.exists(receivedBounty) && this.exists(channel)) channel.send({ content: `<@${killerStat.discordID}>`, embeds: [receivedBounty] }); if (this.exists(receivedBounty) && this.exists(channel)) channel.send({ content: `<@${killerStat.discordID}>`, embeds: [receivedBounty] });
return;
return stats;
} }
async handleAlarms(guildId, data) { async handleAlarms(guildId, data) {
@@ -254,7 +247,6 @@ class DayzArmbands extends Client {
for (let i = 0; i < guild.alarms.length; i++) { for (let i = 0; i < guild.alarms.length; i++) {
let alarm = guild.alarms[i]; let alarm = guild.alarms[i];
if (alarm.disabled) continue; // ignore if alarm is disabled due to emp if (alarm.disabled) continue; // ignore if alarm is disabled due to emp
if (alarm.ignoredPlayers.includes(data.playerID)) continue; if (alarm.ignoredPlayers.includes(data.playerID)) continue;
let diff = [Math.round(alarm.origin[0] - data.pos[0]), Math.round(alarm.origin[1] - data.pos[1])]; let diff = [Math.round(alarm.origin[0] - data.pos[0]), Math.round(alarm.origin[1] - data.pos[1])];
@@ -338,10 +330,7 @@ class DayzArmbands extends Client {
return channel.send({ embeds: {combatLog} }); return channel.send({ embeds: {combatLog} });
} }
async handlePlayerLogs(guildId, line) { async handlePlayerLogs(guildId, stats, line) {
let guild = await this.GetGuild(guildId);
if (guild.playerstats == undefined) guild.playerstats = [];
const connectTemplate = /(.*) \| Player \"(.*)\" is connected \(id=(.*)\)/g; const connectTemplate = /(.*) \| Player \"(.*)\" is connected \(id=(.*)\)/g;
const disconnectTemplate = /(.*) \| Player \"(.*)\"\(id=(.*)\) has been disconnected/g; const disconnectTemplate = /(.*) \| Player \"(.*)\"\(id=(.*)\) has been disconnected/g;
@@ -361,8 +350,8 @@ class DayzArmbands extends Client {
if (!this.exists(info.player) || !this.exists(info.playerID)) return; if (!this.exists(info.player) || !this.exists(info.playerID)) return;
let playerStat = guild.playerstats.find(stat => stat.playerID == info.playerID) let playerStat = stats.find(stat => stat.playerID == info.playerID)
let playerStatIndex = guild.playerstats.indexOf(playerStat); let playerStatIndex = stats.indexOf(playerStat);
if (playerStat == undefined) playerStat = this.getDefaultPlayerStats(info.player, info.playerID); if (playerStat == undefined) playerStat = this.getDefaultPlayerStats(info.player, info.playerID);
let today = new Date(); let today = new Date();
@@ -371,16 +360,8 @@ class DayzArmbands extends Client {
playerStat.lastConnectionDate = newDt; playerStat.lastConnectionDate = newDt;
playerStat.connected = true; playerStat.connected = true;
if (playerStatIndex == -1) guild.playerstats.push(playerStat); if (playerStatIndex == -1) stats.push(playerStat);
else guild.playerstats[playerStatIndex] = playerStat; else stats[playerStatIndex] = playerStat;
await this.dbo.collection("guilds").updateOne({ "server.serverID": guildId }, {
$set: {
"server.playerstats": guild.playerstats
}
}, function (err, res) {
if (err) this.error(err);
});
this.sendConnectionLogs(guildId, { this.sendConnectionLogs(guildId, {
time: info.time, time: info.time,
@@ -403,22 +384,14 @@ class DayzArmbands extends Client {
if (!this.exists(info.player) || !this.exists(info.playerID)) return; if (!this.exists(info.player) || !this.exists(info.playerID)) return;
let playerStat = guild.playerstats.find(stat => stat.playerID == info.playerID) let playerStat = stats.find(stat => stat.playerID == info.playerID)
let playerStatIndex = guild.playerstats.indexOf(playerStat); let playerStatIndex = stats.indexOf(playerStat);
if (playerStat == undefined) playerStat = this.getDefaultPlayerStats(info.player, info.playerID); if (playerStat == undefined) playerStat = this.getDefaultPlayerStats(info.player, info.playerID);
playerStat.connected = false; playerStat.connected = false;
if (playerStatIndex == -1) guild.playerstats.push(playerStat); if (playerStatIndex == -1) stats.push(playerStat);
else guild.playerstats[playerStatIndex] = playerStat; else stats[playerStatIndex] = playerStat;
await this.dbo.collection("guilds").updateOne({ "server.serverID": guildId }, {
$set: {
"server.playerstats": guild.playerstats
}
}, function (err, res) {
if (err) this.error(err);
});
this.sendConnectionLogs(guildId, { this.sendConnectionLogs(guildId, {
time: info.time, time: info.time,
@@ -448,8 +421,8 @@ class DayzArmbands extends Client {
if (!this.exists(info.player) || !this.exists(info.playerID)) return; if (!this.exists(info.player) || !this.exists(info.playerID)) return;
let playerStat = guild.playerstats.find(stat => stat.playerID == info.playerID) let playerStat = stats.find(stat => stat.playerID == info.playerID)
let playerStatIndex = guild.playerstats.indexOf(playerStat); let playerStatIndex = stats.indexOf(playerStat);
if (playerStat == undefined) playerStat = this.getDefaultPlayerStats(info.player, info.playerID); if (playerStat == undefined) playerStat = this.getDefaultPlayerStats(info.player, info.playerID);
playerStat.pos = info.pos; playerStat.pos = info.pos;
@@ -461,16 +434,8 @@ class DayzArmbands extends Client {
pos: info.pos, pos: info.pos,
}); });
if (playerStatIndex == -1) guild.playerstats.push(playerStat); if (playerStatIndex == -1) stats.push(playerStat);
else guild.playerstats[playerStatIndex] = playerStat; else stats[playerStatIndex] = playerStat;
await this.dbo.collection("guilds").updateOne({ "server.serverID": guildId }, {
$set: {
"server.playerstats": guild.playerstats
}
}, function (err, res) {
if (err) this.error(err);
});
} }
if (line.includes('hit by Player')) { if (line.includes('hit by Player')) {
@@ -485,8 +450,8 @@ class DayzArmbands extends Client {
if (!this.exists(info.player) || !this.exists(info.playerID)) return; if (!this.exists(info.player) || !this.exists(info.playerID)) return;
let playerStat = guild.playerstats.find(stat => stat.playerID == info.playerID) let playerStat = stats.find(stat => stat.playerID == info.playerID)
let playerStatIndex = guild.playerstats.indexOf(playerStat); let playerStatIndex = stats.indexOf(playerStat);
if (playerStat == undefined) playerStat = this.getDefaultPlayerStats(info.player, info.playerID); if (playerStat == undefined) playerStat = this.getDefaultPlayerStats(info.player, info.playerID);
let today = new Date(); let today = new Date();
@@ -495,18 +460,11 @@ class DayzArmbands extends Client {
playerStat.lastDamageDate = newDt; playerStat.lastDamageDate = newDt;
playerStat.lastHitBy = data[6]; playerStat.lastHitBy = data[6];
if (playerStatIndex == -1) guild.playerstats.push(playerStat); if (playerStatIndex == -1) stats.push(playerStat);
else guild.playerstatus[playerStatIndex] = playerStat; else stats[playerStatIndex] = playerStat;
}
await this.dbo.collection("guilds").updateOne({ "server.serverID": guildId }, { return stats;
$set: {
"server.playerstats": guild.playerstats
}
}, function (err, res) {
if (err) this.error(err);
});
}
return;
} }
async handleActivePlayersList(guildId) { async handleActivePlayersList(guildId) {
@@ -555,11 +513,23 @@ class DayzArmbands extends Client {
let lines = []; let lines = [];
for await (const line of rl) { lines.push(line); } for await (const line of rl) { lines.push(line); }
let guild = await this.GetGuild(guildId);
if (!this.exists(guild.playerstats)) guild.playerstats = [];
let s = guild.playerstats;
for (let i = lines.indexOf(history.lastLog) + 1; i < lines.length; i++) { for (let i = lines.indexOf(history.lastLog) + 1; i < lines.length; i++) {
if (lines[i].includes('connected') || lines[i].includes('disconnected') || lines[i].includes('pos=<') || lines[1].includes['hit by Player']) await this.handlePlayerLogs(guildId, lines[i]); if (lines[i].includes('connected') || lines[i].includes('disconnected') || lines[i].includes('pos=<') || lines[1].includes['hit by Player']) s = await this.handlePlayerLogs(guildId, s, lines[i]);
if (!(i + 1 >= lines.length) && lines[i + 1].includes('killed by Player')) await this.handleKillfeed(guildId, lines[i]); if (!(i + 1 >= lines.length) && lines[i + 1].includes('killed by Player')) s = await this.handleKillfeed(guildId, s, lines[i]);
} }
await this.dbo.collection("guilds").updateOne({ "server.serverID": guildId }, {
$set: {
"server.playerstats": s
}
}, function (err, res) {
if (err) this.error(err);
});
history.lastLog = lines[lines.length-1]; history.lastLog = lines[lines.length-1];
// write JSON string to a file // write JSON string to a file