From cb84e63a69aae90567553ee8e3ac29a1cd9193b1 Mon Sep 17 00:00:00 2001 From: SowinskiBraeden Date: Sun, 28 Sep 2025 11:53:28 -0700 Subject: [PATCH] refactor/project structure and indents for typescript --- .env.example | 10 +- CONTRIBUTING.md | 2 +- commands/admin.js | 412 ----------- commands/alarm.js | 646 ---------------- commands/armbands.js | 86 --- commands/bank.js | 165 ----- commands/bounty.js | 190 ----- commands/channels.js | 47 -- commands/claim.js | 210 ------ commands/collect-income.js | 108 --- commands/compare-rating.js | 143 ---- commands/config.js | 1143 ----------------------------- commands/event.js | 170 ----- commands/excluded.js | 46 -- commands/factions.js | 87 --- commands/gamertag-link.js | 128 ---- commands/gamertag-unlink.js | 85 --- commands/help.js | 161 ---- commands/leaderboard.js | 135 ---- commands/location.js | 50 -- commands/lookup.js | 90 --- commands/player-list.js | 81 -- commands/player-stats.js | 325 -------- commands/purchase-emp.js | 125 ---- commands/purchase-uav.js | 102 --- commands/reset.js | 111 --- commands/server.js | 414 ----------- commands/weapon-stats.js | 176 ----- config/config.js | 47 -- database/armbands.js | 164 ----- database/destinations.js | 684 ----------------- database/guild.js | 102 --- database/player.js | 131 ---- database/user.js | 43 -- database/weapons.js | 77 -- events/guildCreate.js | 3 - events/guildMemberAdd.js | 17 - events/interactionCreate.js | 21 - events/ready.js | 11 - index.js | 8 - src/DayZRBot.js | 558 ++++++++++++++ src/DayzRBot.js | 558 -------------- bot.js => src/botWrapper.js | 32 +- src/commands/admin.js | 412 +++++++++++ src/commands/alarm.js | 646 ++++++++++++++++ src/commands/armbands.js | 86 +++ src/commands/bank.js | 165 +++++ src/commands/bounty.js | 190 +++++ src/commands/channels.js | 47 ++ src/commands/claim.js | 212 ++++++ src/commands/collect-income.js | 108 +++ src/commands/compare-rating.js | 143 ++++ src/commands/config.js | 1143 +++++++++++++++++++++++++++++ src/commands/event.js | 170 +++++ src/commands/excluded.js | 46 ++ src/commands/factions.js | 87 +++ src/commands/gamertag-link.js | 128 ++++ src/commands/gamertag-unlink.js | 85 +++ src/commands/help.js | 161 ++++ src/commands/leaderboard.js | 135 ++++ src/commands/location.js | 50 ++ src/commands/lookup.js | 90 +++ src/commands/player-list.js | 81 ++ src/commands/player-stats.js | 325 ++++++++ src/commands/purchase-emp.js | 125 ++++ src/commands/purchase-uav.js | 102 +++ src/commands/reset.js | 111 +++ src/commands/server.js | 414 +++++++++++ src/commands/weapon-stats.js | 176 +++++ src/config/config.js | 47 ++ src/database/armbands.js | 164 +++++ src/database/destinations.js | 684 +++++++++++++++++ src/database/guild.js | 102 +++ src/database/player.js | 131 ++++ src/database/user.js | 43 ++ src/database/weapons.js | 77 ++ src/events/guildCreate.js | 3 + src/events/guildMemberAdd.js | 17 + src/events/interactionCreate.js | 21 + src/events/ready.js | 11 + src/index.js | 8 + src/util/AdminLogsHandler.js | 68 ++ src/util/AlarmsHandler.js | 249 +++++++ src/util/CombatRatingHandler.js | 6 + src/util/CommandOptionTypes.js | 15 + src/util/Cryptic.js | 19 + src/util/KillfeedHandler.js | 290 ++++++++ src/util/Logger.js | 40 + src/util/LogsHandler.js | 265 +++++++ src/util/NitradoAPI.js | 311 ++++++++ src/util/RegisterSlashCommands.js | 68 ++ src/util/Vector.js | 12 + src/util/WebhookHandler.js | 56 ++ util/AdminLogsHandler.js | 68 -- util/AlarmsHandler.js | 249 ------- util/CombatRatingHandler.js | 6 - util/CommandOptionTypes.js | 15 - util/Cryptic.js | 19 - util/KillfeedHandler.js | 290 -------- util/Logger.js | 38 - util/LogsHandler.js | 265 ------- util/NitradoAPI.js | 311 -------- util/RegisterSlashCommands.js | 68 -- util/Vector.js | 12 - util/WebhookHandler.js | 56 -- 105 files changed, 8725 insertions(+), 8721 deletions(-) delete mode 100644 commands/admin.js delete mode 100644 commands/alarm.js delete mode 100644 commands/armbands.js delete mode 100644 commands/bank.js delete mode 100644 commands/bounty.js delete mode 100644 commands/channels.js delete mode 100644 commands/claim.js delete mode 100644 commands/collect-income.js delete mode 100644 commands/compare-rating.js delete mode 100644 commands/config.js delete mode 100644 commands/event.js delete mode 100644 commands/excluded.js delete mode 100644 commands/factions.js delete mode 100644 commands/gamertag-link.js delete mode 100644 commands/gamertag-unlink.js delete mode 100644 commands/help.js delete mode 100644 commands/leaderboard.js delete mode 100644 commands/location.js delete mode 100644 commands/lookup.js delete mode 100644 commands/player-list.js delete mode 100644 commands/player-stats.js delete mode 100644 commands/purchase-emp.js delete mode 100644 commands/purchase-uav.js delete mode 100644 commands/reset.js delete mode 100644 commands/server.js delete mode 100644 commands/weapon-stats.js delete mode 100644 config/config.js delete mode 100644 database/armbands.js delete mode 100644 database/destinations.js delete mode 100644 database/guild.js delete mode 100644 database/player.js delete mode 100644 database/user.js delete mode 100644 database/weapons.js delete mode 100644 events/guildCreate.js delete mode 100644 events/guildMemberAdd.js delete mode 100644 events/interactionCreate.js delete mode 100644 events/ready.js delete mode 100644 index.js create mode 100644 src/DayZRBot.js delete mode 100644 src/DayzRBot.js rename bot.js => src/botWrapper.js (50%) create mode 100644 src/commands/admin.js create mode 100644 src/commands/alarm.js create mode 100644 src/commands/armbands.js create mode 100644 src/commands/bank.js create mode 100644 src/commands/bounty.js create mode 100644 src/commands/channels.js create mode 100644 src/commands/claim.js create mode 100644 src/commands/collect-income.js create mode 100644 src/commands/compare-rating.js create mode 100644 src/commands/config.js create mode 100644 src/commands/event.js create mode 100644 src/commands/excluded.js create mode 100644 src/commands/factions.js create mode 100644 src/commands/gamertag-link.js create mode 100644 src/commands/gamertag-unlink.js create mode 100644 src/commands/help.js create mode 100644 src/commands/leaderboard.js create mode 100644 src/commands/location.js create mode 100644 src/commands/lookup.js create mode 100644 src/commands/player-list.js create mode 100644 src/commands/player-stats.js create mode 100644 src/commands/purchase-emp.js create mode 100644 src/commands/purchase-uav.js create mode 100644 src/commands/reset.js create mode 100644 src/commands/server.js create mode 100644 src/commands/weapon-stats.js create mode 100644 src/config/config.js create mode 100644 src/database/armbands.js create mode 100644 src/database/destinations.js create mode 100644 src/database/guild.js create mode 100644 src/database/player.js create mode 100644 src/database/user.js create mode 100644 src/database/weapons.js create mode 100644 src/events/guildCreate.js create mode 100644 src/events/guildMemberAdd.js create mode 100644 src/events/interactionCreate.js create mode 100644 src/events/ready.js create mode 100644 src/index.js create mode 100644 src/util/AdminLogsHandler.js create mode 100644 src/util/AlarmsHandler.js create mode 100644 src/util/CombatRatingHandler.js create mode 100644 src/util/CommandOptionTypes.js create mode 100644 src/util/Cryptic.js create mode 100644 src/util/KillfeedHandler.js create mode 100644 src/util/Logger.js create mode 100644 src/util/LogsHandler.js create mode 100644 src/util/NitradoAPI.js create mode 100644 src/util/RegisterSlashCommands.js create mode 100644 src/util/Vector.js create mode 100644 src/util/WebhookHandler.js delete mode 100644 util/AdminLogsHandler.js delete mode 100644 util/AlarmsHandler.js delete mode 100644 util/CombatRatingHandler.js delete mode 100644 util/CommandOptionTypes.js delete mode 100644 util/Cryptic.js delete mode 100644 util/KillfeedHandler.js delete mode 100644 util/Logger.js delete mode 100644 util/LogsHandler.js delete mode 100644 util/NitradoAPI.js delete mode 100644 util/RegisterSlashCommands.js delete mode 100644 util/Vector.js delete mode 100644 util/WebhookHandler.js diff --git a/.env.example b/.env.example index 815edd0..9e77e2b 100644 --- a/.env.example +++ b/.env.example @@ -1,13 +1,13 @@ # Discord Bot Token -token='Your Discord Bot token' +token="Your Discord Bot token" # MongoDB Information -mongoURI='Your mongodb URI' -dbo='Your mongodb database' +mongoURI="Your mongodb URI" +dbo="Your mongodb database" # Encryption -key='Secret Encryption Key' -iv='Secret Initialization Vector' +key="Secret Encryption Key" +iv="Secret Initialization Vector" # Other Bot Configuration Dev=PROD. # or DEV. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 542ab27..44805eb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -69,7 +69,7 @@ If you're simply looking to add a new command and not make significant changes t SlashCommand: { // Do not change the name of this funciton /** * - * @param {require("../structures/DayzRBot")} client + * @param {require("./structures/DayzRBot")} client * @param {import("discord.js").Message} message * @param {string[]} args * @param {*} param3 diff --git a/commands/admin.js b/commands/admin.js deleted file mode 100644 index 98dfa54..0000000 --- a/commands/admin.js +++ /dev/null @@ -1,412 +0,0 @@ -const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder } = require('discord.js'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const bitfieldCalculator = require('discord-bitfield-calculator'); -const { Armbands } = require('../database/armbands.js'); -const { createUser, addUser } = require('../database/user'); -const { UpdatePlayer } = require('../database/player'); - -module.exports = { - name: "admin", - debug: false, - global: false, - description: "Administrative only commands", - usage: "[command] [options]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [{ - name: "gamertag-link", - description: "Link a gamertag for a user", - value: "gamertag-link", - type: CommandOptions.SubCommand, - options: [{ - name: "user", - description: "User to link gamertag to", - value: "user", - type: CommandOptions.User, - required: true, - }, - { - name: "gamertag", - description: "Gamertag of player", - value: "gamertag", - type: CommandOptions.String, - required: true, - }] - }, { - name: "gamertag-unlink", - description: "Unlink a gamertag for a user", - value: "gamertag-unlink", - type: CommandOptions.SubCommand, - options: [{ - name: "user", - description: "User to link gamertag to", - value: "user", - type: CommandOptions.User, - required: true, - }] - }, { - name: "claim-armband", - description: "Claim an armband for a faction", - value: "claim-armband", - type: CommandOptions.SubCommand, - options: [{ - name: "faction_role", - description: "Claim an armband for this faction role.", - value: "faction_role", - type: CommandOptions.Role, - required: true, - }] - }, { - name: "bounty-clear", - description: "Clear a bounty off a player", - value: "bounty-clear", - type: CommandOptions.SubCommand, - options: [{ - name: "gamertag", - description: "Gamertag of player", - value: "gamertag", - type: CommandOptions.String, - required: true, - }] - }, - { - name: "money", - description: "Add/Remove money to a user", - value: "money", - type: CommandOptions.SubCommandGroup, - options: [{ - name: "add", - description: "Add money to user", - value: "add", - type: CommandOptions.SubCommand, - options: [{ - name: "amount", - description: "The amount to add to balance", - value: "amount", - type: CommandOptions.Float, - min_value: 0.01, - required: true, - }, { - name: "to", - description: "User to alter balance", - value: "to", - type: CommandOptions.User, - required: true, - }], - }, { - name: "remove", - description: "Remove money from a user", - value: "remove", - type: CommandOptions.SubCommand, - options: [{ - name: "amount", - description: "The amount to remove from balance", - value: "amount", - type: CommandOptions.Float, - min_value: 0.01, - required: true, - }, { - name: "from", - description: "User to alter balance", - value: "from", - type: CommandOptions.User, - required: true, - }] - }] - }], - SlashCommand: { - /** - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - run: async (client, interaction, args, { GuildDB }) => { - - const permissions = bitfieldCalculator.permissions(interaction.member.permissions); - let canUseCommand = false; - - if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; - 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 (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)) { - 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."); - - return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); - } - - 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 (client.exists(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?`) - - const opt = new ActionRowBuilder() - .addComponents( - new ButtonBuilder() - .setCustomId(`AdminOverwriteGamertag-yes-${args[0].options[1].value}-${args[0].options[0].value}-${interaction.member.user.id}`) - .setLabel("Yes") - .setStyle(ButtonStyle.Success), - new ButtonBuilder() - .setCustomId(`AdminOverwriteGamertag-no-${args[0].options[1].value}-${args[0].options[0].value}-${interaction.member.user.id}`) - .setLabel("No") - .setStyle(ButtonStyle.Secondary) - ) - - return interaction.send({ embeds: [warnGTOverwrite], components: [opt] }); - } - - playerStat.discordID = args[0].options[0].value; - - await UpdatePlayer(client, playerStat, interaction); - - let member = interaction.guild.members.cache.get(args[0].options[0].value); - if (client.exists(GuildDB.linkedGamertagRole)) { - let role = interaction.guild.roles.cache.get(GuildDB.linkedGamertagRole); - member.roles.add(role); - } - - if (client.exists(GuildDB.memberRole)) { - let role = interaction.guild.roles.cache.get(GuildDB.memberRole); - member.roles.add(role); - } - - let connectedEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .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.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(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."); - - return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); - } - - 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.`)] }); - - 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() - .setCustomId(`AdminUnlinkGamertag-yes-${args[0].options[0].value}-${interaction.member.user.id}`) - .setLabel("Yes") - .setStyle(ButtonStyle.Success), - new ButtonBuilder() - .setCustomId(`AdminUnlinkGamertag-no-${args[0].options[0].value}-${interaction.member.user.id}`) - .setLabel("No") - .setStyle(ButtonStyle.Secondary) - ) - - return interaction.send({ embeds: [warnGTOverwrite], components: [opt] }); - - } else if (args[0].name == 'claim-armband') { - - // Handle invalid roles - if (GuildDB.excludedRoles.includes(args[0].options[0].value)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription('**Notice:**\n> This role has been configured to be excluded to claim an armband.')], flags: (1 << 6) }); - - // If this faction has an existing record in the db - if (GuildDB.factionArmbands[args[0].value]) { - 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() - .setCustomId(`ChangeArmband-yes-${args[0].options[0].value}-${interaction.member.user.id}`) - .setLabel("Yes") - .setStyle(ButtonStyle.Success), - new ButtonBuilder() - .setCustomId(`ChangeArmband-no-${args[0].options[0].value}-${interaction.member.user.id}`) - .setLabel("No") - .setStyle(ButtonStyle.Secondary) - ) - - return interaction.send({ embeds: [warnArmbadChange], components: [opt] }); - } - - // 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') - - let tracker = 0; - for (let i = 0; i < Armbands.length; i++) { - if (!GuildDB.usedArmbands.includes(Armbands[i].name)) { - tracker++; - data = { - label: Armbands[i].name, - description: 'Select this armband', - value: Armbands[i].name, - } - if (tracker > 25) availableNext.addOptions(data); - else available.addOptions(data); - } - } - - let compList = [] - let opt = new ActionRowBuilder().addComponents(available); - compList.push(opt) - let opt2 = undefined; - if (tracker > 25) { - opt2 = new ActionRowBuilder().addComponents(availableNext); - compList.push(opt2); - } - - return interaction.send({ components: compList }); - - } 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)) { - 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."); - - return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); - } - - 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 `.')] }); - - playerStat.bounties = []; - - await UpdatePlayer(client, playerStat, interaction); - - const clearedBounty = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`Successfully cleared **${playerStat.gamertag}'s** bounties`); - - return interaction.send({ embeds: [clearedBounty] }); - - } else if (args[0].name == 'money') { - - const targetUserID = args[0].options[0].options[1].value; - let banking = await client.dbo.collection("users").findOne({"user.userID": targetUserID}).then(banking => banking); - - if (!banking) { - 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); - 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; - - const add = args[0].options[0].name == 'add'; - let newBalance = add - ? banking.guilds[GuildDB.serverID].balance + args[0].options[0].options[0].value - : banking.guilds[GuildDB.serverID].balance - args[0].options[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 ${add ? 'added' : 'removed'} **$${args[0].options[0].options[0].value.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}** ${add ? 'to' : 'from'} <@${targetUserID}>'s balance`) - .setColor(client.config.Colors.Green); - - return interaction.send({ embeds: [successEmbed] }); - - } - } - }, - - Interactions: { - - AdminOverwriteGamertag: { - run: async(client, interaction, GuildDB) => { - 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 = await client.dbo.collection("players").findOne({"gamertag": interaction.customId.split('-')[2]}); - - playerStat.discordID = interaction.customId.split('-')[3]; - - await UpdatePlayer(client, playerStat); - - let member = interaction.guild.members.cache.get(interaction.member.user.id); - if (client.exists(GuildDB.linkedGamertagRole)) { - let role = interaction.guild.roles.cache.get(GuildDB.linkedGamertagRole); - member.roles.add(role); - } - - if (client.exists(GuildDB.memberRole)) { - let role = interaction.guild.roles.cache.get(GuildDB.memberRole); - member.roles.add(role); - } - - let connectedEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`Successfully connected \` ${playerStat.gamertag} \` as <@${interaction.customId.split('-')[3]}>'s gamertag.`); - - return interaction.update({ embeds: [connectedEmbed], components: [] }); - - } else { - const cancel = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription('**Canceled**\n> The gamertag link will not be overwritten'); - - return interaction.update({ embeds: [cancel], components: [] }); - } - } - }, - - AdminUnlinkGamertag: { - run: async(client, interaction, GuildDB) => { - 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 = await client.dbo.collection("players").findOne({"discordID": interaction.customId.split('-')[2]}); - - playerStat.discordID = ""; - - await UpdatePlayer(client, playerStat, interaction); - - let connectedEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`Successfully unlinked \` ${playerStat.gamertag} \` from <@${interaction.customId.split('-')[2]}>.`); - - return interaction.update({ embeds: [connectedEmbed], components: [] }); - - } else { - const cancel = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription('**Canceled**\n> The gamertag unlink will not processed.'); - - return interaction.update({ embeds: [cancel], components: [] }); - } - } - } - - } -} \ No newline at end of file diff --git a/commands/alarm.js b/commands/alarm.js deleted file mode 100644 index 5aaa9cd..0000000 --- a/commands/alarm.js +++ /dev/null @@ -1,646 +0,0 @@ -const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder } = require('discord.js'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const bitfieldCalculator = require('discord-bitfield-calculator'); - -const generateAlarmMenus = (alarms, customId, placeholder, description) => { - let alarmComponents = []; - const max = 25; - let id = 1; - - for (let i = 0; i < alarms.length; i += max) { - let currentAlarmComponents = new StringSelectMenuBuilder() - .setCustomId(`${customId}-${id}`) - .setPlaceholder(placeholder); - alarms.slice(i, i + max).forEach(alarm => { - currentAlarmComponents.addOptions({ - label: alarm.name, - description: description, - value: alarm.name, - }); - }); - alarmComponents.push(new ActionRowBuilder().addComponents(currentAlarmComponents)); - id++; - } - - return alarmComponents; -}; - -module.exports = { - name: "alarm", - debug: false, - global: false, - description: "Manage an Alarm", - usage: "[command] [options]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: ["MANAGE_GUILD"], - }, - options: [ - { - name: "create", - description: "Create a new Zone Ping Alarm", - value: "create", - type: CommandOptions.SubCommand, - options: [ - { - name: "x-coord", - description: "X Coordinate of the origin", - value: "x-coord", - type: CommandOptions.Float, - min_value: 0.01, - required: true, - }, - { - name: "y-coord", - description: "Y Coordinate of the origin", - value: "y-coord", - type: CommandOptions.Float, - min_value: 0.01, - required: true, - }, - { - name: "radius", - description: "Radius of Alarm", - value: "radius", - type: CommandOptions.Float, - min_value: 25.00, - required: true, - }, - { - name: "name", - description: "Alarm Name", - value: "name", - type: CommandOptions.String, - required: true, - }, - { - name: "channel", - description: "Alarm Channel", - value: "channel", - type: CommandOptions.Channel, - channel_types: [0], // Restrict to text channel - required: true, - }, - { - name: "role", - description: "Role to Ping on Alarm", - value: "role", - type: CommandOptions.Role, - required: true, - }, - { - name: "emp-exempt", - description: "Is this Alarm Exempt to EMP Attacks?", - value: false, - type: CommandOptions.Boolean, - required: false, - }, - { - name: "show-player-coords", - description: "Show a players coords when in the radius of the Alarm?", - value: true, - type: CommandOptions.Boolean, - required: false, - } - ] - }, - { - name: "delete", - description: "Delete an Alarm", - value: "delete", - type: CommandOptions.SubCommand, - }, - { - name: "add-player", - description: "Add player to be ignored list of an Alarm", - value: "add-player", - type: CommandOptions.SubCommand, - options: [{ - name: "gamertag", - description: "Gamertag of player to ignore", - value: "gamertag", - type: CommandOptions.String, - required: true, - }] - }, - { - name: "remove-player", - description: "Remove a player from the ignored list of an Alarm", - value: "remove-player", - type: CommandOptions.SubCommand, - options: [{ - name: "gamertag", - description: "Gamertag of player to ignore", - value: "gamertag", - type: CommandOptions.String, - required: true, - }] - }, - { - name: "disable", - description: "Disable an Alarm", - value: "disable", - type: CommandOptions.SubCommand, - }, - { - name: "enable", - description: "Enable an Alarm", - value: "enable", - type: CommandOptions.SubCommand, - }, - { - name: "mute", - description: "Mute the role ping of an Alarm", - value: "mute", - type: CommandOptions.SubCommand, - options: [{ - name: "toggle", - description: "Turn on/off role pings for this alarm", - value: false, - type: CommandOptions.Boolean, - required: true, - }] - }, - { - name: "set-rule", - description: "Add a Rule to an Alarm", - value: "set-rule", - type: CommandOptions.SubCommand, - options: [{ - name: "rule", - description: "Select a rule to add to an Alarm", - value: "rule", - type: CommandOptions.String, - required: true, - choices: [ - { name: 'Ban on Entry', value: 'ban_on_entry' }, - { name: 'Ban on Kill', value: 'ban_on_kill' }, - { name: 'Ban on Fireplace Placement', value: 'ban_on_fireplace_placement' }, - ] - }] - }, - { - name: "remove-rule", - description: "Remove a rule from an Alarm", - value: "remove-rule", - type: CommandOptions.SubCommand, - }, - { - name: "rename", - description: "Rename an Alarm", - value: "rename", - type: CommandOptions.SubCommand, - options: [{ - name: "name", - description: "New Alarm Name", - value: "name", - type: CommandOptions.String, - required: true, - }] - }, - { - name: "move-origin", - description: "Move the origin of an Alarm", - value: "move-origin", - type: CommandOptions.SubCommand, - options: [{ - name: "x-coord", - description: "X Coordinate of the new origin", - value: "x-coord", - type: CommandOptions.Float, - min_value: 0.01, - required: true, - }, - { - name: "y-coord", - description: "Y Coordinate of the new origin", - value: "y-coord", - type: CommandOptions.Float, - min_value: 0.01, - required: true, - }] - } - ], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - run: async (client, interaction, args, { GuildDB }) => { - const permissions = bitfieldCalculator.permissions(interaction.member.permissions); - let canUseCommand = false; - - if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; - 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)) { - 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."); - - return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); - } - - if (args[0].name == 'create') { - if (args[0].options[3].value.includes('-') || args[0].options[3].value.includes(' ')) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Red).setDescription('**Invalid Name:** Alarm Names cannot include hyphens or spaces.')] }) - - let exists = GuildDB.alarms.find(alarm => alarm.name == args[0].options[3].value); - if (exists) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription('**Invalid Name**\nAn alarm already exists with this name.')]}); - - let alarm = { - origin: [args[0].options[0].value, args[0].options[1].value], - radius: args[0].options[2].value, - name: args[0].options[3].value, - channel: args[0].options[4].value, - 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, - disabled: false, - empExpire: null, - }; - - client.dbo.collection('guilds').updateOne({ 'server.serverID': GuildDB.serverID }, { - $push: { - 'server.alarms': alarm, - } - }, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Success:** Successfully set **${alarm.name}** in <#${alarm.channel}>`); - - return interaction.send({ embeds: [successEmbed] }); - - } else if (args[0].name == 'delete') { - - if (GuildDB.alarms.length == 0) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription('**Notice:** No Existing Alarms to Delete.')] }); - - const alarmComponents = generateAlarmMenus( - GuildDB.alarms, - `DeleteAlarmSelect`, - `Select an Alarm to delete.`, - `Delete this alarm` - ); - - return interaction.send({ components: alarmComponents, flags: (1 << 6) }); - - } else if (args[0].name == 'add-player' || args[0].name == 'remove-player') { - - const add = args[0].name == 'add-player'; - - if (GuildDB.alarms.length == 0) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription(`**Notice:** No Existing Alarms to ${add?'Add':'Remove'} Player ${add?'to':'from'}.`)] }); - - const alarmComponents = generateAlarmMenus( - GuildDB.alarms, - `ManageAlarmIgnored-${add?'add':'remove'}-${args[0].options[0].value}`, - `Select an Alarm to ${add?'add':'remove'} player ${add?'to':'from'}.`, - `${add?'Add':'Remove'} player ${add?'to':'from'} this Alarm` - ); - - return interaction.send({ components: alarmComponents, flags: (1 << 6) }); - - } else if (args[0].name == 'set-rule' || args[0].name == 'remove-rule') { - - if (GuildDB.alarms.length == 0) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription('**Notice:** No Existing Alarms to configure.')] }); - - const alarmComponents = generateAlarmMenus( - GuildDB.alarms, - `ManageRule-${args[0].name=='set-rule'?'add':'remove'}${args[0].name=='set-rule'?`-${args[0].options[0].value}`:''}`, - `Select an Alarm to configure.`, - `Configure this alarm` - ); - - return interaction.send({ components: alarmComponents, flags: (1 << 6) }); - - } else if (args[0].name == 'enable' || args[0].name == 'disable') { - - const disable = args[0].name == 'disable'; - const message = disable ? 'disable' : 'enable'; - - if (GuildDB.alarms.length == 0) return interaction.send({ - embeds: [ - new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`**Notice:**\n> No Existing Alarms to ${message}.`) - ] - }); - - if (!GuildDB.alarms.some(alarm => alarm.disabled != disable)) return interaction.send({ - embeds: [ - new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`**Notice:**\n> There are no alarms to ${message}.`) - ] - }); - - const alarmComponents = generateAlarmMenus( - GuildDB.alarms, - `EnableOrDisableAlarm-${message}`, - `Select an Alarm to ${message}`, - `Configure this alarm` - ); - - return interaction.send({ components: alarmComponents, flags: (1 << 6) }); - - } else if (args[0].name == 'rename') { - - if (GuildDB.alarms.length == 0) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription('**Notice:**\n> No Existing Alarms to configure.')] }); - - const alarmComponents = generateAlarmMenus( - GuildDB.alarms, - `RenameAlarm-${args[0].options[0].value}`, - `Select an Alarm to rename.`, - `Rename this alarm` - ); - - return interaction.send({ components: alarmComponents, flags: (1 << 6) }); - - } else if (args[0].name == 'move-origin') { - - if (GuildDB.alarms.length == 0) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription('**Notice:** No Existing Alarms to configure.')] }); - - const alarmComponents = generateAlarmMenus( - GuildDB.alarms, - `MoveOrigin-${args[0].options[0].value}-${args[0].options[1].value}`, - `Select an Alarm to move.`, - `Move this alarm` - ); - - return interaction.send({ components: alarmComponents, flags: (1 << 6) }); - - } else if (args[0].name == 'mute') { - - if (GuildDB.alarms.length == 0) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription('**Notice:** No Existing Alarms to configure.')] }); - - const alarmComponents = generateAlarmMenus( - GuildDB.alarms, - `MuteAlarm-${args[0].options[0].value ? 1 : 0}`, - `Select an Alarm to mute.`, - `Mute this alarm` - ); - - return interaction.send({ components: alarmComponents, flags: (1 << 6) }); - } - }, - }, - - Interactions: { - DeleteAlarmSelect: { - run: async(client, interaction, GuildDB) => { - - let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0]); - - const prompt = new EmbedBuilder() - .setTitle(`Are you sure you want to delete this Zone Alarm?`) - .setColor(client.config.Colors.Default) - - const opt = new ActionRowBuilder() - .addComponents( - new ButtonBuilder() - .setCustomId(`DeleteAlarm-yes-${alarm.name}`) - .setLabel("Yes") - .setStyle(ButtonStyle.Danger), - new ButtonBuilder() - .setCustomId(`DeleteAlarm-no-${alarm.name}`) - .setLabel("No") - .setStyle(ButtonStyle.Success) - ) - - return interaction.update({ embeds: [prompt], components: [opt], flags: (1 << 6) }); - } - }, - DeleteAlarm: { - run: async(client, interaction, GuildDB) => { - - if (interaction.customId.split('-')[1] == 'yes') { - let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.customId.split('-')[2]); - - client.dbo.collection('guilds').updateOne({ 'server.serverID': GuildDB.serverID }, { - $pull: { - 'server.alarms': alarm, - } - }, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Success:** Successfully Deleted **${interaction.customId.split('-')[2]}**`); - - return interaction.update({ embeds: [successEmbed], components: [] }); - } else { - let successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`The Zone Alarm **${interaction.customId.split('-')[2]}** will not be deleted.`); - - return interaction.update({ embeds: [successEmbed], components: []}); - } - } - }, - ManageAlarmIgnored: { - run: async(client, interaction, GuildDB) => { - let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0]); - 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: [] }); - - let add = interaction.customId.split('-')[1] == 'add'; - - if (add) alarm.ignoredPlayers.push(playerStat.playerID); - else alarm.ignoredPlayers = alarm.ignoredPlayers.filter((v) => { - return v != playerStat.playerID; - }); - - GuildDB.alarms[alarmIndex] = alarm; - - client.dbo.collection('guilds').updateOne({ 'server.serverID': GuildDB.serverID }, { - $set: { - 'server.alarms': GuildDB.alarms, - } - }, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Success:** Successfully ${add?'Added':'Removed'} **${interaction.customId.split('-')[2]}** ${add?'to':'from'} **${alarm.name}**`); - - return interaction.update({ embeds: [successEmbed], components: [] }); - } - }, - ManageRule: { - run: async(client, interaction, GuildDB) => { - let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0]); - let alarmIndex = GuildDB.alarms.indexOf(alarm); - - if (interaction.customId.split('-')[1] == 'add') { - - alarm.rules.push(interaction.customId.split('-')[2]); - GuildDB.alarms[alarmIndex] = alarm; - - client.dbo.collection('guilds').updateOne({ 'server.serverID': GuildDB.serverID }, { - $set: { - 'server.alarms': GuildDB.alarms, - } - }, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Success:** Successfully Added Rule **${interaction.customId.split('-')[2]}** to **${alarm.name}**`); - - return interaction.update({ embeds: [successEmbed], components: [] }); - - } else if (interaction.customId.split('-')[1]=='remove') { - - let alarmRules = new StringSelectMenuBuilder() - .setCustomId(`DeleteAlarmRule-${alarm.name}-${interaction.member.user.id}`) - .setPlaceholder(`Select Rule to Remove from ${alarm.name}`); - - for (let i = 0; i < alarm.rules.length; i++) { - alarmRules.addOptions({ - label: alarm.rules[i], - description: `Select this Rule to remove it.`, - value: alarm.rules[i] - }); - } - - const opt = new ActionRowBuilder().addComponents(alarmRules); - - return interaction.update({ components: [opt], flags: (1 << 6) }); - } - } - }, - DeleteAlarmRule: { - run: async(client, interaction, GuildDB) => { - let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.customId.split('-')[1]); - let alarmIndex = GuildDB.alarms.indexOf(alarm); - - alarm.rules = alarm.rules.filter((v) => { - return v != interaction.values[0]; - }); - - GuildDB.alarms[alarmIndex] = alarm; - - client.dbo.collection('guilds').updateOne({ 'server.serverID': GuildDB.serverID }, { - $set: { - 'server.alarms': GuildDB.alarms, - } - }, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Success:** Successfully Removed Rule **${interaction.values[0]}** from **${interaction.customId.split('-')[1]}**`); - - return interaction.update({ embeds: [successEmbed], components: [] }); - } - }, - EnableOrDisableAlarm: { - run: async(client, interaction, GuildDB) => { - let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0]); - let alarmIndex = GuildDB.alarms.indexOf(alarm); - let disable = interaction.customId.split('-')[1] == 'disable'; - alarm.disabled = disable; - GuildDB.alarms[alarmIndex] = alarm - - client.dbo.collection('guilds').updateOne({ 'server.serverID': GuildDB.serverID }, { - $set: { - 'server.alarms': GuildDB.alarms, - } - }, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Success:**\n> Successfully ${disable ? 'disabled' : 'enabled'} the Alarm **${interaction.values[0]}**`); - - return interaction.update({ embeds: [successEmbed], components: [] }); - } - }, - - MoveOrigin: { - run: async(client, interaction, GuildDB) => { - let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0]); - let alarmIndex = GuildDB.alarms.indexOf(alarm); - let origin = [parseFloat(interaction.customId.split('-')[1]), parseFloat(interaction.customId.split('-')[2])]; - alarm.origin = origin; - GuildDB.alarms[alarmIndex] = alarm - - client.dbo.collection('guilds').updateOne({ 'server.serverID': GuildDB.serverID }, { - $set: { - 'server.alarms': GuildDB.alarms, - } - }, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Success:** Successfully moved alarm to new **[origin](https://www.izurvive.com/chernarusplussatmap/#location=${origin[0]};${origin[1]})**`); - - return interaction.update({ embeds: [successEmbed], components: [] }); - } - }, - - RenameAlarm: { - run: async(client, interaction, GuildDB) => { - let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0]); - let alarmIndex = GuildDB.alarms.indexOf(alarm); - let oldName = alarm.name; - alarm.name = interaction.customId.split('-')[1]; - GuildDB.alarms[alarmIndex] = alarm - - client.dbo.collection('guilds').updateOne({ 'server.serverID': GuildDB.serverID }, { - $set: { - 'server.alarms': GuildDB.alarms, - } - }, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Success:** Successfully renamed the Alarm **${oldName}** to **${alarm.name}**`); - - return interaction.update({ embeds: [successEmbed], components: [] }); - } - }, - - MuteAlarm: { - run: async(client, interaction, GuildDB) => { - let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0]); - let alarmIndex = GuildDB.alarms.indexOf(alarm); - let mute = parseInt(interaction.customId.split('-')[1]); - alarm.mute = mute; - GuildDB.alarms[alarmIndex] = alarm - - client.dbo.collection('guilds').updateOne({ 'server.serverID': GuildDB.serverID }, { - $set: { - 'server.alarms': GuildDB.alarms, - } - }, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Success:** Successfully ${mute?'Muted':'Unmuted'} this alarm.`); - - return interaction.update({ embeds: [successEmbed], components: [] }); - } - } - } -} diff --git a/commands/armbands.js b/commands/armbands.js deleted file mode 100644 index 10fb4d3..0000000 --- a/commands/armbands.js +++ /dev/null @@ -1,86 +0,0 @@ -const { StringSelectMenuBuilder, EmbedBuilder, ActionRowBuilder } = require('discord.js'); -const { Armbands } = require('../database/armbands.js'); - -module.exports = { - name: "armbands", - debug: false, - global: false, - description: "View a list of armbads and what their image", - usage: "", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - run: async (client, interaction, args, { GuildDB }) => { - if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) - return interaction.send({ content: `You are not allowed to use the bot in this channel.`, flags: (1 << 6) }); - - let available = new StringSelectMenuBuilder() - .setCustomId(`View-1-${interaction.member.user.id}`) - .setPlaceholder('View an armband from list 1') - - let availableNext = new StringSelectMenuBuilder() - .setCustomId(`View-2-${interaction.member.user.id}`) - .setPlaceholder('View an armband from list 2') - - let tracker = 0; - for (let i = 0; i < Armbands.length; i++) { - tracker++; - data = { - label: Armbands[i].name, - description: 'View this armband', - value: Armbands[i].name, - } - - if (GuildDB.usedArmbands.includes(Armbands[i].name)) data.label += ' - [ Claimed ]' - - if (tracker > 25) availableNext.addOptions(data); - else available.addOptions(data); - } - - let compList = [] - - let opt = new ActionRowBuilder().addComponents(available); - compList.push(opt) - let opt2 = undefined; - if (tracker > 25) { - opt2 = new ActionRowBuilder().addComponents(availableNext); - compList.push(opt2); - } - - return interaction.send({ components: compList, flags: (1 << 6) }); - }, - }, - Interactions: { - View: { - run: async (client, interaction, GuildDB) => { - let armbandURL; - - for (let i = 0; i < Armbands.length; i++) { - if (Armbands[i].name == interaction.values[0]) { - armbandURL = Armbands[i].url; - break; - } - } - - let armbandTitle = `${interaction.values[0]}${GuildDB.usedArmbands.includes(interaction.values[0]) ? ' - [ Claimed ]' : ''}`; - - const success = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTitle(armbandTitle) - .setImage(armbandURL); - - return interaction.update({ embeds: [success], components: [] }); - } - } - } -} diff --git a/commands/bank.js b/commands/bank.js deleted file mode 100644 index ec150c1..0000000 --- a/commands/bank.js +++ /dev/null @@ -1,165 +0,0 @@ -const { EmbedBuilder } = require('discord.js'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const { createUser, addUser } = require('../database/user'); - -module.exports = { - name: "bank", - debug: false, - global: false, - description: "Manage your banking", - usage: "[command] [options]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [ - { - name: "balance", - description: "View your bank balance", - value: "balance", - type: CommandOptions.SubCommand, - options: [{ - name: "user", - description: "User to view ballance", - value: "user", - type: CommandOptions.User, - required: false, - }] - }, - { - name: "transfer", - description: "Transfer money to another user", - value: "transfer", - type: CommandOptions.SubCommand, - options: [ - { - name: "user", - description: "User to transfer to", - value: "user", - type: CommandOptions.User, - required: true, - }, - { - name: "amount", - description: "The amount to transfer", - value: "amount", - type: CommandOptions.Float, - min_value: 0.01, - required: true, - }, - ] - } - ], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - run: async (client, interaction, args, { GuildDB }) => { - if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) { - return interaction.send({ content: `You are not allowed to use the bot in this channel.`, flags: (1 << 6) }); - } - - 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); - } - banking = banking.user; - - 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'); - } - - if (args[0].name == 'balance') { - let balanceEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default); - - if (args[0].options&&args[0].options[0]) { - // 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(targetUserBanking => targetUserBanking); - - if (!targetUserBanking) { - 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'); - } - - // This lame line of code to get username without ping on discord - const DiscordUser = client.users.cache.get(targetUserID); - - balanceEmbed.setTitle(`${DiscordUser.tag.split("#")[0]}'s Bank Records`); - balanceEmbed.addFields({ name: '**Bank**', value: `$${targetUserBanking.guilds[GuildDB.serverID].balance.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}`, inline: true }); - - } else { - // Show command authors balance - - balanceEmbed.setTitle('Personal Bank Records'); - balanceEmbed.addFields({ name: '**Bank**', value: `$${banking.guilds[GuildDB.serverID].balance.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}`, inline: true }); - } - - return interaction.send({ embeds: [balanceEmbed] }); - - } else if (args[0].name == 'transfer') { - // send money from bank - - // prevent sending transfering money to self - const targetUserID = args[0].options[0].value.replace('<@!', '').replace('>', ''); - - if (targetUserID == interaction.member.user.id) return interaction.send({ embeds: [new EmbedBuilder().setDescription('**Invalid** You may not transfer money to yourself').setColor(client.config.Colors.Yellow)], flags: (1 << 6) }) - - if (banking.guilds[GuildDB.serverID].balance.toFixed(2) - args[0].options[1].value < 0) { - let embed = new EmbedBuilder() - .setTitle('**Bank Notice:** NSF. Non sufficient funds') - .setColor(client.config.Colors.Red); - - return interaction.send({ embeds: [embed] }); - } - - const newBalance = banking.guilds[GuildDB.serverID].balance - args[0].options[1].value; - - client.dbo.collection("users").updateOne({"user.userID":interaction.member.user.id},{$set:{[`user.guilds.${GuildDB.serverID}.balance`]:newBalance}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let targetUserBanking = await client.dbo.collection("users").findOne({"user.userID": targetUserID}).then(targetUserBanking => targetUserBanking); - - if (!targetUserBanking) { - 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; - - client.dbo.collection("users").updateOne({"user.userID":targetUserID},{$set:{[`user.guilds.${GuildDB.serverID}.balance`]:newTargetBalance}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - const successEmbed = new EmbedBuilder() - .setTitle('Bank Notice:') - .setDescription(`Successfully transfered <@${targetUserID}> **$${args[0].options[1].value.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}**`) - .setColor(client.config.Colors.Green); - - return interaction.send({ embeds: [successEmbed] }); - } - }, - }, -} \ No newline at end of file diff --git a/commands/bounty.js b/commands/bounty.js deleted file mode 100644 index 3e237d8..0000000 --- a/commands/bounty.js +++ /dev/null @@ -1,190 +0,0 @@ -const { EmbedBuilder } = require('discord.js'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const { createUser, addUser } = require('../database/user'); -const { UpdatePlayer } = require('../database/player'); - -module.exports = { - name: "bounty", - debug: false, - global: false, - description: "Set or view bounties", - usage: "[command] [options]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [{ - name: "set", - description: "Set a bounty on a player", - value: "set", - type: CommandOptions.SubCommand, - options: [{ - name: "gamertag", - description: "Gamertag of player for bounty", - value: "gamertag", - type: CommandOptions.String, - required: true, - }, { - name: "value", - description: "Amount of the bounty", - value: "value", - type: CommandOptions.Float, - min_value: 0.01, - required: true - }, { - name: "anonymous", - description: "Make this bounty anonymous (does not show your name)", - value: false, - type: CommandOptions.Boolean, - required: false - }] - }, { - name: "pay", - description: "Pay off your bounty", - value: "pay", - type: CommandOptions.SubCommand, - }, { - name: "view", - description: "View all active bounties", - value: "view", - type: CommandOptions.SubCommand, - }], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - 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)) { - 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."); - - return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); - } - - 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 = 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); - if (!success) return client.sendInternalError(interaction, 'Failed to add bank'); - } - } - - 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 (args[0].options[1].value > banking.guilds[GuildDB.serverID].balance) { - let nsf = new EmbedBuilder() - .setDescription('**Bank Notice:** NSF. Non sufficient funds') - .setColor(client.config.Colors.Red); - - return interaction.send({ embeds: [nsf] }); - } - - const newBalance = banking.guilds[GuildDB.serverID].balance - args[0].options[1].value; - - client.dbo.collection("users").updateOne({ "user.userID": interaction.member.user.id }, { - $set: { - [`user.guilds.${GuildDB.serverID}.balance`]: newBalance, - } - }, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let anonymous = args[0].options[2]; - - playerStat.bounties.push({ - setBy: (anonymous && !anonymous.value) ? interaction.member.user.id : null, - value: args[0].options[1].value, - }); - playerStat.bountiesLength = playerStat.bounties.length; // Will ensure bounties length = # of bounties, even if bountiesLength does not exists in player stat. - - await UpdatePlayer(client, playerStat, interaction); - - const successEmbed = new EmbedBuilder() - .setTitle('Success') - .setDescription(`Successfully set a **$${args[0].options[1].value.toFixed(2).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}** bounty on \` ${playerStat.gamertag} \`\nThis can be viewed using `) - .setColor(client.config.Colors.Green); - - return interaction.send({ embeds: [successEmbed], flags: (1 << 6) }); - - } 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 (playerStat.bounties.length == 0) { - const noBounty = new EmbedBuilder() - .setColor(client.config.Colors.Yellow) - .setDescription(`You have no bounties to pay off.`) - - return interaction.send({ embeds: [noBounty] }); - } - - let totalBounty = 0; - for (let i = 0; i < playerStat.bounties.length; i++) { - totalBounty += playerStat.bounties[i].value; - } - - if (banking.guilds[GuildDB.serverID].balance.toFixed(2) - (totalBounty * 2) < 0) { - let embed = new EmbedBuilder() - .setTitle('**Bank Notice:** NSF. Non sufficient funds') - .setColor(client.config.Colors.Red); - - return interaction.send({ embeds: [embed], flags: (1 << 6) }); - } - - const newBalance = banking.guilds[GuildDB.serverID].balance - (totalBounty * 2); - - await client.dbo.collection("users").updateOne({"user.userID":interaction.member.user.id},{$set:{[`user.guilds.${GuildDB.serverID}.balance`]:newBalance}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - playerStat.bounties = []; - playerStat.bountiesLength = 0; - - await UpdatePlayer(client, playerStat, interaction); - - const payedOff = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`Successfully paid off **$${(totalBounty * 2).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}** in bounties.`); - - return interaction.send({ embeds: [payedOff] }); - - } else if (args[0].name == 'view') { - - const activeBounties = await client.dbo.collection("players").find({ - "bountiesLength": { $gt: 0 } - }).toArray(); - - let bountiesEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription('**Active Boutnies**'); - - if (activeBounties.length == 0) bountiesEmbed.setDescription('**There are No Active Boutnies**') - for (let i = 0; i < activeBounties.length; i++) { - for (let j = 0; j < activeBounties[i].bounties.length; j++) { - bountiesEmbed.addFields({ name: `${activeBounties[i].gamertag} has a:`, value: `**$${activeBounties[i].bounties[j].value.toFixed(2).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}** bounty set by ${activeBounties[i].bounties[j].setBy == null ? 'Anonymous' : `<@${activeBounties[i].bounties[j].setBy}>`}`, inline: false }); - } - } - - return interaction.send({ embeds: [bountiesEmbed] }); - } - }, - }, -} \ No newline at end of file diff --git a/commands/channels.js b/commands/channels.js deleted file mode 100644 index fc57e6d..0000000 --- a/commands/channels.js +++ /dev/null @@ -1,47 +0,0 @@ -const { EmbedBuilder } = require('discord.js'); - -module.exports = { - name: "channels", - debug: false, - global: false, - description: "View a list of allowed channels", - usage: "", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - run: async (client, interaction, args, { GuildDB }) => { - if (!GuildDB.customChannelStatus) { - let noChannels = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTitle('Channels') - .setDescription('> There are no configured channels'); - - return interaction.send({ embeds: [noChannels] }); - } - - let channels = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTitle('Channels') - - let des = ''; - for (let i = 0; i < GuildDB.allowedChannels.length; i++) { - if (i == 0) des += `> <#${GuildDB.allowedChannels[i]}>`; - else des += `\n> <#${GuildDB.allowedChannels[i]}>`; - } - channels.setDescription(des); - - return interaction.send({ embeds: [channels] }); - }, - }, - Interactions: {} -} diff --git a/commands/claim.js b/commands/claim.js deleted file mode 100644 index bbe188e..0000000 --- a/commands/claim.js +++ /dev/null @@ -1,210 +0,0 @@ -const { ActionRowBuilder, EmbedBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder } = require('discord.js'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const { Armbands } = require('../database/armbands.js'); - -module.exports = { - name: "claim", - debug: false, - global: false, - description: "Claim an available armband for your faction", - usage: "[role]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [{ - name: "faction_role", - description: "Claim an armband for this faction role", - value: "faction_role", - type: CommandOptions.Role, - required: true, - }], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - run: async (client, interaction, args, { GuildDB }) => { - if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) - return interaction.send({ content: `You are not allowed to use the bot in this channel.`, flags: (1 << 6) }); - - // Handle invalid roles - let des; - if (GuildDB.excludedRoles.includes(args[0].value)) des = '**Notice:**\n> This role has been configured to be excluded to claim an armband.'; - if (!interaction.member.roles.includes(args[0].value)) des = '**Notice:**\n> You cannot claim an armband for a role you don\'t have.'; - if (des) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(des)], flags: (1 << 6) }); - - for (let roleID in Object(GuildDB.factionArmbands)) { - if (interaction.member.roles.includes(roleID) && roleID != args[0].value) { - return interaction.send({ embeds: [ - new EmbedBuilder() - .setColor(client.config.Colors.Yellow) - .setDescription('**Notice:**\n> You already have another role with a claimed flag.') - ], flags: (1 << 6) }) - } - } - - // If this faction has an existing record in the db - if (GuildDB.factionArmbands[args[0].value]) { - const warnArmbadChange = new EmbedBuilder() - .setColor(client.config.Colors.Yellow) - .setDescription(`**Notice:**\n> The faction <@&${args[0].value}> already has an armband selected. Are you sure you would like to change this?`) - - const opt = new ActionRowBuilder() - .addComponents( - new ButtonBuilder() - .setCustomId(`ChangeArmband-yes-${args[0].value}-${interaction.member.user.id}`) - .setLabel("Yes") - .setStyle(ButtonStyle.Success), - new ButtonBuilder() - .setCustomId(`ChangeArmband-no-${args[0].value}-${interaction.member.user.id}`) - .setLabel("No") - .setStyle(ButtonStyle.Secondary) - ) - - return interaction.send({ embeds: [warnArmbadChange], components: [opt] }); - } - - let available = new StringSelectMenuBuilder() - .setCustomId(`Claim-${args[0].value}-1-${interaction.member.user.id}`) - .setPlaceholder('Select an armband from list 1 to claim') - - let availableNext = new StringSelectMenuBuilder() - .setCustomId(`Claim-${args[0].value}-2-${interaction.member.user.id}`) - .setPlaceholder('Select an armband from list 2 to claim') - - let tracker = 0; - for (let i = 0; i < Armbands.length; i++) { - if (!GuildDB.usedArmbands.includes(Armbands[i].name)) { - tracker++; - data = { - label: Armbands[i].name, - description: 'Select this armband', - value: Armbands[i].name, - } - if (tracker > 25) availableNext.addOptions(data); - else available.addOptions(data); - } - } - - let compList = [] - - let opt = new ActionRowBuilder().addComponents(available); - compList.push(opt) - let opt2 = undefined; - if (tracker > 25) { - opt2 = new ActionRowBuilder().addComponents(availableNext); - compList.push(opt2); - } - - return interaction.send({ components: compList }); - }, - }, - Interactions: { - Claim: { - run: async (client, interaction, GuildDB) => { - if (!interaction.customId.endsWith(interaction.member.user.id)) - return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) }); - - let factionID = interaction.customId.split('-')[1]; - - let data = { - faction: factionID, - armband: interaction.values[0], - }; - - let query = { - $push: { - 'server.usedArmbands': interaction.values[0] - }, - $set: { - [`server.factionArmbands.${factionID}`]: data - }, - }; - - if (interaction.customId.split('-')[2] == 'update') { - let removeQuery; - for (const [fid, data] of Object.entries(GuildDB.factionArmbands)) { - if (fid == factionID) removeQuery = data.armband; - } - client.dbo.collection("guilds").updateOne({'server.serverID': GuildDB.serverID}, {$pull: {'server.usedArmbands': removeQuery}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }) - } - - client.dbo.collection("guilds").updateOne({'server.serverID': GuildDB.serverID}, query, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }) - - let armbandURL; - - for (let i = 0; i < Armbands.length; i++) { - if (Armbands[i].name == interaction.values[0]) { - armbandURL = Armbands[i].url; - break; - } - } - - const success = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`**Success!**\n> The faction <@&${factionID}> has now claimed ***${interaction.values[0]}***`) - .setImage(armbandURL); - - return interaction.update({ embeds: [success], components: [] }); - } - }, - - ChangeArmband: { - run: async (client, interaction, GuildDB) => { - 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 available = new StringSelectMenuBuilder() - .setCustomId(`Claim-${interaction.customId.split('-')[2]}-update-1-${interaction.member.user.id}`) - .setPlaceholder('Select an armband from list 1 to claim') - - let availableNext = new StringSelectMenuBuilder() - .setCustomId(`Claim-${interaction.customId.split('-')[2]}-update-2-${interaction.member.user.id}`) - .setPlaceholder('Select an armband from list 2 to claim') - - let tracker = 0; - for (let i = 0; i < Armbands.length; i++) { - if (!GuildDB.usedArmbands.includes(Armbands[i].name)) { - tracker++; - data = { - label: Armbands[i].name, - description: 'Select this armband', - value: Armbands[i].name, - } - if (tracker > 25) availableNext.addOptions(data); - else available.addOptions(data); - } - } - - let compList = [] - - let opt = new ActionRowBuilder().addComponents(available); - compList.push(opt) - let opt2 = undefined; - if (tracker > 25) { - opt2 = new ActionRowBuilder().addComponents(availableNext); - compList.push(opt2); - } - - return interaction.update({ embeds: [], components: compList }); - - } else { - const cancel = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription('**Canceled**\n> Your factions armband will remain the same'); - - return interaction.update({ embeds: [cancel], components: [] }); - } - } - } - } -} diff --git a/commands/collect-income.js b/commands/collect-income.js deleted file mode 100644 index 02c9d41..0000000 --- a/commands/collect-income.js +++ /dev/null @@ -1,108 +0,0 @@ -const { EmbedBuilder, } = require('discord.js'); -const { createUser, addUser } = require('../database/user'); - -module.exports = { - name: "collect-income", - debug: false, - global: false, - description: "Collect your income", - usage: "", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - run: async (client, interaction, args, { GuildDB }) => { - if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) { - return interaction.send({ content: `You are not allowed to use the bot in this channel.`, flags: (1 << 6) }); - } - - const hasIncomeRole = GuildDB.incomeRoles.some(data => { - if (interaction.member.roles.includes(data.role)) return true; - return false; - }); - - if (!hasIncomeRole) { - const error = new EmbedBuilder() - .setColor(client.config.Colors.Red) - .setTitle('Missing Income!') - .setDescription(`It appears you don't have any income`) - - return interaction.send({ embeds: [error] }) - } - - 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); - } - banking = banking.user; - - 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'); - } - - if (!client.exists(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 /= (60 * 60); - let hoursBetweenDates = Math.abs(Math.round(diff)); - - if (hoursBetweenDates >= GuildDB.incomeLimiter) { - let roles = []; - let income = []; - for (let i = 0; i < GuildDB.incomeRoles.length; i++) { - if (interaction.member.roles.includes(GuildDB.incomeRoles[i].role)) { - roles.push(GuildDB.incomeRoles[i].role) - income.push(GuildDB.incomeRoles[i].income) - } - } - - let totalIncome = income.reduce((x, y) => x + y, 0) - - let newData = banking.guilds[GuildDB.serverID]; - newData.balance += totalIncome; - newData.lastIncome = now; - - client.dbo.collection("users").updateOne({"user.userID":interaction.member.user.id},{$set:{[`user.guilds.${GuildDB.serverID}`]: newData}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let description = `**You collected**`; - for (let i = 0; i < roles.length; i++) { - description += `\n<@&${roles[i]}> - $**${income[i].toFixed(2).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}**` - } - - const success = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(description) - - return interaction.send({ embeds: [success] }) - - } else { - let date = banking.guilds[GuildDB.serverID].lastIncome; - date.setHours(date.getHours() + GuildDB.incomeLimiter); - diff = (date - now) / 1000; - let timeTillIncome = client.secondsToDhms(diff); - - const error = new EmbedBuilder() - .setColor(client.config.Colors.Red) - .setDescription(`You've already collected your income this week. Wait **${timeTillIncome}** to collect again.`); - - return interaction.send({ embeds: [error] }) - } - }, - }, -} \ No newline at end of file diff --git a/commands/compare-rating.js b/commands/compare-rating.js deleted file mode 100644 index 6096f47..0000000 --- a/commands/compare-rating.js +++ /dev/null @@ -1,143 +0,0 @@ -const { EmbedBuilder } = require('discord.js'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const { insertPVPstats } = require('../database/player'); - -module.exports = { - name: "compare-rating", - debug: false, - global: false, - description: "Compare combat ratings between yourself and another player", - usage: "[user or gamertag]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [{ - name: "discord", - description: "Discord user to lookup stats", - value: "discord", - type: CommandOptions.User, - required: false, - }, { - name: "gamertag", - description: "Gamertag to lookup stats", - type: CommandOptions.String, - required: false, - }], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - 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)) { - 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."); - - return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); - } - - let discord = args[0] && args[0].name == 'discord' ? args[0].value : undefined; - let gamertag = args[0] && args[0].name == 'gamertag' ? args[0].value : undefined; - - if (!discord && !gamertag) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`Please provide a Discord User or Gamertag`)] }); - - let leaderboard = await client.dbo.collection("players").aggregate([ - { $sort: { 'combatRating': -1 } } - ]).toArray(); - - let comp; - if (discord) comp = leaderboard.find(s => s.discordID == discord); - 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.`)] }); - - let lbPosSelf = leaderboard.indexOf(self) + 1; - let lbPosComp = leaderboard.indexOf(comp) + 1; - - let selfData = self.combatRatingHistory; - let compData = comp.combatRatingHistory; - if (selfData.length == 1) selfData.push(self.combatRating) // Make array 2 long for a straight line in the graph - if (compData.length == 1) compData.push(comp.combatRating) // Make array 2 long for a straight line in the graph - 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; - - let tag = comp.discordID != "" ? `<@${comp.discordID}>` : comp.gamertag; - - let statsEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`<@${interaction.member.user.id}> vs ${tag} Combat Rating`) - .addFields( - { name: `${self.gamertag}'s Combat Rating Stats`, value: `> Leaderboard Pos: # ${lbPosSelf}\n> Rating: ${self.combatRating}`, inline: false }, - { name: `${comp.gamertag}'s Combat Rating Stats`, value: `> Leaderboard Pos: # ${lbPosComp}\n> Rating: ${comp.combatRating}`, inline: false }, - { name: 'Rating Difference', value: `${Math.abs(self.combatRating - comp.combatRating)}`, inline: false }, - ); - - const dataMax = Math.max(selfDataMax, compDataMax); - const dataMin = Math.min(Math.min(...selfData), Math.min(...compData)) - - const len = Math.max(selfData.length, compData.length); - const diff = Math.abs(selfData.length - compData.length); - if (selfData.length < compData.length) selfData.unshift(...(new Array(diff).fill(null, 0, diff))); - if (compData.length < selfData.length) compData.unshift(...(new Array(diff).fill(null, 0, diff))); - - const chart = { - type: 'line', - data: { - labels: new Array(len).fill(' ', 0, len), - datasets: [ - { - data: selfData, - label: `${self.gamertag}'s Combat Ratings`, - }, - { - data: compData, - label: `${comp.gamertag}'s Combat Ratings`, - } - ], - }, - options: { - legend: { - labels: { - fontSize: 14, - fontStyle: 'bold', - } - }, - scales: { - // Gives comfortable margin to the top of the y-axis - yAxes: [{ - ticks: { - fontStyle: 'bold', - // max: Math.round(dataMax / 10) * 10 + 10, - // min: Math.round(dataMin / 10) * 10, - }, - }], - }, - // Gives a margin to the right of the whole graph - layout: { - padding: { - right: 40, - }, - }, - }, - }; - - const encodedChart = encodeURIComponent(JSON.stringify(chart)); - const chartURL = `https://quickchart.io/chart?c=${encodedChart}&bkg=${encodeURIComponent("#ded8d7")}`; - - statsEmbed.setImage(chartURL); - - return interaction.send({ embeds: [statsEmbed] }); - }, - }, -} \ No newline at end of file diff --git a/commands/config.js b/commands/config.js deleted file mode 100644 index 9296510..0000000 --- a/commands/config.js +++ /dev/null @@ -1,1143 +0,0 @@ -const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const bitfieldCalculator = require('discord-bitfield-calculator'); -const { getDefaultSettings } = require('../database/guild'); - -module.exports = { - name: "config", - debug: false, - global: false, - description: "Configure your server settings", - usage: "[options] [configuration]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: ["MANAGE_GUILD"], - }, - options: [ - { - name: "killfeed", - description: "Configure the killfeed", - value: "killfeed", - type: CommandOptions.SubCommandGroup, - options: [ - { - name: "channel", - description: "Configure the killfeed channel", - value: "channel", - type: CommandOptions.SubCommand, - options: [{ - name: "channel", - description: "The channel to configure", - value: "channel", - type: CommandOptions.Channel, - required: true - }] - }, - { - name: "show_coords", - description: "Show the coordinates of the victim in the killfeed channel.", - value: "show_coords", - type: CommandOptions.SubCommand, - options: [{ - name: "configuration", - description: "True or False", - value: false, - type: CommandOptions.Boolean, - required: true, - }] - }, - { - name: "show_weapon", - description: "Show the image of the weapon in the killfeed", - value: "show_weapon", - type: CommandOptions.SubCommand, - options: [{ - name: "configuration", - description: "True or False", - value: false, - type: CommandOptions.Boolean, - required: true, - }] - } - ] - }, - { - name: "allowed_channels", - description: "Set channels you're allowed to use the bot in", - value: "allowed_channels", - type: CommandOptions.SubCommandGroup, - options: [ - { - name: "add", - description: "Add channel", - value: "add", - type: CommandOptions.SubCommand, - options: [{ - name: "channel", - description: "The channel to configure", - value: "channel", - type: CommandOptions.Channel, - channel_types: [0], // Restrict to text channel - required: true, - }] - }, - { - name: "remove", - description: "Remove channel", - value: "remove", - type: CommandOptions.SubCommand, - options: [{ - name: "channel", - description: "The channel to configure", - value: "channel", - type: CommandOptions.Channel, - channel_types: [0], // Restrict to text channel - required: true, - }] - }, - { - name: "clear", - description: "Clears all configured channels", - value: "clear", - type: CommandOptions.SubCommand, - }, - { - name: "view", - description: "View configured allowed channels", - value: "view", - type: CommandOptions.SubCommand, - } - ] - }, - { - name: "set_channel", - description: "Configure a channel", - value: "set_channel", - type: CommandOptions.SubCommand, - options:[ - { - name: "channel_type", - description: "Select the channel type", - value: "channel_type", - type: CommandOptions.String, - choices: [ - { name: 'Killfeed', value: 'killfeedChannel' }, { name: 'Admin Logs', value: 'connectionLogsChannel' }, - { name: 'Welcome', value: 'welcomeChannel' }, { name: 'Online Players', value: 'activePlayersChannel' }, - ], - required: true, - }, - { - name: "channel", - description: "The channel to configure", - value: "channel", - type: CommandOptions.Channel, - channel_types: [0], // Restrict to text channel - required: true, - }, - ] - }, - { - name: "linked_gt_role", - description: "Role for users with linked gamertags", - value: "linked_gt_role", - type: CommandOptions.SubCommand, - options: [{ - name: "role", - description: "Role to configure", - value: "role", - type: CommandOptions.Role, - required: true, - }] - }, - { - name: "member_role", - description: "Role for users who join the server", - value: "member_role", - type: CommandOptions.SubCommand, - options: [{ - name: "role", - description: "Role to configure", - value: "role", - type: CommandOptions.Role, - required: true, - }] - }, - { - name: "bot_admin_role", - description: "Set/remove bot admin role", - value: "bot_admin_role", - type: CommandOptions.SubCommandGroup, - options: [ - { - name: "add", - description: "Configure role to be bot admin", - value: "add", - type: CommandOptions.SubCommand, - options: [{ - name: "role", - description: "Role to confiure", - value: "role", - type: CommandOptions.Role, - required: true, - }] - }, - { - name: "remove", - description: "Remove configured role as bot admin", - value: "remove", - type: CommandOptions.SubCommand, - options: [{ - name: "role", - description: "Role to remove", - value: "role", - type: CommandOptions.Role, - required: true, - }] - }, - { - name: "view", - description: "View the configured bot admin roles", - value: "view", - type: CommandOptions.SubCommand, - } - ] - }, - { - name: "admin_ping_role", - description: "Admin role to ping in admin logs channel", - value: "admin_ping_role", - type: CommandOptions.SubCommand, - options: [{ - name: "role", - description: "Role to configure", - value: "role", - type: CommandOptions.Role, - required: true, - }] - }, - { - name: "exclude", - description: "Exclude roles that can be used to claim armbands", - value: "exclude", - type: CommandOptions.SubCommandGroup, - options: [ - { - name: "add", - description: "Configure role to be excluded", - value: "add", - type: CommandOptions.SubCommand, - options: [{ - name: "role", - description: "Role to confiure", - value: "role", - type: CommandOptions.Role, - required: true, - }] - }, - { - name: "remove", - description: "Remove configured role thats excluded", - value: "remove", - type: CommandOptions.SubCommand, - options: [{ - name: "role", - description: "Role to remove", - value: "role", - type: CommandOptions.Role, - required: true, - }] - }, - { - name: "view", - description: "View the configured excluded roles", - value: "view", - type: CommandOptions.SubCommand, - }, - ] - }, - { - name: "reset", - description: "Restore all settings to default configurations", - value: "reset", - type: CommandOptions.SubCommand, - }, - { - name: "view", - description: "View current settings configuration", - value: "view", - type: CommandOptions.SubCommand, - }, - { - name: "starting_balance", - description: "Set the starting balance of a new user", - value: "starting_balance", - type: CommandOptions.SubCommand, - options: [{ - name: "amount", - description: "The amount to set the starting balance", - value: "amount", - type: CommandOptions.Float, - min_value: 1.00, - required: true, - }] - }, - { - name: "uav-price", - description: "Configure the price of a UAV", - value: "uav-price", - type: CommandOptions.SubCommand, - options: [{ - name: "amount", - description: "The amount to set the UAV price", - value: "amount", - type: CommandOptions.Float, - min_value: 0.01, - required: true, - }] - }, - { - name: "emp-price", - description: "Configure the price of an EMP", - value: "emp-price", - type: CommandOptions.SubCommand, - options: [{ - name: "amount", - description: "The amount to set the EMP price", - value: "amount", - type: CommandOptions.Float, - min_value: 0.01, - required: true, - }] - }, - { - name: "income_role", - description: "Set/remove roles to recieve income", - value: "set_income_role", - type: CommandOptions.SubCommandGroup, - options: [ - { - name: "set", - description: "Set role", - value: "set", - type: CommandOptions.SubCommand, - options: [ - { - name: "role", - description: "Role to set", - value: "role", - type: CommandOptions.Role, - required: true, - }, - { - name: "amount", - description: "The amount to collect", - value: 120.00, - type: CommandOptions.Float, - min_value: 0.01, - required: true, - } - ] - }, - { - name: "remove", - description: "Remove role", - value: "remove", - type: CommandOptions.SubCommand, - options: [{ - name: "role", - description: "Role to remove", - value: "role", - type: CommandOptions.Role, - required: true, - }] - }, - ], - }, - { - name: "income_limiter", - description: "Change the number of hours to wait before collecting next income", - value: "income_limiter", - type: CommandOptions.SubCommand, - options: [{ - name: "hours", - description: "Number of hours till income can be collected", - value: 168.00, // 1 week - type: CommandOptions.Float, - min_value: 1.00, - required: true, - }] - }, - { - name: "combat-log-timer", - description: "Adjust number of minutes to detect combat logs (0 disables combat log)", - value: "combat-log-timer", - type: CommandOptions.SubCommand, - options: [{ - name: "minutes", - description: "Minutes to qualify combat log", - value: 5, - type: CommandOptions.Integer, - min_value: 0, - }] - }, - { - name: "toggle-uav-purchase", - description: "Allow/Disallow UAV purchases", - value: "toggle-uav-purchase", - type: CommandOptions.SubCommand, - options: [{ - name: "configuration", - description: "True or False", - value: false, - type: CommandOptions.Boolean, - required: true, - }] - }, - { - name: "toggle-emp-purchase", - description: "Allow/Disallow EMP purchases", - value: "toggle-uav-purchase", - type: CommandOptions.SubCommand, - options: [{ - name: "configuration", - description: "True or False", - value: false, - type: CommandOptions.Boolean, - required: true, - }] - }, - { - name: "welcome_message_server_name", - description: "Configure the server name in the welcome message", - value: "welcome_message_server_name", - type: CommandOptions.SubCommand, - options: [{ - name: "name", - description: "Server name to include in welcome message", - value: "name", - type: CommandOptions.String, - required: true, - }] - } - ], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - run: async (client, interaction, args, { GuildDB }) => { - const permissions = bitfieldCalculator.permissions(interaction.member.permissions); - let canUseCommand = false; - - if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; - 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.' }); - - switch(args[0].name) { - - case 'allowed_channels': - const channels_config = args[0].options[0].name; - const channelid = ['add', 'remove'].includes(channels_config) ? args[0].options[0].options[0].value : null; - - if (channels_config == 'add') { - const channelAdd = client.GetChannel(channelid); - - const newChannelErrorEmbed = new EmbedBuilder().setColor(client.config.Colors.Red) - let error = false; - - if (!channelAdd) {error=true;newChannelErrorEmbed.setDescription(`**Error Notice:** Cannot find that channel.`);} - if (channelAdd.type=="voice") {error=true;newChannelErrorEmbed.setDescription(`**Error Notice:** Cannot add voice channel to allowed channels.`);} - if (error) return interaction.send({ embeds: [newChannelErrorEmbed] }); - - client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID}, {$push:{"server.allowedChannels": channelid}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - const successAddChannelEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Success:** Set <#${channelid}> as an allowed channel.`); - - return interaction.send({ embeds: [successAddChannelEmbed] }); - } else if (channels_config == 'remove') { - - const errorChannelNotAvailable = new EmbedBuilder() - .setDescription(`**Error Notice:** <#${channelid}> is not in allowed channels.`) - .setColor(client.config.Colors.Red) - - if (!GuildDB.allowedChannels.includes(channelid)) return interaction.send({ embeds: [errorChannelNotAvailable] }); - - const promptRemoveChannel = new EmbedBuilder() - .setTitle(`Are you sure you want to remove this channel from allowed channels?`) - .setColor(client.config.Colors.Default) - - const optRemoveChannel = new ActionRowBuilder() - .addComponents( - new ButtonBuilder() - .setCustomId(`RemoveAllowedChannels-yes-${channelid}-${interaction.member.user.id}`) - .setLabel("Yes") - .setStyle(ButtonStyle.Danger), - new ButtonBuilder() - .setCustomId(`RemoveAllowedChannels-no-${channelid}-${interaction.member.user.id}`) - .setLabel("No") - .setStyle(ButtonStyle.Success) - ) - - return interaction.send({ embeds: [promptRemoveChannel], components: [optRemoveChannel], flags: (1 << 6) }); - - } else if (channels_config == 'clear') { - - const errorNoAllowedChannels = new EmbedBuilder() - .setDescription(`**Error Notice:**\n> No allowed channels configured to clear`) - .setColor(client.config.Colors.Red) - - if (GuildDB.allowedChannels.length == 0) return interaction.send({ embeds: [errorNoAllowedChannels] }); - - const promptClearChannels = new EmbedBuilder() - .setTitle(`Are you sure you want to clear all configured channels from allowed channels?`) - .setColor(client.config.Colors.Default) - - const optClearChannels = new ActionRowBuilder() - .addComponents( - new ButtonBuilder() - .setCustomId(`ClearAllowedChannels-yes-${interaction.member.user.id}`) - .setLabel("Yes") - .setStyle(ButtonStyle.Danger), - new ButtonBuilder() - .setCustomId(`ClearAllowedChannels-no-${interaction.member.user.id}`) - .setLabel("No") - .setStyle(ButtonStyle.Success) - ) - - return interaction.send({ embeds: [promptClearChannels], components: [optClearChannels], flags: (1 << 6) }); - - - } else if (channels_config == 'view') { - - if (!GuildDB.customChannelStatus) { - const noConfiguredChannels = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTitle('Channels') - .setDescription('> There are no configured channels'); - - return interaction.send({ embeds: [noConfiguredChannels] }); - } - - const configuredChannels = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTitle('Channels') - - let des = ''; - for (let i = 0; i < GuildDB.allowedChannels.length; i++) { - if (i == 0) des += `> <#${GuildDB.allowedChannels[i]}>`; - else des += `\n> <#${GuildDB.allowedChannels[i]}>`; - } - configuredChannels.setDescription(des); - - return interaction.send({ embeds: [configuredChannels] }); - - } - - case 'bot_admin_role': - const bot_admin_config = args[0].options[0].name; - const botAdminRoleId = ['add', 'remove'].includes(bot_admin_config) ? args[0].options[0].options[0].value : null; - if (bot_admin_config == 'add') { - - client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID},{$push: {"server.botAdminRoles": botAdminRoleId}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - const successSetBotAdminRoleEmbed = new EmbedBuilder() - .setDescription(`Successfully added <@&${botAdminRoleId}> as a bot admin role.\nUsers with this role can use restricted commands.`) - .setColor(client.config.Colors.Green); - - return interaction.send({ embeds: [successSetBotAdminRoleEmbed] }); - - } else if (bot_admin_config == 'remove') { - - if (!GuildDB.botAdminRoles.includes(botAdminRoleId)) { - const nonAdminRoleEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Yellow) - .setDescription(`**Notice:**\n> The role <@&${botAdminRoleId}> has not been configured as a bot admin.`); - - return interaction.send({ embeds: [nonAdminRoleEmbed] }); - } - - const promptRemoveAdminRole = new EmbedBuilder() - .setTitle(`Are you sure you want to remove this role as a bot admin?`) - .setColor(client.config.Colors.Default) - - const optRemoveAdminRole = new ActionRowBuilder() - .addComponents( - new ButtonBuilder() - .setCustomId(`RemoveBotAdminRole-yes-${botAdminRoleId}-${interaction.member.user.id}`) - .setLabel("Yes") - .setStyle(ButtonStyle.Danger), - new ButtonBuilder() - .setCustomId(`RemoveBotAdminRole-no-${botAdminRoleId}-${interaction.member.user.id}`) - .setLabel("No") - .setStyle(ButtonStyle.Success) - ) - - return interaction.send({ embeds: [promptRemoveAdminRole], components: [optRemoveAdminRole], flags: (1 << 6) }); - - } else if (bot_admin_config == 'view') { - - if (GuildDB.botAdminRoles.length == 0) { - const noBotAdminRoles = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTitle('Admin Roles') - .setDescription('> There have been no configured admin roles'); - - return interaction.send({ embeds: [noBotAdminRoles] }); - } - - const botAdminRolesEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTitle('Admin Roles') - - let des = ''; - for (let i = 0; i < GuildDB.botAdminRoles.length; i++) { - des += `\n> <@&${GuildDB.botAdminRoles[i]}>`; - } - botAdminRolesEmbed.setDescription(des); - - return interaction.send({ embeds: [botAdminRolesEmbed] }); - - } - - case 'admin_ping_role': - client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID},{$set: {"server.adminRole": args[0].options[0].value}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - const successSetAdminRoleEmbed = new EmbedBuilder() - .setDescription(`Successfully set <@&${args[0].options[0].value}> as the server admin role..`) - .setColor(client.config.Colors.Green); - - return interaction.send({ embeds: [successSetAdminRoleEmbed] }); - - case 'exclude': - const exclude_config = args[0].options[0].name; - const exclude_roleid = ['add', 'remove'].includes(exclude_config) ? args[0].options[0].options[0].value : null; - - if (exclude_config == 'add') { - client.dbo.collection('guilds').updateOne({'server.serverID': GuildDB.serverID}, {$push: {'server.excludedRoles': exclude_roleid}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }) - - const successExcludeEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Done!**\n> Successfully added <@&${exclude_roleid}> to list of excluded roles.`) - - return interaction.send({ embeds: [successExcludeEmbed] }); - - } else if (exclude_config == 'remove') { - client.dbo.collection('guilds').updateOne({'server.serverID': GuildDB.serverID}, {$pull: {'server.excludedRoles': exclude_roleid}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }) - - const successRemoveExcludeEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Done!**\n> Successfully removed <@&${exclude_roleid}> to list of excluded roles.`) - - return interaction.send({ embeds: [successRemoveExcludeEmbed] }); - - } else if (exclude_config == "view") { - - if (GuildDB.excludedRoles.length == 0) { - const noExcludedRoles = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTitle('Excluded Roles') - .setDescription('> There have been no excluded roles'); - - return interaction.send({ embeds: [noExcludedRoles] }); - } - - const excludedRolesEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTitle('Excluded Roles') - - let des = ''; - for (let i = 0; i < GuildDB.excludedRoles.length; i++) { - des += `\n> <@&${GuildDB.excludedRoles[i]}>`; - } - excludedRolesEmbed.setDescription(des); - - return interaction.send({ embeds: [excludedRolesEmbed] }); - - } - - case 'reset': - const promptReset = new EmbedBuilder() - .setTitle(`Woah!? Hold on.`) - .setDescription('Are you sure you wish to remove all your configurations for this guild?') - .setColor(client.config.Colors.Default) - - const optReset = new ActionRowBuilder() - .addComponents( - new ButtonBuilder() - .setCustomId(`ResetSettings-yes-${interaction.member.user.id}`) - .setLabel("Yes") - .setStyle(ButtonStyle.Danger), - new ButtonBuilder() - .setCustomId(`ResetSettings-no-${interaction.member.user.id}`) - .setLabel("No") - .setStyle(ButtonStyle.Success) - ) - - return interaction.send({ embeds: [promptReset], components: [optReset], flags: (1 << 6) }); - - case 'view': - - // wrappers - const w = "\`\`\`"; - const a = "ansi\n"; - const f = "fix\n"; - const m = "arm\n" - const g = ""; - const r = ""; - - // boolean display - const autoRestart = GuildDB.autoRestart ? `${g}true` : `${r}false`; - const showKillfeedCoords = GuildDB.showKillfeedCoords ? `${g}true` : `${r}false`; - const showKillfeedWeapon = GuildDB.showKillfeedWeapon ? `${g}true` : `${r}false`; - const purchaseUAV = GuildDB.purchaseUAV ? `${g}true` : `${r}false`; - const purchaseEMP = GuildDB.purchaseEMP ? `${g}true` : `${r}false`; - const adminRoles = GuildDB.hasBotAdmin ? `${g}true` : `${r}false` - const excludedRoles = GuildDB.hasExcludedRoles ? `${g}true` : `${r}false`; - - // 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; - - // value display - const incomeLimiter = `${GuildDB.incomeLimiter} hours`; - const startingBalance = `$${GuildDB.startingBalance.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}`; - const uavPrice = `$${GuildDB.uavPrice.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}`; - const empPrice = `$${GuildDB.empPrice.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}`; - const combatLogTimer = `${GuildDB.combatLogTimer} minutes`; - - // Ugly below but kinda nice above - const settingsEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTitle('Current Guild Configurations') - .addFields( - { name: 'Guild ID', value: `${w}${f}${GuildDB.serverID}${w}`, inline: true }, - { name: 'Server Name', value: `${w}${f}${GuildDB.serverName}${w}`, inline: true }, - { name: 'Auto Restart', value: `${w}${a}${autoRestart}${w}`, inline: true }, - { name: 'UAVs Enabled', value: `${w}${a}${purchaseUAV}${w}`, inline: true }, - { name: 'EMPs Enabled', value: `${w}${a}${purchaseEMP}${w}`, inline: true }, - { name: 'Show Killfeed Coords', value: `${w}${a}${showKillfeedCoords}${w}`, inline: true }, - { name: 'Show Killfeed Weapons', value: `${w}${a}${showKillfeedWeapon}${w}`, inline: true }, - { name: 'Has Admin Rols', value: `${w}${a}${adminRoles}${w}`, inline: true }, - { name: 'Has Excluded Roles', value: `${w}${a}${excludedRoles}${w}`, inline: true }, - { name: 'Allowed Channels', value: `${channelsInfo}`, inline: true }, - { name: 'Killfeed Channel', value: `${killfeedChannel}`, inline: true }, - { name: 'Connection Logs Channel', value: `${connectionLogs}`, inline: true }, - { name: 'Player List Channel', value: `${activePlayers}`, inline: true }, - { name: 'Welcome Channel', value: `${welcomeChannel}`, inline: true }, - { name: 'Linked Gamertag Role', value: `${linkedGTRole}`, inline: true }, - { name: 'Member Role', value: `${memberRole}`, inline: true }, - { name: 'Income Limiter', value: `${w}${f}${incomeLimiter}${w}`, inline: true }, - { name: 'Starting Balance', value: `${w}${f}${startingBalance}${w}`, inline: true }, - { name: 'UAV Price', value: `${w}${f}${uavPrice}${w}`, inline: true }, - { name: 'EMP Price', value: `${w}${f}${empPrice}${w}`, inline: true }, - { name: 'Combat Log Timer', value: `${w}${f}${combatLogTimer}${w}`, inline: true }, - ); - - return interaction.send({ embeds: [settingsEmbed] }); - - case 'set_channel': - const channelType = args[0].options[0].value; - const channel = args[0].options[1].value; - - client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID},{$set: {[`server.${channelType}`]: channel}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - const successSetChannelEmbed = new EmbedBuilder() - .setDescription(`Successfully set <#${channel}> as the ${channelType} channel.`) - .setColor(client.config.Colors.Green); - - return interaction.send({ embeds: [successSetChannelEmbed] }); - - case 'linked_gt_role': - const linked_gt_role = args[0].options[0].value; - - client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID},{$set: {"server.linkedGamertagRole": linked_gt_role}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - const successLinkedGTRoleEmbed = new EmbedBuilder() - .setDescription(`Successfully set <@&${linked_gt_role}> to give to users who link their gamertag.`) - .setColor(client.config.Colors.Green); - - return interaction.send({ embeds: [successLinkedGTRoleEmbed] }); - - case 'member_role': - const member_role = args[0].options[0].value; - - client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID},{$set: {"server.memberRole": member_role}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - const successMemberRoleEmbed = new EmbedBuilder() - .setDescription(`Successfully set <@&${member_role}> to give to users who link they join.`) - .setColor(client.config.Colors.Green); - - return interaction.send({ embeds: [successMemberRoleEmbed] }); - - case 'starting_balance': - client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set: {"server.startingBalance":args[0].options[0].value}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successSetStartingBalanceEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`Successfully set $${args[0].options[0].value.toFixed(2)} as starting balance`); - - return interaction.send({ embeds: [successSetStartingBalanceEmbed] }); - - case 'income_role': - if (args[0].options[0].name== 'set') { - const incomeRoleId = args[0].options[0].options[0].value - - if (args[0].options[0].options[1].value <= 0) { - let errorIncomeAmount = new EmbedBuilder() - .setDescription('**Error Notice:** Amount cannot be $0 or less than $0.') - .setColor(client.config.Colors.Red); - - return interaction.send({ embeds: [errorIncomeAmount] }); - } - - const searchIndex = GuildDB.incomeRoles.findIndex((role) => role.role==incomeRoleId); - if (searchIndex == -1) { - const newIncome = { - role: incomeRoleId, - income: args[0].options[0].options[1].value, - } - - client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID}, {$push: {"server.incomeRoles":newIncome}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - } else { - client.dbo.collection("guilds").updateOne({ - "server.serverID": GuildDB.serverID, - "server.incomeRoles.role": incomeRoleId - }, - { - $set: { - "server.incomeRoles.$.income": args[0].options[0].options[1].value - } - }, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - } - const perform = searchIndex == -1 ? 'set' : 'updated'; - - const successIncomeRoleEmbed = new EmbedBuilder() - .setDescription(`Successfully ${perform} <@&${incomeRoleId}>'s income to $${args[0].options[0].options[1].value}`) - .setColor(client.config.Colors.Green); - - return interaction.send({ embeds: [successIncomeRoleEmbed] }); - - } else if (args[0].options[0].name== 'remove') { - const searchIndex = GuildDB.incomeRoles.findIndex((role) => role.role==incomeRoleId); - if (searchIndex == -1) { - const errorIncomeNotFoundEmbed = new EmbedBuilder() - .setDescription('**Error Notice:** Role not found') - .setColor(client.config.Colors.Red); - - return interaction.send({ embeds: [errorIncomeNotFoundEmbed] }); - } else { - const promptRemoveIncomeRole = new EmbedBuilder() - .setTitle(`Are you sure you want to remove this role as an income?`) - .setColor(client.config.Colors.Default) - - const optRemoveIncomeRole = new ActionRowBuilder() - .addComponents( - new ButtonBuilder() - .setCustomId(`RemoveIncomeRole-yes-${incomeRoleId}-${interaction.member.user.id}`) - .setLabel("Yes") - .setStyle(ButtonStyle.Danger), - new ButtonBuilder() - .setCustomId(`RemoveIncomeRole-no-${incomeRoleId}-${interaction.member.user.id}`) - .setLabel("No") - .setStyle(ButtonStyle.Success) - ) - - return interaction.send({ embeds: [promptRemoveIncomeRole], components: [optRemoveIncomeRole], flags: (1 << 6) }); - } - } - - case 'income_limiter': - client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set: {"server.incomeLimiter":args[0].options[0].value}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successIncomeLimiterEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`Successfully set **${args[0].options[0].value} hours** as the wait time to collect income.`); - - return interaction.send({ embeds: [successIncomeLimiterEmbed] }); - - case 'uav-price': - client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set: {"server.uavPrice":args[0].options[0].value}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successUAVPriceEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`Successfully set $${args[0].options[0].value.toFixed(2)} as UAV price`); - - return interaction.send({ embeds: [successUAVPriceEmbed] }); - - case 'emp-price': - client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set: {"server.empPrice":args[0].options[0].value}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successEMPPriceEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`Successfully set $${args[0].options[0].value.toFixed(2)} as EMP price`); - - return interaction.send({ embeds: [successEMPPriceEmbed] }); - - case 'combat-log-timer': - client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set: {"server.combatLogTimer":args[0].options[0].value}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successCobatLogTimerEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`Successfully set combat log timer to **${args[0].options[0].value.toFixed(0)} minutes.**`); - - return interaction.send({ embeds: [successCobatLogTimerEmbed] }); - - case 'toggle-uav-purchase': - const togggleUAVpurchase = args[0].options[0].value ? 1 : 0; - - client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set: {"server.purchaseUAV": togggleUAVpurchase}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successToggleUAVpurchaseEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`Users can ${togggleUAVpurchase ? 'now' : 'no longer'} purchase UAVs.`); - - return interaction.send({ embeds: [successToggleUAVpurchaseEmbed] }); - - case 'toggle-emp-purchase': - const togggleEMPpurchase = args[0].options[0].value ? 1 : 0; - - client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set: {"server.purchaseEMP": togggleEMPpurchase}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successToggleEMPpurchaseEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`Users can ${togggleUAVpurchase ? 'now' : 'no longer'} purchase EMPs.`); - - return interaction.send({ embeds: [successToggleEMPpurchaseEmbed] }); - - case 'killfeed': - const killfeed_configuration = args[0].options[0].name; - - if (killfeed_configuration == 'channel') { - - const channel = args[0].options[0].options[0].value; - - client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID},{$set: {'server.killfeedChannel': channel}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - const successConfigureKillfeedChannel = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`Successfully configured the killfeed channel to <#${channel}>`); - - return interaction.send({ embeds: [successConfigureKillfeedChannel] }); - - } else if (killfeed_configuration == 'show_coords') { - const showKillfeedCoordsConfiguration = args[0].options[0].options[0].value ? 1 : 0; - - client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID},{$set: {"server.showKillfeedCoords": showKillfeedCoordsConfiguration}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - const successConfigureShowKillfeedCoords = new EmbedBuilder() - .setDescription(`Successfully configured the killfeed to ${showKillfeedCoordsConfiguration ? 'show' : 'not show'} coordinates.`) - .setColor(client.config.Colors.Green); - - return interaction.send({ embeds: [successConfigureShowKillfeedCoords] }); - - } else if (killfeed_configuration == 'show_weapon') { - - const showKillfeedWeaponConfiguration = args[0].options[0].options[0].value ? 1 : 0; - - client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID},{$set: {"server.showKillfeedWeapon": showKillfeedWeaponConfiguration}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - const successConfigureShowKillfeedCoords = new EmbedBuilder() - .setDescription(`Successfully configured the killfeed to ${showKillfeedWeaponConfiguration ? 'show' : 'not show'} weapon icons.`) - .setColor(client.config.Colors.Green); - - return interaction.send({ embeds: [successConfigureShowKillfeedCoords] }); - - } - - case 'welcome_message_server_name': - const server_name = args[0].options[0].value; - - client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID},{$set: {"server.serverName":server_name}}, (err, res) => { - if (err) return client.sendInternalError(interacion, err); - }); - - const succcessUpdateServerName = new EmbedBuilder() - .setDescription(`Successfully configured the server name to **${server_name}** in the welcome message.`) - .setColor(client.config.Colors.Green); - - return interaction.send({ embeds: [succcessUpdateServerName] }); - - default: - return client.sendInternalError(interaction, 'There was an error parsing the config command'); - } - }, - }, - - Interactions: { - - RemoveAllowedChannels: { - run: async (client, interaction, GuildDB) => { - if (!interaction.customId.endsWith(interaction.member.user.id)) { - return interaction.reply({ - content: "This button is not for you", - flags: (1 << 6) - }) - } - let action = '' - if (interaction.customId.split('-')[1]=='yes') { - action = 'removed'; - client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID}, {$pull:{"server.allowedChannels": interaction.customId.split('-')[2]}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - } else if (interaction.customId.split('-')[1]=='no') action = 'kept'; - - const successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setTitle(`**Success**\n> Successfullly ${action} the channel.`) - - return interaction.update({ embeds: [successEmbed], components: [] }); - } - }, - - ClearAllowedChannels: { - run: async (client, interaction, GuildDB) => { - if (!interaction.customId.endsWith(interaction.member.user.id)) { - return interaction.reply({ - content: "This buttpm is not for you", - flags: (1 << 6) - }); - } - let action; - if (interaction.customId.split('-')[1] == 'yes') { - action = 'cleared'; - client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set:{"server.allowedChannels":[]}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }) - } else if (interaction.customId.split('-')[1] == 'no') action = 'kept'; - - const successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setTitle(`**Success**\n> Successfully ${action} all configured channels.`); - - return interaction.update({ embeds: [successEmbed], components: [] }); - } - }, - - RemoveBotAdminRole: { - run: async (client, interaction, GuildDB) => { - if (!interaction.customId.endsWith(interaction.member.user.id)) { - return ButtonInteraction.reply({ - content: "This button is not for you", - flags: (1 << 6) - }) - } - let action = ''; - let roleId = interaction.customId.split('-')[2]; - if (interaction.customId.split('-')[1]=='yes') { - action = 'removed'; - client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID}, {$pull: {"server.botAdminRoles": roleId}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - } else if (interaction.customId.split('-')[1]=='no') action = 'kept'; - - const successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Successfully ${action} <@&${roleId}> as the bot admin role.**`) - - return interaction.update({ embeds: [successEmbed], components: [] }); - } - }, - - RemoveIncomeRole: { - run: async (client, interaction, GuildDB) => { - if (!interaction.customId.endsWith(interaction.member.user.id)) { - return ButtonInteraction.reply({ - content: "This button is not for you", - flags: (1 << 6) - }) - } - let action = ''; - let roleId = interaction.customId.split('-')[2]; - if (interaction.customId.split('-')[1]=='yes') { - action = 'removed'; - let income = GuildDB.incemeRoles.find((i) => i.role == roleId); - client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID}, {$pull: {"server.incomeRoles": income}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - } else if (interaction.customId.split('-')[1]=='no') action = 'kept'; - - const successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Successfully ${action} <@&${roleId}> as an income role.**`) - - return interaction.update({ embeds: [successEmbed], components: [] }); - } - }, - - ResetSettings: { - run: async (client, interaction, GuildDB) => { - if (!interaction.customId.endsWith(interaction.member.user.id)) { - return ButtonInteraction.reply({ - content: "This button is not for you", - flags: (1 << 6) - }) - } - let action = ''; - if (interaction.customId.split('-')[1]=='yes') { - action = 'reset'; - 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); - }); - } else if (interaction.customId.split('-')[1]=='no') action = 'kept'; - - const successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setTitle(`Successfully ${action} guild configurations.`) - - return interaction.update({ embeds: [successEmbed], components: [] }); - } - } - } -} \ No newline at end of file diff --git a/commands/event.js b/commands/event.js deleted file mode 100644 index 0ef13d7..0000000 --- a/commands/event.js +++ /dev/null @@ -1,170 +0,0 @@ -const { EmbedBuilder, ActionRowBuilder, StringSelectMenuBuilder } = require('discord.js'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const bitfieldCalculator = require('discord-bitfield-calculator'); - -module.exports = { - name: "event", - debug: false, - global: false, - description: "Admin controlled events", - usage: "[event] [option]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [{ - name: "player-track", - description: "Track a player and announce location", - value: "player-track", - type: CommandOptions.SubCommand, - options: [{ - name: "gamertag", - description: "Gamertag of player", - value: "gamertag", - type: CommandOptions.String, - required: true, - }, - { - name: "time", - description: "Duration of tracking", - value: "time", - type: CommandOptions.Integer, - required: true, - choices: [ - { name: '10-minutes', value: 10 }, { name: '15-minutes', value: 15 }, { name: '20-minutes', value: 20 }, { name: '25-minutes', value: 25 }, - { name: '30-minutes', value: 30 }, { name: '60-minutes', value: 60 }, { name: '90-minutes', value: 90 }, { name: '120-minutes', value: 120 }, - ] - }, - { - name: "event-name", - description: "Name of the event", - value: "event-name", - type: CommandOptions.String, - required: true, - }, - { - name: "channel", - description: "Channel to post tracking data", - value: "channel", - type: CommandOptions.Channel, - channel_types: [0], // Restrict to text channel - required: true, - }, { - name: "role", - description: "Optional role to ping", - value: "role", - type: CommandOptions.Role, - required: false, - }] - }, { - name: "delete", - description: "Delete an active event", - value: "delete", - type: CommandOptions.SubCommand - }], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - 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)) { - 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."); - - return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); - } - - const permissions = bitfieldCalculator.permissions(interaction.member.permissions); - let canUseCommand = false; - - if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; - 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.' }); - - let events = GuildDB.events; - - 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 \`.`)] }); - - let event = { - type: args[0].name, - name: args[0].options[2].value, - gamertag: args[0].options[0].value, - channel: args[0].options[3].value, - role: args[0].options[4] ? args[0].options[4].value : null, - time: args[0].options[1].value, - creationDate: new Date(), - }; - - events.push(event); - - client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { - $set: { - "server.events": events - } - }, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - const successCreatePlayerTrack = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`**Success:** Successfully created **${event.name}** that will last **${event.time} minutes.**`) - - return interaction.send({ embeds: [successCreatePlayerTrack] }); - - } else if (args[0].name == 'delete') { - if (GuildDB.events.length == 0) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription('**Notice:** No Existing Events to Delete.')] }); - - let events = new StringSelectMenuBuilder() - .setCustomId(`DeleteEvent-${interaction.member.user.id}`) - .setPlaceholder(`Select an Event to Delete.`) - - for (let i = 0; i < GuildDB.events.length; i++) { - events.addOptions({ - label: GuildDB.events[i].name, - description: `Delete this Event`, - value: GuildDB.events[i].name - }); - } - - const eventsOptions = new ActionRowBuilder().addComponents(events); - - return interaction.send({ components: [eventsOptions], flags: (1 << 6) }); - } - } - }, - - Interactions: { - - DeleteEvent: { - run: async(client, interaction, GuildDB) => { - if (!interaction.customId.endsWith(interaction.member.user.id)) - return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) }); - - let event = GuildDB.events.find(e => e.name == interaction.values[0]); - - client.dbo.collection('guilds').updateOne({ 'server.serverID': GuildDB.serverID }, { - $pull: { - 'server.events': event, - } - }, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Success:** Successfully Deleted **${event.name} Event**`); - - return interaction.update({ embeds: [successEmbed], components: [] }); - } - } - } -} \ No newline at end of file diff --git a/commands/excluded.js b/commands/excluded.js deleted file mode 100644 index 2e8ebbf..0000000 --- a/commands/excluded.js +++ /dev/null @@ -1,46 +0,0 @@ -const { EmbedBuilder } = require('discord.js'); - -module.exports = { - name: "excluded", - debug: false, - global: false, - description: "View a list of excluded roles", - usage: "", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - run: async (client, interaction, args, { GuildDB }) => { - if (GuildDB.excludedRoles.length == 0) { - let noExcludes = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTitle('Excluded Roles') - .setDescription('> There have been no excluded roles'); - - return interaction.send({ embeds: [noExcludes] }); - } - - let excluded = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTitle('Excluded Roles') - - let des = '*These roles you cannot use to claim an armband.*'; - for (let i = 0; i < GuildDB.excludedRoles.length; i++) { - des += `\n> <@&${GuildDB.excludedRoles[i]}>`; - } - excluded.setDescription(des); - - return interaction.send({ embeds: [excluded] }); - }, - }, - Interactions: {} -} diff --git a/commands/factions.js b/commands/factions.js deleted file mode 100644 index 11c7460..0000000 --- a/commands/factions.js +++ /dev/null @@ -1,87 +0,0 @@ -const { EmbedBuilder } = require('discord.js'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const { Armbands } = require('../database/armbands.js'); - -module.exports = { - name: "factions", - debug: false, - global: false, - description: "View the armband of a faction", - usage: "[role]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [{ - name: "faction_role", - description: "View a specific faction's armband by role", - value: "faction_role", - type: CommandOptions.Role, - required: false, - }], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - run: async (client, interaction, args, { GuildDB }) => { - if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) - return interaction.send({ content: `You are not allowed to use the bot in this channel.`, flags: (1 << 6) }); - - // Return list of factions and their armband. - if (!args) { - - let factions = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTitle('Factions & Armbands') - - let description = ''; - - if (GuildDB.usedArmbands.length == 0) { - description = '> There are no factions that have claimed armbands.'; - } else { - for (const [factionID, data] of Object.entries(GuildDB.factionArmbands)) { - if (description == "") description += `> <@&${factionID}> - ${data.armband}`; - else description += `\n> <@&${factionID}> - *${data.armband}*`; - } - } - - factions.setDescription(description); - - return interaction.send({ embeds: [factions] }); - } - - // Else return specific faction and their armband. - if (!GuildDB.factionArmbands[args[0].value]) { - return interaction.send({ - embeds: [ - new EmbedBuilder() - .setColor(client.config.Colors.Yellow) - .setDescription(`**Notice:**\n> The faction <@&${args[0].value}> has not claimed an armband.`) - ], - flags: (1 << 6) - }); - } - - let armbandURL; - - for (let i = 0; i < Armbands.length; i++) { - if (Armbands[i].name == GuildDB.factionArmbands[args[0].value].armband) { - armbandURL = Armbands[i].url; - break; - } - } - - const faction = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`> Faction <@&${GuildDB.factionArmbands[args[0].value].faction}> - ***${GuildDB.factionArmbands[args[0].value].armband}***`) - .setImage(armbandURL); - - return interaction.send({ embeds: [faction] }); - }, - }, - Interactions: {} -} diff --git a/commands/gamertag-link.js b/commands/gamertag-link.js deleted file mode 100644 index a078952..0000000 --- a/commands/gamertag-link.js +++ /dev/null @@ -1,128 +0,0 @@ -const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const { UpdatePlayer } = require('../database/player'); - -module.exports = { - name: "gamertag-link", - debug: false, - global: false, - description: "Connect DayZ stats to your Discord", - usage: "[gamertag]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [{ - name: "gamertag", - description: "Gamertag of player", - value: "gamertag", - type: CommandOptions.String, - required: true, - }], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - 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)) { - 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."); - - return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); - } - - 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 (client.exists(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?`) - - const opt = new ActionRowBuilder() - .addComponents( - new ButtonBuilder() - .setCustomId(`OverwriteGamertag-yes-${args[0].value}-${interaction.member.user.id}`) - .setLabel("Yes") - .setStyle(ButtonStyle.Success), - new ButtonBuilder() - .setCustomId(`OverwriteGamertag-no-${args[0].value}-${interaction.member.user.id}`) - .setLabel("No") - .setStyle(ButtonStyle.Secondary) - ) - - return interaction.send({ embeds: [warnGTOverwrite], components: [opt] }); - } - - playerStat.discordID = interaction.member.user.id; - - await UpdatePlayer(client, playerStat, interaction); - - let member = interaction.guild.members.cache.get(interaction.member.user.id); - if (client.exists(GuildDB.linkedGamertagRole)) { - let role = interaction.guild.roles.cache.get(GuildDB.linkedGamertagRole); - member.roles.add(role); - } - - if (client.exists(GuildDB.memberRole)) { - let role = interaction.guild.roles.cache.get(GuildDB.memberRole); - member.roles.add(role); - } - - let connectedEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`Successfully connected \` ${playerStat.gamertag} \` as your gamertag.`); - - return interaction.send({ embeds: [connectedEmbed] }) - }, - }, - - Interactions: { - - OverwriteGamertag: { - run: async(client, interaction, GuildDB) => { - 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 = await client.dbo.collection("players").findOne({"gamertag": interaction.customId.split('-')[2]}); - - playerStat.discordID = interaction.member.user.id; - - await UpdatePlayer(client, playerStat, interaction); - - let member = interaction.guild.members.cache.get(interaction.member.user.id); - if (client.exists(GuildDB.linkedGamertagRole)) { - let role = interaction.guild.roles.cache.get(GuildDB.linkedGamertagRole); - member.roles.add(role); - } - - if (client.exists(GuildDB.memberRole)) { - let role = interaction.guild.roles.cache.get(GuildDB.memberRole); - member.roles.add(role); - } - - let connectedEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`Successfully connected \` ${playerStat.gamertag} \` as your gamertag.`); - - return interaction.update({ embeds: [connectedEmbed], components: [] }); - - } else { - const cancel = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription('**Canceled**\n> The gamertag link will not be overwritten'); - - return interaction.update({ embeds: [cancel], components: [] }); - } - } - } - - } -} \ No newline at end of file diff --git a/commands/gamertag-unlink.js b/commands/gamertag-unlink.js deleted file mode 100644 index b52b6f8..0000000 --- a/commands/gamertag-unlink.js +++ /dev/null @@ -1,85 +0,0 @@ -const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle} = require('discord.js'); -const { UpdatePlayer } = require('../database/player'); - -module.exports = { - name: "gamertag-unlink", - debug: false, - global: false, - description: "Disconnect DayZ stats from your Discord", - usage: "", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - 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)) { - 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."); - - return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); - } - - 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.`)] }); - - const warnGTOverwrite = new EmbedBuilder() - .setColor(client.config.Colors.Yellow) - .setDescription(`**Notice:**\n> Are you sure you want to unlink your gamertag? This will limit some automatic features.`); - - const opt = new ActionRowBuilder() - .addComponents( - new ButtonBuilder() - .setCustomId(`UnlinkGamertag-yes-${interaction.member.user.id}`) - .setLabel("Yes") - .setStyle(ButtonStyle.Success), - new ButtonBuilder() - .setCustomId(`UnlinkGamertag-no-${interaction.member.user.id}`) - .setLabel("No") - .setStyle(ButtonStyle.Secondary) - ) - - return interaction.send({ embeds: [warnGTOverwrite], components: [opt] }); - }, - }, - - Interactions: { - - UnlinkGamertag: { - run: async(client, interaction, GuildDB) => { - 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 = await client.dbo.collection("players").findOne({"discordID": interaction.member.user.id}); - - playerStat.discordID = ""; - - await UpdatePlayer(client, playerStat, interaction); - - let connectedEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`Successfully unlinked \` ${playerStat.gamertag} \` as your gamertag.`); - - return interaction.update({ embeds: [connectedEmbed], components: [] }); - - } else { - const cancel = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription('**Canceled**\n> The gamertag unlink will not processed.'); - - return interaction.update({ embeds: [cancel], components: [] }); - } - } - } - } -} \ No newline at end of file diff --git a/commands/help.js b/commands/help.js deleted file mode 100644 index a0d6d1e..0000000 --- a/commands/help.js +++ /dev/null @@ -1,161 +0,0 @@ -const { EmbedBuilder } = require("discord.js"); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const package = require("../package"); - -module.exports = { - name: "help", - debug: false, - global: true, - description: "Get information on a specific command", - usage: "[option]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [ - { - name: "commands", - description: "List all commands", - value: "commands", - type: CommandOptions.SubCommand, - options: [{ - name: "command", - description: "Get information on a specific command", - value: "command", - type: CommandOptions.String, - required: false, - }] - }, - { - name: "support", - description: "Get support for Application", - value: "support", - type: CommandOptions.SubCommand, - }, - { - name: "credits", - description: "DayZ.R Bot Credits", - value: "credits", - type: CommandOptions.SubCommand, - }, - { - name: "stats", - description: "Current Bot Statistics", - value: "stats", - type: CommandOptions.SubCommand, - } - ], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - - run: async (client, interaction, args, {GuildDB}, start) => { - if (args[0].name == 'commands') { - let Commands = client.commands.filter((cmd) => { - return !cmd.debug - }).map((cmd) => - `\`/${cmd.name}${cmd.usage ? " " + cmd.usage : ""}\` - ${cmd.description}` - ); - - let Embed = new EmbedBuilder() - .setTitle('Commands') - .setColor(client.config.Colors.Default) - .setDescription(`${Commands.join("\n")} - - DayZR Bot Version: v${client.config.Version}`); - if (!args[0].options[0]) return interaction.send({ embeds: [Embed] }); - else { - let cmd = - client.commands.get(args[0].options[0].value) || - client.commands.find( - (x) => x.aliases && x.aliases.includes(args[0].options[0].value) - ); - if (!cmd) - return interaction.send({ content: `❌ | Unable to find that command.` }); - - let embed = new EmbedBuilder() - .setDescription(cmd.description) - .setColor(client.config.Colors.Green) - .setTitle(`How to use /${cmd.name} command`) - - if (cmd.SlashCommand.options && cmd.SlashCommand.options[0].type == 1) { - let description = `${cmd.description}\n\n**Usage**\n`; - - for (let i = 0; i < cmd.SlashCommand.options.length; i++) { - if (cmd.SlashCommand.options[i].type == 1) { - let param = ''; - if (cmd.SlashCommand.options[i].options) { - param = cmd.SlashCommand.options[i].options.length > 0 ? ' ' : ''; - for (let j = 0; j < cmd.SlashCommand.options[i].options.length; j++) { - if (cmd.SlashCommand.options[i].options[j].required) param += `[${cmd.SlashCommand.options[i].options[j].name}] ` - } - } - description += `\`/${cmd.name} ${cmd.SlashCommand.options[i].name}${param}\`\n${cmd.SlashCommand.options[i].description}\n\n` - } - } - embed.setDescription(description); - } else embed.addFields({ name: "Usage", value: `\`/${cmd.name}\`${cmd.usage ? " " + cmd.usage : ""}`, inline: true }) - - return interaction.send({ embeds: [embed] }); - } - } else if (args[0].name == 'support') { - const supportEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`**__DayZ.R Bot Support__** - - Are you experiencing troubles with the DayZ.R Bot? - Do you have questions or concerns? - Do you require help to use the bot? - Do you have a feature you'd like to see? - - Join the support server to have all your needs fulfilled. - ╚➤ ${client.config.SupportServer} - `) - - return interaction.send({ embeds: [supportEmbed] }); - - } else if (args[0].name == 'credits') { - const creditsEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTitle('DayzRBot Credits') - .setDescription(` - **Bot Author:** mcdazzzled - **Github:** https://github.com/SowinskiBraeden/dayz-reforger - - ${client.config.SupportServer} - `); - - return interaction.send({ embeds: [creditsEmbed] }) - } else if (args[0].name == 'stats') { - const end = new Date().getTime(); - - const totalGuilds = await client.shard.fetchClientValues("guilds.cache.size").then(results => { - return results.reduce((acc, guildCount) => acc + guildCount, 0); - }); - - const totalUsers = await client.shard.broadcastEval(c => { - c.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0); - }).then(data => data.reduce((acc, memberCount) => acc + memberCount, 0)); - - const stats = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTitle('DayZ Reforger Bot Statistics') - .addFields( - { name: 'Guilds', value: `\`\`\`${totalGuilds}\`\`\``, inline: true }, - { name: 'Users', value: `\`\`\`${totalUsers}\`\`\``, inline: true }, - { name: 'Latency', value: `\`\`\`${end - start}ms\`\`\``, inline: true }, - { name: 'Uptime', value: `\`\`\`${client.secondsToDhms(process.uptime().toFixed(2))}\`\`\``, inline: true }, - { name: 'Bot Version', value: `\`\`\`${client.config.Dev} v${client.config.Version}\`\`\``, inline: true }, - { name: 'Discord Version', value: `\`\`\`Discord.js ${package.dependencies["discord.js"]}\`\`\``, inline: true }, - ); - - return interaction.send({ embeds: [stats] }) - } - }, - }, -}; \ No newline at end of file diff --git a/commands/leaderboard.js b/commands/leaderboard.js deleted file mode 100644 index 2931301..0000000 --- a/commands/leaderboard.js +++ /dev/null @@ -1,135 +0,0 @@ -const { EmbedBuilder } = require('discord.js'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; - -module.exports = { - name: "leaderboard", - debug: false, - global: false, - description: "View server stats leaderboard", - usage: "[category] [limit]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [{ - name: "category", - description: "Leaderboard Category", - value: "category", - type: CommandOptions.String, - required: true, - choices: [ - { name: "Money", value: "money" }, - { name: "Total Time Played", value: "totalSessionTime" }, - { name: "Longest Game Session", value: "longestSessionTime" }, - { name: "Kills", value: "kills" }, - { name: "Kill Streak", value: "killStreak" }, - { name: "Best Kill Streak", value: "bestKillStreak" }, - { name: "Deaths", value: "deaths" }, - { name: "Death Streak", value: "deathStreak" }, - { name: "Worst Death Streak", value: "worstDeathStreak" }, - { name: "Longest Kill", value: "longestKill" }, - { name: "KDR", value: "KDR" }, - { name: "Server Connections", value: "connections" }, - { name: "Shots Landed", value: "shotsLanded" }, - { name: "Times Shot", value: "timesShot" }, - { name: "Combat Rating", value: "combatRating" }, - ] - }, { - name: "limit", - description: "Leaderboard limit", - value: "limit", - type: CommandOptions.Integer, - min_value: 1, - max_value: 25, - required: true, - }], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - 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)) { - 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."); - - return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); - } - - const category = args[0].value; - const limit = args[1].value; - - let leaderboard = []; - if (category == 'money') { - - leaderboard = await client.dbo.collection("users").aggregate([ - { $sort: { [`user.guilds.${GuildDB.serverID}.balance`]: -1 } } - ]).toArray(); - - } else { - - leaderboard = await client.dbo.collection("players").aggregate([ - { $sort: { [`${category}`]: -1 } } - ]).toArray(); - - } - - let leaderboardEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default); - - let title = category == 'kills' ? "Total Kills Leaderboard" : - category == 'killStreak' ? "Current Killstreak Leaderboard" : - category == 'bestKillStreak' ? "Best Killstreak Leaderboard" : - category == 'deaths' ? "Total Deaths Leaderboard" : - category == 'deathStreak' ? "Current Deathstreak Leaderboard" : - category == 'worstDeathStreak' ? "Worst Deathstreak Leaderboard" : - category == 'longestKill' ? "Longest Kill Leaderboard" : - category == 'money' ? "Money Leaderboard" : - category == 'totalSessionTime' ? "Total Time Played" : - category == 'longestSessionTime' ? "Longest Game Session" : - category == 'KDR' ? "Kill Death Ratio" : - category == 'connections' ? "Times Connected" : - category == 'shotsLanded' ? "Shots Landed" : - category == 'timesShot' ? "Times Shot" : - category == 'combatRating' ? "Combat Rating" : 'N/A Error'; - - leaderboardEmbed.setTitle(`**${title} - DayZ Reforger**`); - - let des = ``; - for (let i = 0; i < limit; i++) { - if (leaderboard.length < limit && i == leaderboard.length) break; - - let stats = category == 'kills' ? `${leaderboard[i].kills} Kill${(leaderboard[i].kills>1||leaderboard[i].kills==0)?'s':''}` : - category == 'killStreak' ? `${leaderboard[i].killStreak} Player Killstreak` : - category == 'bestKillStreak' ? `${leaderboard[i].bestKillStreak} Player Killstreak` : - category == 'deaths' ? `${leaderboard[i].deaths} Death${leaderboard[i].deaths>1||leaderboard[i].deaths==0?'s':''}` : - category == 'deathStreak' ? `${leaderboard[i].deathStreak} Deathstreak` : - category == 'worstDeathstreak' ? `${leaderboard[i].worstDeathStreak} Deathstreak` : - category == 'longestKill' ? `${leaderboard[i].longestKill}m` : - category == 'money' ? `$${(leaderboard[i].user.guilds[GuildDB.serverID].balance).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}` : - category == 'totalSessionTime' ? `**Total:** ${client.secondsToDhms(leaderboard[i].totalSessionTime)}\n> **Last Session:** ${client.secondsToDhms(leaderboard[i].lastSessionTime)}` : - category == 'longestSessionTime' ? `**Longest Game Session:** ${client.secondsToDhms(leaderboard[i].longestSessionTime)}` : - category == 'KDR' ? `**KDR: ${leaderboard[i].KDR.toFixed(2)}**` : - category == 'connection' ? `**Connections: ${leaderboard[i].connections}**` : - category == 'combatRating' ? `**Combat Rating:** ${leaderboard[i].combatRating}` : - category == 'shotsLanded' ? `**Shots Landed:** ${leaderboard[i].shotsLanded}` : - category == 'timesShot' ? `**Times Shot:** ${leaderboard[i].timesShot}` : 'N/A Error'; - - if (category == 'money') des += `**${i+1}.** <@${leaderboard[i].user.userID}> - **${stats}**\n` - else if (category == 'totalSessionTime' || category == 'longestSessionTime' || category == 'combatRating') { - tag = leaderboard[i].discordID != "" ? `<@${leaderboard[i].discordID}>` : leaderboard[i].gamertag; - des += `**${i+1}.** ${tag}\n> ${stats}\n\n`; - } else leaderboardEmbed.addFields({ name: `**${i+1}. ${leaderboard[i].gamertag}**`, value: `**${stats}**`, inline: true }); - } - - if (['money', 'totalSessionTime', 'longestSessionTime', 'combatRating'].includes(category)) leaderboardEmbed.setDescription(des); - - return interaction.send({ embeds: [leaderboardEmbed] }); - }, - }, -} diff --git a/commands/location.js b/commands/location.js deleted file mode 100644 index 2c4e3e6..0000000 --- a/commands/location.js +++ /dev/null @@ -1,50 +0,0 @@ -const { EmbedBuilder } = require('discord.js'); -const { nearest } = require('../database/destinations'); - -module.exports = { - name: "location", - debug: false, - global: false, - description: "Find your last known location", - usage: "", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - 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)) { - 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."); - - return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); - } - - 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)}); - - console.log(true); - - let newDt = await client.getDateEST(playerStat.time); - let unixTime = Math.floor(newDt.getTime()/1000); - - const destination = nearest(playerStat.pos, GuildDB.Nitrado.Mission); - - let lastLocation = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`**Location - **\nYour last location was detected at **[${playerStat.pos[0]}, ${playerStat.pos[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${playerStat.pos[0]};${playerStat.pos[1]})**\n${destination}`) - - return interaction.send({ embeds: [lastLocation], flags: (1 << 6) }); - }, - }, -} \ No newline at end of file diff --git a/commands/lookup.js b/commands/lookup.js deleted file mode 100644 index 9c23e42..0000000 --- a/commands/lookup.js +++ /dev/null @@ -1,90 +0,0 @@ -const { EmbedBuilder } = require('discord.js'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; - -module.exports = { - name: "lookup", - debug: false, - global: false, - description: "Search for a user's Discord or Gamertag", - usage: "[option] [parameter]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [{ - name: "discord", - description: "Find a Discord user from a Gamertag", - value: "discord", - type: CommandOptions.SubCommand, - options: [{ - name: "gamertag", - description: "Gamertag of player", - value: "gamertag", - type: CommandOptions.String, - required: true, - }] - }, { - name: "gamertag", - description: "Find a Gamertag from a Discord user", - value: "gamertag", - type: CommandOptions.SubCommand, - options: [{ - name: "user", - description: "Discord User", - value: "user", - type: CommandOptions.User, - required: true, - }] - }], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - 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)) { - 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."); - - return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); - } - - if (args[0].name == 'discord') { - - 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)) { - const found = new EmbedBuilder() - .setColor(client.config.Colors.Yellow) - .setDescription(`**Record Found**\n> The gamertag \` ${playerStat.gamertag} \` is currently linked to <@${playerStat.discordID}>.`) - - return interaction.send({ embeds: [found] }); - } - - let notFound = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`**Record Not Found**\n The gamertag \` ${playerStat.gamertag} \` currently has no linked Discord account.`); - - return interaction.send({ embeds: [notFound] }) - - } else if (args[0].name == 'gamertag') { - - let playerStat = await client.dbo.collection("players").findOne({"discordID": args[0].options[0].value}); - if (playerStat == undefined) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** The user <@${args[0].options[0].value}> has not linked a gamertag.`)] }); - - const found = new EmbedBuilder() - .setColor(client.config.Colors.Yellow) - .setDescription(`**Record Found**\n> The user <@${playerStat.discordID}> has linked the gamertag \` ${playerStat.gamertag} \`.`) - - return interaction.send({ embeds: [found] }); - - } - }, - }, -} \ No newline at end of file diff --git a/commands/player-list.js b/commands/player-list.js deleted file mode 100644 index 25b3307..0000000 --- a/commands/player-list.js +++ /dev/null @@ -1,81 +0,0 @@ -const { FetchServerSettings } = require('../util/NitradoAPI'); -const { Missions } = require('../database/destinations'); -const { EmbedBuilder } = require('discord.js'); - -module.exports = { - name: "player-list", - debug: false, - global: false, - description: "Get current online players", - usage: "", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - 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)) { - 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."); - - return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); - } - - await interaction.deferReply(); - - const data = await FetchServerSettings(GuildDB.Nitrado, client, 'commands/player-list.js'); // Fetch server status - const e = data && data !== 1; // Check if data exists - - const hostname = e ? data.data.gameserver.settings.config.hostname : 'N/A'; - const map = e ? Missions[data.data.gameserver.settings.config.mission] : 'N/A'; - const status = e ? data.data.gameserver.status : 'N/A'; - const slots = e ? data.data.gameserver.slots : 'N/A'; - const playersOnline = e ? data.data.gameserver.query.player_current : 'N/A'; - - const Statuses = { - "started": {emoji: "🟢", text: "Active"}, - "stopped": {emoji: "🔴", text: "Stopped"}, - "restarting": {emoji: "↻", text: "Restarting"}, - }; - - const emojiStatus = e ? Statuses[status].emoji : "❓"; - const textStatus = e ? Statuses[status].text : "Unknown Status"; - - let activePlayers = await client.dbo.collection("players").find({"connected": true}).toArray(); - - let des = activePlayers.length > 0 ? `` : `**No Players Online**`; - for (let i = 0; i < activePlayers.length; i++) { - des += `**- ${activePlayers[i].gamertag}**\n`; - } - - const nodes = activePlayers.length === 0; - const serverEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTitle(`Online List - \` ${playersOnline === undefined ? activePlayers.length : playersOnline} \` Player${playersOnline !== 1 ? 's' : ''} Online`) - .addFields( - { name: 'Server:', value: `\` ${hostname} \``, inline: false }, - { name: 'Map:', value: `\` ${map} \``, inline: true }, - { name: 'Status:', value: `\` ${emojiStatus} ${textStatus} \``, inline: true }, - { name: 'Slots:', value: `\` ${slots} \``, inline: true } - ); - - const activePlayersEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTimestamp() - .setTitle(`Players Online:`) - .setDescription(des || (nodes ? "No Players Online :(" : "")); - - return interaction.editReply({ embeds: [serverEmbed, activePlayersEmbed] }); - }, - }, -} \ No newline at end of file diff --git a/commands/player-stats.js b/commands/player-stats.js deleted file mode 100644 index 9d67edb..0000000 --- a/commands/player-stats.js +++ /dev/null @@ -1,325 +0,0 @@ -const { EmbedBuilder } = require('discord.js'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const { insertPVPstats } = require('../database/player'); - -module.exports = { - name: "player-stats", - debug: false, - global: false, - description: "Check player statistics", - usage: "[category] [user or gamertag]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [{ - name: "category", - description: "Leaderboard Category", - value: "category", - type: CommandOptions.String, - required: true, - choices: [ - { name: "Money", value: "money" }, - { name: "Total Time Played", value: "totalSessionTime" }, - { name: "Longest Game Session", value: "longestSessionTime" }, - { name: "Kills", value: "kills" }, - { name: "Kill Streak", value: "killStreak" }, - { name: "Best Kill Streak", value: "bestKillStreak" }, - { name: "Deaths", value: "deaths" }, - { name: "Death Streak", value: "deathStreak" }, - { name: "Worst Death Streak", value: "worstDeathStreak" }, - { name: "Longest Kill", value: "longestKill" }, - { name: "KDR", value: "KDR" }, - { name: "Server Connections", value: "connections" }, - { name: "Shots Landed", value: "shotsLanded" }, - { name: "Times Shot", value: "timesShot" }, - { name: "Combat Rating", value: "combatRating" } - ] - }, { - name: "discord", - description: "discord user to lookup stats", - value: "discord", - type: CommandOptions.User, - required: false, - }, { - name: "gamertag", - description: "gamertag to lookup stats", - type: CommandOptions.String, - required: false, - }], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - 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)) { - 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."); - - return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); - } - - let category = args[0].value; - let discord = args[1] && args[1].name == 'discord' ? args[1].value : undefined; - let gamertag = args[1] && args[1].name == 'gamertag' ? args[1].value : undefined; - let self = !discord && !gamertag; // searching for self if both discord and gamertag are undefined; - - let query; - let leaderboard; - let leaderboardPos; - - if (category == 'money') { - - leaderboard = await client.dbo.collection("users").aggregate([ - { $sort: { [`user.guilds.${GuildDB.serverID}.balance`]: -1 } } - ]).toArray(); - - if (discord) query = leaderboard.find(u => u.user.userID == discord); // Searching by discord user - 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.`)] }); - leaderboardPos = leaderboard.indexOf(query); - - } else { - - leaderboard = await client.dbo.collection("players").aggregate([ - { $sort: { [`${category}`]: -1 } } - ]).toArray(); - - if (discord) query = leaderboard.find(s => s.discordID == discord); // Searching by discord user - 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.`)] }); - leaderboardPos = leaderboard.indexOf(query); - - } - leaderboardPos++; // add one to leaderboard pos because it is index in array and we want index zero to be num. one, index one to be num. two, etc. etc. - - let title = category == 'kills' ? "Total Kills" : - category == 'killStreak' ? "Current Killstreak" : - category == 'bestkillStreak' ? "Best Killstreak" : - category == 'deaths' ? "Total Deaths" : - category == 'deathStreak' ? "Current Deathstreak" : - category == 'worstDeathStreak' ? "Worst Deathstreak" : - category == 'longestKill' ? "Longest Kill" : - category == 'money' ? "Total Money" : - category == 'totalSessionTime' ? "Total Time Played" : - category == 'longestSessionTime' ? "Longest Game Session" : - category == 'KDR' ? "Kill Death Ratio" : - category == 'connections' ? "Times Connected" : - category == 'shotsLanded' ? "Shots Landed" : - category == 'timesShot' ? "Times Shot" : - category == 'combatRating' ? "Combat Rating" : 'N/A Error'; - - let statsEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default); - - let tag = !discord && !gamertag ? `<@${interaction.member.user.id}>` : - !gamertag && discord ? `<@${discord}>` : - !discord && gamertag ? `**${gamertag}**` : `N/A Error`; - - statsEmbed.setDescription(`${tag}'s ${title}`); - - let stats = category == 'kills' ? `${query.kills} Kill${(query.kills>1||query.kills==0)?'s':''}` : - category == 'killStreak' ? `${query.killStreak} Player Killstreak` : - category == 'bestKillStreak' ? `${query.bestKillStreak} Player Killstreak` : - category == 'deaths' ? `${query.deaths} Death${query.deaths>1||query.deaths==0?'s':''}` : - category == 'deathStreak' ? `${query.deathStreak} Deathstreak` : - category == 'worstDeathStreak' ? `${query.worstDeathStreak} Deathstreak` : - category == 'longestKill' ? `${query.longestKill}m` : - category == 'money' ? `$${(query.user.guilds[GuildDB.serverID].balance).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}` : - category == 'KDR' ? `${query.KDR.toFixed(2)} KDR` : - category == 'connections' ? `${query.connections} connections` : - category == 'combatRating' ? `${query.combatRating}` : 'N/A Error'; - - statsEmbed.addFields({ name: 'Leaderboard Position', value: `# ${leaderboardPos}`, inline: true }); - - if ((category == 'shotsLanded' || category == 'timesShot') && !client.exists(query.shotsLanded)) query = insertPVPstats(query); - - if (category == 'totalSessionTime') { - statsEmbed.addFields( - { name: 'Total Time Played', value: client.secondsToDhms(query.totalSessionTime), inline: true }, - { name: 'Last Session Time', value: client.secondsToDhms(query.lastSessionTime), inline: true } - ); - } else if (category == 'longestSessionTime') { - statsEmbed.addFields( - { name: 'Longest Game Session', value: client.secondsToDhms(query.longestSessionTime), inline: true }, - { name: 'Last Session Time', value: client.secondsToDhms(query.lastSessionTime), inline: true } - ); - } else if (category == 'shotsLanded') { - statsEmbed.addFields( - { name: 'Total Shots Landed', value: `${query.shotsLanded}`, inline: true }, - { name: 'View Weapon stats', value: ``, inline: true } - ); - - const chart = { - type: 'bar', - data: { - labels: ['Head', 'Torso', 'Left Arm', 'Right Arm', 'Left Leg', 'Right Leg'], - datasets: [{ - label: 'Shots Landed', - data: [ - query.shotsLandedPerBodyPart.Head, - query.shotsLandedPerBodyPart.Torso, - query.shotsLandedPerBodyPart.LeftArm, - query.shotsLandedPerBodyPart.RightArm, - query.shotsLandedPerBodyPart.LeftLeg, - query.shotsLandedPerBodyPart.RightLeg, - ], - }], - }, - options: { - legend: { - labels: { - fontSize: 14, - fontStyle: 'bold', - } - }, - scales: { - yAxes: [{ ticks: { fontStyle: 'bold' } }], - xAxes: [{ ticks: { fontStyle: 'bold' } }], - }, - }, - }; - - const encodedChart = encodeURIComponent(JSON.stringify(chart)); - const chartURL = `https://quickchart.io/chart?bkg=${encodeURIComponent("#ded8d7")}&c=${encodedChart}`; - - statsEmbed.setImage(chartURL); - - } else if (category == 'timesShot') { - statsEmbed.addFields( - { name: 'Total Times Shot', value: `${query.timesShot}`, inline: true }, - { name: 'View Weapon stats', value: ``, inline: true }, - ); - - const chart = { - type: 'bar', - data: { - labels: ['Head', 'Torso', 'Left Arm', 'Right Arm', 'Left Leg', 'Right Leg'], - datasets: [{ - label: 'Times Shot', - data: [ - query.timesShotPerBodyPart.Head, - query.timesShotPerBodyPart.Torso, - query.timesShotPerBodyPart.LeftArm, - query.timesShotPerBodyPart.RightArm, - query.timesShotPerBodyPart.LeftLeg, - query.timesShotPerBodyPart.RightLeg, - ], - }], - }, - options: { - legend: { - labels: { - fontSize: 14, - fontStyle: 'bold', - } - }, - scales: { - yAxes: [{ ticks: { fontStyle: 'bold' } }], - xAxes: [{ ticks: { fontStyle: 'bold' } }], - }, - }, - }; - - const encodedChart = encodeURIComponent(JSON.stringify(chart)); - const chartURL = `https://quickchart.io/chart?bkg=${encodeURIComponent("#ded8d7")}&c=${encodedChart}`; - - statsEmbed.setImage(chartURL); - - } else if (category == 'combatRating') { - - let data = query.combatRatingHistory; - - 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; - - statsEmbed.addFields( - { name: 'Combat Rating', value: `${query.combatRating}`, inline: true }, - { name: 'Highest Rating', value: `${query.highestCombatRating}`, inline: true }, - { name: 'Lowest Rating', value: `${query.lowestCombatRating}`, inline: true }, - ); - - if (data.length == 1) data.push(query.combatRating) // Make array 2 long for a straight line in the graph - - const chart = { - type: 'line', - data: { - labels: new Array(data.length).fill(' ', 0, data.length), - datasets: [{ - data: data, - label: `Last ${data.length} Combat Ratings`, - }], - }, - options: { - legend: { - labels: { - fontSize: 14, - fontStyle: 'bold', - } - }, - scales: { - // Gives comfortable margin to the top of the y-axis - yAxes: [{ - ticks: { - fontStyle: 'bold', - min: Math.round(Math.min(...data)/10)*10 - 10, - max: Math.round(Math.max(...data)/10)*10 + 10, - }, - }], - xAxes: [{ ticks: { fontStyle: 'bold' } }], - }, - // Gives a margin to the right of the whole graph - layout: { - padding: { - right: 40, - }, - }, - // Labels points on the graph to show evolution of combat rating - plugins: { - datalabels: { - display: true, - align: 'top', - color: '#000', - backgroundColor: '#ccc', - borderRadius: 4, - offset: 10, - display: (context) => { - const index = context.dataIndex; - const value = context.dataset.data[index]; - const min = Math.min.apply(null, context.dataset.data); - const max = Math.max.apply(null, context.dataset.data); - return ( - index == 0 || - index == context.dataset.data.length - 1 || - value == min || - value == max - ); - }, - }, - }, - }, - }; - - const encodedChart = encodeURIComponent(JSON.stringify(chart)); - const chartURL = `https://quickchart.io/chart?bkg=${encodeURIComponent("#ded8d7")}&c=${encodedChart}`; - - statsEmbed.setImage(chartURL); - - } else statsEmbed.addFields({ name: title, value: stats, inline: true }); - - return interaction.send({ embeds: [statsEmbed] }); - }, - }, -} \ No newline at end of file diff --git a/commands/purchase-emp.js b/commands/purchase-emp.js deleted file mode 100644 index a13ee40..0000000 --- a/commands/purchase-emp.js +++ /dev/null @@ -1,125 +0,0 @@ -const { EmbedBuilder, ActionRowBuilder, StringSelectMenuBuilder } = require('discord.js'); -const { createUser, addUser } = require('../database/user'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; - -module.exports = { - name: "purchase-emp", - debug: false, - global: false, - description: "EMP an Alarm to prevent any updates for 30 or 60 minutes", - usage: "", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: ["MANAGE_GUILD"], - }, - options: [{ - name: "duration", - description: "Select the duration of the emp (30 or 60 minutes)", - value: "duration", - type: CommandOptions.Integer, - required: true, - choices: [ - { name: "30 Minutes", value: 30 }, - { name: "60 Minutes", value: 60 } - ] - }], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - 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)) { - 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."); - - 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')] }); - - 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); - } - banking = banking.user; - - 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'); - } - - if (banking.guilds[GuildDB.serverID].balance.toFixed(2) - GuildDB.empPrice < 0) { - let embed = new EmbedBuilder() - .setTitle('**Bank Notice:** NSF. Non sufficient funds') - .setColor(client.config.Colors.Red); - - return interaction.send({ embeds: [embed], flags: (1 << 6) }); - } - - const price = duration == 30 ? GuildDB.empPrice : GuildDB.empPrice * 2; - const newBalance = banking.guilds[GuildDB.serverID].balance - price; - - if (GuildDB.alarms.length == 0) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription('**Notice:** No Existing Alarms to EMP.')], flags: (1 << 6) }); - - client.dbo.collection("users").updateOne({"user.userID":interaction.member.user.id},{$set:{[`user.guilds.${GuildDB.serverID}.balance`]:newBalance}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let alarms = new StringSelectMenuBuilder() - .setCustomId(`EMPAlarmSelect-${interaction.member.user.id}`) - .setPlaceholder(`Select an Alarm to EMP.`) - - for (let i = 0; i < GuildDB.alarms.length; i++) { - if (!GuildDB.alarms[i].empExempt) { - alarms.addOptions({ - label: GuildDB.alarms[i].name, - description: `EMP this Alarm for $${price.toLocaleString(undefined, {minimumFractionDigits: 0, maximumFractionDigits: 0})}}`, - value: `${GuildDB.alarms[i].name}-${duration}`, - }); - } - } - - const opt = new ActionRowBuilder().addComponents(alarms); - - return interaction.send({ components: [opt], flags: (1 << 6) }); - }, - }, - - Interactions: { - EMPAlarmSelect: { - run: async (client, interaction, GuildDB) => { - let duration = parseInt(interaction.values[0].split('-')[1]); - let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0].split('-')[0]); - let alarms = GuildDB.alarms; - let alarmIndex = alarms.indexOf(alarm); - alarm.disabled = true; - let d = new Date(); - alarm.empExpire = new Date(d.getTime() + (duration * 60 * 1000)); - alarms[alarmIndex] = alarm; - - client.dbo.collection('guilds').updateOne({ 'server.serverID': GuildDB.serverID }, { - $set: { - 'server.alarms': alarms, - } - }, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Success:** Successfully EMP'd **${alarm.name}** for 30 minutes.`); - - return interaction.update({ embeds: [successEmbed], components: [] }); - } - } - } -} diff --git a/commands/purchase-uav.js b/commands/purchase-uav.js deleted file mode 100644 index cc52779..0000000 --- a/commands/purchase-uav.js +++ /dev/null @@ -1,102 +0,0 @@ -const { EmbedBuilder } = require('discord.js'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const { createUser, addUser } = require('../database/user') - -module.exports = { - name: "purchase-uav", - debug: false, - global: false, - description: "Send a UAV to scout for 30 minutes (500m range)", - usage: "[x-coord] [y-coord]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: ["MANAGE_GUILD"], - }, - options: [ - { - name: "x-coord", - description: "X Coordinate of the origin", - value: "x-coord", - type: CommandOptions.Float, - min_value: 0.01, - required: true, - }, - { - name: "y-coord", - description: "Y Coordinate of the origin", - value: "y-coord", - type: CommandOptions.Float, - min_value: 0.01, - required: true, - }, - ], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - 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)) { - 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."); - - 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')] }); - - 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); - } - banking = banking.user; - - 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'); - } - - if (banking.guilds[GuildDB.serverID].balance.toFixed(2) - GuildDB.uavPrice < 0) { - let embed = new EmbedBuilder() - .setTitle('**Bank Notice:** NSF. Non sufficient funds') - .setColor(client.config.Colors.Red); - - return interaction.send({ embeds: [embed], flags: (1 << 6) }); - } - - const newBalance = banking.guilds[GuildDB.serverID].balance - GuildDB.uavPrice; - - client.dbo.collection("users").updateOne({"user.userID":interaction.member.user.id},{$set:{[`user.guilds.${GuildDB.serverID}.balance`]:newBalance}}, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let uav = { - origin: [args[0].value, args[1].value], - radius: 250, - owner: interaction.member.user.id, - creationDate: new Date(), - }; - - client.dbo.collection('guilds').updateOne({ 'server.serverID': GuildDB.serverID }, { - $push: { - 'server.uavs': uav, - } - }, (err, res) => { - if (err) return client.sendInternalError(interaction, err); - }); - - let successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Success:** Successfully deployed a UAV to **[${uav.origin[0]}, ${uav.origin[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${uav.origin[0]};${uav.origin[1]})**\nRange: 500m`); - - return interaction.send({ embeds: [successEmbed], flags: (1 << 6) }); - }, - } -} diff --git a/commands/reset.js b/commands/reset.js deleted file mode 100644 index 57b68ae..0000000 --- a/commands/reset.js +++ /dev/null @@ -1,111 +0,0 @@ -const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const { addUser } = require('../database/user'); -const bitfieldCalculator = require('discord-bitfield-calculator'); - -module.exports = { - name: "reset", - debug: false, - global: false, - description: "Reset a user's bank/money", - usage: "[user]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: ["MANAGE_GUILD"], - }, - options: [{ - name: "user", - description: "User to reset", - value: "user", - type: CommandOptions.User, - required: true, - }], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - run: async (client, interaction, args, { GuildDB }) => { - const permissions = bitfieldCalculator.permissions(interaction.member.permissions); - let canUseCommand = false; - - if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; - if (client.exists(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('>', ''); - - const prompt = new EmbedBuilder() - .setTitle(`Are you sure you want to reset this user?`) - .setDescription('**Notice:** This will reset this users cash and balance.') - .setColor(client.config.Colors.Yellow) - - const opt = new ActionRowBuilder() - .addComponents( - new ButtonBuilder() - .setCustomId(`Reset-yes-${targetUserID}-${interaction.member.user.id}`) - .setLabel("Yes") - .setStyle(ButtonStyle.Danger), - new ButtonBuilder() - .setCustomId(`Reset-no-${targetUserID}-${interaction.member.user.id}`) - .setLabel("No") - .setStyle(ButtonStyle.Success) - ) - - return interaction.send({ embeds: [prompt], components: [opt], flags: (1 << 6) }); - - }, - }, - - Interactions: { - - Reset: { - run: async (client, interaction, GuildDB) => { - const choice = interaction.customId.split('-')[1]; - const targetUserID = interaction.customId.split('-')[2]; - - if (!interaction.customId.endsWith(interaction.member.user.id)) { - return interaction.reply({ - content: "This button is not for you", - flags: (1 << 6) - }) - } - if (choice=='yes') { - const successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setTitle('Successfully reset user\'s data') - - let banking = await client.dbo.collection("users").findOne({"user.userID": interaction.member.user.id}).then(banking => banking); - - let bankingReset = false; - if (!banking) bankingReset = true - else banking = banking.user - - if (!bankingReset) { - const success = addUser(banking.guilds, GuildDB.serverID, targetUserID, client, GuildDB.startingBalance); - if (!success) { - client.error(err); - 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(client.config.Colors.Red) - - return interaction.update({ embeds: [embed], components: [] }); - } - } - - return interaction.update({ embeds: [successEmbed], components: [] }); - - } else if (choice=='no') { - const successEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setTitle(`The User was not reset`); - - return interaction.update({ embeds: [successEmbed], components: [] }); - } - } - } - } -} \ No newline at end of file diff --git a/commands/server.js b/commands/server.js deleted file mode 100644 index fb66f2a..0000000 --- a/commands/server.js +++ /dev/null @@ -1,414 +0,0 @@ -const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, ModalBuilder, TextInputBuilder, TextInputStyle } = require('discord.js'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const bitfieldCalculator = require('discord-bitfield-calculator'); -const { BanPlayer, UnbanPlayer, RestartServer, CheckServerStatus, DisableBaseDamage, DisableContainerDamage, NitradoCredentialStatus } = require('../util/NitradoAPI'); -const { encrypt, decrypt } = require('../util/Cryptic'); - -module.exports = { - name: "server", - debug: false, - global: false, - description: "Nitrado DayZ Server Administrative Commands", - usage: "[command] [options]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [{ - name: "initialize", - description: "Connect your Nitrado server to the bot", - value: "initialize", - type: CommandOptions.SubCommand, - }, - { - name: "disconnect", - description: "Delete your Nitrado server from the bot database", - value: "disconnect", - type: CommandOptions.SubCommand, - }, - { - name: "credentials-status", - description: "Check the status of your Nitrado Credentials", - value: "credentials-status", - type: CommandOptions.SubCommand, - }, - { - name: "retry-credentials", - description: "If your credentials are marked as FAILED, try retreiving Nitrado logs again.", - value: "retry-credentials", - type: CommandOptions.SubCommand, - }, - { - name: "ban-player", - description: "Ban a player from the DayZ server", - value: "ban-player", - type: CommandOptions.SubCommand, - options: [{ - name: "gamertag", - description: "gamertag of the player to ban.", - value: "gamertag", - type: CommandOptions.String, - required: true, - }] - }, { - name: "unban-player", - description: "Unban a player from the DayZ server", - value: "unban-player", - type: CommandOptions.SubCommand, - options: [{ - name: "gamertag", - description: "gamertag of the player to unban.", - value: "gamertag", - type: CommandOptions.String, - required: true, - }] - }, - { - name: "restart", - description: "Restart the DayZ Server", - value: "restart", - type: CommandOptions.SubCommand, - }, { - name: "auto-restart", - description: "Enable/Disable periodic server checks and restart if stopped", - value: "auto-restart", - type: CommandOptions.SubCommand, - }, { - name: "disable-base-damage", - description: "Disable/Enable base damage", - value: "disable-base-damage", - type: CommandOptions.SubCommand, - options: [{ - name: "preference", - description: "DisableBaseDamage Preference", - value: true, - type: CommandOptions.Boolean, - required: true, - }] - }, { - name: "disable-container-damage", - description: "Disable/Enable container damage", - value: "disable-container-damage", - type: CommandOptions.SubCommand, - options: [{ - name: "preference", - description: "disableContainerDamage Preference", - value: true, - type: CommandOptions.Boolean, - required: true, - }] - }], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - run: async (client, interaction, args, { GuildDB }) => { - - const permissions = bitfieldCalculator.permissions(interaction.member.permissions); - let canUseCommand = false; - - if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; - 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 (args[0].name == 'initialize') { - - if (client.exists(GuildDB.Nitrado)) { - const prompt = new EmbedBuilder() - .setTitle(`Nitrado Server Information Already Configured!`) - .setDescription('**Notice:** This will overwrite your previously configured Nitrado Server Information') - .setColor(client.config.Colors.Yellow) - - const opt = new ActionRowBuilder() - .addComponents( - new ButtonBuilder() - .setCustomId(`OverwriteNitrado-yes-${interaction.member.user.id}`) - .setLabel("Yes") - .setStyle(ButtonStyle.Danger), - new ButtonBuilder() - .setCustomId(`OverwriteNitrado-no-${interaction.member.user.id}`) - .setLabel("No") - .setStyle(ButtonStyle.Success) - ) - - return interaction.send({ embeds: [prompt], components: [opt], flags: (1 << 6) }); - } - - const NitradoCredentials = new ModalBuilder() - .setTitle('Connect your Nitrado Server') - .setCustomId(`NitradoCredentials-${interaction.member.user.id}`); - - const ServerID = new ActionRowBuilder().addComponents(new TextInputBuilder() - .setCustomId('ServerIDInput') - .setLabel('Your Nitrado Server ID') - .setStyle(TextInputStyle.Short) - .setRequired(true) - ); - - const UserID = new ActionRowBuilder().addComponents(new TextInputBuilder() - .setCustomId('UserIDInput') - .setLabel('Your Nitrado User ID') - .setStyle(TextInputStyle.Short) - .setRequired(true) - ); - - const Auth = new ActionRowBuilder().addComponents(new TextInputBuilder() - .setCustomId('AuthInput') - .setLabel('Your Nitrado Authentication Token') - .setPlaceholder("This will be encrypted to protect your server!") - .setStyle(TextInputStyle.Short) - .setRequired(true) - ); - - NitradoCredentials.addComponents(ServerID, UserID, Auth); - - return interaction.showModal(NitradoCredentials); - - } else if (args[0].name == 'disconnect') { - - const prompt = new EmbedBuilder() - .setTitle(`Delete your Nitrado Server?`) - .setDescription('**Notice:** This will completely delete your configured Nitrado server from the bot database.') - .setColor(client.config.Colors.Yellow) - - const opt = new ActionRowBuilder() - .addComponents( - new ButtonBuilder() - .setCustomId(`DeleteNitrado-yes-${interaction.member.user.id}`) - .setLabel("Yes") - .setStyle(ButtonStyle.Danger), - new ButtonBuilder() - .setCustomId(`DeleteNitrado-no-${interaction.member.user.id}`) - .setLabel("No") - .setStyle(ButtonStyle.Success) - ) - - 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 (args[0].name == 'credentials-status') { - - const ok = GuildDB.Nitrado.Status == NitradoCredentialStatus.OK; - const notice = ok ? "Your provided Nitrado Credentials are working correctly, logs are being checked." : "Your provided Nitrado Credentials are not working. They may be incorrect, or your server may be down. Ensure your DayZ server is online, and try to initialize your server again and verify your credentials are correct." - const statusEmbed = new EmbedBuilder() - .setColor(ok ? client.config.Colors.Green : client.config.Colors.Red) - .setTitle("Nitrado Credentials Status") - .setDescription(`**Status:** \`${GuildDB.Nitrado.Status}\`\n> ${notice}`); - - return interaction.send({ embeds: [statusEmbed] }); - - } else if (args[0].name == 'retry-credentials') { - - client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set:{"Nitrado.Status": NitradoCredentialStatus.OK}}, (err, _) => { - if (err) return client.sendInternalError(interaction, err); - }); - - const updatedEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setTitle("Updated Nitrado Credentials Status") - .setDescription(`**Success**\n> Successfully retrying your existing Nitrado Credentials to check DayZ logs.`); - - return interaction.send({ embeds: [updatedEmbed] }); - - } else if (args[0].name == 'ban-player') { - - let data = await BanPlayer(GuildDB.Nitrado, client, args[0].options[0].value); - - if (data == 1) { - let failed = new EmbedBuilder() - .setColor(client.config.Colors.Red) - .setDescription(`Failed to ban **${args[0].options[0].value}**. This can result from a variety of reasons:\nNitrado servers may be experiencing issues\nThe DayZ.R Bot may be experiencing issues\nYour Nitrado credentials were entered incorrectly`); - - return interaction.send({ embeds: [failed], flags: (1 << 6) }); - } - - let banned = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`Successfully **banned** **${args[0].options[0].value}** from the DayZ Server`); - - return interaction.send({ embeds: [banned] }); - - } else if (args[0].name == 'unban-player') { - - let data = UnbanPlayer(GuildDB.Nitrado, client, args[0].options[0].value); - - if (data == 1) { - let failed = new EmbedBuilder() - .setColor(client.config.Colors.Red) - .setDescription(`Failed to unban **${args[0].options[0].value}**. This can result from a variety of reasons:\nNitrado servers may be experiencing issues\nThe DayZ.R Bot may be experiencing issues\nYour Nitrado credentials were entered incorrectly`); - - return interaction.send({ embeds: [failed] }); - } - - let banned = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`Successfully **unbanned** **${args[0].options[0].value}** from the DayZ Server`); - - return interaction.send({ embeds: [banned] }); - - } else if (args[0].name == "restart") { - // Write optional "restart_message" to set in the Nitrado server logs and send a notice "message" to your server community. - restart_message = 'Server being restarted by an admin.'; - message = 'The server was restarted by an admin!'; - - RestartServer(GuildDB.Nitrado, client, restart_message, message); - return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription('The server will restart shortly.')], flags: (1 << 6) }); - - } else if (args[0].name == "auto-restart") { - let msg = 'Auto server restart periodic check enabled.'; - let pref = 0; - - // Enable/Disable a 10min periodic server status check. - if (!client.arIntervalIds.has(GuildDB.serverID)) { - client.arIntervalIds.set(GuildDB.serverID, setInterval(CheckServerStatus, client.arInterval, GuildDB.Nitrado, client)); - pref = 1; - } else { - msg = 'Auto server restart periodic check disabled.' - clearInterval(client.arIntervalIds.get(GuildDB.serverID)); - } - - // Update DB preference - client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { - $set: { - "server.autoRestart": pref, - } - }, function (err, res) { - if (err) return client.sendInternalError(interaction, err); - }); - - return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(msg)], flags: (1 << 6) }); - - } else if (args[0].name == 'disable-base-damage') { - const preference = args[0].options[0].value; - await interaction.deferReply({ flags: (1 << 6) }); - - const disableBaseDamageFailed = await DisableBaseDamage(GuildDB.Nitrado, client, preference); - - if (disableBaseDamageFailed) return interaction.editReply({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Red).setDescription('Failed to set **disableBaseDamage**. This can result from a variety of reasons:\nNitrado servers may be experiencing issues\nThe DayZ.R Bot may be experiencing issues\nYour Nitrado credentials were entered incorrectly')], flags: (1 << 6) }); - return interaction.editReply({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Green).setDescription(`Successfully set **disableBaseDamage** to ${preference}.\nRestart the DayZ server to apply these changes.`)], flags: (1 << 6) }); - - } else if (args[0].name == 'disable-container-damage') { - const preference = args[0].options[0].value; - await interaction.deferReply({ flags: (1 << 6) }); - - const disableContainerDamageFailed = await DisableContainerDamage(GuildDB.Nitrado, client, preference); - - if (disableContainerDamageFailed) return interaction.editReply({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Red).setDescription('Failed to set **disableContainerDamage**. This can result from a variety of reasons:\nNitrado servers may be experiencing issues\nThe DayZ.R Bot may be experiencing issues\nYour Nitrado credentials were entered incorrectly')], flags: (1 << 6) }); - return interaction.editReply({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Green).setDescription(`Successfully set **disableContainerDamage** to ${preference}.\nRestart the DayZ server to apply these changes.`)], flags: (1 << 6) }); - - } - } - }, - - Interactions: { - - NitradoCredentials: { - run: async(client, interaction, GuildDB) => { - if (!interaction.customId.endsWith(interaction.member.user.id)) - return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) }); - - const Nitrado = { - ServerID: interaction.fields.fields.get('ServerIDInput').value, - UserID: interaction.fields.fields.get('UserIDInput').value, - Auth: encrypt( - interaction.fields.fields.get('AuthInput').value, - client.config.EncryptionMethod, - client.key, - client.encryptionIV - ), // Encrypt the Authentication Token - Status: NitradoCredentialStatus.OK, // Indicate if these credentials dont work - }; - - await client.dbo.collection('guilds').updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "Nitrado": Nitrado } }, (err, res) => { - if (err) client.sendInternalError(interaction, err); - }); - - client.initNewNitradoServer(GuildDB.serverID, Nitrado); - - return interaction.reply({ content: 'Successfully configured your Nitrado Server Information', flags: (1 << 6) }); - } - }, - - OverwriteNitrado: { - run: async(client, interaction, GuildDB) => { - 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') { - const NitradoCredentials = new ModalBuilder() - .setTitle('Connect your Nitrado Server') - .setCustomId(`NitradoCredentials-${interaction.member.user.id}`); - - const ServerID = new ActionRowBuilder().addComponents(new TextInputBuilder() - .setCustomId('ServerIDInput') - .setLabel('Your Nitrado Server ID') - .setStyle(TextInputStyle.Short) - .setRequired(true) - ); - - const UserID = new ActionRowBuilder().addComponents(new TextInputBuilder() - .setCustomId('UserIDInput') - .setLabel('Your Nitrado User ID') - .setStyle(TextInputStyle.Short) - .setRequired(true) - ); - - const Auth = new ActionRowBuilder().addComponents(new TextInputBuilder() - .setCustomId('AuthInput') - .setLabel('Your Nitrado Authentication Token') - .setPlaceholder("This will be encrypted to protect your server!") - .setStyle(TextInputStyle.Short) - .setRequired(true) - ); - - NitradoCredentials.addComponents(ServerID, UserID, Auth); - - // TODO: Figure out how to remove the prompt buttons and the embed. - return interaction.showModal(NitradoCredentials); - } else { - return interaction.update({ embeds: [], components: [], content: 'Cancelled Overwriting Nitrado Server Information', flags: (1 << 6) }); - } - } - }, - - DeleteNitrado: { - run: async(client, interaction, GuildDB) => { - 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') { - await client.dbo.collection('guilds').updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "Nitrado": null } }, (err, _) => { - if (err) client.sendInternalError(interaction, err); - }); - - return interaction.update({ - embeds: [ - new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Success**\n> Successfully removed your Nitrado credentials from the database.`) - ], - components: [], - flags: (1 << 6) - }); - } else { - return interaction.update({ - embeds: [ - new EmbedBuilder() - .setColor(client.config.Colors.Green) - .setDescription(`**Cancelled**\n> Your Nitrado credentials were not removed from the database.`) - ], - components: [], - flags: (1 << 6) - }); - } - } - }, - - } -} diff --git a/commands/weapon-stats.js b/commands/weapon-stats.js deleted file mode 100644 index 90bfc06..0000000 --- a/commands/weapon-stats.js +++ /dev/null @@ -1,176 +0,0 @@ -const { EmbedBuilder, ActionRowBuilder, StringSelectMenuBuilder } = require('discord.js'); -const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; -const { weapons } = require('../database/weapons'); -const { insertPVPstats, createWeaponStats } = require('../database/player'); - -module.exports = { - name: "weapon-stats", - debug: false, - global: false, - description: "Check player weapon statistics", - usage: "[category] [user or gamertag]", - permissions: { - channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], - member: [], - }, - options: [{ - name: "category", - description: "Weapon category", - value: "category", - type: CommandOptions.String, - required: true, - choices: [ - { name: "Handguns", value: "handguns" }, - { name: "Shotguns", value: "shotguns" }, - { name: "Submachine Guns", value: "subMachineGuns" }, - { name: "Assault Rifles", value: "assaultRifles" }, - { name: "Battle Rifles", value: "battleRifles" }, - { name: "Bolt-action Rifles", value: "boltActionRifles" }, - { name: "Break-action Rifles", value: "breakActionRifles" }, - { name: "Lever-action Rifles", value: "leverActionRifles" }, - { name: "Marksman Rifles", value: "marksmanRifles" }, - { name: "Semi-automatic Rifles", value: "semiAutomaticRifles" }, - { name: "Other", value: "other" }, - ] - }, { - name: "discord", - description: "Discord user to lookup stats", - value: "discord", - type: CommandOptions.User, - required: false, - }, { - name: "gamertag", - description: "Gamertag to lookup stats", - type: CommandOptions.String, - required: false, - }], - SlashCommand: { - /** - * - * @param {require("../structures/DayzRBot")} client - * @param {import("discord.js").Message} message - * @param {string[]} args - * @param {*} param3 - */ - 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)) { - 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."); - - return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); - } - - let discord = args[1] && args[1].name == 'discord' ? args[1].value : undefined; - let gamertag = args[1] && args[1].name == 'gamertag' ? args[1].value : undefined; - let self = !discord && !gamertag; // searching for self if both discord and gamertag are undefined - const weaponClass = args[0].value; - - let query; - - // Searching by Discord - if (discord) query = await client.dbo.collection("players").findOne({"discordID": discord}); - - // Searching by Gamertag - if (gamertag) query = await client.dbo.collection("players").findOne({"gamertag": gamertag}); - - // 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.`)] }); - - let weaponSelect = new StringSelectMenuBuilder() - .setCustomId(`ViewWeaponStats-${query.playerID}-${interaction.member.user.id}`) - .setPlaceholder(`Select an weapon to view stat.`) - - for (const [name, _] of Object.entries(weapons[weaponClass])) { - weaponSelect.addOptions({ - label: name, - description: `View this weapon's stats.`, - value: `${weaponClass}_${name}`, - }); - } - - const opt = new ActionRowBuilder().addComponents(weaponSelect); - - return interaction.send({ components: [opt] }); - }, - }, - - Interactions: { - ViewWeaponStats: { - run: async(client, interaction, GuildDB) => { - if (!interaction.customId.endsWith(interaction.member.user.id)) - return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) }); - - const weapon = interaction.values[0].split("_")[1]; - const weaponClass = interaction.values[0].split("_")[0]; - const playerID = interaction.customId.split('-')[1]; - 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); - - let stats = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`${tag} stats for the **${weapon}**`) - .setThumbnail(weapons[weaponClass][weapon]) - .addFields( - { name: `Kills`, value: `${player.weaponStats[weapon].kills}`, inline: true }, - { name: `Deaths`, value: `${player.weaponStats[weapon].deaths}`, inline: true }, - { name: `Shots Landed`, value: `${player.weaponStats[weapon].shotsLanded}`, inline: true }, - { name: `Times Shot`, value: `${player.weaponStats[weapon].timesShot}`, inline: true }, - ); - - const chart = { - type: 'bar', - data: { - labels: ['Head', 'Torso', 'Left Arm', 'Right Arm', 'Left Leg', 'Right Leg'], - datasets: [{ - label: `Shots landed with a ${weapon}`, - data: [ - player.weaponStats[weapon].shotsLandedPerBodyPart.Head, - player.weaponStats[weapon].shotsLandedPerBodyPart.Torso, - player.weaponStats[weapon].shotsLandedPerBodyPart.LeftArm, - player.weaponStats[weapon].shotsLandedPerBodyPart.RightArm, - player.weaponStats[weapon].shotsLandedPerBodyPart.LeftLeg, - player.weaponStats[weapon].shotsLandedPerBodyPart.RightLeg, - ], - }, { - label: `Times Shot by a ${weapon}`, - data: [ - player.weaponStats[weapon].timesShotPerBodyPart.Head, - player.weaponStats[weapon].timesShotPerBodyPart.Torso, - player.weaponStats[weapon].timesShotPerBodyPart.LeftArm, - player.weaponStats[weapon].timesShotPerBodyPart.RightArm, - player.weaponStats[weapon].timesShotPerBodyPart.LeftLeg, - player.weaponStats[weapon].timesShotPerBodyPart.RightLeg, - ], - }], - }, - options: { - legend: { - labels: { - fontSize: 14, - fontStyle: 'bold', - } - }, - scales: { - yAxes: [{ ticks: { fontStyle: 'bold' } }], - xAxes: [{ ticks: { fontStyle: 'bold' } }], - }, - }, - }; - - const encodedChart = encodeURIComponent(JSON.stringify(chart)); - const chartURL = `https://quickchart.io/chart?bkg=${encodeURIComponent("#ded8d7")}&c=${encodedChart}`; - - stats.setImage(chartURL); - - return interaction.update({ components: [], embeds: [stats] }); - } - } - } -} diff --git a/config/config.js b/config/config.js deleted file mode 100644 index 8d936a4..0000000 --- a/config/config.js +++ /dev/null @@ -1,47 +0,0 @@ -const package = require('../package.json'); -require('dotenv').config(); - -const PresenceTypes = { - Playing: 0, - Streaming: 1, - Listening: 2, - Watching: 3, - Custom: 4, - Competing: 5, -}; - -const PresenceStatus = { - Online: "online", - Offline: "offline", - Idle: "idle", - DoNotDisturb: "dnd", -}; - -module.exports = { - Dev: process.env.Dev || "DEV.", - Version: package.version, // (major).(minor).(patch) - Admins: ["362791661274660874", "329371697570381824"], // Admins of the bot - SupportServer: "https://discord.gg/KVFJCvvFtK", // Support Server Link - Token: process.env.token || "", //Discord Bot Token - SecretKey: process.env.key || "01234567891", - SecretIv: process.env.iv || "9876543210", - EncryptionMethod: process.env.encryptionMethod || "aes-256-cbc", - Scopes: ["identify", "guilds", "applications.commands"], //Discord OAuth2 Scopes - IconURL: "https://cdn.discordapp.com/app-icons/1049045393415098450/f8e7f76ac9e843360b989c796fc21990.png?size=256", - AvatarData: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgaElEQVR4nO2dfYxU5fXHv/dt7szuwi7orvIi7wICVdR2qUIjQm0sYmvTqo3VWBqjtEm1ao3ampKqtdFfjMYqtLa0jW+o1FoQ26DWiorBl6DRNmJFodBClSKwy87MfZvz+2M5D3eWXdzdmWXn3ud8kpt9mdm59z57n+9znvOccx6DiAiCIGiJOdgXIAjC4CECIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgakzoBICL1lYhQKpUG+Yr6Dl8730vX17r7fqCIomjAzzEQ9NR+n/aabtiDfQHVhogQhiEMw4BhGCAiGIYx2JfVJ7rr5HwvTKlUgmmahzzIldwrC2ZcOA3DgGnW3jgRbxe+5yiKEIYhHMc55P2GYSCKInUvSXwuBgKDUiaFRIQoimAYBnzfh213alwtPsQ9USqVEIYhTNOEZVkIwxCWZcGyLNU5TdMse6hN00QURbAsq98PNo+MYRjC931ks1l17lprPxYoy7IAdHZ+Fi9uD74X27aVKHB7SefvJHUCwCYrP8BAZaNircKjHVsGmUymKgLAHSQMQxARXNet8pUfeYIgUG3DAlFJO6WJ1E0BgM4OHwQBvv3tb2PHjh2wbTsxvgDWY9u20dDQgGHDhmH48OEYM2YMTjjhBBxzzDEYPnw4mpubUVdXp/4uDEOUSiUYhqFGxb7C5n4+n0c2m8VPfvITPPPMMxg6dGjN+gLYlDcMA67roqWlBaNGjcL48eNx/PHHY8SIERgxYgSampoAlLeTWAIpFID43H/9+vX4z3/+M9iXVDV4GtDc3IyTTjoJJ598Mo4//njMmTMHEydOVO/rOk3oKzzqf//738dHH32E3/72t1W7hyOJbdvIZrM46aSTMHv2bJx88sn44he/iKOPPlq9hy0DXUndFIDVvb29Ha2trXj//fdhWVZiLICucAeOrwx0/ZeNGTMG06dPx8KFCzFv3jxMnTpVvVYqlVAqlcqsoLjjrCvxz+b33HbbbViyZAkAwHEclEolBEFQ06Nnd21lmiamTp2KuXPn4oILLsDs2bNh2zaiKCqzJHgqlET/UZ+hlFEqlYiIaN++fTRp0iQCQKZpEoDUHIZhkOM45Lou2bZd9trw4cPpkksuoT/+8Y/U0dFBRERhGFI+n6cgCIiIKAgC1U6HI4oiiqKIiIh+/vOfq/Patn3IeWv1MAyDMpkMZbPZsufAdV36yle+Qn/4wx/UPfq+T2EYkud5FEURBUGg2iytiAAk+LAsizKZDJmmSa7rkuM46l4ty6LTTz+dHnjgAdq9ezcRERWLRfJ9n4rFYq8EgNuTO8GSJUsIwCGdqdYPy7LItm311XVdymQyBIAcx6GFCxfSa6+9RkSd4uh5HgVBQFEUURiGvW6rJCICkNCDO79hGGSaJpmmqb53XZey2ax676xZs+ihhx4i3/eJiCifz5Pneb1uU8/zqFAoEBHRNddcozrOYLdBbw7DMMiyLPUcsEiyELAlM2TIELr++uupvb2diIj27t1LHR0dyhpIKyIACT34IeYHOd75WQyy2WyZEJxzzjllI11vH+woipT1EAQBXXzxxQQgUdMA27bVVxYCy7LUFIEtgs9//vO0ceNGIiJqa2sbmIe0hhABSPARv6+4FcBiAHRaCq7rkuu6BHSOdHfccYeyBtjEPZwglEol8n2fPM+jMAxpz549dMYZZxDQOR3gjjTY7XE4AehqKcXbj3/PbdTS0kKrV68mok6/QBRFVCqV1Nc0TQtEADQ4eORzHEeNdF//+tdp8+bNqq2KxWKPAsAOsVKpRMVikYiI3n33XRo/fjxZlqUsjVoWgd4ePLXJ5XL0+9//noiICoUCFQoFJZIsnmkgxesbQhyKxfk7joMnnngCZ599Np5//vlPDfSJLxtyiPXUqVNx++23AzgYlZj05TKOB8hms/B9H1dccQVWrFhRFhJNsWSzVDC4+lN9xAI49GBnoWVZyhOey+XItm0aMmQIPfLII0REytHXXZvySkCpVCr7+fLLLycA1NDQkPh25mVO0zRVmw0dOpSeffZZIiLlA+GpQBoQAdDgME1TdXx2erHz0LIschxHmbs9rXvz3DcMw7I18h07dtD06dOVr2Gw77XSg2MGHMdRDtRx48bRP//5T9U+nuelRgCSbbMJvSJumluWBd/3YZomfN9XeRNXXHEFHnnkEdi2rRKBmDAM1edweLFlWYiiCCNGjMCtt96q3sdJNkmMtefMyyAI1JTJcRxs3boVV111FfL5vMo0TQ2DrUDVRiyA3lsF7B1nL34ul6Onn36aiA6auz0FDbE1wO8777zzCOh0nsWXKJMSL3C4gx2ny5YtIyLqUyBVrSMWgKbE8wKICJZloVAoYPHixfj73/8Ox3HUiN4dXIvAMAzYto0bb7wRTU1NKBaLqjYB1zVIOpxY9X//93/YunUrHMdJjRNQBEBjeGrAYpDJZLB9+3YsXrwYe/bsUSLQ3cMerxQUBAFaW1vxrW99S+Xb8+tp6CimaaKurg4ffvgh7rnnnsSvdsRJz50IfYZHNv7e9324rov169fj5ptvVh24uwee/5azL6MowpVXXomWlhYEQaBGyVqsJtQXDMNAqVSC53mwLAuPPvooPvjgg/SI22BfQFIYDMfPQJ6TR2juwPw1CALYto2lS5fiqaeeQi6X69aMZycgpwf7vo/JkyfjG9/4xiF1DAezo1SjDfkzXNfFzp078cgjjwBAYlPM46SuHgAdyOtua2vDqaeeis2bN6sHvRK4phyPaqVSaUA8wvHPi9f8Yw813193uf19qdoTrzMQ/51t22qFYMqUKVi3bh2OOuoo+L6PTCajzPvuOrlpmnjttdfw5S9/GW1tbchkMqocV7XbKX7+ePHXuG8inttfCfGKQ8ViESeffDLWrl2Lo48++pB7S5q1k6yrHSR4tIsXmqQDy0RRFA3IwctR7EjzPA9A5zzdtm213MaC1Ndlt+5GZu5ERATbtrFp0ybce++9hxQk5SMeHciOv9bWVpxxxhll1z8Q7dRd+/M549dbKdz5LcuC53moq6vDxo0bsXHjRgCdosvFUZLW+YEUlgQbCHg92PM83HTTTTjxxBPheV7V6+Tx6JXJZGAYBv773/9i27Zt+Ne//oV///vfeO+999De3g6gs9xV12pBbCVUcv4gCGCaJjKZDMIwxPLly3HxxRfj+OOPRxiGCMMQ2Wy2W4uKBfKmm27CggULkMvlVBtV09CMj/K5XA6e52Hbtm3YtGkT3n77bbzzzjsAgPr6eiVC/T1/V4uM2/fpp5/GWWedVWZp9OQvqWkGboVxcBiIOACOngNAL7744qDc1/79+2ndunX005/+lGbOnKmujdNaOdKv0vvkmAAOhwVAV155JRGRKpTRU+YgZ8wNJrt376Zf/epXNHXqVAKgUqUraReOluQaDABoxowZlM/nVXJQUqsHiQ+gF8Rrzz/zzDOYP3/+YdfIq0F8Hhu3CgBg165dWLt2Le655x68/vrragrApnF/YR8AHTCv2aIYPnw41q1bh2nTpqFYLJbV2Y9DB+bbFJsqhGGIXC43YD6AONxmvJx5/fXXY8WKFWoK11+4NiAdGOGjKEJzczNeeOEFTJ06VZVnT1rkIwCxAHpzxKvKcGLIQKl91wgzTr7hWPx4Kuonn3xCP/vZz6i+vp4AqFh/HsEty+rXvccLaPB9L1myhIhIVcgJw7Db6+dcgYFso3i7dHf+YrFIQRBQPp+niy66SFlKHP3Yn+hELiISb58VK1aUtUkSowMTNmGpHQZK6bt+LlsB7Iji9XXf99HY2Igf/ehHWLVqFY477ji1LZbrumo0749zimKOTjow6j322GPYuXMnHMdRfoLuiK/788g5EPRU2dgwDDiOo2Iabr/9dkyZMkUtWfb3mrgSMgC1ccqWLVvU65RQQ1oEIIGwGBQKBXieh/nz52P16tWYMWOGcnoBB5N4Kpn+cEnxTZs24eWXXy7z/Nca8X0N6+rqEIYhRo8ejR/+8IdqSkKx6U1/4XvfuXMngIPOz1psk09DBCChxK2BQqGAmTNn4qGHHsKxxx6rHnBeCqv0weQlv1WrVvW4KWktwPfJGY9A58h89tlnY9q0acpyqdYS4f79+9V5qxFrMhiIACQUfoAdx4FlWSgWizjppJOwbNkyOI6j1sarAS9zvfLKK9i9e7eK/qs1eJmOd/thIRg9ejROPPFEAJ3RfGzK9xdu+7a2trJ4iCQiApBgHMdR04FMJgPP8/DVr34Vl19+uVo5ACo31zkIaufOndiwYYP6Xa3B05V4DgOL1+TJkwFAlS6rlgVQLBYBHFyBSBoiAAklXnSDHW+8Q/DVV1+NSZMmwfO8HoN2+orjOCgWi1i/fj2A2gx5jbcFO0B5iXTEiBEAAM/zKu78/PcU2005/vskUXv/RaHfsAk8duxYLFq0qGr5CnEB2bp1ayIj3tgaYudfJZ2V25NFl3+XtDYBRABSBzsGL7zwQowdO1aV/6oUFoEPP/wQe/furVlHYE9wCHXccqqUuro6ZDKZxK4AACIAqYMjAidOnIi5c+dW5eGMpwtv3rwZ27dvB5Ask/fDDz9U31d63dyeTU1NZXkJSWoPRgQgZXDwDhHhzDPPrMrW6FwM1LZt7NmzR61/1+IDH5+f89coipRo8e+qce1DhgwBUF5YJWkk86qFbokHuRiGgTlz5uDoo4+ueKkqHkADAHv37q3SFVefeC1Cz/NgmibeeecdvPrqq2XmeqXtAQDHHXccgIPLpEmcBogApIh4QEqpVEJzczOGDRumXquE+LJfrQpAvLoRd1LTNPHoo49ix44dqm0qCdrhz3ccRwkAd/5atIg+DRGAFMGmbXyLqzFjxlT8uV0jCv/3v/8BqN1wYMZ1XTz//PNYunSpCl7izMBKr72lpQWtra2HVFRKGiIAKYOIUCwWQUTIZDJKACp5OONBNQCwb9++qlxrtYj7PXhTD9d18eabb+Kyyy5DR0cHgM4goHgptf7Ac/0RI0Zg5MiRiKIItm2XWR1JQgQgRcRr+vHDWF9fX/Hndo36KxQKff6MeCetxsGfCZSX7aqrq4Nt23j44YexYMECbNmyRQUH8cFr95Vw5plnqs9J6vwfkJJgqYTLeQGoWpRa/AE/XBgwd9B41uBAbA4Sd+ZFUYRCoYC2tja88MILWLlyJdasWVNWJo2tGM4T6O1oHXcYxgOAzjrrrB7flyREAFIGZwdyxR7ufJU8nF0dXD3l1MfrB7CzrVgs4rrrrsPWrVvhum5VzGTu9LZtw7ZttLe3Y/v27fjoo4+wa9cuNf2J1zQADvoH+iJI/LdciNXzPMyaNQuf+9znygqyJhURgBTBa978sBIRPvnkk4o/t2tJrYaGhsNeQ/zr/v37sWbNGmzdurXi6/g0uHQ3F++oRgwEADXH5+jHc889F01NTcqaSDIiACmCzVAeoT3PUx2vkilA17n38OHDezx/104XRRFc11WBRNVylMXNceDgEmDc0ccdtNLAH074CYIA48aNw0UXXVR2DUlGBCBl8Do1VwziqL1K6BrqetRRRwE4VFTiP/M17Nu3Dx0dHSoxqdqechY7rs3Px+H2NewrLGxhGGLRokUYN25cKkZ/QAQgVfAUgOelW7ZsUVOASrPf4g97Y2Njj++NB+MAwO7du9UyXCX1+bu7Jl72i/8OgKqZGK/Z31vYzI+vMJimCc/zMGXKFHznO99JZMBPT8gyYIrgjspFKv76179i7969qtR3f4mvJJimqSyA7s7fNdvuk08+UQJQTbq7n/iuRRy63Nft0uJmvWVZysKwLAu33HILRo8erfwLaUAEIIW4roswDPHCCy9U5fPic+pRo0Zh5MiRAA6dA3ddlweA7du3w/f9qtXhG2i4enDclxEEAb773e/i/PPPRxiGFQtqLSECkDJ4CvDGG2/g5ZdfrspIFS8AMnHiRIwaNQpA9yXMu2bF7d69u9v31iLcqXlzEy6BPnfuXCxZsgS+7ytREAEQahKe8/7mN79RO/RWa3dcAJgwYQLq6up6jKdnRx/PpY/E8l+1iCdTZbNZ+L6PSZMmYenSpSqrMqnVf3tCBCBFcAzAhg0bsHLlSvWwViMKkB/6iRMnAuh5BORqxKZpoqOjAx988MFh3z/YdLfPgW3byOfzGDlyJB544AGccMIJZfP+eB3ApCOrAAklvu22bdtqbtrR0YEbb7wRbW1tcF23LDKvvxhG567BQ4cOxbx583p8X9e02I8//hibNm1S11tLxGsDxvdW5F2gx4wZg4cffhinnXaa2nGp69+mgXTImKawGc7r3ZZl4eabb8a6deuUI7Ba6+AAMHr0aEybNq1HqyLuBASgwnNrMVc+3vF52c+2bXiehxNPPBFPPvkk5syZg0KhcEjocxL8Gb1FBCChxHe44TnrvffeizvvvBMNDQ1qx9q4+V4pCxYswJAhQ+D7frf5AF13x33ppZdqduMM3t/PcRz1ve/7uOiii/DMM8/glFNOged53e6CnCZEABJKFEWq5FUul8Ndd92Fa6+9Vo1iTLxASH+IR9adc845KtS4u07d1QKo5T0E4sVBgiDAhAkT8Otf/xoPP/wwmpqaehS5tJH+O0wZPOIbhoH6+nrs3r0bN9xwA5YvX662w4ovx/FOOP2FY+Dnz5+P1tZWde7ucuD5vKZpYsuWLXj33XfVNdcqjY2NuOCCC3DDDTfguOOOK9s/8HC7IKcFEYBe0DVCjDvhQDwcXTsWL6vx77iTFwoFrF69GrfddhvefvtttdzHIbBdq+L2Fjbju1bO+drXvoa6ujplFvdkAfi+j2w2i+eeew7btm1DJpNR19SX++9OZOLlvOJFSvsK/31zczMefPBBzJs3D6VSSe2hwOfkPRbSjAhAL4gHwvT0cFYL7uz82fFUVADYsWMH/vKXv+Dxxx/Hs88+qwJWeDWgWltfcWWhIAgwefJknHfeeepcfJ1dBTAuPK+//rras7AvxTd4RYP9GyxenIxj23bFSUV8f7t27cKf/vQnnHHGGeqz46sBOkwD0n13VYTXfn3fBxFVzcPeFf7MMAxRKBTQ0dGB9vZ2vPnmm1i3bh1effVV/OMf/wBwcHPQeKhuNeDOxrn1l112GUaNGqUy7ngk7ioAURQhl8vhzTffxIMPPogwDNUW2r2Fk3viST7xZU7f96sS3MQC9otf/AJDhw7FrbfeimKxqIqMcOXftFsABqXsDnlkbmtrw6mnnorNmzdXvA4e32121qxZGDlyJAqFwoBYAWziep6HXbt24aOPPkJHRwfy+bx6GF3XVe/hGnfxkb+SfymPvCwC06ZNw7p169DQ0KBe43l+13vna3/rrbdw//33I5vNqiKdvW0nnn8XCgXU19fjb3/7G9566y3kcjllonNFn0rvk52jvu9j2bJlWLx4sSqo6rpu2TWlFkoZpVKJiIj27dtHkyZNIgBkmiYB6PdhGAbZtk2O41T0OZWc33EcymQylMlkyLIschxH3Re/Xo37zGQyZJomZTIZAkD3338/EREVi0XyPI+CIKAwDHtse8/z1P+gGmzevJlOOOEEsm2bXNcl13Wr8r+wbZuy2Sy5rkuO41B9fT2tWrWKiIjy+TxFUURhGFIQBFW7l1pELIBewnPP+MhHA2AB8GfGA1TinncubBn3Q8Rf62/oL1s5XE6sWCziS1/6EtasWVNW6Yc9/T3dOx2YHsWr8fR2BKWYBcNTG67tf+6556rYBrYqKnl049WT6EBdgTFjxmDlypVobW1FR0cHstmsapPUckTl5ggwEBZAGg/DMMiyLNU2lmWVWQDDhg2jN954g8Iw7HHEPxLwCHzXXXcRADViV7s9uB2mTJlCW7duJSKiQqEwqPd+JEjx5Eb4NIjKa+zH6+stWbIEp556KvL5/KDGvluWBd/3cdVVV+Hyyy+H53nIZrNVt7zY6ffee+/hkksuwb59+1IV898jgyxAVUcsgL6PfNw+PLJecMEF5Pt+zYyAQRBQEATU3t5O8+fPV5bAQLRHLpcjAHT++eeT53kUhmFVfRq1hlgAmsJzefYf2LaNIAhw2mmn4Ze//KXy9Pu+P6jXSQeslCiK0NDQgKVLl2LMmDFqBaTa8PLnypUr8eMf/1j5PihdrjKFCICmcMfnoJcwDDFu3Dj87ne/Q1NTkwqDZUfYYF4nBx8Vi0VMnjwZy5YtQy6XU68D1Vuq4/gCx3Fw55134r777isTgaTuAdgTIgCawB7vTCajOovjOKryzfjx4/Hkk09iypQpKruQI+MGO5uvVCohk8mo+PwFCxbglltuUb/PZDI9Jij1FToQzsyrGNdccw2eeOIJtSvQQJQ2H0xEADQgvnTHI77jOLBtW42qTz31FGbOnKnCcGsNXorkQKArr7wSl156KTzP67aqT3/PEV/iBTojEr/3ve9hw4YNyGazh+yRkHREADSATWg2b3lenc/n0draij//+c+YPn16Tce+cwwGdzzHcXDHHXdg5syZ8DyvatuAxeFMyo8//hiLFi3CBx98gGw2W7M1DvqDCIAGBEGgAnzY2ef7Pr75zW9i9erVGD9+PPL5fE0/1Ny5+T5830dLSwuWL1+O5uZmeJ5XsXixMMYtCt7abNOmTVi0aBF27dqlqjClARGABNPbDhtPJfY8D0OHDsXtt9+OBx98EMccc4xK4a3V0Z8dgRxhyCOw7/s45ZRTcNdddykfQaUi1p0IBEGATCaDl156CYsXL1YxE6mYBhzZVceBR6c4AF7D54g+0zTJtm0V1WcYBpmmSfX19epvTj/9dFq/fr1qK17nr+W1br62UqlU9n0+n6d8Pk9ERDfeeCMBoEwmo9qAD8Mw+t3G8YhJzo+47rrriIhUnMCn5UjUMiIACT0syypL3OEOn8vlyLIssm2b6urq1PsnTJhAd999N7W3txNRZ8JLLXf6TyOKIioWi+T7PhWLRSoWi7Rw4UICQA0NDaptHMepSAC4rVkEuE3vvvtuIupsxzAMqVAoJLI9RQASenDHtyxL/cxZgjxSAaDRo0fTtddeq+LboyiitrY28n1/MP9NFcPWgOd5VCwWKQxD2rZtG82YMYMMwyDXdatiAcQFgLMuOZPwscceI6LOTEnOHkwaIgAJPmzbViZv19DYyZMn00033UTvvfeeaptCoUC+71OpVEq8AHCH832foiiiQqFARESvvPIKNTY2kmVZlMvllGVUqQCwwGYyGXJdlwzDoGHDhtGLL75IRFT1NOgjhaQDJ4Cu69zx9eq4N3rEiBGYOXMmLr30UsyZM0ft4ZfP51UVHV5LT3qRiyiKytKOgc7/fTabxX333Ycf/OAHqpJQpR57Xj3hZVSOq/A8DxMmTMDatWsxadIkBEGQuDLiqRMA9hC3t7dj1qxZ2Lx584CsEQ80FMvU6ykW3bZttLS04Atf+AJmz56NuXPn4jOf+Yx6PV7CK+4d5/JaSSYeF8D1EAGgUCigrq4OV199Ne6++24MGTJEbZfeH+J7K3CpMB5kcrkc9u/fj9mzZ2PVqlVobGwcsFqRA0XqBIAfjLa2NkyePBkff/zxYF9SxWQyGTQ2NqK5uRlDhgzB2LFjcdppp+Gzn/0sRo4cifHjx6uHjh/Q7kp2pZ1SqaQiGYvFIs477zw899xzR+Tcc+bMweOPP45jjz0WQHJ2D0qlAACdZu9DDz2EPXv2lJlvScFxHDQ0NKCxsRFDhw5FS0sLxo4di+HDhx8yevPaOB2o2puUh6/a0IFqRL7vo66uDu+//z5WrlypKhP1l+6qQMcrM1mWhXw+jwsvvBBTp04dsJLxA0EqBYCDN+KFHdMCZ6PFy4QBnYLBD56uAhDfmZitoFrMa6glkj0R7AZOFuEtnvkBSIoiA1DzWnbWUZftvUzTVLXs0rRVdaXwFMB13bLqytXOaGSfAOcK8DPHWYlJInUWAJvCPAKw8yYptxkvBso/d30dOOgkrFYmXFrg6RA7fgfCImIBYOdjfDOXpP0fUicAgiD0HrEdBUFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFj/h+ueo0XyBHLFAAAAABJRU5ErkJggg==", - Colors: { - Default: "#8a7c72", - DarkRed: "#ba0f0f", - Red: "#f55c5c", - Green: "#32a852", - Yellow: "#ffb01f" - }, - Permissions: 2205281600, - mongoURI: process.env.mongoURI || "mongodb://localhost:27017", - dbo: process.env.dbo || "knoldus", - Presence: { - type: PresenceTypes.Watching, - name: "DayZ Logs", // What message you want after type - status: PresenceStatus.Online - }, -} diff --git a/database/armbands.js b/database/armbands.js deleted file mode 100644 index 663c7b2..0000000 --- a/database/armbands.js +++ /dev/null @@ -1,164 +0,0 @@ -module.exports = { - Armbands: [ - { - name: "Black", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/8/82/ArmbandBlack.png/revision/latest?cb=20161127174754" - }, - { - name: "Blue", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/b/bd/ArmbandBlue.png/revision/latest?cb=20161127174803" - }, - { - name: "Green", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/ce/ArmbandGreen.png/revision/latest?cb=20161127174812" - }, - { - name: "Orange", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/e6/ArmbandOrange.png/revision/latest?cb=20161127174846" - }, - { - name: "Pink", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/f/f7/ArmbandPink.png/revision/latest?cb=20161127174854" - }, - { - name: "Red", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/1/14/Armband.png/revision/latest?cb=20161127174901" - }, - { - name: "Yellow", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/8/81/ArmbandYellow.png/revision/latest?cb=20161127174918" - }, - { - name: "White", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/c7/Armband_White.png/revision/latest?cb=20161127174926" - }, - { - name: "Altis", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/ee/Flag_alti_co.png/revision/latest?cb=20200820222622" - }, - { - name: "Asiain Pacific Alliance (APA)", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/c2/Flag_apa_co.png/revision/latest?cb=20200820222623" - }, - { - name: "Bear", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/e1/Flag_bear_co.png/revision/latest?cb=20200820222626" - }, - { - name: "Bohemia Interactive", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/ee/Flag_bi_co.png/revision/latest?cb=20200820222627" - }, - { - name: "Brain", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/7/7d/Flag_brain_co.png/revision/latest?cb=20200820222628" - }, - { - name: "Chernarussian Defence Forces (CDF)", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/d/d6/Flag_cdf_co.png/revision/latest?cb=20200820222629" - }, - { - name: "Chedaki (CHED)", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/9/96/Flag_ched_co.png/revision/latest?cb=20200820222630" - }, - { - name: "CHEL", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/9/98/Flag_chel_co.png/revision/latest?cb=20200820222631" - }, - { - name: "Chernarus", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/ef/Flag_chern_co.png/revision/latest?cb=20200820222632" - }, - { - name: "Chernarus Mining Corporation (CMC)", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/d/da/Flag_cmc_co.png/revision/latest?cb=20200820222634" - }, - { - name: "Rooster", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/4/44/Flag_cock_co.png/revision/latest?cb=20200820222635" - }, - { - name: "DayZ", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/b/b2/Flag_dayz_co.png/revision/latest?cb=20200820222636" - }, - { - name: "North Sahrani (DROS)", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/2/24/Flag_dros_co.png/revision/latest?cb=20200820222637" - }, - { - name: "Fawn", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/d/d2/Flag_fawn_co.png/revision/latest/scale-to-width-down/1000?cb=20200820222639" - }, - { - name: "Pirates", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/a/ab/Flag_jolly_co.png/revision/latest?cb=20200820222643" - }, - { - name: "Cannibals", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/4/42/Flag_jolly_c_co.png/revision/latest?cb=20200820222641" - }, - { - name: "South Sahrani (KOS)", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/a/a1/Flag_kos_co.png/revision/latest?cb=20200820222644" - }, - { - name: "Livonia Army (LDF)", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/c1/Flag_ldf_co.png/revision/latest?cb=20200820222645" - }, - { - name: "Livonia", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/e6/Flag_livo_co.png/revision/latest?cb=20200820222647" - }, - { - name: "NAPA", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/e4/Flag_napa_co.png/revision/latest?cb=20200820222648" - }, - { - name: "Livonia Police", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/6/63/Flag_police_co.png/revision/latest?cb=20200820222649" - }, - { - name: "TEC", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/ea/Flag_tec_co.png/revision/latest?cb=20200820222650" - }, - { - name: "United Earth Coalition (UEC)", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/ca/Flag_uec_co.png/revision/latest?cb=20200820222651" - }, - { - name: "Wolf", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/b/b2/Flag_wolf_co.png/revision/latest?cb=20200820222653" - }, - { - name: "Zenit Radio Station", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/0/05/Flag_zenit_co.png/revision/latest?cb=20200820222654" - }, - { - name: "Zombie Hunters", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/9/97/Flag_zhunters_co.png/revision/latest?cb=20200820222621" - }, - { - name: "RSTA", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/2/20/Flag_rsta_co.png/revision/latest/scale-to-width-down/1000?cb=20210216191221" - }, - { - name: "Refuge", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/8/8e/Flag_refuge_co.png/revision/latest/scale-to-width-down/1000?cb=20210216191205" - }, - { - name: "Snake", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/5/54/Flag_snake_co.png/revision/latest/scale-to-width-down/1000?cb=20210216191234" - }, - { - name: "Zagorky", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/7/75/Flag_zagorky_co.png/revision/latest/scale-to-width-down/1000?cb=20230619164704" - }, - { - name: "Crook", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/c8/Flag_crook_co.png/revision/latest/scale-to-width-down/1000?cb=20230619164705" - }, - { - name: "Rex", - url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/c5/Flag_rex_co.png/revision/latest/scale-to-width-down/1000?cb=20230619164706" - }, - ] -} diff --git a/database/destinations.js b/database/destinations.js deleted file mode 100644 index 0e09527..0000000 --- a/database/destinations.js +++ /dev/null @@ -1,684 +0,0 @@ -const { calculateVector } = require('../util/Vector'); - -module.exports = { - Missions: { - "dayzOffline.chernarusplus": "Chernarus", - "dayzOffline.enoch": "Livonia", - "dayzOffline.sakhal": "Sakhal", - }, - - // Calculates the nearest location to a given coordinate - nearest: (pos, mission) => { - let tempDest; - let lastDist = 1000000; - let destination_dir; - for (let i = 0; i < destinations[mission].length; i++) { - let { distance, theta, dir } = calculateVector(pos, destinations[mission][i].coord); - if (distance < lastDist) { - tempDest = destinations[mission][i].name; - lastDist = distance; - destination_dir = dir; - } - } - return lastDist > 500 ? `${destination_dir} of ${tempDest}` : `Near ${tempDest}`; - } -} - -// A curated list of destinations across DayZ Chernarus and Livonia -const destinations = { - Chernarus: [ - { - name: 'Sinystok', - coord: [1481.47, 11933.38], - }, { - name: 'Novaya Petrovka', - coord: [3437.31, 13010.46], - }, { - name: 'Zaprundoe', - coord: [5171.52, 12753.83], - }, { - name: 'Ratnoe', - coord: [6174.72, 12722.72], - }, { - name: 'Severograd', - coord: [7986.69, 12699.39], - }, { - name: 'Svergino', - coord: [9464.27, 13718.14], - }, { - name: 'West Novodmitrovsk', - coord: [10988.51, 14344.17], - }, { - name: 'East Novodmitrovsk', - coord: [12143.35, 14336.39], - }, { - name: 'North Novodmitrovsk', - coord: [11544.55, 14764.11], - }, { - name: 'Cernaya Polyana', - coord: [12112.25, 13760.91], - }, { - name: 'Turovo', - coord: [13585.94, 14060.32], - }, { - name: 'Karmanovka', - coord: [12679.95, 14678.56], - }, { - name: 'Dobroe', - coord: [12956.02, 15051.85], - }, { - name: 'Belaya Polyana', - coord: [14161.41, 14942.97], - }, { - name: 'Svetlojarsk', - coord: [14001.99, 13251.54], - }, { - name: 'Olsha', - coord: [13348.75, 12897.70], - }, { - name: 'Black Lake', - coord: [13438.18, 12127.80], - }, { - name: 'Krasno Airfield', - coord: [12018.93, 12586.63], - }, { - name: 'Krasnostav', - coord: [11163.49, 12248.34], - }, { - name: 'Rify', - coord: [13811.46, 11210.15], - }, { - name: 'Khelmn', - coord: [12287.22, 10840.75], - }, { - name: 'North Berezino', - coord: [12905.47, 10059.19], - }, { - name: 'Central Berezino', - coord: [12423.31, 9600.36], - }, { - name: 'South Berezino', - coord: [11968.38, 9079.32], - }, { - name: 'Dubrovka', - coord: [10362.48, 9837.55], - }, { - name: 'Vyshnaya Dubrovka', - coord: [9891.99, 10432.47], - }, { - name: 'North Solnichniy', - coord: [13123.22, 7100.15] - }, { - name: 'Solnichniy', - coord: [13418.74, 6248.60], - }, { - name: 'Orlovets', - coord: [12201.68, 7275.12], - }, { - name: 'Polana', - coord: [10743.54, 8134.45], - }, { - name: 'Gorka', - coord: [9487.60, 8811.03], - }, { - name: 'Radio Zenit', - coord: [8128.62, 9230.97], - }, { - name: 'Dolina', - coord: [11276.25, 6594.66], - }, { - name: 'Devil\'s Castle', - coord: [6890.18, 11439.56], - }, { - name: 'Zolotar Castle (Black Mountain)', - coord: [10189.45, 12038.37], - }, { - name: 'Kamensk', - coord: [6684.09, 14410.27], - }, { - name: 'MB Kamensk', - coord: [7862.27, 14698.01], - }, { - name: 'Quarry', - coord: [8614.66, 13333.19], - }, { - name: 'Nagornoe', - coord: [9262.08, 14620.24], - }, { - name: 'Stary Yar', - coord: [4965.44, 15028.52], - }, { - name: 'Tisy', - coord: [3425.65, 14783.55], - }, { - name: 'MB Tisy', - coord: [1543.68, 14052.54], - }, { - name: 'Topolniki', - coord: [2834.62, 12388.32], - }, { - name: 'North NWAF', - coord: [4024.45, 11738.96], - }, { - name: 'Central NWAF', - coord: [4249.98, 10766.87], - }, { - name: 'South NWAF', - coord: [4864.34, 9588.70], - }, { - name: 'Grishino', - coord: [5976.41, 10300.27], - }, { - name: 'Kabanino', - coord: [5284.28, 8604.94], - }, { - name: 'Stary Sobor', - coord: [6058.07, 7792.28], - }, { - name: 'Novy Sobor', - coord: [7088.48, 7648.41], - }, { - name: 'MB VMC', - coord: [4483.28, 8286.10], - }, { - name: 'Vybor', - coord: [3814.48, 8904.35], - }, { - name: 'Pustoshka', - coord: [3060.14, 7905.04], - }, { - name: 'Lopatino', - coord: [2725.74, 10016.42], - }, { - name: 'Vavilovo', - coord: [2228.03, 11039.06], - }, { - name: 'Kalinka', - coord: [3301.22, 11249.03], - }, { - name: 'Biathlon Arena', - coord: [493.82, 11093.50], - }, { - name: 'Krona Castle', - coord: [1395.92, 9246.52], - }, { - name: 'Myshkino', - coord: [2010.28, 7317.90], - }, { - name: 'Polesovo', - coord: [5929.75, 13523.72], - }, { - name: 'Kalinovka', - coord: [7516.20, 13457.62], - }, { - name: 'Skalisty Island', - coord: [13620.93, 3040.70], - }, { - name: 'Kamyshovo', - coord: [12061.70, 3526.74], - }, { - name: 'Elektrozavodsk', - coord: [10273.05, 2010.28], - }, { - name: 'Cherno. Prigorodki', - coord: [7733.95, 3182.62], - }, { - name: 'Chernogorsk', - coord: [6573.28, 2544.93], - }, { - name: 'Cherno. Dubovo', - coord: [6672.43, 3616.18], - }, { - name: 'Cherno. Vysotovo', - coord: [5686.73, 2552.71], - }, { - name: 'Cherno. Novoselki', - coord: [6139.72, 3239.01], - }, { - name: 'Balota Airfield', - coord: [5054.87, 2344.68], - }, { - name: 'Balota', - coord: [4463.84, 2441.89], - }, { - name: 'Komarovo', - coord: [3670.61, 2457.44], - }, { - name: 'Prison Island', - coord: [2702.41, 1296.77], - }, { - name: 'Kamenka', - coord: [1905.30, 2231.92], - }, { - name: 'MB Pavlovo', - coord: [2130.82, 3363.43], - }, { - name: 'Pavlovo', - coord: [1675.88, 3845.59], - }, { - name: 'Bor', - coord: [3324.55, 3985.57], - }, { - name: 'Nadezhdino', - coord: [5867.54, 4790.46], - }, { - name: 'Mogilevka', - coord: [7570.64, 5140.41], - }, { - name: 'Pusta', - coord: [9192.09, 3861.14], - }, { - name: 'Staroye', - coord: [10136.96, 5443.71], - }, { - name: 'MSTA', - coord: [11334.57, 5486.48], - }, { - name: 'Tulga', - coord: [12753.83, 4405.51], - }, { - name: 'Guglovo', - coord: [8437.74, 6680.21], - }, { - name: 'Vyshnoye', - coord: [6586.88, 6054.18], - }, { - name: 'Rogovo', - coord: [4763.24, 6765.75], - }, { - name: 'Pulkovo', - coord: [4969.33, 5614.79], - }, { - name: 'Green Mountain', - coord: [3707.55, 6003.63], - }, { - name: 'Zelenogorsk', - coord: [2581.87, 5190.96], - }, { - name: 'Sosnovka', - coord: [2527.43, 6369.14], - }, { - name: 'Plotina Tishina Damn', - coord: [1193.73, 6363.30], - }, { - name: 'Zvir', - coord: [571.59, 5294.00], - }, { - name: 'Shakhovka', - coord: [9658.69, 6555.78], - }, { - name: 'Black Forrest', - coord: [9021.00, 7792.28], - }, { - name: 'Nizhneye', - coord: [12971.57, 8142.23], - }, { - name: 'Rog Castle', - coord: [11249.03, 4281.09], - }, { - name: 'Krasnoe', - coord: [6400.24, 15012.96], - }, { - name: 'Zub Castle', - coord: [6538.28, 5595.35], - }, { - name: 'Pogorevka', - coord: [4417.18, 6400.24], - }, { - name: 'Kozlovka', - coord: [4389.96, 4693.25], - }, { - name: 'Logging Yard', - coord: [940.98, 7660.07], - }, { - name: 'Zabolotye', - coord: [1193.73, 10020.31], - }, { - name: 'Ski Resort Peak', - coord: [250.80, 11867.28], - }, - ], - Livonia: [ - { - name: 'Lukow', - coord: [3575.00, 11925.00], - }, { - name: 'Brena', - coord: [6518.75, 11228.13], - }, { - name: 'Kolembrody', - coord: [8406.25, 11968.75], - }, { - name: 'Grabin', - coord: [10756.25, 11062.50], - }, { - name: 'Sitnik', - coord: [11440.63, 9543.75], - }, { - name: 'Tarnow', - coord: [9275.00, 10921.88], - }, { - name: 'Sobatka', - coord: [6250.00, 10193.75], - }, { - name: 'Gliniska', - coord: [5012.50, 9881.25], - }, { - name: 'Gliniska Airfield', - coord: [3968.75, 10278.13] - }, { - name: 'Kopa', - coord: [5545.31, 8748.44], - }, { - name: 'Olszanka', - coord: [4856.25, 7571.88], - }, { - name: 'Radacz', - coord: [4006.25, 7972.66], - }, { - name: 'Topolin', - coord: [1665.62, 7378.13], - }, { - name: 'Bielawa', - coord: [1525.00, 9700.00], - }, { - name: 'Adamow', - coord: [3081.25, 6793.75], - }, { - name: 'Muratyn', - coord: [4587.50, 6387.50], - }, { - name: 'Lipina', - coord: [5943.75, 6787.50], - }, { - name: 'Nidek', - coord: [6118.75, 8056.25], - }, { - name: 'Zapadlisko', - coord: [8093.75, 8710.94], - }, { - name: 'Krsnik Military', - coord: [7841.02, 10075.39], - }, { - name: 'Zalesie', - coord: [878.12, 5512.50], - }, { - name: 'Borek Military', - coord: [9807.81, 8500.00], - }, { - name: 'Polkrabiec', - coord: [11878.13, 6571.09], - }, { - name: 'Lembork', - coord: [8825.00, 6628.13], - }, { - name: 'Karlin', - coord: [10064.39, 6924.93], - }, { - name: 'Radunin', - coord: [7301.89, 6418.68], - }, { - name: 'Roztoka', - coord: [7650.00, 5246.88], - }, { - name: 'Sarnowek', - coord: [3287.50, 5009.38], - }, { - name: 'Huta', - coord: [5154.69, 5520.31], - }, { - name: 'Drewniki', - coord: [5834.38, 5084.38], - }, { - name: 'Nadbor', - coord: [6056.25, 4103.13], - }, { - name: 'Nadbor Military', - coord: [5625.00, 3787.50], - }, { - name: 'Max', - coord: [6448.44, 4732.81], - }, { - name: 'Wrzeszcz', - coord: [9042.19, 4385.94], - }, { - name: 'Gieraltow', - coord: [11243.75, 4332.81], - }, { - name: 'Konopki', - coord: [11460.16, 2889.84], - }, { - name: 'Swarog Military', - coord: [5017.19, 2146.88], - }, { - name: 'Hedrykow', - coord: [4487.50, 4825.00], - }, { - name: 'Polana', - coord: [3296.87, 2043.75], - }, { - name: 'Dambog', - coord: [597.27, 1138.67], - }, { - name: 'Dolnik', - coord: [11410.94, 578.12], - }, { - name: 'Widok', - coord: [10234.38, 2165.63], - }, - ], - Sakhal: [ - { - name: 'Tochka', - coord: [3731.25, 14404.69], - }, - { - name: 'Utes', - coord: [5396.25, 14539.69], - }, - { - name: 'Sputnik', - coord: [7738.13, 14820.00], - }, - { - name: 'West Uzhki', - coord: [10501.88, 14588.44], - }, - { - name: 'East Uzhki', - coord: [11251.88, 14420.63], - }, - { - name: 'Tungar', - coord: [12673.13, 14116.88], - }, - { - name: 'Jasnomorsk', - coord: [6953.44, 13388.44], - }, - { - name: 'Jevai', - coord: [7937.81, 13541.25], - }, - { - name: 'Tumanovo', - coord: [8444.06, 13693.13], - }, - { - name: 'Severomorsk', - coord: [9570.94, 13525.31], - }, - { - name: 'Orlovo', - coord: [10369.69, 13320.94], - }, - { - name: 'Podgornoe', - coord: [10984.69, 13170.94], - }, - { - name: 'Rybnoe', - coord: [12423.75, 12722.81], - }, - { - name: 'Rudnogorsk', - coord: [13573.13, 11874.38], - }, - { - name: 'Matrosovo', - coord: [14266.88, 11621.25], - }, - { - name: 'Vajkovo', - coord: [14555.63, 9804.38], - }, - { - name: 'Sumnoe', - coord: [14385.00, 8866.88], - }, - { - name: 'Vostok', - coord: [13908.75, 8362.50], - }, - { - name: 'Aniva', - coord: [12823.13, 7370.63], - }, - { - name: 'Juznoe', - coord: [10950.00, 6313.13], - }, - { - name: 'Taranay', - coord: [9703.13, 6547.50], - }, - { - name: 'Nogovo', - coord: [7681.88, 7848.75], - }, - { - name: 'Airfield', - coord: [7104.38, 7325.63], - }, - { - name: 'Dudino', - coord: [6133.13, 7286.25], - }, - { - name: 'Bolotnoe', - coord: [5083.13, 8660.63], - }, - { - name: 'South Petropavlovsk-Sachalsky', - coord: [5443.13, 10001.25], - }, - { - name: 'North Petropavlovsk-Sachalsky', - coord: [5585.63, 11197.50], - }, - { - name: 'Zupanovo', - coord: [5747.81, 12585.94], - }, - { - name: 'Sovetskoe', - coord: [6398.44, 12825.00], - }, - { - name: 'Neran', - coord: [2685.00, 9251.25], - }, - { - name: 'Tugar', - coord: [1742.81, 6121.88], - }, - { - name: 'Cerny Mys', - coord: [5173.13, 3828.75], - }, - { - name: 'Kekra', - coord: [7066.88, 4280.63], - }, - { - name: 'Slomanyy', - coord: [6333.75, 6453.75], - }, - { - name: 'Utichy', - coord: [8563.13, 5079.38], - }, - { - name: 'Elizarovo', - coord: [13395.00, 5175.00], - }, - { - name: 'Solisko', - coord: [12693.75, 2291.25], - }, - { - name: 'Mrak', - coord: [8480.63, 1313.44], - }, - { - name: 'Ketoj', - coord: [5626.88, 1991.25], - }, - { - name: 'Urup', - coord: [1680.00, 870.00], - }, - { - name: 'Ayan', - coord: [1018.12, 2891.25], - }, - { - name: 'Cerepacha', - coord: [813.75, 11287.50], - }, - { - name: 'Odinokij Vulkan', - coord: [10020.00, 12008.44], - }, - { - name: 'Pik Bolcij', - coord: [8195.63, 11675.63], - }, - { - name: 'Sakhalskaj GeoES', - coord: [8366.25, 10274.06], - }, - { - name: 'Dolinovka', - coord: [9823.13, 9838.13], - }, - { - name: 'Lesogorovka', - coord: [11006.25, 9729.38], - }, - { - name: 'Sachalag Military', - coord: [12140.63, 9757.50], - }, - { - name: 'Goriachevo', - coord: [8887.50, 10018.13], - }, - { - name: 'Yasnaya Polyana', - coord: [8128.13, 9150.00], - }, - { - name: 'Tichoe', - coord: [6245.63, 8655.00], - }, - { - name: 'Ledanoj Greben Military', - coord: [10378.13, 8555.63], - }, - { - name: 'Vysokoe', - coord: [11165.63, 7910.63], - }, - ], -} \ No newline at end of file diff --git a/database/guild.js b/database/guild.js deleted file mode 100644 index c3071f6..0000000 --- a/database/guild.js +++ /dev/null @@ -1,102 +0,0 @@ -module.exports = { - GetGuild: async (client, GuildId) => { - let guild = undefined; - if (client.databaseConnected) guild = await client.dbo.collection("guilds").findOne({"server.serverID":GuildId}).then(guild => guild); - - // If guild not found, generate guild default - if (!guild) { - guild = {} - guild.server = module.exports.getDefaultSettings(GuildId); - guild.Nitrado = undefined; - if (client.databaseConnected) { - client.dbo.collection("guilds").insertOne(guild, (err, res) => { - if (err) client.error(`GetGuild Insert Error: ${err}`); - }); - } - } - - return { - serverID: GuildId, - Nitrado: guild.Nitrado, - lastLog: guild.server.lastLog, - serverName: guild.server.serverName, - autoRestart: guild.server.autoRestart, - showKillfeedCoords: guild.server.showKillfeedCoords, - showKillfeedWeapon: guild.server.showKillfeedWeapon, - purchaseUAV: guild.server.purchaseUAV, - purchaseEMP: guild.server.purchaseEMP, - allowedChannels: guild.server.allowedChannels, - customChannelStatus: guild.server.allowedChannels.length > 0 ? true : false, - hasBotAdmin: guild.server.botAdminRoles.length > 0 ? true : false, - - killfeedChannel: guild.server.killfeedChannel, - connectionLogsChannel: guild.server.connectionLogsChannel, - activePlayersChannel: guild.server.activePlayersChannel, - welcomeChannel: guild.server.welcomeChannel, - - factionArmbands: guild.server.factionArmbands, - usedArmbands: guild.server.usedArmbands, - excludedRoles: guild.server.excludedRoles, - hasExcludedRoles: guild.server.excludedRoles.length > 0 ? true : false, - botAdminRoles: guild.server.botAdminRoles, - - alarms: guild.server.alarms, - events: guild.server.events, - uavs: guild.server.uavs, - - incomeRoles: guild.server.incomeRoles, - incomeLimiter: guild.server.incomeLimiter, - - startingBalance: guild.server.startingBalance, - uavPrice: guild.server.uavPrice, - empPrice: guild.server.empPrice, - - linkedGamertagRole: guild.server.linkedGamertagRole, - memberRole: guild.server.memberRole, - adminRole: guild.server.adminRole, - - combatLogTimer: guild.server.combatLogTimer, - }; - }, - - getDefaultSettings(GuildId) { - return { - serverID: GuildId, - lastLog: null, - serverName: "our server!", - autoRestart: 0, - showKillfeedCoords: 0, - showKillfeedWeapon: 0, - purchaseUAV: 1, // Allow/Disallow purchase of UAVs - purchaseEMP: 1, // Allow/Disallow purchase of EMPs - allowedChannels: [], - - killfeedChannel: "", - connectionLogsChannel: "", - activePlayersChannel: "", - welcomeChannel: "", - - factionArmbands: {}, - usedArmbands: [], - excludedRoles: [], - botAdminRoles: [], - - 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/player.js b/database/player.js deleted file mode 100644 index da6c2dd..0000000 --- a/database/player.js +++ /dev/null @@ -1,131 +0,0 @@ -const { weapons } = require('./weapons'); - -// Creates a copy of an object to prevent mutation of parent (i.e BodyParts, createWeaponsObject) -const copy = (obj) => JSON.parse(JSON.stringify(obj)); - -const BodyParts = { - Head: 0, - Torso: 0, - RightArm: 0, - LeftArm: 0, - RightLeg: 0, - LeftLeg: 0, -}; - -const createWeaponsObject = (value) => { - const defaultWeapons = {}; - for (const [_, weaponNames] of Object.entries(weapons)) { - for (const [name, _] of Object.entries(weaponNames)) { - defaultWeapons[name] = value; - } - } - return copy(defaultWeapons); -}; - -module.exports = { - UpdatePlayer: async (client, player, interaction=null) => { - /* Wrapping this function in a promise solves some bugs */ - return new Promise(resolve => { - client.dbo.collection("players").updateOne( - { "playerID": player.playerID }, - { $set: {...player} }, - { upsert: true }, // Create player stat document if it does not exist - (err, _) => { - if (err) { - if (interaction == null) return client.error(`UpdatePlayer Error: ${err}`); - else return client.sendInternalError(interaction, `UpdatePlayer Error: ${err}`); - } else resolve(); - } - ); - }); - }, - - getDefaultPlayer(gamertag, playerId, nitradoServerId) { - return { - // Identifiers - gamertag: gamertag, - playerID: playerId, - discordID: "", - nitradoServerID: nitradoServerId, - - // General PVP Stats - KDR: 0.00, - kills: 0, - deaths: 0, - killStreak: 0, - bestKillStreak: 0, - longestKill: 0, - deathStreak: 0, - worstDeathStreak: 0, - - // In depth PVP Stats - shotsLanded: 0, - timesShot: 0, - shotsLandedPerBodyPart: copy(BodyParts), - timesShotPerBodyPart: copy(BodyParts), - weaponStats: createWeaponsObject({ - kills: 0, - deaths: 0, - shotsLanded: 0, - timesShot: 0, - shotsLandedPerBodyPart: copy(BodyParts), - timesShotPerBodyPart: copy(BodyParts), - }), - combatRating: 800, - highestCombatRating: 800, - lowestCombatRating: 800, - combatRatingHistory: [800], - - // General Session Data - lastConnectionDate: null, - lastDisconnectionDate: null, - lastDamageDate: null, - lastDeathDate: null, - lastHitBy: null, - connected: false, - pos: [], - lastPos: [], - time: null, - lastTime: null, - - // Session Stats - totalSessionTime: 0, - lastSessionTime: 0, - longestSessionTime: 0, - connections: 0, - - // Other - bounties: [], - bountiesLength: 0, - } - }, - - insertPVPstats(player) { - player.shotsLanded = 0; - player.timesShot = 0; - player.shotsLandedPerBodyPart = copy(BodyParts); - player.timesShotPerBodyPart = copy(BodyParts); - player.weaponStats = createWeaponsObject({ - kills: 0, - deaths: 0, - shotsLanded: 0, - timesShot: 0, - shotsLandedPerBodyPart: copy(BodyParts), - timesShotPerBodyPart: copy(BodyParts), - }); - return player; - }, - - // If a new weapon is not in the existing weaponStats, this will add it. - createWeaponStats(player, weapon) { - player.weaponStats[weapon] = { - kills: 0, - deaths: 0, - shotsLanded: 0, - timesShot: 0, - shotsLandedPerBodyPart: copy(BodyParts), - timesShotPerBodyPart: copy(BodyParts), - } - return player; - } -} diff --git a/database/user.js b/database/user.js deleted file mode 100644 index 05e57ac..0000000 --- a/database/user.js +++ /dev/null @@ -1,43 +0,0 @@ -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/database/weapons.js b/database/weapons.js deleted file mode 100644 index 36b0221..0000000 --- a/database/weapons.js +++ /dev/null @@ -1,77 +0,0 @@ -module.exports = { - weapons: { - handguns: { - "CR-75": "https://static.wikia.nocookie.net/dayz_gamepedia/images/4/40/CZ75.png/revision/latest/scale-to-width-down/112?cb=20210505021307", - "Deagle": "https://static.wikia.nocookie.net/dayz_gamepedia/images/6/62/Deagle.png/revision/latest/scale-to-width-down/127?cb=20210512003023", - "Derringer": "https://static.wikia.nocookie.net/dayz_gamepedia/images/9/9f/Derringer_Black.png/revision/latest/scale-to-width-down/105?cb=20220521175445", - "FX-45": "https://static.wikia.nocookie.net/dayz_gamepedia/images/f/fd/FNX45.png/revision/latest/scale-to-width-down/104?cb=20210505025055", - "IJ-70": "https://static.wikia.nocookie.net/dayz_gamepedia/images/2/26/MakarovIJ70.png/revision/latest/scale-to-width-down/92?cb=20210209000551", - "Kolt 1911": "https://static.wikia.nocookie.net/dayz_gamepedia/images/f/f9/Colt1911.png/revision/latest/scale-to-width-down/112?cb=20210505030200", - "Longhorn": "https://static.wikia.nocookie.net/dayz_gamepedia/images/7/79/Longhorn.png/revision/latest/scale-to-width-down/222?cb=20220324214533", - "MK II": "https://static.wikia.nocookie.net/dayz_gamepedia/images/0/0d/MKII.png/revision/latest/scale-to-width-down/171?cb=20210210153348", - "Mlock-91": "https://static.wikia.nocookie.net/dayz_gamepedia/images/9/9b/Glock19.png/revision/latest/scale-to-width-down/121?cb=20210505024259", - "P1": "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/cc/P1.png/revision/latest/scale-to-width-down/120?cb=20220518204515", - "Revolver": "https://static.wikia.nocookie.net/dayz_gamepedia/images/6/6d/Revolver.png/revision/latest/scale-to-width-down/148?cb=20210208232303", - "Signal Pistol": "https://static.wikia.nocookie.net/dayz_gamepedia/images/a/a7/Flaregun.png/revision/latest/scale-to-width-down/107?cb=20210501150913", - }, - shotguns: { - "BK-12": "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/cb/Izh18Shotgun.png/revision/latest/scale-to-width-down/256?cb=20220922184507", - "BK-133": "https://static.wikia.nocookie.net/dayz_gamepedia/images/5/5c/MP-133-Shotgun.png/revision/latest/scale-to-width-down/256?cb=20210210190104", - "BK-43": "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/c7/Izh43Shotgun.png/revision/latest/scale-to-width-down/256?cb=20210210185835", - "Vaiga": "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/c8/Vaiga.png/revision/latest/scale-to-width-down/256?cb=20220220185225", - }, - subMachineGuns: { - "Bizon": "https://static.wikia.nocookie.net/dayz_gamepedia/images/a/af/PP19.png/revision/latest/scale-to-width-down/251?cb=20220127132305", - "CR-61 Skorpion": "https://static.wikia.nocookie.net/dayz_gamepedia/images/6/63/VZ61Scorpion.png/revision/latest/scale-to-width-down/222?cb=20220518204508", - "SG5-K": "https://static.wikia.nocookie.net/dayz_gamepedia/images/f/fc/MP5-K.png/revision/latest/scale-to-width-down/158?cb=20220221011343", - "USG-45": "https://static.wikia.nocookie.net/dayz_gamepedia/images/d/d7/UMP45.png/revision/latest/scale-to-width-down/153?cb=20220221002354", - }, - assaultRifles: { - "AUR A1": "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/e6/AugShort.png/revision/latest/scale-to-width-down/173?cb=20211104175243", - "AUR AX": "https://static.wikia.nocookie.net/dayz_gamepedia/images/b/be/Aug.png/revision/latest/scale-to-width-down/233?cb=20211104182427", - "KA-101": "https://static.wikia.nocookie.net/dayz_gamepedia/images/f/f2/AK101.png/revision/latest/scale-to-width-down/251?cb=20210207040122", - "KA-74": "https://static.wikia.nocookie.net/dayz_gamepedia/images/8/8b/AK74.png/revision/latest/scale-to-width-down/253?cb=20210505013141", - "KAS-74U": "https://static.wikia.nocookie.net/dayz_gamepedia/images/0/0b/AKS74U.png/revision/latest/scale-to-width-down/191?cb=20210505014222", - "KA-M": "https://static.wikia.nocookie.net/dayz_gamepedia/images/6/6c/AKM.png/revision/latest/scale-to-width-down/244?cb=20210505011614", - "LE-MAS": "https://static.wikia.nocookie.net/dayz_gamepedia/images/2/21/FAMAS.png/revision/latest/scale-to-width-down/197?cb=20210902183114", - "M16-A2": "https://static.wikia.nocookie.net/dayz_gamepedia/images/b/b3/M16-A2.png/revision/latest/scale-to-width-down/256?cb=20220221002601", - "M4-A1": "https://static.wikia.nocookie.net/dayz_gamepedia/images/a/a1/M4A1.png/revision/latest/scale-to-width-down/223?cb=20220330014851", - "SVAL": "https://static.wikia.nocookie.net/dayz_gamepedia/images/3/39/ASVAL.png/revision/latest/scale-to-width-down/256?cb=20210208015731", - "Vikhr": "https://static.wikia.nocookie.net/dayz_gamepedia/images/0/0d/Vikhr.png/revision/latest/scale-to-width-down/173?cb=20240116163108" - }, - battleRifles: { - "LAR": "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/e9/FAL.png/revision/latest/scale-to-width-down/256?cb=20220221001123", - }, - boltActionRifles: { - "CR-527": "https://static.wikia.nocookie.net/dayz_gamepedia/images/f/f0/CR527Wood.png/revision/latest/scale-to-width-down/256?cb=20220518204503 ", - "CR-550 Savanna": "https://static.wikia.nocookie.net/dayz_gamepedia/images/4/44/CR-550_Savanna.png/revision/latest/scale-to-width-down/256?cb=20220518204410", - "M70 Tundra": "https://static.wikia.nocookie.net/dayz_gamepedia/images/6/62/Winchester70.png/revision/latest/scale-to-width-down/256?cb=20220517152918", - "Mosin 91/30": "https://static.wikia.nocookie.net/dayz_gamepedia/images/a/a8/Mosin9130.png/revision/latest/scale-to-width-down/256?cb=20230126021955", - "Pioneer": "https://static.wikia.nocookie.net/dayz_gamepedia/images/6/69/Scout.png/revision/latest/scale-to-width-down/256?cb=20220518204357", - "SSG 82": "https://static.wikia.nocookie.net/dayz_gamepedia/images/1/10/SSG82.png/revision/latest/scale-to-width-down/256?cb=20220922192455", - "VS-89": "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/ea/SV98.png/revision/latest/scale-to-width-down/256?cb=20240424164607", - }, - breakActionRifles: { - "BK-18": "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/cb/IZH18_Rifle.png/revision/latest/scale-to-width-down/256?cb=20220517154121", - "Blaze": "https://static.wikia.nocookie.net/dayz_gamepedia/images/8/8a/Blaze_95_Double_Rifle_Wood.png/revision/latest/scale-to-width-down/256?cb=20220517154129", - }, - leverActionRifles: { - "Repeater Carbine": "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/ce/Repeater.png/revision/latest/scale-to-width-down/256?cb=20220517154151", - }, - marksmanRifles: { - "VSD": "https://static.wikia.nocookie.net/dayz_gamepedia/images/a/a2/SVD_w._PSO-1.png/revision/latest/scale-to-width-down/256?cb=20220220235826", - "VSS": "https://static.wikia.nocookie.net/dayz_gamepedia/images/8/83/VSSVintorez.png/revision/latest/scale-to-width-down/256?cb=20210208202042", - }, - semiAutomaticRifles: { - "DMR": "https://static.wikia.nocookie.net/dayz_gamepedia/images/b/b4/M14.png/revision/latest/scale-to-width-down/350?cb=20231005142636", - "SK 59/66": "https://static.wikia.nocookie.net/dayz_gamepedia/images/f/fe/SKS.png/revision/latest/scale-to-width-down/256?cb=20220517154633", - "Sporter 22": "https://static.wikia.nocookie.net/dayz_gamepedia/images/5/5b/Sporter_22_Wood.png/revision/latest/scale-to-width-down/256?cb=20220518204154", - }, - other: { - "Crossbow": "https://static.wikia.nocookie.net/dayz_gamepedia/images/7/79/Crossbow.png/revision/latest/scale-to-width-down/212?cb=20180121164101", - "M79": "https://static.wikia.nocookie.net/dayz_gamepedia/images/b/b7/M79.png/revision/latest/scale-to-width-down/256?cb=20220521184052", - }, - }, - - weaponClassOf: (weapon) => Object.keys(module.exports.weapons).filter(c => weapon in module.exports.weapons[c])[0], -} diff --git a/events/guildCreate.js b/events/guildCreate.js deleted file mode 100644 index ee141d1..0000000 --- a/events/guildCreate.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = (client, guild) => { - require("../util/RegisterSlashCommands").RegisterGuildCommands(client, guild.id); -}; \ No newline at end of file diff --git a/events/guildMemberAdd.js b/events/guildMemberAdd.js deleted file mode 100644 index f128f74..0000000 --- a/events/guildMemberAdd.js +++ /dev/null @@ -1,17 +0,0 @@ -const { EmbedBuilder } = require('discord.js'); -const { GetGuild } = require('../database/guild'); - -module.exports = async (client, member) => { - - let GuildDB = await GetGuild(client, member.guild.id); - if (!client.exists(GuildDB.welcomeChannel)) return; - const channel = client.GetChannel(GuildDB.welcomeChannel); - - if (GuildDB.serverName == "") GuildDB.serverName = "our server!" - - let embed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`**Welcome** <@${member.user.id}> to **${GuildDB.serverName}**\nUse the command to link your Discord to your gamertag.`); - - channel.send({ content: `<@${member.user.id}>`, embeds: [embed] }); -}; diff --git a/events/interactionCreate.js b/events/interactionCreate.js deleted file mode 100644 index 621aa14..0000000 --- a/events/interactionCreate.js +++ /dev/null @@ -1,21 +0,0 @@ -const { InteractionType } = require('discord.js'); -const { GetGuild } = require('../database/guild'); - - -module.exports = async (client, interaction) => { - if (interaction.type == InteractionType.ApplicationCommand) return; - /* - This file routes any menu, modal & button interactions - from any command - */ - - let GuildDB = await GetGuild(client, interaction.guildId); - const interactionName = interaction.customId.split("-")[0]; - let interactionHandler = client.interactionHandlers.get(interactionName); - - try { - interactionHandler.run(client, interaction, GuildDB); - } catch (err) { - client.sendInternalError(interaction, err); - } -} \ No newline at end of file diff --git a/events/ready.js b/events/ready.js deleted file mode 100644 index 0892534..0000000 --- a/events/ready.js +++ /dev/null @@ -1,11 +0,0 @@ -module.exports = async (client) => { - (client.Ready = true), - client.user.setActivity({ - type: client.config.Presence.type, - name: client.config.Presence.name - }); - client.log(`Successfully Logged in as ${client.user.tag}`); - client.log(`Ready to serve in ${client.channels.cache.size} channels on ${client.guilds.cache.size} servers, for a total of ${client.users.cache.size} users.`) - client.RegisterSlashCommands(); - setInterval(client.logsUpdateTimer, client.timer, client); -}; diff --git a/index.js b/index.js deleted file mode 100644 index 2ce095a..0000000 --- a/index.js +++ /dev/null @@ -1,8 +0,0 @@ -const { ShardingManager } = require('discord.js'); -const config = require('./config/config'); - -const manager = new ShardingManager('./bot.js', { token: config.Token }); - -manager.on('shardCreate', shard => console.log(`Launched shard ${shard.id}`)); - -manager.spawn(); diff --git a/src/DayZRBot.js b/src/DayZRBot.js new file mode 100644 index 0000000..3729fe0 --- /dev/null +++ b/src/DayZRBot.js @@ -0,0 +1,558 @@ +const { RegisterGlobalCommands, RegisterGuildCommands } = require("./util/RegisterSlashCommands"); +const { Collection, Client, EmbedBuilder, Routes, InteractionResponseType, InteractionType, GatewayDispatchEvents } = require("discord.js"); +const MongoClient = require("mongodb").MongoClient; +const { REST } = require("@discordjs/rest"); +const Logger = require("./util/Logger"); +const crypto = require("crypto"); + +// custom util imports +const { DownloadNitradoFile, CheckServerStatus, FetchServerSettings, PostServerSettings, NitradoCredentialStatus } = require("../util/NitradoAPI"); +const { HandlePlayerLogs, HandleActivePlayersList } = require("../util/LogsHandler"); +const { HandleKillfeed, UpdateLastDeathDate } = require("../util/KillfeedHandler"); +const { HandleExpiredUAVs, HandleEvents, PlaceFireplaceInAlarm } = require("../util/AlarmsHandler"); +const { decrypt } = require("../util/Cryptic"); +const { GetWebhook, WebhookSend } = require("./util/WebhookHandler"); + +// Data structures imports +const { getDefaultPlayer, UpdatePlayer } = require("../database/player"); +const { Missions } = require("../database/destinations"); +const { GetGuild } = require("../database/guild"); + +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 10 minutes (600,000ms) + +class DayzRBot extends Client { + + constructor(options, config) { + super(options); + + this.config = config; + this.commands = new Collection(); + this.interactionHandlers = new Collection(); + 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.SecretKey === "" || + this.config.SecretIv === "" + ) { + throw new TypeError( + "The config.js is not filled out. Please make sure nothing is blank, otherwise the bot will not work properly." + ); + } + + if (!["DEV.", "PROD."].includes(this.config.Dev)) { + throw new TypeError( + "The Dev version in the config.js does not match the allowed cases of \"DEV.\" or \"PROD.\"" + ); + } + + // Generate secret hash with crypto to use for encryption + this.key = crypto + .createHash("sha512") + .update(this.config.SecretKey) + .digest("hex") + .substring(0, 32); + + this.encryptionIV = crypto + .createHash("sha512") + .update(this.config.SecretIv) + .digest("hex") + .substring(0, 16); + + this.db; + this.dbo; + + this.databaseConnected = false; + this.arInterval = arInterval; + this.arIntervalIds = new Map(); + this.playerSessions = new Map(); + this.logHistory = new Map(); + this.alarmPingQueue = new Map(); + this.playerListMsgIds = new Map(); + + this.initialize(); + this.LoadCommandsAndInteractionHandlers(); + this.LoadEvents(); + + this.Ready = false; + this.activePlayersTick = 11; + + this.ws.on(GatewayDispatchEvents.InteractionCreate, async (interaction) => { + const start = new Date().getTime(); + if (interaction.type == InteractionType.ApplicationCommand) { + let GuildDB = await GetGuild(this, interaction.guild_id); + + if (this.exists(GuildDB.Nitrado) && this.exists(GuildDB.Nitrado.Auth)) { + GuildDB.Nitrado.Auth = decrypt( + GuildDB.Nitrado.Auth, + this.config.EncryptionMethod, + this.key, + this.encryptionIV + ); + } + + const command = interaction.data.name.toLowerCase(); + const args = interaction.data.options; + + // Free unused armbands for related commands + if (["armbands", "claim", "factions"].includes(command)) { + for (const [factionID, data] of Object.entries(GuildDB.factionArmbands)) { + const guild = this.guilds.cache.get(GuildDB.serverID); + const role = guild.roles.cache.find(role => role.id == factionID); + if (!role) { + let query = { + $pull: { "server.usedArmbands": data.armband }, + $unset: { [`server.factionArmbands.${factionID}`]: "" }, + }; + this.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, query, (err, res) => { + if (err) return this.sendInternalError(interaction, err); + }); + } + } + } + + this.log(`Interaction [${interaction.guild_id}] - ${command}`); + + const rest = new REST({ version: "10" }).setToken(this.config.Token); + + // Easy to send response so ;) + interaction.guild = await this.guilds.fetch(interaction.guild_id); + const handleCallback = async (interactionType, message) => { + return await rest.post(Routes.interactionCallback(interaction.id, interaction.token), { + body: { + type: interactionType, + data: message, + } + }); + } + + // Nicely name our custom callback functions and pass correct type because discord is picky with numbers... + interaction.send = async (message) => handleCallback(InteractionResponseType.ChannelMessageWithSource, message); + interaction.deferReply = async (message) => handleCallback(InteractionResponseType.DeferredChannelMessageWithSource, message); + interaction.showModal = async (message) => handleCallback(InteractionResponseType.Modal, message); + + interaction.editReply = async (message) => { + return await rest.patch(Routes.webhookMessage(this.application.id, interaction.token), { + body: message, + }); + }; + + if (!this.databaseConnected) { + let dbFailedEmbed = new EmbedBuilder() + .setDescription(`**Internal Error:**\nUh Oh D: Its not you, its me.\nThe bot has failed to connect to the database 5 times!\nContact the Developers\nhttps://discord.gg/YCXhvy9uZw`) + .setColor(this.config.Colors.Red) + + return interaction.send({ embeds: [dbFailedEmbed] }); + } + + 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) { + this.sendInternalError(interaction, err); + } + } + }); + } + + log(Text) { this.logger.log(Text); } + error(Text) { this.logger.error(Text); } + + async getDateEST(time) { + 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 + 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(guild) { + const fileStream = fs.createReadStream(`./logs/${guild.Nitrado.ServerID}-logs.ADM`); + + const rl = readline.createInterface({ + input: fileStream, + crlfDelay: Infinity + }); + let lines = []; + for await (const line of rl) { lines.push(line); } + + let logIndex = lines.indexOf(this.logHistory.get(guild.Nitrado.ServerID)); + + if (this.playerSessions.get(guild.Nitrado.ServerID).size === 0) { + let players = await this.dbo.collection("players").find({ "nitradoServerID": guild.Nitrado.ServerID }) // Get all players of this server + .toArray().then(all => all.filter(p => p.connected).map(p => p.connected = false)); // assume all players who were previously connected are not connected on init only. + + for (let i = 0; i < players.length; i++) { + await UpdatePlayer(this, players[i]) + } + } + + for (let i = logIndex + 1; i < lines.length; i++) { + // Handle lines to skip + 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 + + // Handle general logs + if (lines[i].includes("connected") || lines[i].includes("pos=<")) await HandlePlayerLogs(guild.Nitrado.ServerID, this, guild, lines[i], guild.combatLogTimer); + if (lines[i].includes("killed by Zmb") || lines[i].includes(">) died.")) await UpdateLastDeathDate(guild.Nitrado.ServerID, this, lines[i]); // Updates users last death date for non PVP deaths. + if (lines[i].includes(") placed Fireplace")) await PlaceFireplaceInAlarm(this, guild, lines[i]); + + // Handle killfeed logs + if ( + (lines[i].includes("killed by with") || lines[i].includes("killed by LandMineTrap")) || // Handle explosive deaths + (!(i + 1 >= lines.length) && lines[i + 1].includes("killed by") && lines[i].includes("TransportHit")) || // Handle vehicle deaths + (!(i + 1 >= lines.length) && lines[i + 1].includes("killed by Player") && lines[i].includes("hit by Player")) || // Handle PVP deaths + (lines[i].includes("killed by Player") && !lines[i - 1].includes("hit by Player")) // Handle deaths missing hit by log + ) await HandleKillfeed(guild.Nitrado.ServerID, this, guild, lines[i]); + } + + // Handle alarm pings + const maxEmbed = 10; + + this.alarmPingQueue.forEach(queue => { + queue.forEach(async (data, channel_id) => { + const channel = this.GetChannel(channel_id); + if (!channel) return; + + const NAME = "DayZ.R Zone Alert"; + const webhook = await GetWebhook(this, NAME, channel_id); + + data.forEach(async (embeds, role) => { + let embedArrays = []; + while (embeds.length > 0) + embedArrays.push(embeds.splice(0, maxEmbed)); + + for (let i = 0; i < embedArrays.length; i++) { + let content = { embeds: embedArrays[i] }; + if (role != "-no-role-ping-") content.content = `<@&${role}>`; + WebhookSend(this, webhook, content); + + // if (role == "-no-role-ping-") channel.send({ embeds: embedArrays[i] }); + // else channel.send({ content: `<@&${role}>`, embeds: embedArrays[i] }); + } + }); + }); + }); + + this.alarmPingQueue.set(guild.serverID, new Map()); // Clear alarm queue for this guild + + const playerTemplate = /(.*) \| Player \"(.*)\" \(id=(.*) pos=<(.*)>\)/g; + let previouslyConnected = await this.dbo.collection("players").find({ "nitradoServerID": guild.Nitrado.ServerID }) + .toArray().then(players => players.filter(p => p.connected)); // All players with connection log captured above and no disconnect log + let lastDetectedTime; + + for (let i = lines.length - 1; i > 0; i--) { + if (lines[i].includes("PlayerList log:")) { + for (let j = i + 1; j < lines.length; j++) { + let line = lines[j]; + if (line.includes("| ####")) break; + + let data = [...line.matchAll(playerTemplate)][0]; + if (!data) continue; + + let info = { + time: data[1], + player: data[2], + playerID: data[3], + }; + + if (!this.exists(info.player) || !this.exists(info.playerID)) continue; // Skip this player if the player does not exist. + + lastDetectedTime = await this.getDateEST(info.time); + + let playerStat = await this.dbo.collection("players").findOne({ "playerID": info.playerID }); + if (!this.exists(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, guild.Nitrado.ServerID); + + 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. + + // Track adjusted sessions this instance has handled (e.g. no bot crashes or restarts). + if (this.playerSessions.get(guild.Nitrado.ServerID).has(info.playerID)) { + // Player is already in a session, update the session"s end time. + const session = this.playerSessions.get(guild.Nitrado.ServerID).get(info.playerID); + session.endTime = lastDetectedTime; // Update end time. + } else { + // Player is not in a session, create a new session. + const newSession = { + startTime: lastDetectedTime, + endTime: null, // Initialize end time as null. + }; + this.playerSessions.get(guild.Nitrado.ServerID).set(info.playerID, newSession); + + // Check if the player has been marked as connected before, but only if a session doesn"t exist + // in the map, indicating the connection was discovered in the logs during this session. + if (!previouslyConnected.includes(playerStat)) { + playerStat.connected = true; + playerStat.lastConnectionDate = lastDetectedTime; // Update last connection date. + } + } + + await UpdatePlayer(this, playerStat); + } + break; + } + } + + const lastLine = lines[lines.length - 1] + this.logHistory.set(guild.Nitrado.ServerID, lastLine); + this.dbo.collection("guilds").updateOne({ "server.serverID": guild.serverID }, { $set: { "server.lastLog": lastLine } }, (err, res) => { + if (err) this.error(`Failed to save last log to guild config [${guild.serverID}] for nitrado server [${guild.Nitrado.ServerID}]`); + }); + } + + async logsUpdateTimer(c) { + c.activePlayersTick++; + + c.guilds.cache.forEach(async (guild) => { + let GuildDB = await GetGuild(c, guild.id); + + /* + Note to self: + return statements do not prematurely exit out of a forEach loop like it does in a for loop. + */ + + if (!c.exists(GuildDB.Nitrado)) return; // Continue if no nitrado credentials + if (GuildDB.Nitrado.Status == NitradoCredentialStatus.FAILED) return; // Continue if these credentials are marked as failed + + const NitradoCred = { + ServerID: GuildDB.Nitrado.ServerID, + UserID: GuildDB.Nitrado.UserID, + Auth: decrypt( + GuildDB.Nitrado.Auth, + c.config.EncryptionMethod, + c.key, + c.encryptionIV + ), + }; + + const response = await FetchServerSettings(NitradoCred, c, "logsUpdateTimer").then(res => res); + if (response == 1) { + c.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "Nitrado.Status": NitradoCredentialStatus.FAILED } }, (err, _) => { + if (err) this.error(`Failed to update Nitrado status to failed. [${GuildDB.serverID}]`); + }); + return; + }; + const settings = response.data.gameserver; + + // Update Nitrado DayZ Mission if change is detected + if (GuildDB.Nitrado.Mission !== Missions[settings.settings.config.mission]) { + c.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "Nitrado.Mission": Missions[settings.settings.config.mission] } }, (err, res) => { + if (err) this.error(`Failed to save mission to guild config [${GuildDB.serverID}] for nitrado server [${GuildDB.Nitrado.ServerID}]`); + }); + } + + GuildDB.Nitrado.Mission = Missions[settings.settings.config.mission]; + + if (settings.game_specific.log_files.length == 0) return; // Ignore if no log files on Nitrado server + const filename = settings.game_specific.log_files.sort((a, b) => a.length - b.length)[0]; + const path = `${settings.game_specific.path.slice(0, -1)}${filename.split(settings.game)[1]}`; + + // Ensure Player List is logged for next update + const playerListEnabled = parseInt(settings.settings.config.adminLogPlayerList) + if (!playerListEnabled) PostServerSettings(NitradoCred, c, "config", "adminLogPlayerList", "1") + + await DownloadNitradoFile(NitradoCred, c, path, `./logs/${NitradoCred.ServerID}-logs.ADM`).then(async (status) => { + if (status == 1) return c.error(`Failed to Download Nitrado Log Files - [${NitradoCred.ServerID}]`); + await c.readLogs(GuildDB).then(async () => { + HandleExpiredUAVs(c, GuildDB); + HandleEvents(c, GuildDB) + if (c.activePlayersTick == 12) await HandleActivePlayersList(NitradoCred, c, GuildDB); + }) + }); + }); + } + + async connectMongo(mongoURI, dbo) { + let failed = false; + + let dbLogDir = path.join(__dirname, "..", "logs", "database-logs.json"); + let databaselogs; + try { + databaselogs = JSON.parse(fs.readFileSync(dbLogDir)); + } catch (err) { + databaselogs = { + attempts: 0, + connected: false, + }; + } + + if (databaselogs.attempts >= 5) { + this.error("Failed to connect to mongodb after multiple attempts"); + return; // prevent further attempts + } + + try { + // Connect to Mongo database. + this.db = await MongoClient.connect(mongoURI, { connectTimeoutMS: 1000 }); + this.dbo = this.db.db(dbo); + this.log("Successfully connected to mongoDB"); + databaselogs.connected = true; + databaselogs.attempts = 0; // reset attempts + this.databaseConnected = true; + } catch (err) { + databaselogs.attempts++; + databaselogs.connected = false; + let db = mongoURI.includes("@") ? mongoURI.split("@")[1] : mongoURI.split("//")[1]; + db = db.includes("/") ? db.split("/")[0] : db; + this.error(`Failed to connect to mongodb (mongodb://${db}/${dbo}): attempt ${databaselogs.attempts} - ${err}`); + failed = true; + } + + // write JSON string to a file + fs.writeFileSync(dbLogDir, JSON.stringify(databaselogs)); + + if (failed) process.exit(-1); + } + + async initialize() { + // Wait for MongoDB to connect + await this.connectMongo(this.config.mongoURI, this.config.dbo); + + if (!this.databaseConnected) return; + let guilds = await this.dbo.collection("guilds").find({}).toArray(); + + /* + Initialize auto restart for enabled servers + Initialize last logs + Initialize Player Sessions + */ + for (let i = 0; i < guilds.length; i++) { + if (!this.exists(guilds[i].Nitrado)) continue; + if (guilds[i].server.autoRestart) { + const NitradoCred = { + ServerID: guilds[i].Nitrado.ServerID, + UserID: guilds[i].Nitrado.UserID, + Auth: decrypt( + guilds[i].Nitrado.Auth, + this.config.EncryptionMethod, + this.key, + this.encryptionIV + ) + }; + this.arIntervalIds.set(guilds[i].server.serverID, setInterval(CheckServerStatus, this.arInterval, NitradoCred, this)) + } + this.logHistory.set(guilds[i].Nitrado.ServerID, guilds[i].server.lastLog); // Using Nitrado Server ID over guild ID in case of future support for multiple nitrado servers in a single guild + this.playerSessions.set(guilds[i].Nitrado.ServerID, new Map()); // Same reason here as named above. + this.alarmPingQueue.set(guilds[i].server.serverID, new Map()); // Initialize alarm queue to be empty + this.playerListMsgIds.set(guilds[i].server.serverID, ""); // Initialize player list message ids + this.log(`[${guilds[i].server.serverID}] Initialized existing Nitrado Server: (${guilds[i].Nitrado.ServerID})`); + } + } + + async initNewNitradoServer(guildId, Nitrado) { + let guild = await GetGuild(this, guildId) + + if (guild.autoRestart) this.arIntervalIds.set(guildId, setInterval(CheckServerStatus, this.arInterval, Nitrado, this)) + this.logHistory.set(Nitrado.ServerID, guild.lastLog); + this.playerSessions.set(Nitrado.ServerID, new Map()); + this.alarmPingQueue.set(guildId, new Map()); + this.playerListMsgIds.set(guildId, ""); + this.log(`[${guildId}] Initialized new Nitrado`); + } + + exists(n) { return typeof (n) == "number" ? !isNaN(n) : 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 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, ") : ""; + const sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : ""; + return dDisplay + hDisplay + mDisplay + sDisplay; + } + + LoadCommandsAndInteractionHandlers() { + let CommandsDir = path.join(__dirname, "..", "commands"); + fs.readdir(CommandsDir, (err, files) => { + if (err) this.error(err); + else + files.forEach((file) => { + let cmd = require(CommandsDir + "/" + file); + 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" + ); + this.commands.set(file.split(".")[0].toLowerCase(), cmd); + if (this.exists(cmd.Interactions)) { + for (let [interaction, handler] of Object.entries(cmd.Interactions)) { + this.interactionHandlers.set(interaction, handler); + } + } + this.log("Command Loaded: " + file.split(".")[0]); + }); + }); + } + + LoadEvents() { + let EventsDir = path.join(__dirname, "..", "events"); + fs.readdir(EventsDir, (err, files) => { + if (err) this.error(err); + 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)); + else this.on(file.split(".")[0], event.bind(null, this)); + this.log("Event Loaded: " + file.split(".")[0]); + }); + }); + } + + // Allows shorter lines of code elsewhere + GetChannel(channel_id) { return this.channels.cache.get(channel_id); } + + sendError(Channel, Error) { + this.error(Error); + let embed = new EmbedBuilder() + .setColor(this.config.Red) + .setDescription(Error); + + Channel.send(embed); + } + + // Handles internal errors for slash commands. E.g failed to update database from slash command. + sendInternalError(Interaction, Error) { + this.error(Error); + const embed = new EmbedBuilder() + .setDescription(`**Internal Error:**\nUh Oh D: Its not you, its me.\nThis command has crashed\nContact the Developers\nhttps://discord.gg/YCXhvy9uZw`) + .setColor(this.config.Colors.Red) + + try { + Interaction.send({ embeds: [embed] }); + } catch { + Interaction.update({ embeds: [embed], components: [] }); + } + } + + // Calls register for guild and global commands + RegisterSlashCommands() { + RegisterGlobalCommands(this); + let p = Promise.resolve() + this.guilds.cache.forEach((guild) => { + p = p.then(() => { + RegisterGuildCommands(this, guild.id); + return new Promise((resolve) => { + setTimeout(resolve, 500); + }) + }) + }); + } + + build() { + this.login(this.config.Token); + } +} + +module.exports = DayzRBot; diff --git a/src/DayzRBot.js b/src/DayzRBot.js deleted file mode 100644 index ba872cc..0000000 --- a/src/DayzRBot.js +++ /dev/null @@ -1,558 +0,0 @@ -const { RegisterGlobalCommands, RegisterGuildCommands } = require("../util/RegisterSlashCommands"); -const { Collection, Client, EmbedBuilder, Routes, InteractionResponseType, InteractionType, GatewayDispatchEvents } = require('discord.js'); -const MongoClient = require('mongodb').MongoClient; -const { REST } = require('@discordjs/rest'); -const Logger = require("../util/Logger"); -const crypto = require('crypto'); - -// custom util imports -const { DownloadNitradoFile, CheckServerStatus, FetchServerSettings, PostServerSettings, NitradoCredentialStatus } = require('../util/NitradoAPI'); -const { HandlePlayerLogs, HandleActivePlayersList } = require('../util/LogsHandler'); -const { HandleKillfeed, UpdateLastDeathDate } = require('../util/KillfeedHandler'); -const { HandleExpiredUAVs, HandleEvents, PlaceFireplaceInAlarm } = require('../util/AlarmsHandler'); -const { decrypt } = require('../util/Cryptic'); -const { GetWebhook, WebhookSend } = require("../util/WebhookHandler"); - -// Data structures imports -const { getDefaultPlayer, UpdatePlayer } = require('../database/player'); -const { Missions } = require('../database/destinations'); -const { GetGuild } = require('../database/guild'); - -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 10 minutes (600,000ms) - -class DayzRBot extends Client { - - constructor(options, config) { - super(options); - - this.config = config; - this.commands = new Collection(); - this.interactionHandlers = new Collection(); - 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.SecretKey === "" || - this.config.SecretIv === "" - ) { - throw new TypeError( - "The config.js is not filled out. Please make sure nothing is blank, otherwise the bot will not work properly." - ); - } - - if (!["DEV.", "PROD."].includes(this.config.Dev)) { - throw new TypeError( - "The Dev version in the config.js does not match the allowed cases of 'DEV.' or 'PROD.'" - ); - } - - // Generate secret hash with crypto to use for encryption - this.key = crypto - .createHash('sha512') - .update(this.config.SecretKey) - .digest('hex') - .substring(0, 32); - - this.encryptionIV = crypto - .createHash('sha512') - .update(this.config.SecretIv) - .digest('hex') - .substring(0, 16); - - this.db; - this.dbo; - - this.databaseConnected = false; - this.arInterval = arInterval; - this.arIntervalIds = new Map(); - this.playerSessions = new Map(); - this.logHistory = new Map(); - this.alarmPingQueue = new Map(); - this.playerListMsgIds = new Map(); - - this.initialize(); - this.LoadCommandsAndInteractionHandlers(); - this.LoadEvents(); - - this.Ready = false; - this.activePlayersTick = 11; - - this.ws.on(GatewayDispatchEvents.InteractionCreate, async (interaction) => { - const start = new Date().getTime(); - if (interaction.type == InteractionType.ApplicationCommand) { - let GuildDB = await GetGuild(this, interaction.guild_id); - - if (this.exists(GuildDB.Nitrado) && this.exists(GuildDB.Nitrado.Auth)) { - GuildDB.Nitrado.Auth = decrypt( - GuildDB.Nitrado.Auth, - this.config.EncryptionMethod, - this.key, - this.encryptionIV - ); - } - - const command = interaction.data.name.toLowerCase(); - const args = interaction.data.options; - - // Free unused armbands for related commands - if (['armbands', 'claim', 'factions'].includes(command)) { - for (const [factionID, data] of Object.entries(GuildDB.factionArmbands)) { - const guild = this.guilds.cache.get(GuildDB.serverID); - const role = guild.roles.cache.find(role => role.id == factionID); - if (!role) { - let query = { - $pull: { 'server.usedArmbands': data.armband }, - $unset: { [`server.factionArmbands.${factionID}`]: "" }, - }; - this.dbo.collection("guilds").updateOne({ 'server.serverID': GuildDB.serverID }, query, (err, res) => { - if (err) return this.sendInternalError(interaction, err); - }); - } - } - } - - this.log(`Interaction [${interaction.guild_id}] - ${command}`); - - const rest = new REST({ version: '10' }).setToken(this.config.Token); - - // Easy to send response so ;) - interaction.guild = await this.guilds.fetch(interaction.guild_id); - const handleCallback = async (interactionType, message) => { - return await rest.post(Routes.interactionCallback(interaction.id, interaction.token), { - body: { - type: interactionType, - data: message, - } - }); - } - - // Nicely name our custom callback functions and pass correct type because discord is picky with numbers... - interaction.send = async (message) => handleCallback(InteractionResponseType.ChannelMessageWithSource, message); - interaction.deferReply = async (message) => handleCallback(InteractionResponseType.DeferredChannelMessageWithSource, message); - interaction.showModal = async (message) => handleCallback(InteractionResponseType.Modal, message); - - interaction.editReply = async (message) => { - return await rest.patch(Routes.webhookMessage(this.application.id, interaction.token), { - body: message, - }); - }; - - if (!this.databaseConnected) { - let dbFailedEmbed = new EmbedBuilder() - .setDescription(`**Internal Error:**\nUh Oh D: Its not you, its me.\nThe bot has failed to connect to the database 5 times!\nContact the Developers\nhttps://discord.gg/YCXhvy9uZw`) - .setColor(this.config.Colors.Red) - - return interaction.send({ embeds: [dbFailedEmbed] }); - } - - 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) { - this.sendInternalError(interaction, err); - } - } - }); - } - - log(Text) { this.logger.log(Text); } - error(Text) { this.logger.error(Text); } - - async getDateEST(time) { - 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 - 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(guild) { - const fileStream = fs.createReadStream(`./logs/${guild.Nitrado.ServerID}-logs.ADM`); - - const rl = readline.createInterface({ - input: fileStream, - crlfDelay: Infinity - }); - let lines = []; - for await (const line of rl) { lines.push(line); } - - let logIndex = lines.indexOf(this.logHistory.get(guild.Nitrado.ServerID)); - - if (this.playerSessions.get(guild.Nitrado.ServerID).size === 0) { - let players = await this.dbo.collection('players').find({"nitradoServerID": guild.Nitrado.ServerID}) // Get all players of this server - .toArray().then(all => all.filter(p => p.connected).map(p => p.connected = false)); // assume all players who were previously connected are not connected on init only. - - for (let i = 0; i < players.length; i++) { - await UpdatePlayer(this, players[i]) - } - } - - for (let i = logIndex + 1; i < lines.length; i++) { - // Handle lines to skip - 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 - - // Handle general logs - if (lines[i].includes('connected') || lines[i].includes('pos=<')) await HandlePlayerLogs(guild.Nitrado.ServerID, this, guild, lines[i], guild.combatLogTimer); - if (lines[i].includes('killed by Zmb') || lines[i].includes('>) died.')) await UpdateLastDeathDate(guild.Nitrado.ServerID, this, lines[i]); // Updates users last death date for non PVP deaths. - if (lines[i].includes(') placed Fireplace')) await PlaceFireplaceInAlarm(this, guild, lines[i]); - - // Handle killfeed logs - if ( - (lines[i].includes('killed by with') || lines[i].includes('killed by LandMineTrap')) || // Handle explosive deaths - (!(i + 1 >= lines.length) && lines[i + 1].includes('killed by') && lines[i].includes('TransportHit')) || // Handle vehicle deaths - (!(i + 1 >= lines.length) && lines[i + 1].includes('killed by Player') && lines[i].includes('hit by Player')) || // Handle PVP deaths - (lines[i].includes('killed by Player') && !lines[i - 1].includes('hit by Player')) // Handle deaths missing hit by log - ) await HandleKillfeed(guild.Nitrado.ServerID, this, guild, lines[i]); - } - - // Handle alarm pings - const maxEmbed = 10; - - this.alarmPingQueue.forEach(queue => { - queue.forEach(async (data, channel_id) => { - const channel = this.GetChannel(channel_id); - if (!channel) return; - - const NAME = "DayZ.R Zone Alert"; - const webhook = await GetWebhook(this, NAME, channel_id); - - data.forEach(async (embeds, role) => { - let embedArrays = []; - while (embeds.length > 0) - embedArrays.push(embeds.splice(0, maxEmbed)); - - for (let i = 0; i < embedArrays.length; i++) { - let content = { embeds: embedArrays[i] }; - if (role != '-no-role-ping-') content.content = `<@&${role}>`; - WebhookSend(this, webhook, content); - - // if (role == '-no-role-ping-') channel.send({ embeds: embedArrays[i] }); - // else channel.send({ content: `<@&${role}>`, embeds: embedArrays[i] }); - } - }); - }); - }); - - this.alarmPingQueue.set(guild.serverID, new Map()); // Clear alarm queue for this guild - - const playerTemplate = /(.*) \| Player \"(.*)\" \(id=(.*) pos=<(.*)>\)/g; - let previouslyConnected = await this.dbo.collection('players').find({"nitradoServerID": guild.Nitrado.ServerID}) - .toArray().then(players => players.filter(p => p.connected)); // All players with connection log captured above and no disconnect log - let lastDetectedTime; - - for (let i = lines.length - 1; i > 0; i--) { - if (lines[i].includes('PlayerList log:')) { - for (let j = i + 1; j < lines.length; j++) { - let line = lines[j]; - if (line.includes('| ####')) break; - - let data = [...line.matchAll(playerTemplate)][0]; - if (!data) continue; - - let info = { - time: data[1], - player: data[2], - playerID: data[3], - }; - - if (!this.exists(info.player) || !this.exists(info.playerID)) continue; // Skip this player if the player does not exist. - - lastDetectedTime = await this.getDateEST(info.time); - - let playerStat = await this.dbo.collection("players").findOne({"playerID": info.playerID}); - if (!this.exists(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, guild.Nitrado.ServerID); - - 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. - - // Track adjusted sessions this instance has handled (e.g. no bot crashes or restarts). - if (this.playerSessions.get(guild.Nitrado.ServerID).has(info.playerID)) { - // Player is already in a session, update the session's end time. - const session = this.playerSessions.get(guild.Nitrado.ServerID).get(info.playerID); - session.endTime = lastDetectedTime; // Update end time. - } else { - // Player is not in a session, create a new session. - const newSession = { - startTime: lastDetectedTime, - endTime: null, // Initialize end time as null. - }; - this.playerSessions.get(guild.Nitrado.ServerID).set(info.playerID, newSession); - - // Check if the player has been marked as connected before, but only if a session doesn't exist - // in the map, indicating the connection was discovered in the logs during this session. - if (!previouslyConnected.includes(playerStat)) { - playerStat.connected = true; - playerStat.lastConnectionDate = lastDetectedTime; // Update last connection date. - } - } - - await UpdatePlayer(this, playerStat); - } - break; - } - } - - const lastLine = lines[lines.length - 1] - this.logHistory.set(guild.Nitrado.ServerID, lastLine); - this.dbo.collection("guilds").updateOne({ "server.serverID": guild.serverID }, {$set: { "server.lastLog": lastLine }}, (err, res) => { - if (err) this.error(`Failed to save last log to guild config [${guild.serverID}] for nitrado server [${guild.Nitrado.ServerID}]`); - }); - } - - async logsUpdateTimer(c) { - c.activePlayersTick++; - - c.guilds.cache.forEach(async (guild) => { - let GuildDB = await GetGuild(c, guild.id); - - /* - Note to self: - return statements do not prematurely exit out of a forEach loop like it does in a for loop. - */ - - if (!c.exists(GuildDB.Nitrado)) return; // Continue if no nitrado credentials - if (GuildDB.Nitrado.Status == NitradoCredentialStatus.FAILED) return; // Continue if these credentials are marked as failed - - const NitradoCred = { - ServerID: GuildDB.Nitrado.ServerID, - UserID: GuildDB.Nitrado.UserID, - Auth: decrypt( - GuildDB.Nitrado.Auth, - c.config.EncryptionMethod, - c.key, - c.encryptionIV - ), - }; - - const response = await FetchServerSettings(NitradoCred, c, "logsUpdateTimer").then(res => res); - if (response == 1) { - c.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID }, {$set: { "Nitrado.Status": NitradoCredentialStatus.FAILED }}, (err, _) => { - if (err) this.error(`Failed to update Nitrado status to failed. [${GuildDB.serverID}]`); - }); - return; - }; - const settings = response.data.gameserver; - - // Update Nitrado DayZ Mission if change is detected - if (GuildDB.Nitrado.Mission !== Missions[settings.settings.config.mission]) { - c.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set: { "Nitrado.Mission": Missions[settings.settings.config.mission] }}, (err, res) => { - if (err) this.error(`Failed to save mission to guild config [${GuildDB.serverID}] for nitrado server [${GuildDB.Nitrado.ServerID}]`); - }); - } - - GuildDB.Nitrado.Mission = Missions[settings.settings.config.mission]; - - if (settings.game_specific.log_files.length == 0) return; // Ignore if no log files on Nitrado server - const filename = settings.game_specific.log_files.sort((a, b) => a.length - b.length)[0]; - const path = `${settings.game_specific.path.slice(0, -1)}${filename.split(settings.game)[1]}`; - - // Ensure Player List is logged for next update - const playerListEnabled = parseInt(settings.settings.config.adminLogPlayerList) - if (!playerListEnabled) PostServerSettings(NitradoCred, c, "config", "adminLogPlayerList", '1') - - await DownloadNitradoFile(NitradoCred, c, path, `./logs/${NitradoCred.ServerID}-logs.ADM`).then(async (status) => { - if (status == 1) return c.error(`Failed to Download Nitrado Log Files - [${NitradoCred.ServerID}]`); - await c.readLogs(GuildDB).then(async () => { - HandleExpiredUAVs(c, GuildDB); - HandleEvents(c, GuildDB) - if (c.activePlayersTick == 12) await HandleActivePlayersList(NitradoCred, c, GuildDB); - }) - }); - }); - } - - async connectMongo(mongoURI, dbo) { - let failed = false; - - let dbLogDir = path.join(__dirname, '..', 'logs', 'database-logs.json'); - let databaselogs; - try { - databaselogs = JSON.parse(fs.readFileSync(dbLogDir)); - } catch (err) { - databaselogs = { - attempts: 0, - connected: false, - }; - } - - if (databaselogs.attempts >= 5) { - this.error('Failed to connect to mongodb after multiple attempts'); - return; // prevent further attempts - } - - try { - // Connect to Mongo database. - this.db = await MongoClient.connect(mongoURI, { connectTimeoutMS: 1000 }); - this.dbo = this.db.db(dbo); - this.log('Successfully connected to mongoDB'); - databaselogs.connected = true; - databaselogs.attempts = 0; // reset attempts - this.databaseConnected = true; - } catch (err) { - databaselogs.attempts++; - databaselogs.connected = false; - let db = mongoURI.includes("@") ? mongoURI.split("@")[1] : mongoURI.split("//")[1]; - db = db.includes("/") ? db.split("/")[0] : db; - this.error(`Failed to connect to mongodb (mongodb://${db}/${dbo}): attempt ${databaselogs.attempts} - ${err}`); - failed = true; - } - - // write JSON string to a file - fs.writeFileSync(dbLogDir, JSON.stringify(databaselogs)); - - if (failed) process.exit(-1); - } - - async initialize() { - // Wait for MongoDB to connect - await this.connectMongo(this.config.mongoURI, this.config.dbo); - - if (!this.databaseConnected) return; - let guilds = await this.dbo.collection("guilds").find({}).toArray(); - - /* - Initialize auto restart for enabled servers - Initialize last logs - Initialize Player Sessions - */ - for (let i = 0; i < guilds.length; i++) { - if (!this.exists(guilds[i].Nitrado)) continue; - if (guilds[i].server.autoRestart) { - const NitradoCred = { - ServerID: guilds[i].Nitrado.ServerID, - UserID: guilds[i].Nitrado.UserID, - Auth: decrypt( - guilds[i].Nitrado.Auth, - this.config.EncryptionMethod, - this.key, - this.encryptionIV - ) - }; - this.arIntervalIds.set(guilds[i].server.serverID, setInterval(CheckServerStatus, this.arInterval, NitradoCred, this)) - } - this.logHistory.set(guilds[i].Nitrado.ServerID, guilds[i].server.lastLog); // Using Nitrado Server ID over guild ID in case of future support for multiple nitrado servers in a single guild - this.playerSessions.set(guilds[i].Nitrado.ServerID, new Map()); // Same reason here as named above. - this.alarmPingQueue.set(guilds[i].server.serverID, new Map()); // Initialize alarm queue to be empty - this.playerListMsgIds.set(guilds[i].server.serverID, ""); // Initialize player list message ids - this.log(`[${guilds[i].server.serverID}] Initialized existing Nitrado Server: (${guilds[i].Nitrado.ServerID})`); - } - } - - async initNewNitradoServer(guildId, Nitrado) { - let guild = await GetGuild(this, guildId) - - if (guild.autoRestart) this.arIntervalIds.set(guildId, setInterval(CheckServerStatus, this.arInterval, Nitrado, this)) - this.logHistory.set(Nitrado.ServerID, guild.lastLog); - this.playerSessions.set(Nitrado.ServerID, new Map()); - this.alarmPingQueue.set(guildId, new Map()); - this.playerListMsgIds.set(guildId, ""); - this.log(`[${guildId}] Initialized new Nitrado`); - } - - exists(n) { return typeof(n) == 'number' ? !isNaN(n) : 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 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, ") : ""; - const sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : ""; - return dDisplay + hDisplay + mDisplay + sDisplay; - } - - LoadCommandsAndInteractionHandlers() { - let CommandsDir = path.join(__dirname, '..', 'commands'); - fs.readdir(CommandsDir, (err, files) => { - if (err) this.error(err); - else - files.forEach((file) => { - let cmd = require(CommandsDir + "/" + file); - 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" - ); - this.commands.set(file.split(".")[0].toLowerCase(), cmd); - if (this.exists(cmd.Interactions)) { - for (let [interaction, handler] of Object.entries(cmd.Interactions)) { - this.interactionHandlers.set(interaction, handler); - } - } - this.log("Command Loaded: " + file.split(".")[0]); - }); - }); - } - - LoadEvents() { - let EventsDir = path.join(__dirname, '..', 'events'); - fs.readdir(EventsDir, (err, files) => { - if (err) this.error(err); - 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)); - else this.on(file.split(".")[0], event.bind(null, this)); - this.log("Event Loaded: " + file.split(".")[0]); - }); - }); - } - - // Allows shorter lines of code elsewhere - GetChannel(channel_id) { return this.channels.cache.get(channel_id); } - - sendError(Channel, Error) { - this.error(Error); - let embed = new EmbedBuilder() - .setColor(this.config.Red) - .setDescription(Error); - - Channel.send(embed); - } - - // Handles internal errors for slash commands. E.g failed to update database from slash command. - sendInternalError(Interaction, Error) { - this.error(Error); - const embed = new EmbedBuilder() - .setDescription(`**Internal Error:**\nUh Oh D: Its not you, its me.\nThis command has crashed\nContact the Developers\nhttps://discord.gg/YCXhvy9uZw`) - .setColor(this.config.Colors.Red) - - try { - Interaction.send({ embeds: [embed] }); - } catch { - Interaction.update({ embeds: [embed], components: [] }); - } - } - - // Calls register for guild and global commands - RegisterSlashCommands() { - RegisterGlobalCommands(this); - let p = Promise.resolve() - this.guilds.cache.forEach((guild) => { - p = p.then(() => { - RegisterGuildCommands(this, guild.id); - return new Promise((resolve) => { - setTimeout(resolve, 500); - }) - }) - }); - } - - build() { - this.login(this.config.Token); - } -} - -module.exports = DayzRBot; diff --git a/bot.js b/src/botWrapper.js similarity index 50% rename from bot.js rename to src/botWrapper.js index 3856eaa..9008224 100644 --- a/bot.js +++ b/src/botWrapper.js @@ -1,28 +1,28 @@ -const DayzR = require('./src/DayzRBot'); -const config = require('./config/config'); -const { GatewayIntentBits } = require('discord.js'); +const DayzR = require("./DayZRBot"); +const config = require("./config/config"); +const { GatewayIntentBits } = require("discord.js"); const path = require("path"); -const fs = require('fs'); -const { HandleActivePlayersList } = require('./util/LogsHandler'); +const fs = require("fs"); +const { HandleActivePlayersList } = require("./util/LogsHandler"); // Log all uncaught exceptions before killing process. -process.on('uncaughtException', async (error) => { +process.on("uncaughtException", async (error) => { console.trace(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(); - } - }); + 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 diff --git a/src/commands/admin.js b/src/commands/admin.js new file mode 100644 index 0000000..03c3a17 --- /dev/null +++ b/src/commands/admin.js @@ -0,0 +1,412 @@ +const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; +const bitfieldCalculator = require("discord-bitfield-calculator"); +const { Armbands } = require("../database/armbands.js"); +const { createUser, addUser } = require("../database/user"); +const { UpdatePlayer } = require("../database/player"); + +module.exports = { + name: "admin", + debug: false, + global: false, + description: "Administrative only commands", + usage: "[command] [options]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [{ + name: "gamertag-link", + description: "Link a gamertag for a user", + value: "gamertag-link", + type: CommandOptions.SubCommand, + options: [{ + name: "user", + description: "User to link gamertag to", + value: "user", + type: CommandOptions.User, + required: true, + }, + { + name: "gamertag", + description: "Gamertag of player", + value: "gamertag", + type: CommandOptions.String, + required: true, + }] + }, { + name: "gamertag-unlink", + description: "Unlink a gamertag for a user", + value: "gamertag-unlink", + type: CommandOptions.SubCommand, + options: [{ + name: "user", + description: "User to link gamertag to", + value: "user", + type: CommandOptions.User, + required: true, + }] + }, { + name: "claim-armband", + description: "Claim an armband for a faction", + value: "claim-armband", + type: CommandOptions.SubCommand, + options: [{ + name: "faction_role", + description: "Claim an armband for this faction role.", + value: "faction_role", + type: CommandOptions.Role, + required: true, + }] + }, { + name: "bounty-clear", + description: "Clear a bounty off a player", + value: "bounty-clear", + type: CommandOptions.SubCommand, + options: [{ + name: "gamertag", + description: "Gamertag of player", + value: "gamertag", + type: CommandOptions.String, + required: true, + }] + }, + { + name: "money", + description: "Add/Remove money to a user", + value: "money", + type: CommandOptions.SubCommandGroup, + options: [{ + name: "add", + description: "Add money to user", + value: "add", + type: CommandOptions.SubCommand, + options: [{ + name: "amount", + description: "The amount to add to balance", + value: "amount", + type: CommandOptions.Float, + min_value: 0.01, + required: true, + }, { + name: "to", + description: "User to alter balance", + value: "to", + type: CommandOptions.User, + required: true, + }], + }, { + name: "remove", + description: "Remove money from a user", + value: "remove", + type: CommandOptions.SubCommand, + options: [{ + name: "amount", + description: "The amount to remove from balance", + value: "amount", + type: CommandOptions.Float, + min_value: 0.01, + required: true, + }, { + name: "from", + description: "User to alter balance", + value: "from", + type: CommandOptions.User, + required: true, + }] + }] + }], + SlashCommand: { + /** + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + run: async (client, interaction, args, { GuildDB }) => { + + const permissions = bitfieldCalculator.permissions(interaction.member.permissions); + let canUseCommand = false; + + if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; + 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 (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)) { + 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."); + + return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); + } + + 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 (client.exists(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?`) + + const opt = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId(`AdminOverwriteGamertag-yes-${args[0].options[1].value}-${args[0].options[0].value}-${interaction.member.user.id}`) + .setLabel("Yes") + .setStyle(ButtonStyle.Success), + new ButtonBuilder() + .setCustomId(`AdminOverwriteGamertag-no-${args[0].options[1].value}-${args[0].options[0].value}-${interaction.member.user.id}`) + .setLabel("No") + .setStyle(ButtonStyle.Secondary) + ) + + return interaction.send({ embeds: [warnGTOverwrite], components: [opt] }); + } + + playerStat.discordID = args[0].options[0].value; + + await UpdatePlayer(client, playerStat, interaction); + + let member = interaction.guild.members.cache.get(args[0].options[0].value); + if (client.exists(GuildDB.linkedGamertagRole)) { + let role = interaction.guild.roles.cache.get(GuildDB.linkedGamertagRole); + member.roles.add(role); + } + + if (client.exists(GuildDB.memberRole)) { + let role = interaction.guild.roles.cache.get(GuildDB.memberRole); + member.roles.add(role); + } + + let connectedEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .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.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(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."); + + return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); + } + + 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.`)] }); + + 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() + .setCustomId(`AdminUnlinkGamertag-yes-${args[0].options[0].value}-${interaction.member.user.id}`) + .setLabel("Yes") + .setStyle(ButtonStyle.Success), + new ButtonBuilder() + .setCustomId(`AdminUnlinkGamertag-no-${args[0].options[0].value}-${interaction.member.user.id}`) + .setLabel("No") + .setStyle(ButtonStyle.Secondary) + ) + + return interaction.send({ embeds: [warnGTOverwrite], components: [opt] }); + + } else if (args[0].name == "claim-armband") { + + // Handle invalid roles + if (GuildDB.excludedRoles.includes(args[0].options[0].value)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription("**Notice:**\n> This role has been configured to be excluded to claim an armband.")], flags: (1 << 6) }); + + // If this faction has an existing record in the db + if (GuildDB.factionArmbands[args[0].value]) { + 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() + .setCustomId(`ChangeArmband-yes-${args[0].options[0].value}-${interaction.member.user.id}`) + .setLabel("Yes") + .setStyle(ButtonStyle.Success), + new ButtonBuilder() + .setCustomId(`ChangeArmband-no-${args[0].options[0].value}-${interaction.member.user.id}`) + .setLabel("No") + .setStyle(ButtonStyle.Secondary) + ) + + return interaction.send({ embeds: [warnArmbadChange], components: [opt] }); + } + + // 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") + + let tracker = 0; + for (let i = 0; i < Armbands.length; i++) { + if (!GuildDB.usedArmbands.includes(Armbands[i].name)) { + tracker++; + data = { + label: Armbands[i].name, + description: "Select this armband", + value: Armbands[i].name, + } + if (tracker > 25) availableNext.addOptions(data); + else available.addOptions(data); + } + } + + let compList = [] + let opt = new ActionRowBuilder().addComponents(available); + compList.push(opt) + let opt2 = undefined; + if (tracker > 25) { + opt2 = new ActionRowBuilder().addComponents(availableNext); + compList.push(opt2); + } + + return interaction.send({ components: compList }); + + } 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)) { + 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."); + + return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); + } + + 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 `.")] }); + + playerStat.bounties = []; + + await UpdatePlayer(client, playerStat, interaction); + + const clearedBounty = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`Successfully cleared **${playerStat.gamertag}"s** bounties`); + + return interaction.send({ embeds: [clearedBounty] }); + + } else if (args[0].name == "money") { + + const targetUserID = args[0].options[0].options[1].value; + let banking = await client.dbo.collection("users").findOne({ "user.userID": targetUserID }).then(banking => banking); + + if (!banking) { + 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); + 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; + + const add = args[0].options[0].name == "add"; + let newBalance = add + ? banking.guilds[GuildDB.serverID].balance + args[0].options[0].options[0].value + : banking.guilds[GuildDB.serverID].balance - args[0].options[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 ${add ? "added" : "removed"} **$${args[0].options[0].options[0].value.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}** ${add ? "to" : "from"} <@${targetUserID}>"s balance`) + .setColor(client.config.Colors.Green); + + return interaction.send({ embeds: [successEmbed] }); + + } + } + }, + + Interactions: { + + AdminOverwriteGamertag: { + run: async (client, interaction, GuildDB) => { + 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 = await client.dbo.collection("players").findOne({ "gamertag": interaction.customId.split("-")[2] }); + + playerStat.discordID = interaction.customId.split("-")[3]; + + await UpdatePlayer(client, playerStat); + + let member = interaction.guild.members.cache.get(interaction.member.user.id); + if (client.exists(GuildDB.linkedGamertagRole)) { + let role = interaction.guild.roles.cache.get(GuildDB.linkedGamertagRole); + member.roles.add(role); + } + + if (client.exists(GuildDB.memberRole)) { + let role = interaction.guild.roles.cache.get(GuildDB.memberRole); + member.roles.add(role); + } + + let connectedEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`Successfully connected \` ${playerStat.gamertag} \` as <@${interaction.customId.split("-")[3]}>"s gamertag.`); + + return interaction.update({ embeds: [connectedEmbed], components: [] }); + + } else { + const cancel = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription("**Canceled**\n> The gamertag link will not be overwritten"); + + return interaction.update({ embeds: [cancel], components: [] }); + } + } + }, + + AdminUnlinkGamertag: { + run: async (client, interaction, GuildDB) => { + 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 = await client.dbo.collection("players").findOne({ "discordID": interaction.customId.split("-")[2] }); + + playerStat.discordID = ""; + + await UpdatePlayer(client, playerStat, interaction); + + let connectedEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`Successfully unlinked \` ${playerStat.gamertag} \` from <@${interaction.customId.split("-")[2]}>.`); + + return interaction.update({ embeds: [connectedEmbed], components: [] }); + + } else { + const cancel = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription("**Canceled**\n> The gamertag unlink will not processed."); + + return interaction.update({ embeds: [cancel], components: [] }); + } + } + } + + } +} \ No newline at end of file diff --git a/src/commands/alarm.js b/src/commands/alarm.js new file mode 100644 index 0000000..eb4a0a9 --- /dev/null +++ b/src/commands/alarm.js @@ -0,0 +1,646 @@ +const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; +const bitfieldCalculator = require("discord-bitfield-calculator"); + +const generateAlarmMenus = (alarms, customId, placeholder, description) => { + let alarmComponents = []; + const max = 25; + let id = 1; + + for (let i = 0; i < alarms.length; i += max) { + let currentAlarmComponents = new StringSelectMenuBuilder() + .setCustomId(`${customId}-${id}`) + .setPlaceholder(placeholder); + alarms.slice(i, i + max).forEach(alarm => { + currentAlarmComponents.addOptions({ + label: alarm.name, + description: description, + value: alarm.name, + }); + }); + alarmComponents.push(new ActionRowBuilder().addComponents(currentAlarmComponents)); + id++; + } + + return alarmComponents; +}; + +module.exports = { + name: "alarm", + debug: false, + global: false, + description: "Manage an Alarm", + usage: "[command] [options]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: ["MANAGE_GUILD"], + }, + options: [ + { + name: "create", + description: "Create a new Zone Ping Alarm", + value: "create", + type: CommandOptions.SubCommand, + options: [ + { + name: "x-coord", + description: "X Coordinate of the origin", + value: "x-coord", + type: CommandOptions.Float, + min_value: 0.01, + required: true, + }, + { + name: "y-coord", + description: "Y Coordinate of the origin", + value: "y-coord", + type: CommandOptions.Float, + min_value: 0.01, + required: true, + }, + { + name: "radius", + description: "Radius of Alarm", + value: "radius", + type: CommandOptions.Float, + min_value: 25.00, + required: true, + }, + { + name: "name", + description: "Alarm Name", + value: "name", + type: CommandOptions.String, + required: true, + }, + { + name: "channel", + description: "Alarm Channel", + value: "channel", + type: CommandOptions.Channel, + channel_types: [0], // Restrict to text channel + required: true, + }, + { + name: "role", + description: "Role to Ping on Alarm", + value: "role", + type: CommandOptions.Role, + required: true, + }, + { + name: "emp-exempt", + description: "Is this Alarm Exempt to EMP Attacks?", + value: false, + type: CommandOptions.Boolean, + required: false, + }, + { + name: "show-player-coords", + description: "Show a players coords when in the radius of the Alarm?", + value: true, + type: CommandOptions.Boolean, + required: false, + } + ] + }, + { + name: "delete", + description: "Delete an Alarm", + value: "delete", + type: CommandOptions.SubCommand, + }, + { + name: "add-player", + description: "Add player to be ignored list of an Alarm", + value: "add-player", + type: CommandOptions.SubCommand, + options: [{ + name: "gamertag", + description: "Gamertag of player to ignore", + value: "gamertag", + type: CommandOptions.String, + required: true, + }] + }, + { + name: "remove-player", + description: "Remove a player from the ignored list of an Alarm", + value: "remove-player", + type: CommandOptions.SubCommand, + options: [{ + name: "gamertag", + description: "Gamertag of player to ignore", + value: "gamertag", + type: CommandOptions.String, + required: true, + }] + }, + { + name: "disable", + description: "Disable an Alarm", + value: "disable", + type: CommandOptions.SubCommand, + }, + { + name: "enable", + description: "Enable an Alarm", + value: "enable", + type: CommandOptions.SubCommand, + }, + { + name: "mute", + description: "Mute the role ping of an Alarm", + value: "mute", + type: CommandOptions.SubCommand, + options: [{ + name: "toggle", + description: "Turn on/off role pings for this alarm", + value: false, + type: CommandOptions.Boolean, + required: true, + }] + }, + { + name: "set-rule", + description: "Add a Rule to an Alarm", + value: "set-rule", + type: CommandOptions.SubCommand, + options: [{ + name: "rule", + description: "Select a rule to add to an Alarm", + value: "rule", + type: CommandOptions.String, + required: true, + choices: [ + { name: "Ban on Entry", value: "ban_on_entry" }, + { name: "Ban on Kill", value: "ban_on_kill" }, + { name: "Ban on Fireplace Placement", value: "ban_on_fireplace_placement" }, + ] + }] + }, + { + name: "remove-rule", + description: "Remove a rule from an Alarm", + value: "remove-rule", + type: CommandOptions.SubCommand, + }, + { + name: "rename", + description: "Rename an Alarm", + value: "rename", + type: CommandOptions.SubCommand, + options: [{ + name: "name", + description: "New Alarm Name", + value: "name", + type: CommandOptions.String, + required: true, + }] + }, + { + name: "move-origin", + description: "Move the origin of an Alarm", + value: "move-origin", + type: CommandOptions.SubCommand, + options: [{ + name: "x-coord", + description: "X Coordinate of the new origin", + value: "x-coord", + type: CommandOptions.Float, + min_value: 0.01, + required: true, + }, + { + name: "y-coord", + description: "Y Coordinate of the new origin", + value: "y-coord", + type: CommandOptions.Float, + min_value: 0.01, + required: true, + }] + } + ], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + run: async (client, interaction, args, { GuildDB }) => { + const permissions = bitfieldCalculator.permissions(interaction.member.permissions); + let canUseCommand = false; + + if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; + 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)) { + 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."); + + return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); + } + + if (args[0].name == "create") { + if (args[0].options[3].value.includes("-") || args[0].options[3].value.includes(" ")) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Red).setDescription("**Invalid Name:** Alarm Names cannot include hyphens or spaces.")] }) + + let exists = GuildDB.alarms.find(alarm => alarm.name == args[0].options[3].value); + if (exists) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription("**Invalid Name**\nAn alarm already exists with this name.")] }); + + let alarm = { + origin: [args[0].options[0].value, args[0].options[1].value], + radius: args[0].options[2].value, + name: args[0].options[3].value, + channel: args[0].options[4].value, + 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, + disabled: false, + empExpire: null, + }; + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { + $push: { + "server.alarms": alarm, + } + }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Success:** Successfully set **${alarm.name}** in <#${alarm.channel}>`); + + return interaction.send({ embeds: [successEmbed] }); + + } else if (args[0].name == "delete") { + + if (GuildDB.alarms.length == 0) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription("**Notice:** No Existing Alarms to Delete.")] }); + + const alarmComponents = generateAlarmMenus( + GuildDB.alarms, + `DeleteAlarmSelect`, + `Select an Alarm to delete.`, + `Delete this alarm` + ); + + return interaction.send({ components: alarmComponents, flags: (1 << 6) }); + + } else if (args[0].name == "add-player" || args[0].name == "remove-player") { + + const add = args[0].name == "add-player"; + + if (GuildDB.alarms.length == 0) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription(`**Notice:** No Existing Alarms to ${add ? "Add" : "Remove"} Player ${add ? "to" : "from"}.`)] }); + + const alarmComponents = generateAlarmMenus( + GuildDB.alarms, + `ManageAlarmIgnored-${add ? "add" : "remove"}-${args[0].options[0].value}`, + `Select an Alarm to ${add ? "add" : "remove"} player ${add ? "to" : "from"}.`, + `${add ? "Add" : "Remove"} player ${add ? "to" : "from"} this Alarm` + ); + + return interaction.send({ components: alarmComponents, flags: (1 << 6) }); + + } else if (args[0].name == "set-rule" || args[0].name == "remove-rule") { + + if (GuildDB.alarms.length == 0) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription("**Notice:** No Existing Alarms to configure.")] }); + + const alarmComponents = generateAlarmMenus( + GuildDB.alarms, + `ManageRule-${args[0].name == "set-rule" ? "add" : "remove"}${args[0].name == "set-rule" ? `-${args[0].options[0].value}` : ""}`, + `Select an Alarm to configure.`, + `Configure this alarm` + ); + + return interaction.send({ components: alarmComponents, flags: (1 << 6) }); + + } else if (args[0].name == "enable" || args[0].name == "disable") { + + const disable = args[0].name == "disable"; + const message = disable ? "disable" : "enable"; + + if (GuildDB.alarms.length == 0) return interaction.send({ + embeds: [ + new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`**Notice:**\n> No Existing Alarms to ${message}.`) + ] + }); + + if (!GuildDB.alarms.some(alarm => alarm.disabled != disable)) return interaction.send({ + embeds: [ + new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`**Notice:**\n> There are no alarms to ${message}.`) + ] + }); + + const alarmComponents = generateAlarmMenus( + GuildDB.alarms, + `EnableOrDisableAlarm-${message}`, + `Select an Alarm to ${message}`, + `Configure this alarm` + ); + + return interaction.send({ components: alarmComponents, flags: (1 << 6) }); + + } else if (args[0].name == "rename") { + + if (GuildDB.alarms.length == 0) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription("**Notice:**\n> No Existing Alarms to configure.")] }); + + const alarmComponents = generateAlarmMenus( + GuildDB.alarms, + `RenameAlarm-${args[0].options[0].value}`, + `Select an Alarm to rename.`, + `Rename this alarm` + ); + + return interaction.send({ components: alarmComponents, flags: (1 << 6) }); + + } else if (args[0].name == "move-origin") { + + if (GuildDB.alarms.length == 0) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription("**Notice:** No Existing Alarms to configure.")] }); + + const alarmComponents = generateAlarmMenus( + GuildDB.alarms, + `MoveOrigin-${args[0].options[0].value}-${args[0].options[1].value}`, + `Select an Alarm to move.`, + `Move this alarm` + ); + + return interaction.send({ components: alarmComponents, flags: (1 << 6) }); + + } else if (args[0].name == "mute") { + + if (GuildDB.alarms.length == 0) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription("**Notice:** No Existing Alarms to configure.")] }); + + const alarmComponents = generateAlarmMenus( + GuildDB.alarms, + `MuteAlarm-${args[0].options[0].value ? 1 : 0}`, + `Select an Alarm to mute.`, + `Mute this alarm` + ); + + return interaction.send({ components: alarmComponents, flags: (1 << 6) }); + } + }, + }, + + Interactions: { + DeleteAlarmSelect: { + run: async (client, interaction, GuildDB) => { + + let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0]); + + const prompt = new EmbedBuilder() + .setTitle(`Are you sure you want to delete this Zone Alarm?`) + .setColor(client.config.Colors.Default) + + const opt = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId(`DeleteAlarm-yes-${alarm.name}`) + .setLabel("Yes") + .setStyle(ButtonStyle.Danger), + new ButtonBuilder() + .setCustomId(`DeleteAlarm-no-${alarm.name}`) + .setLabel("No") + .setStyle(ButtonStyle.Success) + ) + + return interaction.update({ embeds: [prompt], components: [opt], flags: (1 << 6) }); + } + }, + DeleteAlarm: { + run: async (client, interaction, GuildDB) => { + + if (interaction.customId.split("-")[1] == "yes") { + let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.customId.split("-")[2]); + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { + $pull: { + "server.alarms": alarm, + } + }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Success:** Successfully Deleted **${interaction.customId.split("-")[2]}**`); + + return interaction.update({ embeds: [successEmbed], components: [] }); + } else { + let successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`The Zone Alarm **${interaction.customId.split("-")[2]}** will not be deleted.`); + + return interaction.update({ embeds: [successEmbed], components: [] }); + } + } + }, + ManageAlarmIgnored: { + run: async (client, interaction, GuildDB) => { + let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0]); + 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: [] }); + + let add = interaction.customId.split("-")[1] == "add"; + + if (add) alarm.ignoredPlayers.push(playerStat.playerID); + else alarm.ignoredPlayers = alarm.ignoredPlayers.filter((v) => { + return v != playerStat.playerID; + }); + + GuildDB.alarms[alarmIndex] = alarm; + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { + $set: { + "server.alarms": GuildDB.alarms, + } + }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Success:** Successfully ${add ? "Added" : "Removed"} **${interaction.customId.split("-")[2]}** ${add ? "to" : "from"} **${alarm.name}**`); + + return interaction.update({ embeds: [successEmbed], components: [] }); + } + }, + ManageRule: { + run: async (client, interaction, GuildDB) => { + let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0]); + let alarmIndex = GuildDB.alarms.indexOf(alarm); + + if (interaction.customId.split("-")[1] == "add") { + + alarm.rules.push(interaction.customId.split("-")[2]); + GuildDB.alarms[alarmIndex] = alarm; + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { + $set: { + "server.alarms": GuildDB.alarms, + } + }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Success:** Successfully Added Rule **${interaction.customId.split("-")[2]}** to **${alarm.name}**`); + + return interaction.update({ embeds: [successEmbed], components: [] }); + + } else if (interaction.customId.split("-")[1] == "remove") { + + let alarmRules = new StringSelectMenuBuilder() + .setCustomId(`DeleteAlarmRule-${alarm.name}-${interaction.member.user.id}`) + .setPlaceholder(`Select Rule to Remove from ${alarm.name}`); + + for (let i = 0; i < alarm.rules.length; i++) { + alarmRules.addOptions({ + label: alarm.rules[i], + description: `Select this Rule to remove it.`, + value: alarm.rules[i] + }); + } + + const opt = new ActionRowBuilder().addComponents(alarmRules); + + return interaction.update({ components: [opt], flags: (1 << 6) }); + } + } + }, + DeleteAlarmRule: { + run: async (client, interaction, GuildDB) => { + let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.customId.split("-")[1]); + let alarmIndex = GuildDB.alarms.indexOf(alarm); + + alarm.rules = alarm.rules.filter((v) => { + return v != interaction.values[0]; + }); + + GuildDB.alarms[alarmIndex] = alarm; + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { + $set: { + "server.alarms": GuildDB.alarms, + } + }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Success:** Successfully Removed Rule **${interaction.values[0]}** from **${interaction.customId.split("-")[1]}**`); + + return interaction.update({ embeds: [successEmbed], components: [] }); + } + }, + EnableOrDisableAlarm: { + run: async (client, interaction, GuildDB) => { + let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0]); + let alarmIndex = GuildDB.alarms.indexOf(alarm); + let disable = interaction.customId.split("-")[1] == "disable"; + alarm.disabled = disable; + GuildDB.alarms[alarmIndex] = alarm + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { + $set: { + "server.alarms": GuildDB.alarms, + } + }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Success:**\n> Successfully ${disable ? "disabled" : "enabled"} the Alarm **${interaction.values[0]}**`); + + return interaction.update({ embeds: [successEmbed], components: [] }); + } + }, + + MoveOrigin: { + run: async (client, interaction, GuildDB) => { + let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0]); + let alarmIndex = GuildDB.alarms.indexOf(alarm); + let origin = [parseFloat(interaction.customId.split("-")[1]), parseFloat(interaction.customId.split("-")[2])]; + alarm.origin = origin; + GuildDB.alarms[alarmIndex] = alarm + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { + $set: { + "server.alarms": GuildDB.alarms, + } + }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Success:** Successfully moved alarm to new **[origin](https://www.izurvive.com/chernarusplussatmap/#location=${origin[0]};${origin[1]})**`); + + return interaction.update({ embeds: [successEmbed], components: [] }); + } + }, + + RenameAlarm: { + run: async (client, interaction, GuildDB) => { + let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0]); + let alarmIndex = GuildDB.alarms.indexOf(alarm); + let oldName = alarm.name; + alarm.name = interaction.customId.split("-")[1]; + GuildDB.alarms[alarmIndex] = alarm + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { + $set: { + "server.alarms": GuildDB.alarms, + } + }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Success:** Successfully renamed the Alarm **${oldName}** to **${alarm.name}**`); + + return interaction.update({ embeds: [successEmbed], components: [] }); + } + }, + + MuteAlarm: { + run: async (client, interaction, GuildDB) => { + let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0]); + let alarmIndex = GuildDB.alarms.indexOf(alarm); + let mute = parseInt(interaction.customId.split("-")[1]); + alarm.mute = mute; + GuildDB.alarms[alarmIndex] = alarm + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { + $set: { + "server.alarms": GuildDB.alarms, + } + }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Success:** Successfully ${mute ? "Muted" : "Unmuted"} this alarm.`); + + return interaction.update({ embeds: [successEmbed], components: [] }); + } + } + } +} diff --git a/src/commands/armbands.js b/src/commands/armbands.js new file mode 100644 index 0000000..85184f1 --- /dev/null +++ b/src/commands/armbands.js @@ -0,0 +1,86 @@ +const { StringSelectMenuBuilder, EmbedBuilder, ActionRowBuilder } = require("discord.js"); +const { Armbands } = require("../database/armbands.js"); + +module.exports = { + name: "armbands", + debug: false, + global: false, + description: "View a list of armbads and what their image", + usage: "", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + run: async (client, interaction, args, { GuildDB }) => { + if (GuildDB.customChannelStatus == true && !GuildDB.allowedChannels.includes(interaction.channel_id)) + return interaction.send({ content: `You are not allowed to use the bot in this channel.`, flags: (1 << 6) }); + + let available = new StringSelectMenuBuilder() + .setCustomId(`View-1-${interaction.member.user.id}`) + .setPlaceholder("View an armband from list 1") + + let availableNext = new StringSelectMenuBuilder() + .setCustomId(`View-2-${interaction.member.user.id}`) + .setPlaceholder("View an armband from list 2") + + let tracker = 0; + for (let i = 0; i < Armbands.length; i++) { + tracker++; + data = { + label: Armbands[i].name, + description: "View this armband", + value: Armbands[i].name, + } + + if (GuildDB.usedArmbands.includes(Armbands[i].name)) data.label += " - [ Claimed ]" + + if (tracker > 25) availableNext.addOptions(data); + else available.addOptions(data); + } + + let compList = [] + + let opt = new ActionRowBuilder().addComponents(available); + compList.push(opt) + let opt2 = undefined; + if (tracker > 25) { + opt2 = new ActionRowBuilder().addComponents(availableNext); + compList.push(opt2); + } + + return interaction.send({ components: compList, flags: (1 << 6) }); + }, + }, + Interactions: { + View: { + run: async (client, interaction, GuildDB) => { + let armbandURL; + + for (let i = 0; i < Armbands.length; i++) { + if (Armbands[i].name == interaction.values[0]) { + armbandURL = Armbands[i].url; + break; + } + } + + let armbandTitle = `${interaction.values[0]}${GuildDB.usedArmbands.includes(interaction.values[0]) ? " - [ Claimed ]" : ""}`; + + const success = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTitle(armbandTitle) + .setImage(armbandURL); + + return interaction.update({ embeds: [success], components: [] }); + } + } + } +} diff --git a/src/commands/bank.js b/src/commands/bank.js new file mode 100644 index 0000000..9ac075f --- /dev/null +++ b/src/commands/bank.js @@ -0,0 +1,165 @@ +const { EmbedBuilder } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; +const { createUser, addUser } = require("../database/user"); + +module.exports = { + name: "bank", + debug: false, + global: false, + description: "Manage your banking", + usage: "[command] [options]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [ + { + name: "balance", + description: "View your bank balance", + value: "balance", + type: CommandOptions.SubCommand, + options: [{ + name: "user", + description: "User to view ballance", + value: "user", + type: CommandOptions.User, + required: false, + }] + }, + { + name: "transfer", + description: "Transfer money to another user", + value: "transfer", + type: CommandOptions.SubCommand, + options: [ + { + name: "user", + description: "User to transfer to", + value: "user", + type: CommandOptions.User, + required: true, + }, + { + name: "amount", + description: "The amount to transfer", + value: "amount", + type: CommandOptions.Float, + min_value: 0.01, + required: true, + }, + ] + } + ], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + run: async (client, interaction, args, { GuildDB }) => { + if (GuildDB.customChannelStatus == true && !GuildDB.allowedChannels.includes(interaction.channel_id)) { + return interaction.send({ content: `You are not allowed to use the bot in this channel.`, flags: (1 << 6) }); + } + + 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); + } + banking = banking.user; + + 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"); + } + + if (args[0].name == "balance") { + let balanceEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default); + + if (args[0].options && args[0].options[0]) { + // 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(targetUserBanking => targetUserBanking); + + if (!targetUserBanking) { + 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"); + } + + // This lame line of code to get username without ping on discord + const DiscordUser = client.users.cache.get(targetUserID); + + balanceEmbed.setTitle(`${DiscordUser.tag.split("#")[0]}"s Bank Records`); + balanceEmbed.addFields({ name: "**Bank**", value: `$${targetUserBanking.guilds[GuildDB.serverID].balance.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`, inline: true }); + + } else { + // Show command authors balance + + balanceEmbed.setTitle("Personal Bank Records"); + balanceEmbed.addFields({ name: "**Bank**", value: `$${banking.guilds[GuildDB.serverID].balance.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`, inline: true }); + } + + return interaction.send({ embeds: [balanceEmbed] }); + + } else if (args[0].name == "transfer") { + // send money from bank + + // prevent sending transfering money to self + const targetUserID = args[0].options[0].value.replace("<@!", "").replace(">", ""); + + if (targetUserID == interaction.member.user.id) return interaction.send({ embeds: [new EmbedBuilder().setDescription("**Invalid** You may not transfer money to yourself").setColor(client.config.Colors.Yellow)], flags: (1 << 6) }) + + if (banking.guilds[GuildDB.serverID].balance.toFixed(2) - args[0].options[1].value < 0) { + let embed = new EmbedBuilder() + .setTitle("**Bank Notice:** NSF. Non sufficient funds") + .setColor(client.config.Colors.Red); + + return interaction.send({ embeds: [embed] }); + } + + const newBalance = banking.guilds[GuildDB.serverID].balance - args[0].options[1].value; + + client.dbo.collection("users").updateOne({ "user.userID": interaction.member.user.id }, { $set: { [`user.guilds.${GuildDB.serverID}.balance`]: newBalance } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let targetUserBanking = await client.dbo.collection("users").findOne({ "user.userID": targetUserID }).then(targetUserBanking => targetUserBanking); + + if (!targetUserBanking) { + 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; + + client.dbo.collection("users").updateOne({ "user.userID": targetUserID }, { $set: { [`user.guilds.${GuildDB.serverID}.balance`]: newTargetBalance } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + const successEmbed = new EmbedBuilder() + .setTitle("Bank Notice:") + .setDescription(`Successfully transfered <@${targetUserID}> **$${args[0].options[1].value.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}**`) + .setColor(client.config.Colors.Green); + + return interaction.send({ embeds: [successEmbed] }); + } + }, + }, +} \ No newline at end of file diff --git a/src/commands/bounty.js b/src/commands/bounty.js new file mode 100644 index 0000000..5d5c40e --- /dev/null +++ b/src/commands/bounty.js @@ -0,0 +1,190 @@ +const { EmbedBuilder } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; +const { createUser, addUser } = require("../database/user"); +const { UpdatePlayer } = require("../database/player"); + +module.exports = { + name: "bounty", + debug: false, + global: false, + description: "Set or view bounties", + usage: "[command] [options]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [{ + name: "set", + description: "Set a bounty on a player", + value: "set", + type: CommandOptions.SubCommand, + options: [{ + name: "gamertag", + description: "Gamertag of player for bounty", + value: "gamertag", + type: CommandOptions.String, + required: true, + }, { + name: "value", + description: "Amount of the bounty", + value: "value", + type: CommandOptions.Float, + min_value: 0.01, + required: true + }, { + name: "anonymous", + description: "Make this bounty anonymous (does not show your name)", + value: false, + type: CommandOptions.Boolean, + required: false + }] + }, { + name: "pay", + description: "Pay off your bounty", + value: "pay", + type: CommandOptions.SubCommand, + }, { + name: "view", + description: "View all active bounties", + value: "view", + type: CommandOptions.SubCommand, + }], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + 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)) { + 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."); + + return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); + } + + 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 = 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); + if (!success) return client.sendInternalError(interaction, "Failed to add bank"); + } + } + + 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 (args[0].options[1].value > banking.guilds[GuildDB.serverID].balance) { + let nsf = new EmbedBuilder() + .setDescription("**Bank Notice:** NSF. Non sufficient funds") + .setColor(client.config.Colors.Red); + + return interaction.send({ embeds: [nsf] }); + } + + const newBalance = banking.guilds[GuildDB.serverID].balance - args[0].options[1].value; + + client.dbo.collection("users").updateOne({ "user.userID": interaction.member.user.id }, { + $set: { + [`user.guilds.${GuildDB.serverID}.balance`]: newBalance, + } + }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let anonymous = args[0].options[2]; + + playerStat.bounties.push({ + setBy: (anonymous && !anonymous.value) ? interaction.member.user.id : null, + value: args[0].options[1].value, + }); + playerStat.bountiesLength = playerStat.bounties.length; // Will ensure bounties length = # of bounties, even if bountiesLength does not exists in player stat. + + await UpdatePlayer(client, playerStat, interaction); + + const successEmbed = new EmbedBuilder() + .setTitle("Success") + .setDescription(`Successfully set a **$${args[0].options[1].value.toFixed(2).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}** bounty on \` ${playerStat.gamertag} \`\nThis can be viewed using `) + .setColor(client.config.Colors.Green); + + return interaction.send({ embeds: [successEmbed], flags: (1 << 6) }); + + } 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 (playerStat.bounties.length == 0) { + const noBounty = new EmbedBuilder() + .setColor(client.config.Colors.Yellow) + .setDescription(`You have no bounties to pay off.`) + + return interaction.send({ embeds: [noBounty] }); + } + + let totalBounty = 0; + for (let i = 0; i < playerStat.bounties.length; i++) { + totalBounty += playerStat.bounties[i].value; + } + + if (banking.guilds[GuildDB.serverID].balance.toFixed(2) - (totalBounty * 2) < 0) { + let embed = new EmbedBuilder() + .setTitle("**Bank Notice:** NSF. Non sufficient funds") + .setColor(client.config.Colors.Red); + + return interaction.send({ embeds: [embed], flags: (1 << 6) }); + } + + const newBalance = banking.guilds[GuildDB.serverID].balance - (totalBounty * 2); + + await client.dbo.collection("users").updateOne({ "user.userID": interaction.member.user.id }, { $set: { [`user.guilds.${GuildDB.serverID}.balance`]: newBalance } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + playerStat.bounties = []; + playerStat.bountiesLength = 0; + + await UpdatePlayer(client, playerStat, interaction); + + const payedOff = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`Successfully paid off **$${(totalBounty * 2).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}** in bounties.`); + + return interaction.send({ embeds: [payedOff] }); + + } else if (args[0].name == "view") { + + const activeBounties = await client.dbo.collection("players").find({ + "bountiesLength": { $gt: 0 } + }).toArray(); + + let bountiesEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription("**Active Boutnies**"); + + if (activeBounties.length == 0) bountiesEmbed.setDescription("**There are No Active Boutnies**") + for (let i = 0; i < activeBounties.length; i++) { + for (let j = 0; j < activeBounties[i].bounties.length; j++) { + bountiesEmbed.addFields({ name: `${activeBounties[i].gamertag} has a:`, value: `**$${activeBounties[i].bounties[j].value.toFixed(2).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}** bounty set by ${activeBounties[i].bounties[j].setBy == null ? "Anonymous" : `<@${activeBounties[i].bounties[j].setBy}>`}`, inline: false }); + } + } + + return interaction.send({ embeds: [bountiesEmbed] }); + } + }, + }, +} \ No newline at end of file diff --git a/src/commands/channels.js b/src/commands/channels.js new file mode 100644 index 0000000..8ed8ddd --- /dev/null +++ b/src/commands/channels.js @@ -0,0 +1,47 @@ +const { EmbedBuilder } = require("discord.js"); + +module.exports = { + name: "channels", + debug: false, + global: false, + description: "View a list of allowed channels", + usage: "", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + run: async (client, interaction, args, { GuildDB }) => { + if (!GuildDB.customChannelStatus) { + let noChannels = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTitle("Channels") + .setDescription("> There are no configured channels"); + + return interaction.send({ embeds: [noChannels] }); + } + + let channels = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTitle("Channels") + + let des = ""; + for (let i = 0; i < GuildDB.allowedChannels.length; i++) { + if (i == 0) des += `> <#${GuildDB.allowedChannels[i]}>`; + else des += `\n> <#${GuildDB.allowedChannels[i]}>`; + } + channels.setDescription(des); + + return interaction.send({ embeds: [channels] }); + }, + }, + Interactions: {} +} diff --git a/src/commands/claim.js b/src/commands/claim.js new file mode 100644 index 0000000..3cdf364 --- /dev/null +++ b/src/commands/claim.js @@ -0,0 +1,212 @@ +const { ActionRowBuilder, EmbedBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; +const { Armbands } = require("../database/armbands.js"); + +module.exports = { + name: "claim", + debug: false, + global: false, + description: "Claim an available armband for your faction", + usage: "[role]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [{ + name: "faction_role", + description: "Claim an armband for this faction role", + value: "faction_role", + type: CommandOptions.Role, + required: true, + }], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + run: async (client, interaction, args, { GuildDB }) => { + if (GuildDB.customChannelStatus == true && !GuildDB.allowedChannels.includes(interaction.channel_id)) + return interaction.send({ content: `You are not allowed to use the bot in this channel.`, flags: (1 << 6) }); + + // Handle invalid roles + let des; + if (GuildDB.excludedRoles.includes(args[0].value)) des = "**Notice:**\n> This role has been configured to be excluded to claim an armband."; + if (!interaction.member.roles.includes(args[0].value)) des = "**Notice:**\n> You cannot claim an armband for a role you don\"t have."; + if (des) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(des)], flags: (1 << 6) }); + + for (let roleID in Object(GuildDB.factionArmbands)) { + if (interaction.member.roles.includes(roleID) && roleID != args[0].value) { + return interaction.send({ + embeds: [ + new EmbedBuilder() + .setColor(client.config.Colors.Yellow) + .setDescription("**Notice:**\n> You already have another role with a claimed flag.") + ], flags: (1 << 6) + }) + } + } + + // If this faction has an existing record in the db + if (GuildDB.factionArmbands[args[0].value]) { + const warnArmbadChange = new EmbedBuilder() + .setColor(client.config.Colors.Yellow) + .setDescription(`**Notice:**\n> The faction <@&${args[0].value}> already has an armband selected. Are you sure you would like to change this?`) + + const opt = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId(`ChangeArmband-yes-${args[0].value}-${interaction.member.user.id}`) + .setLabel("Yes") + .setStyle(ButtonStyle.Success), + new ButtonBuilder() + .setCustomId(`ChangeArmband-no-${args[0].value}-${interaction.member.user.id}`) + .setLabel("No") + .setStyle(ButtonStyle.Secondary) + ) + + return interaction.send({ embeds: [warnArmbadChange], components: [opt] }); + } + + let available = new StringSelectMenuBuilder() + .setCustomId(`Claim-${args[0].value}-1-${interaction.member.user.id}`) + .setPlaceholder("Select an armband from list 1 to claim") + + let availableNext = new StringSelectMenuBuilder() + .setCustomId(`Claim-${args[0].value}-2-${interaction.member.user.id}`) + .setPlaceholder("Select an armband from list 2 to claim") + + let tracker = 0; + for (let i = 0; i < Armbands.length; i++) { + if (!GuildDB.usedArmbands.includes(Armbands[i].name)) { + tracker++; + data = { + label: Armbands[i].name, + description: "Select this armband", + value: Armbands[i].name, + } + if (tracker > 25) availableNext.addOptions(data); + else available.addOptions(data); + } + } + + let compList = [] + + let opt = new ActionRowBuilder().addComponents(available); + compList.push(opt) + let opt2 = undefined; + if (tracker > 25) { + opt2 = new ActionRowBuilder().addComponents(availableNext); + compList.push(opt2); + } + + return interaction.send({ components: compList }); + }, + }, + Interactions: { + Claim: { + run: async (client, interaction, GuildDB) => { + if (!interaction.customId.endsWith(interaction.member.user.id)) + return interaction.reply({ content: "This interaction is not for you", flags: (1 << 6) }); + + let factionID = interaction.customId.split("-")[1]; + + let data = { + faction: factionID, + armband: interaction.values[0], + }; + + let query = { + $push: { + "server.usedArmbands": interaction.values[0] + }, + $set: { + [`server.factionArmbands.${factionID}`]: data + }, + }; + + if (interaction.customId.split("-")[2] == "update") { + let removeQuery; + for (const [fid, data] of Object.entries(GuildDB.factionArmbands)) { + if (fid == factionID) removeQuery = data.armband; + } + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $pull: { "server.usedArmbands": removeQuery } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }) + } + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, query, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }) + + let armbandURL; + + for (let i = 0; i < Armbands.length; i++) { + if (Armbands[i].name == interaction.values[0]) { + armbandURL = Armbands[i].url; + break; + } + } + + const success = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`**Success!**\n> The faction <@&${factionID}> has now claimed ***${interaction.values[0]}***`) + .setImage(armbandURL); + + return interaction.update({ embeds: [success], components: [] }); + } + }, + + ChangeArmband: { + run: async (client, interaction, GuildDB) => { + 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 available = new StringSelectMenuBuilder() + .setCustomId(`Claim-${interaction.customId.split("-")[2]}-update-1-${interaction.member.user.id}`) + .setPlaceholder("Select an armband from list 1 to claim") + + let availableNext = new StringSelectMenuBuilder() + .setCustomId(`Claim-${interaction.customId.split("-")[2]}-update-2-${interaction.member.user.id}`) + .setPlaceholder("Select an armband from list 2 to claim") + + let tracker = 0; + for (let i = 0; i < Armbands.length; i++) { + if (!GuildDB.usedArmbands.includes(Armbands[i].name)) { + tracker++; + data = { + label: Armbands[i].name, + description: "Select this armband", + value: Armbands[i].name, + } + if (tracker > 25) availableNext.addOptions(data); + else available.addOptions(data); + } + } + + let compList = [] + + let opt = new ActionRowBuilder().addComponents(available); + compList.push(opt) + let opt2 = undefined; + if (tracker > 25) { + opt2 = new ActionRowBuilder().addComponents(availableNext); + compList.push(opt2); + } + + return interaction.update({ embeds: [], components: compList }); + + } else { + const cancel = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription("**Canceled**\n> Your factions armband will remain the same"); + + return interaction.update({ embeds: [cancel], components: [] }); + } + } + } + } +} diff --git a/src/commands/collect-income.js b/src/commands/collect-income.js new file mode 100644 index 0000000..f41b883 --- /dev/null +++ b/src/commands/collect-income.js @@ -0,0 +1,108 @@ +const { EmbedBuilder, } = require("discord.js"); +const { createUser, addUser } = require("../database/user"); + +module.exports = { + name: "collect-income", + debug: false, + global: false, + description: "Collect your income", + usage: "", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + run: async (client, interaction, args, { GuildDB }) => { + if (GuildDB.customChannelStatus == true && !GuildDB.allowedChannels.includes(interaction.channel_id)) { + return interaction.send({ content: `You are not allowed to use the bot in this channel.`, flags: (1 << 6) }); + } + + const hasIncomeRole = GuildDB.incomeRoles.some(data => { + if (interaction.member.roles.includes(data.role)) return true; + return false; + }); + + if (!hasIncomeRole) { + const error = new EmbedBuilder() + .setColor(client.config.Colors.Red) + .setTitle("Missing Income!") + .setDescription(`It appears you don"t have any income`) + + return interaction.send({ embeds: [error] }) + } + + 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); + } + banking = banking.user; + + 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"); + } + + if (!client.exists(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 /= (60 * 60); + let hoursBetweenDates = Math.abs(Math.round(diff)); + + if (hoursBetweenDates >= GuildDB.incomeLimiter) { + let roles = []; + let income = []; + for (let i = 0; i < GuildDB.incomeRoles.length; i++) { + if (interaction.member.roles.includes(GuildDB.incomeRoles[i].role)) { + roles.push(GuildDB.incomeRoles[i].role) + income.push(GuildDB.incomeRoles[i].income) + } + } + + let totalIncome = income.reduce((x, y) => x + y, 0) + + let newData = banking.guilds[GuildDB.serverID]; + newData.balance += totalIncome; + newData.lastIncome = now; + + client.dbo.collection("users").updateOne({ "user.userID": interaction.member.user.id }, { $set: { [`user.guilds.${GuildDB.serverID}`]: newData } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let description = `**You collected**`; + for (let i = 0; i < roles.length; i++) { + description += `\n<@&${roles[i]}> - $**${income[i].toFixed(2).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}**` + } + + const success = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(description) + + return interaction.send({ embeds: [success] }) + + } else { + let date = banking.guilds[GuildDB.serverID].lastIncome; + date.setHours(date.getHours() + GuildDB.incomeLimiter); + diff = (date - now) / 1000; + let timeTillIncome = client.secondsToDhms(diff); + + const error = new EmbedBuilder() + .setColor(client.config.Colors.Red) + .setDescription(`You"ve already collected your income this week. Wait **${timeTillIncome}** to collect again.`); + + return interaction.send({ embeds: [error] }) + } + }, + }, +} \ No newline at end of file diff --git a/src/commands/compare-rating.js b/src/commands/compare-rating.js new file mode 100644 index 0000000..5c90dbf --- /dev/null +++ b/src/commands/compare-rating.js @@ -0,0 +1,143 @@ +const { EmbedBuilder } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; +const { insertPVPstats } = require("../database/player"); + +module.exports = { + name: "compare-rating", + debug: false, + global: false, + description: "Compare combat ratings between yourself and another player", + usage: "[user or gamertag]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [{ + name: "discord", + description: "Discord user to lookup stats", + value: "discord", + type: CommandOptions.User, + required: false, + }, { + name: "gamertag", + description: "Gamertag to lookup stats", + type: CommandOptions.String, + required: false, + }], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + 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)) { + 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."); + + return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); + } + + let discord = args[0] && args[0].name == "discord" ? args[0].value : undefined; + let gamertag = args[0] && args[0].name == "gamertag" ? args[0].value : undefined; + + if (!discord && !gamertag) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`Please provide a Discord User or Gamertag`)] }); + + let leaderboard = await client.dbo.collection("players").aggregate([ + { $sort: { "combatRating": -1 } } + ]).toArray(); + + let comp; + if (discord) comp = leaderboard.find(s => s.discordID == discord); + 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.`)] }); + + let lbPosSelf = leaderboard.indexOf(self) + 1; + let lbPosComp = leaderboard.indexOf(comp) + 1; + + let selfData = self.combatRatingHistory; + let compData = comp.combatRatingHistory; + if (selfData.length == 1) selfData.push(self.combatRating) // Make array 2 long for a straight line in the graph + if (compData.length == 1) compData.push(comp.combatRating) // Make array 2 long for a straight line in the graph + 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; + + let tag = comp.discordID != "" ? `<@${comp.discordID}>` : comp.gamertag; + + let statsEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`<@${interaction.member.user.id}> vs ${tag} Combat Rating`) + .addFields( + { name: `${self.gamertag}"s Combat Rating Stats`, value: `> Leaderboard Pos: # ${lbPosSelf}\n> Rating: ${self.combatRating}`, inline: false }, + { name: `${comp.gamertag}"s Combat Rating Stats`, value: `> Leaderboard Pos: # ${lbPosComp}\n> Rating: ${comp.combatRating}`, inline: false }, + { name: "Rating Difference", value: `${Math.abs(self.combatRating - comp.combatRating)}`, inline: false }, + ); + + const dataMax = Math.max(selfDataMax, compDataMax); + const dataMin = Math.min(Math.min(...selfData), Math.min(...compData)) + + const len = Math.max(selfData.length, compData.length); + const diff = Math.abs(selfData.length - compData.length); + if (selfData.length < compData.length) selfData.unshift(...(new Array(diff).fill(null, 0, diff))); + if (compData.length < selfData.length) compData.unshift(...(new Array(diff).fill(null, 0, diff))); + + const chart = { + type: "line", + data: { + labels: new Array(len).fill(" ", 0, len), + datasets: [ + { + data: selfData, + label: `${self.gamertag}"s Combat Ratings`, + }, + { + data: compData, + label: `${comp.gamertag}"s Combat Ratings`, + } + ], + }, + options: { + legend: { + labels: { + fontSize: 14, + fontStyle: "bold", + } + }, + scales: { + // Gives comfortable margin to the top of the y-axis + yAxes: [{ + ticks: { + fontStyle: "bold", + // max: Math.round(dataMax / 10) * 10 + 10, + // min: Math.round(dataMin / 10) * 10, + }, + }], + }, + // Gives a margin to the right of the whole graph + layout: { + padding: { + right: 40, + }, + }, + }, + }; + + const encodedChart = encodeURIComponent(JSON.stringify(chart)); + const chartURL = `https://quickchart.io/chart?c=${encodedChart}&bkg=${encodeURIComponent("#ded8d7")}`; + + statsEmbed.setImage(chartURL); + + return interaction.send({ embeds: [statsEmbed] }); + }, + }, +} \ No newline at end of file diff --git a/src/commands/config.js b/src/commands/config.js new file mode 100644 index 0000000..8f70002 --- /dev/null +++ b/src/commands/config.js @@ -0,0 +1,1143 @@ +const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; +const bitfieldCalculator = require("discord-bitfield-calculator"); +const { getDefaultSettings } = require("../database/guild"); + +module.exports = { + name: "config", + debug: false, + global: false, + description: "Configure your server settings", + usage: "[options] [configuration]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: ["MANAGE_GUILD"], + }, + options: [ + { + name: "killfeed", + description: "Configure the killfeed", + value: "killfeed", + type: CommandOptions.SubCommandGroup, + options: [ + { + name: "channel", + description: "Configure the killfeed channel", + value: "channel", + type: CommandOptions.SubCommand, + options: [{ + name: "channel", + description: "The channel to configure", + value: "channel", + type: CommandOptions.Channel, + required: true + }] + }, + { + name: "show_coords", + description: "Show the coordinates of the victim in the killfeed channel.", + value: "show_coords", + type: CommandOptions.SubCommand, + options: [{ + name: "configuration", + description: "True or False", + value: false, + type: CommandOptions.Boolean, + required: true, + }] + }, + { + name: "show_weapon", + description: "Show the image of the weapon in the killfeed", + value: "show_weapon", + type: CommandOptions.SubCommand, + options: [{ + name: "configuration", + description: "True or False", + value: false, + type: CommandOptions.Boolean, + required: true, + }] + } + ] + }, + { + name: "allowed_channels", + description: "Set channels you're allowed to use the bot in", + value: "allowed_channels", + type: CommandOptions.SubCommandGroup, + options: [ + { + name: "add", + description: "Add channel", + value: "add", + type: CommandOptions.SubCommand, + options: [{ + name: "channel", + description: "The channel to configure", + value: "channel", + type: CommandOptions.Channel, + channel_types: [0], // Restrict to text channel + required: true, + }] + }, + { + name: "remove", + description: "Remove channel", + value: "remove", + type: CommandOptions.SubCommand, + options: [{ + name: "channel", + description: "The channel to configure", + value: "channel", + type: CommandOptions.Channel, + channel_types: [0], // Restrict to text channel + required: true, + }] + }, + { + name: "clear", + description: "Clears all configured channels", + value: "clear", + type: CommandOptions.SubCommand, + }, + { + name: "view", + description: "View configured allowed channels", + value: "view", + type: CommandOptions.SubCommand, + } + ] + }, + { + name: "set_channel", + description: "Configure a channel", + value: "set_channel", + type: CommandOptions.SubCommand, + options: [ + { + name: "channel_type", + description: "Select the channel type", + value: "channel_type", + type: CommandOptions.String, + choices: [ + { name: "Killfeed", value: "killfeedChannel" }, { name: "Admin Logs", value: "connectionLogsChannel" }, + { name: "Welcome", value: "welcomeChannel" }, { name: "Online Players", value: "activePlayersChannel" }, + ], + required: true, + }, + { + name: "channel", + description: "The channel to configure", + value: "channel", + type: CommandOptions.Channel, + channel_types: [0], // Restrict to text channel + required: true, + }, + ] + }, + { + name: "linked_gt_role", + description: "Role for users with linked gamertags", + value: "linked_gt_role", + type: CommandOptions.SubCommand, + options: [{ + name: "role", + description: "Role to configure", + value: "role", + type: CommandOptions.Role, + required: true, + }] + }, + { + name: "member_role", + description: "Role for users who join the server", + value: "member_role", + type: CommandOptions.SubCommand, + options: [{ + name: "role", + description: "Role to configure", + value: "role", + type: CommandOptions.Role, + required: true, + }] + }, + { + name: "bot_admin_role", + description: "Set/remove bot admin role", + value: "bot_admin_role", + type: CommandOptions.SubCommandGroup, + options: [ + { + name: "add", + description: "Configure role to be bot admin", + value: "add", + type: CommandOptions.SubCommand, + options: [{ + name: "role", + description: "Role to confiure", + value: "role", + type: CommandOptions.Role, + required: true, + }] + }, + { + name: "remove", + description: "Remove configured role as bot admin", + value: "remove", + type: CommandOptions.SubCommand, + options: [{ + name: "role", + description: "Role to remove", + value: "role", + type: CommandOptions.Role, + required: true, + }] + }, + { + name: "view", + description: "View the configured bot admin roles", + value: "view", + type: CommandOptions.SubCommand, + } + ] + }, + { + name: "admin_ping_role", + description: "Admin role to ping in admin logs channel", + value: "admin_ping_role", + type: CommandOptions.SubCommand, + options: [{ + name: "role", + description: "Role to configure", + value: "role", + type: CommandOptions.Role, + required: true, + }] + }, + { + name: "exclude", + description: "Exclude roles that can be used to claim armbands", + value: "exclude", + type: CommandOptions.SubCommandGroup, + options: [ + { + name: "add", + description: "Configure role to be excluded", + value: "add", + type: CommandOptions.SubCommand, + options: [{ + name: "role", + description: "Role to confiure", + value: "role", + type: CommandOptions.Role, + required: true, + }] + }, + { + name: "remove", + description: "Remove configured role thats excluded", + value: "remove", + type: CommandOptions.SubCommand, + options: [{ + name: "role", + description: "Role to remove", + value: "role", + type: CommandOptions.Role, + required: true, + }] + }, + { + name: "view", + description: "View the configured excluded roles", + value: "view", + type: CommandOptions.SubCommand, + }, + ] + }, + { + name: "reset", + description: "Restore all settings to default configurations", + value: "reset", + type: CommandOptions.SubCommand, + }, + { + name: "view", + description: "View current settings configuration", + value: "view", + type: CommandOptions.SubCommand, + }, + { + name: "starting_balance", + description: "Set the starting balance of a new user", + value: "starting_balance", + type: CommandOptions.SubCommand, + options: [{ + name: "amount", + description: "The amount to set the starting balance", + value: "amount", + type: CommandOptions.Float, + min_value: 1.00, + required: true, + }] + }, + { + name: "uav-price", + description: "Configure the price of a UAV", + value: "uav-price", + type: CommandOptions.SubCommand, + options: [{ + name: "amount", + description: "The amount to set the UAV price", + value: "amount", + type: CommandOptions.Float, + min_value: 0.01, + required: true, + }] + }, + { + name: "emp-price", + description: "Configure the price of an EMP", + value: "emp-price", + type: CommandOptions.SubCommand, + options: [{ + name: "amount", + description: "The amount to set the EMP price", + value: "amount", + type: CommandOptions.Float, + min_value: 0.01, + required: true, + }] + }, + { + name: "income_role", + description: "Set/remove roles to recieve income", + value: "set_income_role", + type: CommandOptions.SubCommandGroup, + options: [ + { + name: "set", + description: "Set role", + value: "set", + type: CommandOptions.SubCommand, + options: [ + { + name: "role", + description: "Role to set", + value: "role", + type: CommandOptions.Role, + required: true, + }, + { + name: "amount", + description: "The amount to collect", + value: 120.00, + type: CommandOptions.Float, + min_value: 0.01, + required: true, + } + ] + }, + { + name: "remove", + description: "Remove role", + value: "remove", + type: CommandOptions.SubCommand, + options: [{ + name: "role", + description: "Role to remove", + value: "role", + type: CommandOptions.Role, + required: true, + }] + }, + ], + }, + { + name: "income_limiter", + description: "Change the number of hours to wait before collecting next income", + value: "income_limiter", + type: CommandOptions.SubCommand, + options: [{ + name: "hours", + description: "Number of hours till income can be collected", + value: 168.00, // 1 week + type: CommandOptions.Float, + min_value: 1.00, + required: true, + }] + }, + { + name: "combat-log-timer", + description: "Adjust number of minutes to detect combat logs (0 disables combat log)", + value: "combat-log-timer", + type: CommandOptions.SubCommand, + options: [{ + name: "minutes", + description: "Minutes to qualify combat log", + value: 5, + type: CommandOptions.Integer, + min_value: 0, + }] + }, + { + name: "toggle-uav-purchase", + description: "Allow/Disallow UAV purchases", + value: "toggle-uav-purchase", + type: CommandOptions.SubCommand, + options: [{ + name: "configuration", + description: "True or False", + value: false, + type: CommandOptions.Boolean, + required: true, + }] + }, + { + name: "toggle-emp-purchase", + description: "Allow/Disallow EMP purchases", + value: "toggle-uav-purchase", + type: CommandOptions.SubCommand, + options: [{ + name: "configuration", + description: "True or False", + value: false, + type: CommandOptions.Boolean, + required: true, + }] + }, + { + name: "welcome_message_server_name", + description: "Configure the server name in the welcome message", + value: "welcome_message_server_name", + type: CommandOptions.SubCommand, + options: [{ + name: "name", + description: "Server name to include in welcome message", + value: "name", + type: CommandOptions.String, + required: true, + }] + } + ], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + run: async (client, interaction, args, { GuildDB }) => { + const permissions = bitfieldCalculator.permissions(interaction.member.permissions); + let canUseCommand = false; + + if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; + 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." }); + + switch (args[0].name) { + + case "allowed_channels": + const channels_config = args[0].options[0].name; + const channelid = ["add", "remove"].includes(channels_config) ? args[0].options[0].options[0].value : null; + + if (channels_config == "add") { + const channelAdd = client.GetChannel(channelid); + + const newChannelErrorEmbed = new EmbedBuilder().setColor(client.config.Colors.Red) + let error = false; + + if (!channelAdd) { error = true; newChannelErrorEmbed.setDescription(`**Error Notice:** Cannot find that channel.`); } + if (channelAdd.type == "voice") { error = true; newChannelErrorEmbed.setDescription(`**Error Notice:** Cannot add voice channel to allowed channels.`); } + if (error) return interaction.send({ embeds: [newChannelErrorEmbed] }); + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $push: { "server.allowedChannels": channelid } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + const successAddChannelEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Success:** Set <#${channelid}> as an allowed channel.`); + + return interaction.send({ embeds: [successAddChannelEmbed] }); + } else if (channels_config == "remove") { + + const errorChannelNotAvailable = new EmbedBuilder() + .setDescription(`**Error Notice:** <#${channelid}> is not in allowed channels.`) + .setColor(client.config.Colors.Red) + + if (!GuildDB.allowedChannels.includes(channelid)) return interaction.send({ embeds: [errorChannelNotAvailable] }); + + const promptRemoveChannel = new EmbedBuilder() + .setTitle(`Are you sure you want to remove this channel from allowed channels?`) + .setColor(client.config.Colors.Default) + + const optRemoveChannel = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId(`RemoveAllowedChannels-yes-${channelid}-${interaction.member.user.id}`) + .setLabel("Yes") + .setStyle(ButtonStyle.Danger), + new ButtonBuilder() + .setCustomId(`RemoveAllowedChannels-no-${channelid}-${interaction.member.user.id}`) + .setLabel("No") + .setStyle(ButtonStyle.Success) + ) + + return interaction.send({ embeds: [promptRemoveChannel], components: [optRemoveChannel], flags: (1 << 6) }); + + } else if (channels_config == "clear") { + + const errorNoAllowedChannels = new EmbedBuilder() + .setDescription(`**Error Notice:**\n> No allowed channels configured to clear`) + .setColor(client.config.Colors.Red) + + if (GuildDB.allowedChannels.length == 0) return interaction.send({ embeds: [errorNoAllowedChannels] }); + + const promptClearChannels = new EmbedBuilder() + .setTitle(`Are you sure you want to clear all configured channels from allowed channels?`) + .setColor(client.config.Colors.Default) + + const optClearChannels = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId(`ClearAllowedChannels-yes-${interaction.member.user.id}`) + .setLabel("Yes") + .setStyle(ButtonStyle.Danger), + new ButtonBuilder() + .setCustomId(`ClearAllowedChannels-no-${interaction.member.user.id}`) + .setLabel("No") + .setStyle(ButtonStyle.Success) + ) + + return interaction.send({ embeds: [promptClearChannels], components: [optClearChannels], flags: (1 << 6) }); + + + } else if (channels_config == "view") { + + if (!GuildDB.customChannelStatus) { + const noConfiguredChannels = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTitle("Channels") + .setDescription("> There are no configured channels"); + + return interaction.send({ embeds: [noConfiguredChannels] }); + } + + const configuredChannels = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTitle("Channels") + + let des = ""; + for (let i = 0; i < GuildDB.allowedChannels.length; i++) { + if (i == 0) des += `> <#${GuildDB.allowedChannels[i]}>`; + else des += `\n> <#${GuildDB.allowedChannels[i]}>`; + } + configuredChannels.setDescription(des); + + return interaction.send({ embeds: [configuredChannels] }); + + } + + case "bot_admin_role": + const bot_admin_config = args[0].options[0].name; + const botAdminRoleId = ["add", "remove"].includes(bot_admin_config) ? args[0].options[0].options[0].value : null; + if (bot_admin_config == "add") { + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $push: { "server.botAdminRoles": botAdminRoleId } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + const successSetBotAdminRoleEmbed = new EmbedBuilder() + .setDescription(`Successfully added <@&${botAdminRoleId}> as a bot admin role.\nUsers with this role can use restricted commands.`) + .setColor(client.config.Colors.Green); + + return interaction.send({ embeds: [successSetBotAdminRoleEmbed] }); + + } else if (bot_admin_config == "remove") { + + if (!GuildDB.botAdminRoles.includes(botAdminRoleId)) { + const nonAdminRoleEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Yellow) + .setDescription(`**Notice:**\n> The role <@&${botAdminRoleId}> has not been configured as a bot admin.`); + + return interaction.send({ embeds: [nonAdminRoleEmbed] }); + } + + const promptRemoveAdminRole = new EmbedBuilder() + .setTitle(`Are you sure you want to remove this role as a bot admin?`) + .setColor(client.config.Colors.Default) + + const optRemoveAdminRole = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId(`RemoveBotAdminRole-yes-${botAdminRoleId}-${interaction.member.user.id}`) + .setLabel("Yes") + .setStyle(ButtonStyle.Danger), + new ButtonBuilder() + .setCustomId(`RemoveBotAdminRole-no-${botAdminRoleId}-${interaction.member.user.id}`) + .setLabel("No") + .setStyle(ButtonStyle.Success) + ) + + return interaction.send({ embeds: [promptRemoveAdminRole], components: [optRemoveAdminRole], flags: (1 << 6) }); + + } else if (bot_admin_config == "view") { + + if (GuildDB.botAdminRoles.length == 0) { + const noBotAdminRoles = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTitle("Admin Roles") + .setDescription("> There have been no configured admin roles"); + + return interaction.send({ embeds: [noBotAdminRoles] }); + } + + const botAdminRolesEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTitle("Admin Roles") + + let des = ""; + for (let i = 0; i < GuildDB.botAdminRoles.length; i++) { + des += `\n> <@&${GuildDB.botAdminRoles[i]}>`; + } + botAdminRolesEmbed.setDescription(des); + + return interaction.send({ embeds: [botAdminRolesEmbed] }); + + } + + case "admin_ping_role": + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "server.adminRole": args[0].options[0].value } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + const successSetAdminRoleEmbed = new EmbedBuilder() + .setDescription(`Successfully set <@&${args[0].options[0].value}> as the server admin role..`) + .setColor(client.config.Colors.Green); + + return interaction.send({ embeds: [successSetAdminRoleEmbed] }); + + case "exclude": + const exclude_config = args[0].options[0].name; + const exclude_roleid = ["add", "remove"].includes(exclude_config) ? args[0].options[0].options[0].value : null; + + if (exclude_config == "add") { + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $push: { "server.excludedRoles": exclude_roleid } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }) + + const successExcludeEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Done!**\n> Successfully added <@&${exclude_roleid}> to list of excluded roles.`) + + return interaction.send({ embeds: [successExcludeEmbed] }); + + } else if (exclude_config == "remove") { + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $pull: { "server.excludedRoles": exclude_roleid } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }) + + const successRemoveExcludeEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Done!**\n> Successfully removed <@&${exclude_roleid}> to list of excluded roles.`) + + return interaction.send({ embeds: [successRemoveExcludeEmbed] }); + + } else if (exclude_config == "view") { + + if (GuildDB.excludedRoles.length == 0) { + const noExcludedRoles = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTitle("Excluded Roles") + .setDescription("> There have been no excluded roles"); + + return interaction.send({ embeds: [noExcludedRoles] }); + } + + const excludedRolesEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTitle("Excluded Roles") + + let des = ""; + for (let i = 0; i < GuildDB.excludedRoles.length; i++) { + des += `\n> <@&${GuildDB.excludedRoles[i]}>`; + } + excludedRolesEmbed.setDescription(des); + + return interaction.send({ embeds: [excludedRolesEmbed] }); + + } + + case "reset": + const promptReset = new EmbedBuilder() + .setTitle(`Woah!? Hold on.`) + .setDescription("Are you sure you wish to remove all your configurations for this guild?") + .setColor(client.config.Colors.Default) + + const optReset = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId(`ResetSettings-yes-${interaction.member.user.id}`) + .setLabel("Yes") + .setStyle(ButtonStyle.Danger), + new ButtonBuilder() + .setCustomId(`ResetSettings-no-${interaction.member.user.id}`) + .setLabel("No") + .setStyle(ButtonStyle.Success) + ) + + return interaction.send({ embeds: [promptReset], components: [optReset], flags: (1 << 6) }); + + case "view": + + // wrappers + const w = "\`\`\`"; + const a = "ansi\n"; + const f = "fix\n"; + const m = "arm\n" + const g = ""; + const r = ""; + + // boolean display + const autoRestart = GuildDB.autoRestart ? `${g}true` : `${r}false`; + const showKillfeedCoords = GuildDB.showKillfeedCoords ? `${g}true` : `${r}false`; + const showKillfeedWeapon = GuildDB.showKillfeedWeapon ? `${g}true` : `${r}false`; + const purchaseUAV = GuildDB.purchaseUAV ? `${g}true` : `${r}false`; + const purchaseEMP = GuildDB.purchaseEMP ? `${g}true` : `${r}false`; + const adminRoles = GuildDB.hasBotAdmin ? `${g}true` : `${r}false` + const excludedRoles = GuildDB.hasExcludedRoles ? `${g}true` : `${r}false`; + + // 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; + + // value display + const incomeLimiter = `${GuildDB.incomeLimiter} hours`; + const startingBalance = `$${GuildDB.startingBalance.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; + const uavPrice = `$${GuildDB.uavPrice.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; + const empPrice = `$${GuildDB.empPrice.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; + const combatLogTimer = `${GuildDB.combatLogTimer} minutes`; + + // Ugly below but kinda nice above + const settingsEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTitle("Current Guild Configurations") + .addFields( + { name: "Guild ID", value: `${w}${f}${GuildDB.serverID}${w}`, inline: true }, + { name: "Server Name", value: `${w}${f}${GuildDB.serverName}${w}`, inline: true }, + { name: "Auto Restart", value: `${w}${a}${autoRestart}${w}`, inline: true }, + { name: "UAVs Enabled", value: `${w}${a}${purchaseUAV}${w}`, inline: true }, + { name: "EMPs Enabled", value: `${w}${a}${purchaseEMP}${w}`, inline: true }, + { name: "Show Killfeed Coords", value: `${w}${a}${showKillfeedCoords}${w}`, inline: true }, + { name: "Show Killfeed Weapons", value: `${w}${a}${showKillfeedWeapon}${w}`, inline: true }, + { name: "Has Admin Rols", value: `${w}${a}${adminRoles}${w}`, inline: true }, + { name: "Has Excluded Roles", value: `${w}${a}${excludedRoles}${w}`, inline: true }, + { name: "Allowed Channels", value: `${channelsInfo}`, inline: true }, + { name: "Killfeed Channel", value: `${killfeedChannel}`, inline: true }, + { name: "Connection Logs Channel", value: `${connectionLogs}`, inline: true }, + { name: "Player List Channel", value: `${activePlayers}`, inline: true }, + { name: "Welcome Channel", value: `${welcomeChannel}`, inline: true }, + { name: "Linked Gamertag Role", value: `${linkedGTRole}`, inline: true }, + { name: "Member Role", value: `${memberRole}`, inline: true }, + { name: "Income Limiter", value: `${w}${f}${incomeLimiter}${w}`, inline: true }, + { name: "Starting Balance", value: `${w}${f}${startingBalance}${w}`, inline: true }, + { name: "UAV Price", value: `${w}${f}${uavPrice}${w}`, inline: true }, + { name: "EMP Price", value: `${w}${f}${empPrice}${w}`, inline: true }, + { name: "Combat Log Timer", value: `${w}${f}${combatLogTimer}${w}`, inline: true }, + ); + + return interaction.send({ embeds: [settingsEmbed] }); + + case "set_channel": + const channelType = args[0].options[0].value; + const channel = args[0].options[1].value; + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { [`server.${channelType}`]: channel } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + const successSetChannelEmbed = new EmbedBuilder() + .setDescription(`Successfully set <#${channel}> as the ${channelType} channel.`) + .setColor(client.config.Colors.Green); + + return interaction.send({ embeds: [successSetChannelEmbed] }); + + case "linked_gt_role": + const linked_gt_role = args[0].options[0].value; + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "server.linkedGamertagRole": linked_gt_role } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + const successLinkedGTRoleEmbed = new EmbedBuilder() + .setDescription(`Successfully set <@&${linked_gt_role}> to give to users who link their gamertag.`) + .setColor(client.config.Colors.Green); + + return interaction.send({ embeds: [successLinkedGTRoleEmbed] }); + + case "member_role": + const member_role = args[0].options[0].value; + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "server.memberRole": member_role } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + const successMemberRoleEmbed = new EmbedBuilder() + .setDescription(`Successfully set <@&${member_role}> to give to users who link they join.`) + .setColor(client.config.Colors.Green); + + return interaction.send({ embeds: [successMemberRoleEmbed] }); + + case "starting_balance": + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "server.startingBalance": args[0].options[0].value } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successSetStartingBalanceEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`Successfully set $${args[0].options[0].value.toFixed(2)} as starting balance`); + + return interaction.send({ embeds: [successSetStartingBalanceEmbed] }); + + case "income_role": + if (args[0].options[0].name == "set") { + const incomeRoleId = args[0].options[0].options[0].value + + if (args[0].options[0].options[1].value <= 0) { + let errorIncomeAmount = new EmbedBuilder() + .setDescription("**Error Notice:** Amount cannot be $0 or less than $0.") + .setColor(client.config.Colors.Red); + + return interaction.send({ embeds: [errorIncomeAmount] }); + } + + const searchIndex = GuildDB.incomeRoles.findIndex((role) => role.role == incomeRoleId); + if (searchIndex == -1) { + const newIncome = { + role: incomeRoleId, + income: args[0].options[0].options[1].value, + } + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $push: { "server.incomeRoles": newIncome } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + } else { + client.dbo.collection("guilds").updateOne({ + "server.serverID": GuildDB.serverID, + "server.incomeRoles.role": incomeRoleId + }, + { + $set: { + "server.incomeRoles.$.income": args[0].options[0].options[1].value + } + }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + } + const perform = searchIndex == -1 ? "set" : "updated"; + + const successIncomeRoleEmbed = new EmbedBuilder() + .setDescription(`Successfully ${perform} <@&${incomeRoleId}>"s income to $${args[0].options[0].options[1].value}`) + .setColor(client.config.Colors.Green); + + return interaction.send({ embeds: [successIncomeRoleEmbed] }); + + } else if (args[0].options[0].name == "remove") { + const searchIndex = GuildDB.incomeRoles.findIndex((role) => role.role == incomeRoleId); + if (searchIndex == -1) { + const errorIncomeNotFoundEmbed = new EmbedBuilder() + .setDescription("**Error Notice:** Role not found") + .setColor(client.config.Colors.Red); + + return interaction.send({ embeds: [errorIncomeNotFoundEmbed] }); + } else { + const promptRemoveIncomeRole = new EmbedBuilder() + .setTitle(`Are you sure you want to remove this role as an income?`) + .setColor(client.config.Colors.Default) + + const optRemoveIncomeRole = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId(`RemoveIncomeRole-yes-${incomeRoleId}-${interaction.member.user.id}`) + .setLabel("Yes") + .setStyle(ButtonStyle.Danger), + new ButtonBuilder() + .setCustomId(`RemoveIncomeRole-no-${incomeRoleId}-${interaction.member.user.id}`) + .setLabel("No") + .setStyle(ButtonStyle.Success) + ) + + return interaction.send({ embeds: [promptRemoveIncomeRole], components: [optRemoveIncomeRole], flags: (1 << 6) }); + } + } + + case "income_limiter": + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "server.incomeLimiter": args[0].options[0].value } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successIncomeLimiterEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`Successfully set **${args[0].options[0].value} hours** as the wait time to collect income.`); + + return interaction.send({ embeds: [successIncomeLimiterEmbed] }); + + case "uav-price": + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "server.uavPrice": args[0].options[0].value } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successUAVPriceEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`Successfully set $${args[0].options[0].value.toFixed(2)} as UAV price`); + + return interaction.send({ embeds: [successUAVPriceEmbed] }); + + case "emp-price": + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "server.empPrice": args[0].options[0].value } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successEMPPriceEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`Successfully set $${args[0].options[0].value.toFixed(2)} as EMP price`); + + return interaction.send({ embeds: [successEMPPriceEmbed] }); + + case "combat-log-timer": + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "server.combatLogTimer": args[0].options[0].value } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successCobatLogTimerEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`Successfully set combat log timer to **${args[0].options[0].value.toFixed(0)} minutes.**`); + + return interaction.send({ embeds: [successCobatLogTimerEmbed] }); + + case "toggle-uav-purchase": + const togggleUAVpurchase = args[0].options[0].value ? 1 : 0; + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "server.purchaseUAV": togggleUAVpurchase } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successToggleUAVpurchaseEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`Users can ${togggleUAVpurchase ? "now" : "no longer"} purchase UAVs.`); + + return interaction.send({ embeds: [successToggleUAVpurchaseEmbed] }); + + case "toggle-emp-purchase": + const togggleEMPpurchase = args[0].options[0].value ? 1 : 0; + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "server.purchaseEMP": togggleEMPpurchase } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successToggleEMPpurchaseEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`Users can ${togggleUAVpurchase ? "now" : "no longer"} purchase EMPs.`); + + return interaction.send({ embeds: [successToggleEMPpurchaseEmbed] }); + + case "killfeed": + const killfeed_configuration = args[0].options[0].name; + + if (killfeed_configuration == "channel") { + + const channel = args[0].options[0].options[0].value; + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "server.killfeedChannel": channel } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + const successConfigureKillfeedChannel = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`Successfully configured the killfeed channel to <#${channel}>`); + + return interaction.send({ embeds: [successConfigureKillfeedChannel] }); + + } else if (killfeed_configuration == "show_coords") { + const showKillfeedCoordsConfiguration = args[0].options[0].options[0].value ? 1 : 0; + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "server.showKillfeedCoords": showKillfeedCoordsConfiguration } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + const successConfigureShowKillfeedCoords = new EmbedBuilder() + .setDescription(`Successfully configured the killfeed to ${showKillfeedCoordsConfiguration ? "show" : "not show"} coordinates.`) + .setColor(client.config.Colors.Green); + + return interaction.send({ embeds: [successConfigureShowKillfeedCoords] }); + + } else if (killfeed_configuration == "show_weapon") { + + const showKillfeedWeaponConfiguration = args[0].options[0].options[0].value ? 1 : 0; + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "server.showKillfeedWeapon": showKillfeedWeaponConfiguration } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + const successConfigureShowKillfeedCoords = new EmbedBuilder() + .setDescription(`Successfully configured the killfeed to ${showKillfeedWeaponConfiguration ? "show" : "not show"} weapon icons.`) + .setColor(client.config.Colors.Green); + + return interaction.send({ embeds: [successConfigureShowKillfeedCoords] }); + + } + + case "welcome_message_server_name": + const server_name = args[0].options[0].value; + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "server.serverName": server_name } }, (err, res) => { + if (err) return client.sendInternalError(interacion, err); + }); + + const succcessUpdateServerName = new EmbedBuilder() + .setDescription(`Successfully configured the server name to **${server_name}** in the welcome message.`) + .setColor(client.config.Colors.Green); + + return interaction.send({ embeds: [succcessUpdateServerName] }); + + default: + return client.sendInternalError(interaction, "There was an error parsing the config command"); + } + }, + }, + + Interactions: { + + RemoveAllowedChannels: { + run: async (client, interaction, GuildDB) => { + if (!interaction.customId.endsWith(interaction.member.user.id)) { + return interaction.reply({ + content: "This button is not for you", + flags: (1 << 6) + }) + } + let action = "" + if (interaction.customId.split("-")[1] == "yes") { + action = "removed"; + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $pull: { "server.allowedChannels": interaction.customId.split("-")[2] } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + } else if (interaction.customId.split("-")[1] == "no") action = "kept"; + + const successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setTitle(`**Success**\n> Successfullly ${action} the channel.`) + + return interaction.update({ embeds: [successEmbed], components: [] }); + } + }, + + ClearAllowedChannels: { + run: async (client, interaction, GuildDB) => { + if (!interaction.customId.endsWith(interaction.member.user.id)) { + return interaction.reply({ + content: "This buttpm is not for you", + flags: (1 << 6) + }); + } + let action; + if (interaction.customId.split("-")[1] == "yes") { + action = "cleared"; + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "server.allowedChannels": [] } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }) + } else if (interaction.customId.split("-")[1] == "no") action = "kept"; + + const successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setTitle(`**Success**\n> Successfully ${action} all configured channels.`); + + return interaction.update({ embeds: [successEmbed], components: [] }); + } + }, + + RemoveBotAdminRole: { + run: async (client, interaction, GuildDB) => { + if (!interaction.customId.endsWith(interaction.member.user.id)) { + return ButtonInteraction.reply({ + content: "This button is not for you", + flags: (1 << 6) + }) + } + let action = ""; + let roleId = interaction.customId.split("-")[2]; + if (interaction.customId.split("-")[1] == "yes") { + action = "removed"; + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $pull: { "server.botAdminRoles": roleId } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + } else if (interaction.customId.split("-")[1] == "no") action = "kept"; + + const successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Successfully ${action} <@&${roleId}> as the bot admin role.**`) + + return interaction.update({ embeds: [successEmbed], components: [] }); + } + }, + + RemoveIncomeRole: { + run: async (client, interaction, GuildDB) => { + if (!interaction.customId.endsWith(interaction.member.user.id)) { + return ButtonInteraction.reply({ + content: "This button is not for you", + flags: (1 << 6) + }) + } + let action = ""; + let roleId = interaction.customId.split("-")[2]; + if (interaction.customId.split("-")[1] == "yes") { + action = "removed"; + let income = GuildDB.incemeRoles.find((i) => i.role == roleId); + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $pull: { "server.incomeRoles": income } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + } else if (interaction.customId.split("-")[1] == "no") action = "kept"; + + const successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Successfully ${action} <@&${roleId}> as an income role.**`) + + return interaction.update({ embeds: [successEmbed], components: [] }); + } + }, + + ResetSettings: { + run: async (client, interaction, GuildDB) => { + if (!interaction.customId.endsWith(interaction.member.user.id)) { + return ButtonInteraction.reply({ + content: "This button is not for you", + flags: (1 << 6) + }) + } + let action = ""; + if (interaction.customId.split("-")[1] == "yes") { + action = "reset"; + 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); + }); + } else if (interaction.customId.split("-")[1] == "no") action = "kept"; + + const successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setTitle(`Successfully ${action} guild configurations.`) + + return interaction.update({ embeds: [successEmbed], components: [] }); + } + } + } +} \ No newline at end of file diff --git a/src/commands/event.js b/src/commands/event.js new file mode 100644 index 0000000..bdfc70c --- /dev/null +++ b/src/commands/event.js @@ -0,0 +1,170 @@ +const { EmbedBuilder, ActionRowBuilder, StringSelectMenuBuilder } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; +const bitfieldCalculator = require("discord-bitfield-calculator"); + +module.exports = { + name: "event", + debug: false, + global: false, + description: "Admin controlled events", + usage: "[event] [option]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [{ + name: "player-track", + description: "Track a player and announce location", + value: "player-track", + type: CommandOptions.SubCommand, + options: [{ + name: "gamertag", + description: "Gamertag of player", + value: "gamertag", + type: CommandOptions.String, + required: true, + }, + { + name: "time", + description: "Duration of tracking", + value: "time", + type: CommandOptions.Integer, + required: true, + choices: [ + { name: "10-minutes", value: 10 }, { name: "15-minutes", value: 15 }, { name: "20-minutes", value: 20 }, { name: "25-minutes", value: 25 }, + { name: "30-minutes", value: 30 }, { name: "60-minutes", value: 60 }, { name: "90-minutes", value: 90 }, { name: "120-minutes", value: 120 }, + ] + }, + { + name: "event-name", + description: "Name of the event", + value: "event-name", + type: CommandOptions.String, + required: true, + }, + { + name: "channel", + description: "Channel to post tracking data", + value: "channel", + type: CommandOptions.Channel, + channel_types: [0], // Restrict to text channel + required: true, + }, { + name: "role", + description: "Optional role to ping", + value: "role", + type: CommandOptions.Role, + required: false, + }] + }, { + name: "delete", + description: "Delete an active event", + value: "delete", + type: CommandOptions.SubCommand + }], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + 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)) { + 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."); + + return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); + } + + const permissions = bitfieldCalculator.permissions(interaction.member.permissions); + let canUseCommand = false; + + if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; + 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." }); + + let events = GuildDB.events; + + 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 \`.`)] }); + + let event = { + type: args[0].name, + name: args[0].options[2].value, + gamertag: args[0].options[0].value, + channel: args[0].options[3].value, + role: args[0].options[4] ? args[0].options[4].value : null, + time: args[0].options[1].value, + creationDate: new Date(), + }; + + events.push(event); + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { + $set: { + "server.events": events + } + }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + const successCreatePlayerTrack = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`**Success:** Successfully created **${event.name}** that will last **${event.time} minutes.**`) + + return interaction.send({ embeds: [successCreatePlayerTrack] }); + + } else if (args[0].name == "delete") { + if (GuildDB.events.length == 0) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription("**Notice:** No Existing Events to Delete.")] }); + + let events = new StringSelectMenuBuilder() + .setCustomId(`DeleteEvent-${interaction.member.user.id}`) + .setPlaceholder(`Select an Event to Delete.`) + + for (let i = 0; i < GuildDB.events.length; i++) { + events.addOptions({ + label: GuildDB.events[i].name, + description: `Delete this Event`, + value: GuildDB.events[i].name + }); + } + + const eventsOptions = new ActionRowBuilder().addComponents(events); + + return interaction.send({ components: [eventsOptions], flags: (1 << 6) }); + } + } + }, + + Interactions: { + + DeleteEvent: { + run: async (client, interaction, GuildDB) => { + if (!interaction.customId.endsWith(interaction.member.user.id)) + return interaction.reply({ content: "This interaction is not for you", flags: (1 << 6) }); + + let event = GuildDB.events.find(e => e.name == interaction.values[0]); + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { + $pull: { + "server.events": event, + } + }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Success:** Successfully Deleted **${event.name} Event**`); + + return interaction.update({ embeds: [successEmbed], components: [] }); + } + } + } +} \ No newline at end of file diff --git a/src/commands/excluded.js b/src/commands/excluded.js new file mode 100644 index 0000000..f02f891 --- /dev/null +++ b/src/commands/excluded.js @@ -0,0 +1,46 @@ +const { EmbedBuilder } = require("discord.js"); + +module.exports = { + name: "excluded", + debug: false, + global: false, + description: "View a list of excluded roles", + usage: "", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + run: async (client, interaction, args, { GuildDB }) => { + if (GuildDB.excludedRoles.length == 0) { + let noExcludes = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTitle("Excluded Roles") + .setDescription("> There have been no excluded roles"); + + return interaction.send({ embeds: [noExcludes] }); + } + + let excluded = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTitle("Excluded Roles") + + let des = "*These roles you cannot use to claim an armband.*"; + for (let i = 0; i < GuildDB.excludedRoles.length; i++) { + des += `\n> <@&${GuildDB.excludedRoles[i]}>`; + } + excluded.setDescription(des); + + return interaction.send({ embeds: [excluded] }); + }, + }, + Interactions: {} +} diff --git a/src/commands/factions.js b/src/commands/factions.js new file mode 100644 index 0000000..6b803e5 --- /dev/null +++ b/src/commands/factions.js @@ -0,0 +1,87 @@ +const { EmbedBuilder } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; +const { Armbands } = require("../database/armbands.js"); + +module.exports = { + name: "factions", + debug: false, + global: false, + description: "View the armband of a faction", + usage: "[role]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [{ + name: "faction_role", + description: "View a specific faction's armband by role", + value: "faction_role", + type: CommandOptions.Role, + required: false, + }], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + run: async (client, interaction, args, { GuildDB }) => { + if (GuildDB.customChannelStatus == true && !GuildDB.allowedChannels.includes(interaction.channel_id)) + return interaction.send({ content: `You are not allowed to use the bot in this channel.`, flags: (1 << 6) }); + + // Return list of factions and their armband. + if (!args) { + + let factions = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTitle("Factions & Armbands") + + let description = ""; + + if (GuildDB.usedArmbands.length == 0) { + description = "> There are no factions that have claimed armbands."; + } else { + for (const [factionID, data] of Object.entries(GuildDB.factionArmbands)) { + if (description == "") description += `> <@&${factionID}> - ${data.armband}`; + else description += `\n> <@&${factionID}> - *${data.armband}*`; + } + } + + factions.setDescription(description); + + return interaction.send({ embeds: [factions] }); + } + + // Else return specific faction and their armband. + if (!GuildDB.factionArmbands[args[0].value]) { + return interaction.send({ + embeds: [ + new EmbedBuilder() + .setColor(client.config.Colors.Yellow) + .setDescription(`**Notice:**\n> The faction <@&${args[0].value}> has not claimed an armband.`) + ], + flags: (1 << 6) + }); + } + + let armbandURL; + + for (let i = 0; i < Armbands.length; i++) { + if (Armbands[i].name == GuildDB.factionArmbands[args[0].value].armband) { + armbandURL = Armbands[i].url; + break; + } + } + + const faction = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`> Faction <@&${GuildDB.factionArmbands[args[0].value].faction}> - ***${GuildDB.factionArmbands[args[0].value].armband}***`) + .setImage(armbandURL); + + return interaction.send({ embeds: [faction] }); + }, + }, + Interactions: {} +} diff --git a/src/commands/gamertag-link.js b/src/commands/gamertag-link.js new file mode 100644 index 0000000..32b9c45 --- /dev/null +++ b/src/commands/gamertag-link.js @@ -0,0 +1,128 @@ +const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; +const { UpdatePlayer } = require("../database/player"); + +module.exports = { + name: "gamertag-link", + debug: false, + global: false, + description: "Connect DayZ stats to your Discord", + usage: "[gamertag]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [{ + name: "gamertag", + description: "Gamertag of player", + value: "gamertag", + type: CommandOptions.String, + required: true, + }], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + 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)) { + 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."); + + return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); + } + + 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 (client.exists(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?`) + + const opt = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId(`OverwriteGamertag-yes-${args[0].value}-${interaction.member.user.id}`) + .setLabel("Yes") + .setStyle(ButtonStyle.Success), + new ButtonBuilder() + .setCustomId(`OverwriteGamertag-no-${args[0].value}-${interaction.member.user.id}`) + .setLabel("No") + .setStyle(ButtonStyle.Secondary) + ) + + return interaction.send({ embeds: [warnGTOverwrite], components: [opt] }); + } + + playerStat.discordID = interaction.member.user.id; + + await UpdatePlayer(client, playerStat, interaction); + + let member = interaction.guild.members.cache.get(interaction.member.user.id); + if (client.exists(GuildDB.linkedGamertagRole)) { + let role = interaction.guild.roles.cache.get(GuildDB.linkedGamertagRole); + member.roles.add(role); + } + + if (client.exists(GuildDB.memberRole)) { + let role = interaction.guild.roles.cache.get(GuildDB.memberRole); + member.roles.add(role); + } + + let connectedEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`Successfully connected \` ${playerStat.gamertag} \` as your gamertag.`); + + return interaction.send({ embeds: [connectedEmbed] }) + }, + }, + + Interactions: { + + OverwriteGamertag: { + run: async (client, interaction, GuildDB) => { + 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 = await client.dbo.collection("players").findOne({ "gamertag": interaction.customId.split("-")[2] }); + + playerStat.discordID = interaction.member.user.id; + + await UpdatePlayer(client, playerStat, interaction); + + let member = interaction.guild.members.cache.get(interaction.member.user.id); + if (client.exists(GuildDB.linkedGamertagRole)) { + let role = interaction.guild.roles.cache.get(GuildDB.linkedGamertagRole); + member.roles.add(role); + } + + if (client.exists(GuildDB.memberRole)) { + let role = interaction.guild.roles.cache.get(GuildDB.memberRole); + member.roles.add(role); + } + + let connectedEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`Successfully connected \` ${playerStat.gamertag} \` as your gamertag.`); + + return interaction.update({ embeds: [connectedEmbed], components: [] }); + + } else { + const cancel = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription("**Canceled**\n> The gamertag link will not be overwritten"); + + return interaction.update({ embeds: [cancel], components: [] }); + } + } + } + + } +} \ No newline at end of file diff --git a/src/commands/gamertag-unlink.js b/src/commands/gamertag-unlink.js new file mode 100644 index 0000000..80ab4c0 --- /dev/null +++ b/src/commands/gamertag-unlink.js @@ -0,0 +1,85 @@ +const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require("discord.js"); +const { UpdatePlayer } = require("../database/player"); + +module.exports = { + name: "gamertag-unlink", + debug: false, + global: false, + description: "Disconnect DayZ stats from your Discord", + usage: "", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + 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)) { + 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."); + + return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); + } + + 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.`)] }); + + const warnGTOverwrite = new EmbedBuilder() + .setColor(client.config.Colors.Yellow) + .setDescription(`**Notice:**\n> Are you sure you want to unlink your gamertag? This will limit some automatic features.`); + + const opt = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId(`UnlinkGamertag-yes-${interaction.member.user.id}`) + .setLabel("Yes") + .setStyle(ButtonStyle.Success), + new ButtonBuilder() + .setCustomId(`UnlinkGamertag-no-${interaction.member.user.id}`) + .setLabel("No") + .setStyle(ButtonStyle.Secondary) + ) + + return interaction.send({ embeds: [warnGTOverwrite], components: [opt] }); + }, + }, + + Interactions: { + + UnlinkGamertag: { + run: async (client, interaction, GuildDB) => { + 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 = await client.dbo.collection("players").findOne({ "discordID": interaction.member.user.id }); + + playerStat.discordID = ""; + + await UpdatePlayer(client, playerStat, interaction); + + let connectedEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`Successfully unlinked \` ${playerStat.gamertag} \` as your gamertag.`); + + return interaction.update({ embeds: [connectedEmbed], components: [] }); + + } else { + const cancel = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription("**Canceled**\n> The gamertag unlink will not processed."); + + return interaction.update({ embeds: [cancel], components: [] }); + } + } + } + } +} \ No newline at end of file diff --git a/src/commands/help.js b/src/commands/help.js new file mode 100644 index 0000000..4ee1e21 --- /dev/null +++ b/src/commands/help.js @@ -0,0 +1,161 @@ +const { EmbedBuilder } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; +const package = require("../package"); + +module.exports = { + name: "help", + debug: false, + global: true, + description: "Get information on a specific command", + usage: "[option]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [ + { + name: "commands", + description: "List all commands", + value: "commands", + type: CommandOptions.SubCommand, + options: [{ + name: "command", + description: "Get information on a specific command", + value: "command", + type: CommandOptions.String, + required: false, + }] + }, + { + name: "support", + description: "Get support for Application", + value: "support", + type: CommandOptions.SubCommand, + }, + { + name: "credits", + description: "DayZ.R Bot Credits", + value: "credits", + type: CommandOptions.SubCommand, + }, + { + name: "stats", + description: "Current Bot Statistics", + value: "stats", + type: CommandOptions.SubCommand, + } + ], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + + run: async (client, interaction, args, { GuildDB }, start) => { + if (args[0].name == "commands") { + let Commands = client.commands.filter((cmd) => { + return !cmd.debug + }).map((cmd) => + `\`/${cmd.name}${cmd.usage ? " " + cmd.usage : ""}\` - ${cmd.description}` + ); + + let Embed = new EmbedBuilder() + .setTitle("Commands") + .setColor(client.config.Colors.Default) + .setDescription(`${Commands.join("\n")} + + DayZR Bot Version: v${client.config.Version}`); + if (!args[0].options[0]) return interaction.send({ embeds: [Embed] }); + else { + let cmd = + client.commands.get(args[0].options[0].value) || + client.commands.find( + (x) => x.aliases && x.aliases.includes(args[0].options[0].value) + ); + if (!cmd) + return interaction.send({ content: `❌ | Unable to find that command.` }); + + let embed = new EmbedBuilder() + .setDescription(cmd.description) + .setColor(client.config.Colors.Green) + .setTitle(`How to use /${cmd.name} command`) + + if (cmd.SlashCommand.options && cmd.SlashCommand.options[0].type == 1) { + let description = `${cmd.description}\n\n**Usage**\n`; + + for (let i = 0; i < cmd.SlashCommand.options.length; i++) { + if (cmd.SlashCommand.options[i].type == 1) { + let param = ""; + if (cmd.SlashCommand.options[i].options) { + param = cmd.SlashCommand.options[i].options.length > 0 ? " " : ""; + for (let j = 0; j < cmd.SlashCommand.options[i].options.length; j++) { + if (cmd.SlashCommand.options[i].options[j].required) param += `[${cmd.SlashCommand.options[i].options[j].name}] ` + } + } + description += `\`/${cmd.name} ${cmd.SlashCommand.options[i].name}${param}\`\n${cmd.SlashCommand.options[i].description}\n\n` + } + } + embed.setDescription(description); + } else embed.addFields({ name: "Usage", value: `\`/${cmd.name}\`${cmd.usage ? " " + cmd.usage : ""}`, inline: true }) + + return interaction.send({ embeds: [embed] }); + } + } else if (args[0].name == "support") { + const supportEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`**__DayZ.R Bot Support__** + + Are you experiencing troubles with the DayZ.R Bot? + Do you have questions or concerns? + Do you require help to use the bot? + Do you have a feature you"d like to see? + + Join the support server to have all your needs fulfilled. + ╚➤ ${client.config.SupportServer} + `) + + return interaction.send({ embeds: [supportEmbed] }); + + } else if (args[0].name == "credits") { + const creditsEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTitle("DayzRBot Credits") + .setDescription(` + **Bot Author:** mcdazzzled + **Github:** https://github.com/SowinskiBraeden/dayz-reforger + + ${client.config.SupportServer} + `); + + return interaction.send({ embeds: [creditsEmbed] }) + } else if (args[0].name == "stats") { + const end = new Date().getTime(); + + const totalGuilds = await client.shard.fetchClientValues("guilds.cache.size").then(results => { + return results.reduce((acc, guildCount) => acc + guildCount, 0); + }); + + const totalUsers = await client.shard.broadcastEval(c => { + c.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0); + }).then(data => data.reduce((acc, memberCount) => acc + memberCount, 0)); + + const stats = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTitle("DayZ Reforger Bot Statistics") + .addFields( + { name: "Guilds", value: `\`\`\`${totalGuilds}\`\`\``, inline: true }, + { name: "Users", value: `\`\`\`${totalUsers}\`\`\``, inline: true }, + { name: "Latency", value: `\`\`\`${end - start}ms\`\`\``, inline: true }, + { name: "Uptime", value: `\`\`\`${client.secondsToDhms(process.uptime().toFixed(2))}\`\`\``, inline: true }, + { name: "Bot Version", value: `\`\`\`${client.config.Dev} v${client.config.Version}\`\`\``, inline: true }, + { name: "Discord Version", value: `\`\`\`Discord.js ${package.dependencies["discord.js"]}\`\`\``, inline: true }, + ); + + return interaction.send({ embeds: [stats] }) + } + }, + }, +}; \ No newline at end of file diff --git a/src/commands/leaderboard.js b/src/commands/leaderboard.js new file mode 100644 index 0000000..23af4fe --- /dev/null +++ b/src/commands/leaderboard.js @@ -0,0 +1,135 @@ +const { EmbedBuilder } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; + +module.exports = { + name: "leaderboard", + debug: false, + global: false, + description: "View server stats leaderboard", + usage: "[category] [limit]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [{ + name: "category", + description: "Leaderboard Category", + value: "category", + type: CommandOptions.String, + required: true, + choices: [ + { name: "Money", value: "money" }, + { name: "Total Time Played", value: "totalSessionTime" }, + { name: "Longest Game Session", value: "longestSessionTime" }, + { name: "Kills", value: "kills" }, + { name: "Kill Streak", value: "killStreak" }, + { name: "Best Kill Streak", value: "bestKillStreak" }, + { name: "Deaths", value: "deaths" }, + { name: "Death Streak", value: "deathStreak" }, + { name: "Worst Death Streak", value: "worstDeathStreak" }, + { name: "Longest Kill", value: "longestKill" }, + { name: "KDR", value: "KDR" }, + { name: "Server Connections", value: "connections" }, + { name: "Shots Landed", value: "shotsLanded" }, + { name: "Times Shot", value: "timesShot" }, + { name: "Combat Rating", value: "combatRating" }, + ] + }, { + name: "limit", + description: "Leaderboard limit", + value: "limit", + type: CommandOptions.Integer, + min_value: 1, + max_value: 25, + required: true, + }], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + 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)) { + 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."); + + return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); + } + + const category = args[0].value; + const limit = args[1].value; + + let leaderboard = []; + if (category == "money") { + + leaderboard = await client.dbo.collection("users").aggregate([ + { $sort: { [`user.guilds.${GuildDB.serverID}.balance`]: -1 } } + ]).toArray(); + + } else { + + leaderboard = await client.dbo.collection("players").aggregate([ + { $sort: { [`${category}`]: -1 } } + ]).toArray(); + + } + + let leaderboardEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default); + + let title = category == "kills" ? "Total Kills Leaderboard" : + category == "killStreak" ? "Current Killstreak Leaderboard" : + category == "bestKillStreak" ? "Best Killstreak Leaderboard" : + category == "deaths" ? "Total Deaths Leaderboard" : + category == "deathStreak" ? "Current Deathstreak Leaderboard" : + category == "worstDeathStreak" ? "Worst Deathstreak Leaderboard" : + category == "longestKill" ? "Longest Kill Leaderboard" : + category == "money" ? "Money Leaderboard" : + category == "totalSessionTime" ? "Total Time Played" : + category == "longestSessionTime" ? "Longest Game Session" : + category == "KDR" ? "Kill Death Ratio" : + category == "connections" ? "Times Connected" : + category == "shotsLanded" ? "Shots Landed" : + category == "timesShot" ? "Times Shot" : + category == "combatRating" ? "Combat Rating" : "N/A Error"; + + leaderboardEmbed.setTitle(`**${title} - DayZ Reforger**`); + + let des = ``; + for (let i = 0; i < limit; i++) { + if (leaderboard.length < limit && i == leaderboard.length) break; + + let stats = category == "kills" ? `${leaderboard[i].kills} Kill${(leaderboard[i].kills > 1 || leaderboard[i].kills == 0) ? "s" : ""}` : + category == "killStreak" ? `${leaderboard[i].killStreak} Player Killstreak` : + category == "bestKillStreak" ? `${leaderboard[i].bestKillStreak} Player Killstreak` : + category == "deaths" ? `${leaderboard[i].deaths} Death${leaderboard[i].deaths > 1 || leaderboard[i].deaths == 0 ? "s" : ""}` : + category == "deathStreak" ? `${leaderboard[i].deathStreak} Deathstreak` : + category == "worstDeathstreak" ? `${leaderboard[i].worstDeathStreak} Deathstreak` : + category == "longestKill" ? `${leaderboard[i].longestKill}m` : + category == "money" ? `$${(leaderboard[i].user.guilds[GuildDB.serverID].balance).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` : + category == "totalSessionTime" ? `**Total:** ${client.secondsToDhms(leaderboard[i].totalSessionTime)}\n> **Last Session:** ${client.secondsToDhms(leaderboard[i].lastSessionTime)}` : + category == "longestSessionTime" ? `**Longest Game Session:** ${client.secondsToDhms(leaderboard[i].longestSessionTime)}` : + category == "KDR" ? `**KDR: ${leaderboard[i].KDR.toFixed(2)}**` : + category == "connection" ? `**Connections: ${leaderboard[i].connections}**` : + category == "combatRating" ? `**Combat Rating:** ${leaderboard[i].combatRating}` : + category == "shotsLanded" ? `**Shots Landed:** ${leaderboard[i].shotsLanded}` : + category == "timesShot" ? `**Times Shot:** ${leaderboard[i].timesShot}` : "N/A Error"; + + if (category == "money") des += `**${i + 1}.** <@${leaderboard[i].user.userID}> - **${stats}**\n` + else if (category == "totalSessionTime" || category == "longestSessionTime" || category == "combatRating") { + tag = leaderboard[i].discordID != "" ? `<@${leaderboard[i].discordID}>` : leaderboard[i].gamertag; + des += `**${i + 1}.** ${tag}\n> ${stats}\n\n`; + } else leaderboardEmbed.addFields({ name: `**${i + 1}. ${leaderboard[i].gamertag}**`, value: `**${stats}**`, inline: true }); + } + + if (["money", "totalSessionTime", "longestSessionTime", "combatRating"].includes(category)) leaderboardEmbed.setDescription(des); + + return interaction.send({ embeds: [leaderboardEmbed] }); + }, + }, +} diff --git a/src/commands/location.js b/src/commands/location.js new file mode 100644 index 0000000..dc2bec6 --- /dev/null +++ b/src/commands/location.js @@ -0,0 +1,50 @@ +const { EmbedBuilder } = require("discord.js"); +const { nearest } = require("../database/destinations"); + +module.exports = { + name: "location", + debug: false, + global: false, + description: "Find your last known location", + usage: "", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + 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)) { + 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."); + + return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); + } + + 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) }); + + console.log(true); + + let newDt = await client.getDateEST(playerStat.time); + let unixTime = Math.floor(newDt.getTime() / 1000); + + const destination = nearest(playerStat.pos, GuildDB.Nitrado.Mission); + + let lastLocation = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`**Location - **\nYour last location was detected at **[${playerStat.pos[0]}, ${playerStat.pos[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${playerStat.pos[0]};${playerStat.pos[1]})**\n${destination}`) + + return interaction.send({ embeds: [lastLocation], flags: (1 << 6) }); + }, + }, +} \ No newline at end of file diff --git a/src/commands/lookup.js b/src/commands/lookup.js new file mode 100644 index 0000000..ea13237 --- /dev/null +++ b/src/commands/lookup.js @@ -0,0 +1,90 @@ +const { EmbedBuilder } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; + +module.exports = { + name: "lookup", + debug: false, + global: false, + description: "Search for a user's Discord or Gamertag", + usage: "[option] [parameter]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [{ + name: "discord", + description: "Find a Discord user from a Gamertag", + value: "discord", + type: CommandOptions.SubCommand, + options: [{ + name: "gamertag", + description: "Gamertag of player", + value: "gamertag", + type: CommandOptions.String, + required: true, + }] + }, { + name: "gamertag", + description: "Find a Gamertag from a Discord user", + value: "gamertag", + type: CommandOptions.SubCommand, + options: [{ + name: "user", + description: "Discord User", + value: "user", + type: CommandOptions.User, + required: true, + }] + }], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + 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)) { + 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."); + + return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); + } + + if (args[0].name == "discord") { + + 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)) { + const found = new EmbedBuilder() + .setColor(client.config.Colors.Yellow) + .setDescription(`**Record Found**\n> The gamertag \` ${playerStat.gamertag} \` is currently linked to <@${playerStat.discordID}>.`) + + return interaction.send({ embeds: [found] }); + } + + let notFound = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`**Record Not Found**\n The gamertag \` ${playerStat.gamertag} \` currently has no linked Discord account.`); + + return interaction.send({ embeds: [notFound] }) + + } else if (args[0].name == "gamertag") { + + let playerStat = await client.dbo.collection("players").findOne({ "discordID": args[0].options[0].value }); + if (playerStat == undefined) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** The user <@${args[0].options[0].value}> has not linked a gamertag.`)] }); + + const found = new EmbedBuilder() + .setColor(client.config.Colors.Yellow) + .setDescription(`**Record Found**\n> The user <@${playerStat.discordID}> has linked the gamertag \` ${playerStat.gamertag} \`.`) + + return interaction.send({ embeds: [found] }); + + } + }, + }, +} \ No newline at end of file diff --git a/src/commands/player-list.js b/src/commands/player-list.js new file mode 100644 index 0000000..de0b2af --- /dev/null +++ b/src/commands/player-list.js @@ -0,0 +1,81 @@ +const { FetchServerSettings } = require("../util/NitradoAPI"); +const { Missions } = require("../database/destinations"); +const { EmbedBuilder } = require("discord.js"); + +module.exports = { + name: "player-list", + debug: false, + global: false, + description: "Get current online players", + usage: "", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + 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)) { + 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."); + + return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); + } + + await interaction.deferReply(); + + const data = await FetchServerSettings(GuildDB.Nitrado, client, "commands/player-list.js"); // Fetch server status + const e = data && data !== 1; // Check if data exists + + const hostname = e ? data.data.gameserver.settings.config.hostname : "N/A"; + const map = e ? Missions[data.data.gameserver.settings.config.mission] : "N/A"; + const status = e ? data.data.gameserver.status : "N/A"; + const slots = e ? data.data.gameserver.slots : "N/A"; + const playersOnline = e ? data.data.gameserver.query.player_current : "N/A"; + + const Statuses = { + "started": { emoji: "🟢", text: "Active" }, + "stopped": { emoji: "🔴", text: "Stopped" }, + "restarting": { emoji: "↻", text: "Restarting" }, + }; + + const emojiStatus = e ? Statuses[status].emoji : "❓"; + const textStatus = e ? Statuses[status].text : "Unknown Status"; + + let activePlayers = await client.dbo.collection("players").find({ "connected": true }).toArray(); + + let des = activePlayers.length > 0 ? `` : `**No Players Online**`; + for (let i = 0; i < activePlayers.length; i++) { + des += `**- ${activePlayers[i].gamertag}**\n`; + } + + const nodes = activePlayers.length === 0; + const serverEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTitle(`Online List - \` ${playersOnline === undefined ? activePlayers.length : playersOnline} \` Player${playersOnline !== 1 ? "s" : ""} Online`) + .addFields( + { name: "Server:", value: `\` ${hostname} \``, inline: false }, + { name: "Map:", value: `\` ${map} \``, inline: true }, + { name: "Status:", value: `\` ${emojiStatus} ${textStatus} \``, inline: true }, + { name: "Slots:", value: `\` ${slots} \``, inline: true } + ); + + const activePlayersEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTimestamp() + .setTitle(`Players Online:`) + .setDescription(des || (nodes ? "No Players Online :(" : "")); + + return interaction.editReply({ embeds: [serverEmbed, activePlayersEmbed] }); + }, + }, +} \ No newline at end of file diff --git a/src/commands/player-stats.js b/src/commands/player-stats.js new file mode 100644 index 0000000..69288cb --- /dev/null +++ b/src/commands/player-stats.js @@ -0,0 +1,325 @@ +const { EmbedBuilder } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; +const { insertPVPstats } = require("../database/player"); + +module.exports = { + name: "player-stats", + debug: false, + global: false, + description: "Check player statistics", + usage: "[category] [user or gamertag]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [{ + name: "category", + description: "Leaderboard Category", + value: "category", + type: CommandOptions.String, + required: true, + choices: [ + { name: "Money", value: "money" }, + { name: "Total Time Played", value: "totalSessionTime" }, + { name: "Longest Game Session", value: "longestSessionTime" }, + { name: "Kills", value: "kills" }, + { name: "Kill Streak", value: "killStreak" }, + { name: "Best Kill Streak", value: "bestKillStreak" }, + { name: "Deaths", value: "deaths" }, + { name: "Death Streak", value: "deathStreak" }, + { name: "Worst Death Streak", value: "worstDeathStreak" }, + { name: "Longest Kill", value: "longestKill" }, + { name: "KDR", value: "KDR" }, + { name: "Server Connections", value: "connections" }, + { name: "Shots Landed", value: "shotsLanded" }, + { name: "Times Shot", value: "timesShot" }, + { name: "Combat Rating", value: "combatRating" } + ] + }, { + name: "discord", + description: "discord user to lookup stats", + value: "discord", + type: CommandOptions.User, + required: false, + }, { + name: "gamertag", + description: "gamertag to lookup stats", + type: CommandOptions.String, + required: false, + }], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + 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)) { + 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."); + + return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); + } + + let category = args[0].value; + let discord = args[1] && args[1].name == "discord" ? args[1].value : undefined; + let gamertag = args[1] && args[1].name == "gamertag" ? args[1].value : undefined; + let self = !discord && !gamertag; // searching for self if both discord and gamertag are undefined; + + let query; + let leaderboard; + let leaderboardPos; + + if (category == "money") { + + leaderboard = await client.dbo.collection("users").aggregate([ + { $sort: { [`user.guilds.${GuildDB.serverID}.balance`]: -1 } } + ]).toArray(); + + if (discord) query = leaderboard.find(u => u.user.userID == discord); // Searching by discord user + 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.`)] }); + leaderboardPos = leaderboard.indexOf(query); + + } else { + + leaderboard = await client.dbo.collection("players").aggregate([ + { $sort: { [`${category}`]: -1 } } + ]).toArray(); + + if (discord) query = leaderboard.find(s => s.discordID == discord); // Searching by discord user + 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.`)] }); + leaderboardPos = leaderboard.indexOf(query); + + } + leaderboardPos++; // add one to leaderboard pos because it is index in array and we want index zero to be num. one, index one to be num. two, etc. etc. + + let title = category == "kills" ? "Total Kills" : + category == "killStreak" ? "Current Killstreak" : + category == "bestkillStreak" ? "Best Killstreak" : + category == "deaths" ? "Total Deaths" : + category == "deathStreak" ? "Current Deathstreak" : + category == "worstDeathStreak" ? "Worst Deathstreak" : + category == "longestKill" ? "Longest Kill" : + category == "money" ? "Total Money" : + category == "totalSessionTime" ? "Total Time Played" : + category == "longestSessionTime" ? "Longest Game Session" : + category == "KDR" ? "Kill Death Ratio" : + category == "connections" ? "Times Connected" : + category == "shotsLanded" ? "Shots Landed" : + category == "timesShot" ? "Times Shot" : + category == "combatRating" ? "Combat Rating" : "N/A Error"; + + let statsEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default); + + let tag = !discord && !gamertag ? `<@${interaction.member.user.id}>` : + !gamertag && discord ? `<@${discord}>` : + !discord && gamertag ? `**${gamertag}**` : `N/A Error`; + + statsEmbed.setDescription(`${tag}"s ${title}`); + + let stats = category == "kills" ? `${query.kills} Kill${(query.kills > 1 || query.kills == 0) ? "s" : ""}` : + category == "killStreak" ? `${query.killStreak} Player Killstreak` : + category == "bestKillStreak" ? `${query.bestKillStreak} Player Killstreak` : + category == "deaths" ? `${query.deaths} Death${query.deaths > 1 || query.deaths == 0 ? "s" : ""}` : + category == "deathStreak" ? `${query.deathStreak} Deathstreak` : + category == "worstDeathStreak" ? `${query.worstDeathStreak} Deathstreak` : + category == "longestKill" ? `${query.longestKill}m` : + category == "money" ? `$${(query.user.guilds[GuildDB.serverID].balance).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` : + category == "KDR" ? `${query.KDR.toFixed(2)} KDR` : + category == "connections" ? `${query.connections} connections` : + category == "combatRating" ? `${query.combatRating}` : "N/A Error"; + + statsEmbed.addFields({ name: "Leaderboard Position", value: `# ${leaderboardPos}`, inline: true }); + + if ((category == "shotsLanded" || category == "timesShot") && !client.exists(query.shotsLanded)) query = insertPVPstats(query); + + if (category == "totalSessionTime") { + statsEmbed.addFields( + { name: "Total Time Played", value: client.secondsToDhms(query.totalSessionTime), inline: true }, + { name: "Last Session Time", value: client.secondsToDhms(query.lastSessionTime), inline: true } + ); + } else if (category == "longestSessionTime") { + statsEmbed.addFields( + { name: "Longest Game Session", value: client.secondsToDhms(query.longestSessionTime), inline: true }, + { name: "Last Session Time", value: client.secondsToDhms(query.lastSessionTime), inline: true } + ); + } else if (category == "shotsLanded") { + statsEmbed.addFields( + { name: "Total Shots Landed", value: `${query.shotsLanded}`, inline: true }, + { name: "View Weapon stats", value: ``, inline: true } + ); + + const chart = { + type: "bar", + data: { + labels: ["Head", "Torso", "Left Arm", "Right Arm", "Left Leg", "Right Leg"], + datasets: [{ + label: "Shots Landed", + data: [ + query.shotsLandedPerBodyPart.Head, + query.shotsLandedPerBodyPart.Torso, + query.shotsLandedPerBodyPart.LeftArm, + query.shotsLandedPerBodyPart.RightArm, + query.shotsLandedPerBodyPart.LeftLeg, + query.shotsLandedPerBodyPart.RightLeg, + ], + }], + }, + options: { + legend: { + labels: { + fontSize: 14, + fontStyle: "bold", + } + }, + scales: { + yAxes: [{ ticks: { fontStyle: "bold" } }], + xAxes: [{ ticks: { fontStyle: "bold" } }], + }, + }, + }; + + const encodedChart = encodeURIComponent(JSON.stringify(chart)); + const chartURL = `https://quickchart.io/chart?bkg=${encodeURIComponent("#ded8d7")}&c=${encodedChart}`; + + statsEmbed.setImage(chartURL); + + } else if (category == "timesShot") { + statsEmbed.addFields( + { name: "Total Times Shot", value: `${query.timesShot}`, inline: true }, + { name: "View Weapon stats", value: ``, inline: true }, + ); + + const chart = { + type: "bar", + data: { + labels: ["Head", "Torso", "Left Arm", "Right Arm", "Left Leg", "Right Leg"], + datasets: [{ + label: "Times Shot", + data: [ + query.timesShotPerBodyPart.Head, + query.timesShotPerBodyPart.Torso, + query.timesShotPerBodyPart.LeftArm, + query.timesShotPerBodyPart.RightArm, + query.timesShotPerBodyPart.LeftLeg, + query.timesShotPerBodyPart.RightLeg, + ], + }], + }, + options: { + legend: { + labels: { + fontSize: 14, + fontStyle: "bold", + } + }, + scales: { + yAxes: [{ ticks: { fontStyle: "bold" } }], + xAxes: [{ ticks: { fontStyle: "bold" } }], + }, + }, + }; + + const encodedChart = encodeURIComponent(JSON.stringify(chart)); + const chartURL = `https://quickchart.io/chart?bkg=${encodeURIComponent("#ded8d7")}&c=${encodedChart}`; + + statsEmbed.setImage(chartURL); + + } else if (category == "combatRating") { + + let data = query.combatRatingHistory; + + 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; + + statsEmbed.addFields( + { name: "Combat Rating", value: `${query.combatRating}`, inline: true }, + { name: "Highest Rating", value: `${query.highestCombatRating}`, inline: true }, + { name: "Lowest Rating", value: `${query.lowestCombatRating}`, inline: true }, + ); + + if (data.length == 1) data.push(query.combatRating) // Make array 2 long for a straight line in the graph + + const chart = { + type: "line", + data: { + labels: new Array(data.length).fill(" ", 0, data.length), + datasets: [{ + data: data, + label: `Last ${data.length} Combat Ratings`, + }], + }, + options: { + legend: { + labels: { + fontSize: 14, + fontStyle: "bold", + } + }, + scales: { + // Gives comfortable margin to the top of the y-axis + yAxes: [{ + ticks: { + fontStyle: "bold", + min: Math.round(Math.min(...data) / 10) * 10 - 10, + max: Math.round(Math.max(...data) / 10) * 10 + 10, + }, + }], + xAxes: [{ ticks: { fontStyle: "bold" } }], + }, + // Gives a margin to the right of the whole graph + layout: { + padding: { + right: 40, + }, + }, + // Labels points on the graph to show evolution of combat rating + plugins: { + datalabels: { + display: true, + align: "top", + color: "#000", + backgroundColor: "#ccc", + borderRadius: 4, + offset: 10, + display: (context) => { + const index = context.dataIndex; + const value = context.dataset.data[index]; + const min = Math.min.apply(null, context.dataset.data); + const max = Math.max.apply(null, context.dataset.data); + return ( + index == 0 || + index == context.dataset.data.length - 1 || + value == min || + value == max + ); + }, + }, + }, + }, + }; + + const encodedChart = encodeURIComponent(JSON.stringify(chart)); + const chartURL = `https://quickchart.io/chart?bkg=${encodeURIComponent("#ded8d7")}&c=${encodedChart}`; + + statsEmbed.setImage(chartURL); + + } else statsEmbed.addFields({ name: title, value: stats, inline: true }); + + return interaction.send({ embeds: [statsEmbed] }); + }, + }, +} \ No newline at end of file diff --git a/src/commands/purchase-emp.js b/src/commands/purchase-emp.js new file mode 100644 index 0000000..722999a --- /dev/null +++ b/src/commands/purchase-emp.js @@ -0,0 +1,125 @@ +const { EmbedBuilder, ActionRowBuilder, StringSelectMenuBuilder } = require("discord.js"); +const { createUser, addUser } = require("../database/user"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; + +module.exports = { + name: "purchase-emp", + debug: false, + global: false, + description: "EMP an Alarm to prevent any updates for 30 or 60 minutes", + usage: "", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: ["MANAGE_GUILD"], + }, + options: [{ + name: "duration", + description: "Select the duration of the emp (30 or 60 minutes)", + value: "duration", + type: CommandOptions.Integer, + required: true, + choices: [ + { name: "30 Minutes", value: 30 }, + { name: "60 Minutes", value: 60 } + ] + }], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + 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)) { + 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."); + + 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")] }); + + 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); + } + banking = banking.user; + + 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"); + } + + if (banking.guilds[GuildDB.serverID].balance.toFixed(2) - GuildDB.empPrice < 0) { + let embed = new EmbedBuilder() + .setTitle("**Bank Notice:** NSF. Non sufficient funds") + .setColor(client.config.Colors.Red); + + return interaction.send({ embeds: [embed], flags: (1 << 6) }); + } + + const price = duration == 30 ? GuildDB.empPrice : GuildDB.empPrice * 2; + const newBalance = banking.guilds[GuildDB.serverID].balance - price; + + if (GuildDB.alarms.length == 0) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Default).setDescription("**Notice:** No Existing Alarms to EMP.")], flags: (1 << 6) }); + + client.dbo.collection("users").updateOne({ "user.userID": interaction.member.user.id }, { $set: { [`user.guilds.${GuildDB.serverID}.balance`]: newBalance } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let alarms = new StringSelectMenuBuilder() + .setCustomId(`EMPAlarmSelect-${interaction.member.user.id}`) + .setPlaceholder(`Select an Alarm to EMP.`) + + for (let i = 0; i < GuildDB.alarms.length; i++) { + if (!GuildDB.alarms[i].empExempt) { + alarms.addOptions({ + label: GuildDB.alarms[i].name, + description: `EMP this Alarm for $${price.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 0 })}}`, + value: `${GuildDB.alarms[i].name}-${duration}`, + }); + } + } + + const opt = new ActionRowBuilder().addComponents(alarms); + + return interaction.send({ components: [opt], flags: (1 << 6) }); + }, + }, + + Interactions: { + EMPAlarmSelect: { + run: async (client, interaction, GuildDB) => { + let duration = parseInt(interaction.values[0].split("-")[1]); + let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0].split("-")[0]); + let alarms = GuildDB.alarms; + let alarmIndex = alarms.indexOf(alarm); + alarm.disabled = true; + let d = new Date(); + alarm.empExpire = new Date(d.getTime() + (duration * 60 * 1000)); + alarms[alarmIndex] = alarm; + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { + $set: { + "server.alarms": alarms, + } + }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Success:** Successfully EMP"d **${alarm.name}** for 30 minutes.`); + + return interaction.update({ embeds: [successEmbed], components: [] }); + } + } + } +} diff --git a/src/commands/purchase-uav.js b/src/commands/purchase-uav.js new file mode 100644 index 0000000..d6587ab --- /dev/null +++ b/src/commands/purchase-uav.js @@ -0,0 +1,102 @@ +const { EmbedBuilder } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; +const { createUser, addUser } = require("../database/user") + +module.exports = { + name: "purchase-uav", + debug: false, + global: false, + description: "Send a UAV to scout for 30 minutes (500m range)", + usage: "[x-coord] [y-coord]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: ["MANAGE_GUILD"], + }, + options: [ + { + name: "x-coord", + description: "X Coordinate of the origin", + value: "x-coord", + type: CommandOptions.Float, + min_value: 0.01, + required: true, + }, + { + name: "y-coord", + description: "Y Coordinate of the origin", + value: "y-coord", + type: CommandOptions.Float, + min_value: 0.01, + required: true, + }, + ], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + 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)) { + 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."); + + 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")] }); + + 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); + } + banking = banking.user; + + 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"); + } + + if (banking.guilds[GuildDB.serverID].balance.toFixed(2) - GuildDB.uavPrice < 0) { + let embed = new EmbedBuilder() + .setTitle("**Bank Notice:** NSF. Non sufficient funds") + .setColor(client.config.Colors.Red); + + return interaction.send({ embeds: [embed], flags: (1 << 6) }); + } + + const newBalance = banking.guilds[GuildDB.serverID].balance - GuildDB.uavPrice; + + client.dbo.collection("users").updateOne({ "user.userID": interaction.member.user.id }, { $set: { [`user.guilds.${GuildDB.serverID}.balance`]: newBalance } }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let uav = { + origin: [args[0].value, args[1].value], + radius: 250, + owner: interaction.member.user.id, + creationDate: new Date(), + }; + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { + $push: { + "server.uavs": uav, + } + }, (err, res) => { + if (err) return client.sendInternalError(interaction, err); + }); + + let successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Success:** Successfully deployed a UAV to **[${uav.origin[0]}, ${uav.origin[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${uav.origin[0]};${uav.origin[1]})**\nRange: 500m`); + + return interaction.send({ embeds: [successEmbed], flags: (1 << 6) }); + }, + } +} diff --git a/src/commands/reset.js b/src/commands/reset.js new file mode 100644 index 0000000..a93b743 --- /dev/null +++ b/src/commands/reset.js @@ -0,0 +1,111 @@ +const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; +const { addUser } = require("../database/user"); +const bitfieldCalculator = require("discord-bitfield-calculator"); + +module.exports = { + name: "reset", + debug: false, + global: false, + description: "Reset a user's bank/money", + usage: "[user]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: ["MANAGE_GUILD"], + }, + options: [{ + name: "user", + description: "User to reset", + value: "user", + type: CommandOptions.User, + required: true, + }], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + run: async (client, interaction, args, { GuildDB }) => { + const permissions = bitfieldCalculator.permissions(interaction.member.permissions); + let canUseCommand = false; + + if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; + if (client.exists(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(">", ""); + + const prompt = new EmbedBuilder() + .setTitle(`Are you sure you want to reset this user?`) + .setDescription("**Notice:** This will reset this users cash and balance.") + .setColor(client.config.Colors.Yellow) + + const opt = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId(`Reset-yes-${targetUserID}-${interaction.member.user.id}`) + .setLabel("Yes") + .setStyle(ButtonStyle.Danger), + new ButtonBuilder() + .setCustomId(`Reset-no-${targetUserID}-${interaction.member.user.id}`) + .setLabel("No") + .setStyle(ButtonStyle.Success) + ) + + return interaction.send({ embeds: [prompt], components: [opt], flags: (1 << 6) }); + + }, + }, + + Interactions: { + + Reset: { + run: async (client, interaction, GuildDB) => { + const choice = interaction.customId.split("-")[1]; + const targetUserID = interaction.customId.split("-")[2]; + + if (!interaction.customId.endsWith(interaction.member.user.id)) { + return interaction.reply({ + content: "This button is not for you", + flags: (1 << 6) + }) + } + if (choice == "yes") { + const successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setTitle("Successfully reset user\"s data") + + let banking = await client.dbo.collection("users").findOne({ "user.userID": interaction.member.user.id }).then(banking => banking); + + let bankingReset = false; + if (!banking) bankingReset = true + else banking = banking.user + + if (!bankingReset) { + const success = addUser(banking.guilds, GuildDB.serverID, targetUserID, client, GuildDB.startingBalance); + if (!success) { + client.error(err); + 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(client.config.Colors.Red) + + return interaction.update({ embeds: [embed], components: [] }); + } + } + + return interaction.update({ embeds: [successEmbed], components: [] }); + + } else if (choice == "no") { + const successEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setTitle(`The User was not reset`); + + return interaction.update({ embeds: [successEmbed], components: [] }); + } + } + } + } +} \ No newline at end of file diff --git a/src/commands/server.js b/src/commands/server.js new file mode 100644 index 0000000..328b570 --- /dev/null +++ b/src/commands/server.js @@ -0,0 +1,414 @@ +const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, ModalBuilder, TextInputBuilder, TextInputStyle } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; +const bitfieldCalculator = require("discord-bitfield-calculator"); +const { BanPlayer, UnbanPlayer, RestartServer, CheckServerStatus, DisableBaseDamage, DisableContainerDamage, NitradoCredentialStatus } = require("../util/NitradoAPI"); +const { encrypt, decrypt } = require("../util/Cryptic"); + +module.exports = { + name: "server", + debug: false, + global: false, + description: "Nitrado DayZ Server Administrative Commands", + usage: "[command] [options]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [{ + name: "initialize", + description: "Connect your Nitrado server to the bot", + value: "initialize", + type: CommandOptions.SubCommand, + }, + { + name: "disconnect", + description: "Delete your Nitrado server from the bot database", + value: "disconnect", + type: CommandOptions.SubCommand, + }, + { + name: "credentials-status", + description: "Check the status of your Nitrado Credentials", + value: "credentials-status", + type: CommandOptions.SubCommand, + }, + { + name: "retry-credentials", + description: "If your credentials are marked as FAILED, try retreiving Nitrado logs again.", + value: "retry-credentials", + type: CommandOptions.SubCommand, + }, + { + name: "ban-player", + description: "Ban a player from the DayZ server", + value: "ban-player", + type: CommandOptions.SubCommand, + options: [{ + name: "gamertag", + description: "gamertag of the player to ban.", + value: "gamertag", + type: CommandOptions.String, + required: true, + }] + }, { + name: "unban-player", + description: "Unban a player from the DayZ server", + value: "unban-player", + type: CommandOptions.SubCommand, + options: [{ + name: "gamertag", + description: "gamertag of the player to unban.", + value: "gamertag", + type: CommandOptions.String, + required: true, + }] + }, + { + name: "restart", + description: "Restart the DayZ Server", + value: "restart", + type: CommandOptions.SubCommand, + }, { + name: "auto-restart", + description: "Enable/Disable periodic server checks and restart if stopped", + value: "auto-restart", + type: CommandOptions.SubCommand, + }, { + name: "disable-base-damage", + description: "Disable/Enable base damage", + value: "disable-base-damage", + type: CommandOptions.SubCommand, + options: [{ + name: "preference", + description: "DisableBaseDamage Preference", + value: true, + type: CommandOptions.Boolean, + required: true, + }] + }, { + name: "disable-container-damage", + description: "Disable/Enable container damage", + value: "disable-container-damage", + type: CommandOptions.SubCommand, + options: [{ + name: "preference", + description: "disableContainerDamage Preference", + value: true, + type: CommandOptions.Boolean, + required: true, + }] + }], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + run: async (client, interaction, args, { GuildDB }) => { + + const permissions = bitfieldCalculator.permissions(interaction.member.permissions); + let canUseCommand = false; + + if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; + 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 (args[0].name == "initialize") { + + if (client.exists(GuildDB.Nitrado)) { + const prompt = new EmbedBuilder() + .setTitle(`Nitrado Server Information Already Configured!`) + .setDescription("**Notice:** This will overwrite your previously configured Nitrado Server Information") + .setColor(client.config.Colors.Yellow) + + const opt = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId(`OverwriteNitrado-yes-${interaction.member.user.id}`) + .setLabel("Yes") + .setStyle(ButtonStyle.Danger), + new ButtonBuilder() + .setCustomId(`OverwriteNitrado-no-${interaction.member.user.id}`) + .setLabel("No") + .setStyle(ButtonStyle.Success) + ) + + return interaction.send({ embeds: [prompt], components: [opt], flags: (1 << 6) }); + } + + const NitradoCredentials = new ModalBuilder() + .setTitle("Connect your Nitrado Server") + .setCustomId(`NitradoCredentials-${interaction.member.user.id}`); + + const ServerID = new ActionRowBuilder().addComponents(new TextInputBuilder() + .setCustomId("ServerIDInput") + .setLabel("Your Nitrado Server ID") + .setStyle(TextInputStyle.Short) + .setRequired(true) + ); + + const UserID = new ActionRowBuilder().addComponents(new TextInputBuilder() + .setCustomId("UserIDInput") + .setLabel("Your Nitrado User ID") + .setStyle(TextInputStyle.Short) + .setRequired(true) + ); + + const Auth = new ActionRowBuilder().addComponents(new TextInputBuilder() + .setCustomId("AuthInput") + .setLabel("Your Nitrado Authentication Token") + .setPlaceholder("This will be encrypted to protect your server!") + .setStyle(TextInputStyle.Short) + .setRequired(true) + ); + + NitradoCredentials.addComponents(ServerID, UserID, Auth); + + return interaction.showModal(NitradoCredentials); + + } else if (args[0].name == "disconnect") { + + const prompt = new EmbedBuilder() + .setTitle(`Delete your Nitrado Server?`) + .setDescription("**Notice:** This will completely delete your configured Nitrado server from the bot database.") + .setColor(client.config.Colors.Yellow) + + const opt = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId(`DeleteNitrado-yes-${interaction.member.user.id}`) + .setLabel("Yes") + .setStyle(ButtonStyle.Danger), + new ButtonBuilder() + .setCustomId(`DeleteNitrado-no-${interaction.member.user.id}`) + .setLabel("No") + .setStyle(ButtonStyle.Success) + ) + + 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 (args[0].name == "credentials-status") { + + const ok = GuildDB.Nitrado.Status == NitradoCredentialStatus.OK; + const notice = ok ? "Your provided Nitrado Credentials are working correctly, logs are being checked." : "Your provided Nitrado Credentials are not working. They may be incorrect, or your server may be down. Ensure your DayZ server is online, and try to initialize your server again and verify your credentials are correct." + const statusEmbed = new EmbedBuilder() + .setColor(ok ? client.config.Colors.Green : client.config.Colors.Red) + .setTitle("Nitrado Credentials Status") + .setDescription(`**Status:** \`${GuildDB.Nitrado.Status}\`\n> ${notice}`); + + return interaction.send({ embeds: [statusEmbed] }); + + } else if (args[0].name == "retry-credentials") { + + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "Nitrado.Status": NitradoCredentialStatus.OK } }, (err, _) => { + if (err) return client.sendInternalError(interaction, err); + }); + + const updatedEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setTitle("Updated Nitrado Credentials Status") + .setDescription(`**Success**\n> Successfully retrying your existing Nitrado Credentials to check DayZ logs.`); + + return interaction.send({ embeds: [updatedEmbed] }); + + } else if (args[0].name == "ban-player") { + + let data = await BanPlayer(GuildDB.Nitrado, client, args[0].options[0].value); + + if (data == 1) { + let failed = new EmbedBuilder() + .setColor(client.config.Colors.Red) + .setDescription(`Failed to ban **${args[0].options[0].value}**. This can result from a variety of reasons:\nNitrado servers may be experiencing issues\nThe DayZ.R Bot may be experiencing issues\nYour Nitrado credentials were entered incorrectly`); + + return interaction.send({ embeds: [failed], flags: (1 << 6) }); + } + + let banned = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`Successfully **banned** **${args[0].options[0].value}** from the DayZ Server`); + + return interaction.send({ embeds: [banned] }); + + } else if (args[0].name == "unban-player") { + + let data = UnbanPlayer(GuildDB.Nitrado, client, args[0].options[0].value); + + if (data == 1) { + let failed = new EmbedBuilder() + .setColor(client.config.Colors.Red) + .setDescription(`Failed to unban **${args[0].options[0].value}**. This can result from a variety of reasons:\nNitrado servers may be experiencing issues\nThe DayZ.R Bot may be experiencing issues\nYour Nitrado credentials were entered incorrectly`); + + return interaction.send({ embeds: [failed] }); + } + + let banned = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`Successfully **unbanned** **${args[0].options[0].value}** from the DayZ Server`); + + return interaction.send({ embeds: [banned] }); + + } else if (args[0].name == "restart") { + // Write optional "restart_message" to set in the Nitrado server logs and send a notice "message" to your server community. + restart_message = "Server being restarted by an admin."; + message = "The server was restarted by an admin!"; + + RestartServer(GuildDB.Nitrado, client, restart_message, message); + return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription("The server will restart shortly.")], flags: (1 << 6) }); + + } else if (args[0].name == "auto-restart") { + let msg = "Auto server restart periodic check enabled."; + let pref = 0; + + // Enable/Disable a 10min periodic server status check. + if (!client.arIntervalIds.has(GuildDB.serverID)) { + client.arIntervalIds.set(GuildDB.serverID, setInterval(CheckServerStatus, client.arInterval, GuildDB.Nitrado, client)); + pref = 1; + } else { + msg = "Auto server restart periodic check disabled." + clearInterval(client.arIntervalIds.get(GuildDB.serverID)); + } + + // Update DB preference + client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { + $set: { + "server.autoRestart": pref, + } + }, function (err, res) { + if (err) return client.sendInternalError(interaction, err); + }); + + return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(msg)], flags: (1 << 6) }); + + } else if (args[0].name == "disable-base-damage") { + const preference = args[0].options[0].value; + await interaction.deferReply({ flags: (1 << 6) }); + + const disableBaseDamageFailed = await DisableBaseDamage(GuildDB.Nitrado, client, preference); + + if (disableBaseDamageFailed) return interaction.editReply({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Red).setDescription("Failed to set **disableBaseDamage**. This can result from a variety of reasons:\nNitrado servers may be experiencing issues\nThe DayZ.R Bot may be experiencing issues\nYour Nitrado credentials were entered incorrectly")], flags: (1 << 6) }); + return interaction.editReply({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Green).setDescription(`Successfully set **disableBaseDamage** to ${preference}.\nRestart the DayZ server to apply these changes.`)], flags: (1 << 6) }); + + } else if (args[0].name == "disable-container-damage") { + const preference = args[0].options[0].value; + await interaction.deferReply({ flags: (1 << 6) }); + + const disableContainerDamageFailed = await DisableContainerDamage(GuildDB.Nitrado, client, preference); + + if (disableContainerDamageFailed) return interaction.editReply({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Red).setDescription("Failed to set **disableContainerDamage**. This can result from a variety of reasons:\nNitrado servers may be experiencing issues\nThe DayZ.R Bot may be experiencing issues\nYour Nitrado credentials were entered incorrectly")], flags: (1 << 6) }); + return interaction.editReply({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Green).setDescription(`Successfully set **disableContainerDamage** to ${preference}.\nRestart the DayZ server to apply these changes.`)], flags: (1 << 6) }); + + } + } + }, + + Interactions: { + + NitradoCredentials: { + run: async (client, interaction, GuildDB) => { + if (!interaction.customId.endsWith(interaction.member.user.id)) + return interaction.reply({ content: "This interaction is not for you", flags: (1 << 6) }); + + const Nitrado = { + ServerID: interaction.fields.fields.get("ServerIDInput").value, + UserID: interaction.fields.fields.get("UserIDInput").value, + Auth: encrypt( + interaction.fields.fields.get("AuthInput").value, + client.config.EncryptionMethod, + client.key, + client.encryptionIV + ), // Encrypt the Authentication Token + Status: NitradoCredentialStatus.OK, // Indicate if these credentials dont work + }; + + await client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "Nitrado": Nitrado } }, (err, res) => { + if (err) client.sendInternalError(interaction, err); + }); + + client.initNewNitradoServer(GuildDB.serverID, Nitrado); + + return interaction.reply({ content: "Successfully configured your Nitrado Server Information", flags: (1 << 6) }); + } + }, + + OverwriteNitrado: { + run: async (client, interaction, GuildDB) => { + 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") { + const NitradoCredentials = new ModalBuilder() + .setTitle("Connect your Nitrado Server") + .setCustomId(`NitradoCredentials-${interaction.member.user.id}`); + + const ServerID = new ActionRowBuilder().addComponents(new TextInputBuilder() + .setCustomId("ServerIDInput") + .setLabel("Your Nitrado Server ID") + .setStyle(TextInputStyle.Short) + .setRequired(true) + ); + + const UserID = new ActionRowBuilder().addComponents(new TextInputBuilder() + .setCustomId("UserIDInput") + .setLabel("Your Nitrado User ID") + .setStyle(TextInputStyle.Short) + .setRequired(true) + ); + + const Auth = new ActionRowBuilder().addComponents(new TextInputBuilder() + .setCustomId("AuthInput") + .setLabel("Your Nitrado Authentication Token") + .setPlaceholder("This will be encrypted to protect your server!") + .setStyle(TextInputStyle.Short) + .setRequired(true) + ); + + NitradoCredentials.addComponents(ServerID, UserID, Auth); + + // TODO: Figure out how to remove the prompt buttons and the embed. + return interaction.showModal(NitradoCredentials); + } else { + return interaction.update({ embeds: [], components: [], content: "Cancelled Overwriting Nitrado Server Information", flags: (1 << 6) }); + } + } + }, + + DeleteNitrado: { + run: async (client, interaction, GuildDB) => { + 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") { + await client.dbo.collection("guilds").updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "Nitrado": null } }, (err, _) => { + if (err) client.sendInternalError(interaction, err); + }); + + return interaction.update({ + embeds: [ + new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Success**\n> Successfully removed your Nitrado credentials from the database.`) + ], + components: [], + flags: (1 << 6) + }); + } else { + return interaction.update({ + embeds: [ + new EmbedBuilder() + .setColor(client.config.Colors.Green) + .setDescription(`**Cancelled**\n> Your Nitrado credentials were not removed from the database.`) + ], + components: [], + flags: (1 << 6) + }); + } + } + }, + + } +} diff --git a/src/commands/weapon-stats.js b/src/commands/weapon-stats.js new file mode 100644 index 0000000..d63a126 --- /dev/null +++ b/src/commands/weapon-stats.js @@ -0,0 +1,176 @@ +const { EmbedBuilder, ActionRowBuilder, StringSelectMenuBuilder } = require("discord.js"); +const CommandOptions = require("../util/CommandOptionTypes").CommandOptionTypes; +const { weapons } = require("../database/weapons"); +const { insertPVPstats, createWeaponStats } = require("../database/player"); + +module.exports = { + name: "weapon-stats", + debug: false, + global: false, + description: "Check player weapon statistics", + usage: "[category] [user or gamertag]", + permissions: { + channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], + member: [], + }, + options: [{ + name: "category", + description: "Weapon category", + value: "category", + type: CommandOptions.String, + required: true, + choices: [ + { name: "Handguns", value: "handguns" }, + { name: "Shotguns", value: "shotguns" }, + { name: "Submachine Guns", value: "subMachineGuns" }, + { name: "Assault Rifles", value: "assaultRifles" }, + { name: "Battle Rifles", value: "battleRifles" }, + { name: "Bolt-action Rifles", value: "boltActionRifles" }, + { name: "Break-action Rifles", value: "breakActionRifles" }, + { name: "Lever-action Rifles", value: "leverActionRifles" }, + { name: "Marksman Rifles", value: "marksmanRifles" }, + { name: "Semi-automatic Rifles", value: "semiAutomaticRifles" }, + { name: "Other", value: "other" }, + ] + }, { + name: "discord", + description: "Discord user to lookup stats", + value: "discord", + type: CommandOptions.User, + required: false, + }, { + name: "gamertag", + description: "Gamertag to lookup stats", + type: CommandOptions.String, + required: false, + }], + SlashCommand: { + /** + * + * @param {require("../structures/DayzRBot")} client + * @param {import("discord.js").Message} message + * @param {string[]} args + * @param {*} param3 + */ + 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)) { + 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."); + + return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); + } + + let discord = args[1] && args[1].name == "discord" ? args[1].value : undefined; + let gamertag = args[1] && args[1].name == "gamertag" ? args[1].value : undefined; + let self = !discord && !gamertag; // searching for self if both discord and gamertag are undefined + const weaponClass = args[0].value; + + let query; + + // Searching by Discord + if (discord) query = await client.dbo.collection("players").findOne({ "discordID": discord }); + + // Searching by Gamertag + if (gamertag) query = await client.dbo.collection("players").findOne({ "gamertag": gamertag }); + + // 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.`)] }); + + let weaponSelect = new StringSelectMenuBuilder() + .setCustomId(`ViewWeaponStats-${query.playerID}-${interaction.member.user.id}`) + .setPlaceholder(`Select an weapon to view stat.`) + + for (const [name, _] of Object.entries(weapons[weaponClass])) { + weaponSelect.addOptions({ + label: name, + description: `View this weapon"s stats.`, + value: `${weaponClass}_${name}`, + }); + } + + const opt = new ActionRowBuilder().addComponents(weaponSelect); + + return interaction.send({ components: [opt] }); + }, + }, + + Interactions: { + ViewWeaponStats: { + run: async (client, interaction, GuildDB) => { + if (!interaction.customId.endsWith(interaction.member.user.id)) + return interaction.reply({ content: "This interaction is not for you", flags: (1 << 6) }); + + const weapon = interaction.values[0].split("_")[1]; + const weaponClass = interaction.values[0].split("_")[0]; + const playerID = interaction.customId.split("-")[1]; + 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); + + let stats = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`${tag} stats for the **${weapon}**`) + .setThumbnail(weapons[weaponClass][weapon]) + .addFields( + { name: `Kills`, value: `${player.weaponStats[weapon].kills}`, inline: true }, + { name: `Deaths`, value: `${player.weaponStats[weapon].deaths}`, inline: true }, + { name: `Shots Landed`, value: `${player.weaponStats[weapon].shotsLanded}`, inline: true }, + { name: `Times Shot`, value: `${player.weaponStats[weapon].timesShot}`, inline: true }, + ); + + const chart = { + type: "bar", + data: { + labels: ["Head", "Torso", "Left Arm", "Right Arm", "Left Leg", "Right Leg"], + datasets: [{ + label: `Shots landed with a ${weapon}`, + data: [ + player.weaponStats[weapon].shotsLandedPerBodyPart.Head, + player.weaponStats[weapon].shotsLandedPerBodyPart.Torso, + player.weaponStats[weapon].shotsLandedPerBodyPart.LeftArm, + player.weaponStats[weapon].shotsLandedPerBodyPart.RightArm, + player.weaponStats[weapon].shotsLandedPerBodyPart.LeftLeg, + player.weaponStats[weapon].shotsLandedPerBodyPart.RightLeg, + ], + }, { + label: `Times Shot by a ${weapon}`, + data: [ + player.weaponStats[weapon].timesShotPerBodyPart.Head, + player.weaponStats[weapon].timesShotPerBodyPart.Torso, + player.weaponStats[weapon].timesShotPerBodyPart.LeftArm, + player.weaponStats[weapon].timesShotPerBodyPart.RightArm, + player.weaponStats[weapon].timesShotPerBodyPart.LeftLeg, + player.weaponStats[weapon].timesShotPerBodyPart.RightLeg, + ], + }], + }, + options: { + legend: { + labels: { + fontSize: 14, + fontStyle: "bold", + } + }, + scales: { + yAxes: [{ ticks: { fontStyle: "bold" } }], + xAxes: [{ ticks: { fontStyle: "bold" } }], + }, + }, + }; + + const encodedChart = encodeURIComponent(JSON.stringify(chart)); + const chartURL = `https://quickchart.io/chart?bkg=${encodeURIComponent("#ded8d7")}&c=${encodedChart}`; + + stats.setImage(chartURL); + + return interaction.update({ components: [], embeds: [stats] }); + } + } + } +} diff --git a/src/config/config.js b/src/config/config.js new file mode 100644 index 0000000..12e4715 --- /dev/null +++ b/src/config/config.js @@ -0,0 +1,47 @@ +const package = require("../../package.json"); +require("dotenv").config(); + +const PresenceTypes = { + Playing: 0, + Streaming: 1, + Listening: 2, + Watching: 3, + Custom: 4, + Competing: 5, +}; + +const PresenceStatus = { + Online: "online", + Offline: "offline", + Idle: "idle", + DoNotDisturb: "dnd", +}; + +module.exports = { + Dev: process.env.Dev || "DEV.", + Version: package.version, // (major).(minor).(patch) + Admins: ["362791661274660874", "329371697570381824"], // Admins of the bot + SupportServer: "https://discord.gg/KVFJCvvFtK", // Support Server Link + Token: process.env.token || "", //Discord Bot Token + SecretKey: process.env.key || "01234567891", + SecretIv: process.env.iv || "9876543210", + EncryptionMethod: process.env.encryptionMethod || "aes-256-cbc", + Scopes: ["identify", "guilds", "applications.commands"], //Discord OAuth2 Scopes + IconURL: "https://cdn.discordapp.com/app-icons/1049045393415098450/f8e7f76ac9e843360b989c796fc21990.png?size=256", + AvatarData: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgaElEQVR4nO2dfYxU5fXHv/dt7szuwi7orvIi7wICVdR2qUIjQm0sYmvTqo3VWBqjtEm1ao3ampKqtdFfjMYqtLa0jW+o1FoQ26DWiorBl6DRNmJFodBClSKwy87MfZvz+2M5D3eWXdzdmWXn3ud8kpt9mdm59z57n+9znvOccx6DiAiCIGiJOdgXIAjC4CECIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgaIwIgCBojAiAIGiMCIAgakzoBICL1lYhQKpUG+Yr6Dl8730vX17r7fqCIomjAzzEQ9NR+n/aabtiDfQHVhogQhiEMw4BhGCAiGIYx2JfVJ7rr5HwvTKlUgmmahzzIldwrC2ZcOA3DgGnW3jgRbxe+5yiKEIYhHMc55P2GYSCKInUvSXwuBgKDUiaFRIQoimAYBnzfh213alwtPsQ9USqVEIYhTNOEZVkIwxCWZcGyLNU5TdMse6hN00QURbAsq98PNo+MYRjC931ks1l17lprPxYoy7IAdHZ+Fi9uD74X27aVKHB7SefvJHUCwCYrP8BAZaNircKjHVsGmUymKgLAHSQMQxARXNet8pUfeYIgUG3DAlFJO6WJ1E0BgM4OHwQBvv3tb2PHjh2wbTsxvgDWY9u20dDQgGHDhmH48OEYM2YMTjjhBBxzzDEYPnw4mpubUVdXp/4uDEOUSiUYhqFGxb7C5n4+n0c2m8VPfvITPPPMMxg6dGjN+gLYlDcMA67roqWlBaNGjcL48eNx/PHHY8SIERgxYgSampoAlLeTWAIpFID43H/9+vX4z3/+M9iXVDV4GtDc3IyTTjoJJ598Mo4//njMmTMHEydOVO/rOk3oKzzqf//738dHH32E3/72t1W7hyOJbdvIZrM46aSTMHv2bJx88sn44he/iKOPPlq9hy0DXUndFIDVvb29Ha2trXj//fdhWVZiLICucAeOrwx0/ZeNGTMG06dPx8KFCzFv3jxMnTpVvVYqlVAqlcqsoLjjrCvxz+b33HbbbViyZAkAwHEclEolBEFQ06Nnd21lmiamTp2KuXPn4oILLsDs2bNh2zaiKCqzJHgqlET/UZ+hlFEqlYiIaN++fTRp0iQCQKZpEoDUHIZhkOM45Lou2bZd9trw4cPpkksuoT/+8Y/U0dFBRERhGFI+n6cgCIiIKAgC1U6HI4oiiqKIiIh+/vOfq/Patn3IeWv1MAyDMpkMZbPZsufAdV36yle+Qn/4wx/UPfq+T2EYkud5FEURBUGg2iytiAAk+LAsizKZDJmmSa7rkuM46l4ty6LTTz+dHnjgAdq9ezcRERWLRfJ9n4rFYq8EgNuTO8GSJUsIwCGdqdYPy7LItm311XVdymQyBIAcx6GFCxfSa6+9RkSd4uh5HgVBQFEUURiGvW6rJCICkNCDO79hGGSaJpmmqb53XZey2ax676xZs+ihhx4i3/eJiCifz5Pneb1uU8/zqFAoEBHRNddcozrOYLdBbw7DMMiyLPUcsEiyELAlM2TIELr++uupvb2diIj27t1LHR0dyhpIKyIACT34IeYHOd75WQyy2WyZEJxzzjllI11vH+woipT1EAQBXXzxxQQgUdMA27bVVxYCy7LUFIEtgs9//vO0ceNGIiJqa2sbmIe0hhABSPARv6+4FcBiAHRaCq7rkuu6BHSOdHfccYeyBtjEPZwglEol8n2fPM+jMAxpz549dMYZZxDQOR3gjjTY7XE4AehqKcXbj3/PbdTS0kKrV68mok6/QBRFVCqV1Nc0TQtEADQ4eORzHEeNdF//+tdp8+bNqq2KxWKPAsAOsVKpRMVikYiI3n33XRo/fjxZlqUsjVoWgd4ePLXJ5XL0+9//noiICoUCFQoFJZIsnmkgxesbQhyKxfk7joMnnngCZ599Np5//vlPDfSJLxtyiPXUqVNx++23AzgYlZj05TKOB8hms/B9H1dccQVWrFhRFhJNsWSzVDC4+lN9xAI49GBnoWVZyhOey+XItm0aMmQIPfLII0REytHXXZvySkCpVCr7+fLLLycA1NDQkPh25mVO0zRVmw0dOpSeffZZIiLlA+GpQBoQAdDgME1TdXx2erHz0LIschxHmbs9rXvz3DcMw7I18h07dtD06dOVr2Gw77XSg2MGHMdRDtRx48bRP//5T9U+nuelRgCSbbMJvSJumluWBd/3YZomfN9XeRNXXHEFHnnkEdi2rRKBmDAM1edweLFlWYiiCCNGjMCtt96q3sdJNkmMtefMyyAI1JTJcRxs3boVV111FfL5vMo0TQ2DrUDVRiyA3lsF7B1nL34ul6Onn36aiA6auz0FDbE1wO8777zzCOh0nsWXKJMSL3C4gx2ny5YtIyLqUyBVrSMWgKbE8wKICJZloVAoYPHixfj73/8Ox3HUiN4dXIvAMAzYto0bb7wRTU1NKBaLqjYB1zVIOpxY9X//93/YunUrHMdJjRNQBEBjeGrAYpDJZLB9+3YsXrwYe/bsUSLQ3cMerxQUBAFaW1vxrW99S+Xb8+tp6CimaaKurg4ffvgh7rnnnsSvdsRJz50IfYZHNv7e9324rov169fj5ptvVh24uwee/5azL6MowpVXXomWlhYEQaBGyVqsJtQXDMNAqVSC53mwLAuPPvooPvjgg/SI22BfQFIYDMfPQJ6TR2juwPw1CALYto2lS5fiqaeeQi6X69aMZycgpwf7vo/JkyfjG9/4xiF1DAezo1SjDfkzXNfFzp078cgjjwBAYlPM46SuHgAdyOtua2vDqaeeis2bN6sHvRK4phyPaqVSaUA8wvHPi9f8Yw813193uf19qdoTrzMQ/51t22qFYMqUKVi3bh2OOuoo+L6PTCajzPvuOrlpmnjttdfw5S9/GW1tbchkMqocV7XbKX7+ePHXuG8inttfCfGKQ8ViESeffDLWrl2Lo48++pB7S5q1k6yrHSR4tIsXmqQDy0RRFA3IwctR7EjzPA9A5zzdtm213MaC1Ndlt+5GZu5ERATbtrFp0ybce++9hxQk5SMeHciOv9bWVpxxxhll1z8Q7dRd+/M549dbKdz5LcuC53moq6vDxo0bsXHjRgCdosvFUZLW+YEUlgQbCHg92PM83HTTTTjxxBPheV7V6+Tx6JXJZGAYBv773/9i27Zt+Ne//oV///vfeO+999De3g6gs9xV12pBbCVUcv4gCGCaJjKZDMIwxPLly3HxxRfj+OOPRxiGCMMQ2Wy2W4uKBfKmm27CggULkMvlVBtV09CMj/K5XA6e52Hbtm3YtGkT3n77bbzzzjsAgPr6eiVC/T1/V4uM2/fpp5/GWWedVWZp9OQvqWkGboVxcBiIOACOngNAL7744qDc1/79+2ndunX005/+lGbOnKmujdNaOdKv0vvkmAAOhwVAV155JRGRKpTRU+YgZ8wNJrt376Zf/epXNHXqVAKgUqUraReOluQaDABoxowZlM/nVXJQUqsHiQ+gF8Rrzz/zzDOYP3/+YdfIq0F8Hhu3CgBg165dWLt2Le655x68/vrragrApnF/YR8AHTCv2aIYPnw41q1bh2nTpqFYLJbV2Y9DB+bbFJsqhGGIXC43YD6AONxmvJx5/fXXY8WKFWoK11+4NiAdGOGjKEJzczNeeOEFTJ06VZVnT1rkIwCxAHpzxKvKcGLIQKl91wgzTr7hWPx4Kuonn3xCP/vZz6i+vp4AqFh/HsEty+rXvccLaPB9L1myhIhIVcgJw7Db6+dcgYFso3i7dHf+YrFIQRBQPp+niy66SFlKHP3Yn+hELiISb58VK1aUtUkSowMTNmGpHQZK6bt+LlsB7Iji9XXf99HY2Igf/ehHWLVqFY477ji1LZbrumo0749zimKOTjow6j322GPYuXMnHMdRfoLuiK/788g5EPRU2dgwDDiOo2Iabr/9dkyZMkUtWfb3mrgSMgC1ccqWLVvU65RQQ1oEIIGwGBQKBXieh/nz52P16tWYMWOGcnoBB5N4Kpn+cEnxTZs24eWXXy7z/Nca8X0N6+rqEIYhRo8ejR/+8IdqSkKx6U1/4XvfuXMngIPOz1psk09DBCChxK2BQqGAmTNn4qGHHsKxxx6rHnBeCqv0weQlv1WrVvW4KWktwPfJGY9A58h89tlnY9q0acpyqdYS4f79+9V5qxFrMhiIACQUfoAdx4FlWSgWizjppJOwbNkyOI6j1sarAS9zvfLKK9i9e7eK/qs1eJmOd/thIRg9ejROPPFEAJ3RfGzK9xdu+7a2trJ4iCQiApBgHMdR04FMJgPP8/DVr34Vl19+uVo5ACo31zkIaufOndiwYYP6Xa3B05V4DgOL1+TJkwFAlS6rlgVQLBYBHFyBSBoiAAklXnSDHW+8Q/DVV1+NSZMmwfO8HoN2+orjOCgWi1i/fj2A2gx5jbcFO0B5iXTEiBEAAM/zKu78/PcU2005/vskUXv/RaHfsAk8duxYLFq0qGr5CnEB2bp1ayIj3tgaYudfJZ2V25NFl3+XtDYBRABSBzsGL7zwQowdO1aV/6oUFoEPP/wQe/furVlHYE9wCHXccqqUuro6ZDKZxK4AACIAqYMjAidOnIi5c+dW5eGMpwtv3rwZ27dvB5Ask/fDDz9U31d63dyeTU1NZXkJSWoPRgQgZXDwDhHhzDPPrMrW6FwM1LZt7NmzR61/1+IDH5+f89coipRo8e+qce1DhgwBUF5YJWkk86qFbokHuRiGgTlz5uDoo4+ueKkqHkADAHv37q3SFVefeC1Cz/NgmibeeecdvPrqq2XmeqXtAQDHHXccgIPLpEmcBogApIh4QEqpVEJzczOGDRumXquE+LJfrQpAvLoRd1LTNPHoo49ix44dqm0qCdrhz3ccRwkAd/5atIg+DRGAFMGmbXyLqzFjxlT8uV0jCv/3v/8BqN1wYMZ1XTz//PNYunSpCl7izMBKr72lpQWtra2HVFRKGiIAKYOIUCwWQUTIZDJKACp5OONBNQCwb9++qlxrtYj7PXhTD9d18eabb+Kyyy5DR0cHgM4goHgptf7Ac/0RI0Zg5MiRiKIItm2XWR1JQgQgRcRr+vHDWF9fX/Hndo36KxQKff6MeCetxsGfCZSX7aqrq4Nt23j44YexYMECbNmyRQUH8cFr95Vw5plnqs9J6vwfkJJgqYTLeQGoWpRa/AE/XBgwd9B41uBAbA4Sd+ZFUYRCoYC2tja88MILWLlyJdasWVNWJo2tGM4T6O1oHXcYxgOAzjrrrB7flyREAFIGZwdyxR7ufJU8nF0dXD3l1MfrB7CzrVgs4rrrrsPWrVvhum5VzGTu9LZtw7ZttLe3Y/v27fjoo4+wa9cuNf2J1zQADvoH+iJI/LdciNXzPMyaNQuf+9znygqyJhURgBTBa978sBIRPvnkk4o/t2tJrYaGhsNeQ/zr/v37sWbNGmzdurXi6/g0uHQ3F++oRgwEADXH5+jHc889F01NTcqaSDIiACmCzVAeoT3PUx2vkilA17n38OHDezx/104XRRFc11WBRNVylMXNceDgEmDc0ccdtNLAH074CYIA48aNw0UXXVR2DUlGBCBl8Do1VwziqL1K6BrqetRRRwE4VFTiP/M17Nu3Dx0dHSoxqdqechY7rs3Px+H2NewrLGxhGGLRokUYN25cKkZ/QAQgVfAUgOelW7ZsUVOASrPf4g97Y2Njj++NB+MAwO7du9UyXCX1+bu7Jl72i/8OgKqZGK/Z31vYzI+vMJimCc/zMGXKFHznO99JZMBPT8gyYIrgjspFKv76179i7969qtR3f4mvJJimqSyA7s7fNdvuk08+UQJQTbq7n/iuRRy63Nft0uJmvWVZysKwLAu33HILRo8erfwLaUAEIIW4roswDPHCCy9U5fPic+pRo0Zh5MiRAA6dA3ddlweA7du3w/f9qtXhG2i4enDclxEEAb773e/i/PPPRxiGFQtqLSECkDJ4CvDGG2/g5ZdfrspIFS8AMnHiRIwaNQpA9yXMu2bF7d69u9v31iLcqXlzEy6BPnfuXCxZsgS+7ytREAEQahKe8/7mN79RO/RWa3dcAJgwYQLq6up6jKdnRx/PpY/E8l+1iCdTZbNZ+L6PSZMmYenSpSqrMqnVf3tCBCBFcAzAhg0bsHLlSvWwViMKkB/6iRMnAuh5BORqxKZpoqOjAx988MFh3z/YdLfPgW3byOfzGDlyJB544AGccMIJZfP+eB3ApCOrAAklvu22bdtqbtrR0YEbb7wRbW1tcF23LDKvvxhG567BQ4cOxbx583p8X9e02I8//hibNm1S11tLxGsDxvdW5F2gx4wZg4cffhinnXaa2nGp69+mgXTImKawGc7r3ZZl4eabb8a6deuUI7Ba6+AAMHr0aEybNq1HqyLuBASgwnNrMVc+3vF52c+2bXiehxNPPBFPPvkk5syZg0KhcEjocxL8Gb1FBCChxHe44TnrvffeizvvvBMNDQ1qx9q4+V4pCxYswJAhQ+D7frf5AF13x33ppZdqduMM3t/PcRz1ve/7uOiii/DMM8/glFNOged53e6CnCZEABJKFEWq5FUul8Ndd92Fa6+9Vo1iTLxASH+IR9adc845KtS4u07d1QKo5T0E4sVBgiDAhAkT8Otf/xoPP/wwmpqaehS5tJH+O0wZPOIbhoH6+nrs3r0bN9xwA5YvX662w4ovx/FOOP2FY+Dnz5+P1tZWde7ucuD5vKZpYsuWLXj33XfVNdcqjY2NuOCCC3DDDTfguOOOK9s/8HC7IKcFEYBe0DVCjDvhQDwcXTsWL6vx77iTFwoFrF69GrfddhvefvtttdzHIbBdq+L2Fjbju1bO+drXvoa6ujplFvdkAfi+j2w2i+eeew7btm1DJpNR19SX++9OZOLlvOJFSvsK/31zczMefPBBzJs3D6VSSe2hwOfkPRbSjAhAL4gHwvT0cFYL7uz82fFUVADYsWMH/vKXv+Dxxx/Hs88+qwJWeDWgWltfcWWhIAgwefJknHfeeepcfJ1dBTAuPK+//rras7AvxTd4RYP9GyxenIxj23bFSUV8f7t27cKf/vQnnHHGGeqz46sBOkwD0n13VYTXfn3fBxFVzcPeFf7MMAxRKBTQ0dGB9vZ2vPnmm1i3bh1effVV/OMf/wBwcHPQeKhuNeDOxrn1l112GUaNGqUy7ngk7ioAURQhl8vhzTffxIMPPogwDNUW2r2Fk3viST7xZU7f96sS3MQC9otf/AJDhw7FrbfeimKxqIqMcOXftFsABqXsDnlkbmtrw6mnnorNmzdXvA4e32121qxZGDlyJAqFwoBYAWziep6HXbt24aOPPkJHRwfy+bx6GF3XVe/hGnfxkb+SfymPvCwC06ZNw7p169DQ0KBe43l+13vna3/rrbdw//33I5vNqiKdvW0nnn8XCgXU19fjb3/7G9566y3kcjllonNFn0rvk52jvu9j2bJlWLx4sSqo6rpu2TWlFkoZpVKJiIj27dtHkyZNIgBkmiYB6PdhGAbZtk2O41T0OZWc33EcymQylMlkyLIschxH3Re/Xo37zGQyZJomZTIZAkD3338/EREVi0XyPI+CIKAwDHtse8/z1P+gGmzevJlOOOEEsm2bXNcl13Wr8r+wbZuy2Sy5rkuO41B9fT2tWrWKiIjy+TxFUURhGFIQBFW7l1pELIBewnPP+MhHA2AB8GfGA1TinncubBn3Q8Rf62/oL1s5XE6sWCziS1/6EtasWVNW6Yc9/T3dOx2YHsWr8fR2BKWYBcNTG67tf+6556rYBrYqKnl049WT6EBdgTFjxmDlypVobW1FR0cHstmsapPUckTl5ggwEBZAGg/DMMiyLNU2lmWVWQDDhg2jN954g8Iw7HHEPxLwCHzXXXcRADViV7s9uB2mTJlCW7duJSKiQqEwqPd+JEjx5Eb4NIjKa+zH6+stWbIEp556KvL5/KDGvluWBd/3cdVVV+Hyyy+H53nIZrNVt7zY6ffee+/hkksuwb59+1IV898jgyxAVUcsgL6PfNw+PLJecMEF5Pt+zYyAQRBQEATU3t5O8+fPV5bAQLRHLpcjAHT++eeT53kUhmFVfRq1hlgAmsJzefYf2LaNIAhw2mmn4Ze//KXy9Pu+P6jXSQeslCiK0NDQgKVLl2LMmDFqBaTa8PLnypUr8eMf/1j5PihdrjKFCICmcMfnoJcwDDFu3Dj87ne/Q1NTkwqDZUfYYF4nBx8Vi0VMnjwZy5YtQy6XU68D1Vuq4/gCx3Fw55134r777isTgaTuAdgTIgCawB7vTCajOovjOKryzfjx4/Hkk09iypQpKruQI+MGO5uvVCohk8mo+PwFCxbglltuUb/PZDI9Jij1FToQzsyrGNdccw2eeOIJtSvQQJQ2H0xEADQgvnTHI77jOLBtW42qTz31FGbOnKnCcGsNXorkQKArr7wSl156KTzP67aqT3/PEV/iBTojEr/3ve9hw4YNyGazh+yRkHREADSATWg2b3lenc/n0draij//+c+YPn16Tce+cwwGdzzHcXDHHXdg5syZ8DyvatuAxeFMyo8//hiLFi3CBx98gGw2W7M1DvqDCIAGBEGgAnzY2ef7Pr75zW9i9erVGD9+PPL5fE0/1Ny5+T5830dLSwuWL1+O5uZmeJ5XsXixMMYtCt7abNOmTVi0aBF27dqlqjClARGABNPbDhtPJfY8D0OHDsXtt9+OBx98EMccc4xK4a3V0Z8dgRxhyCOw7/s45ZRTcNdddykfQaUi1p0IBEGATCaDl156CYsXL1YxE6mYBhzZVceBR6c4AF7D54g+0zTJtm0V1WcYBpmmSfX19epvTj/9dFq/fr1qK17nr+W1br62UqlU9n0+n6d8Pk9ERDfeeCMBoEwmo9qAD8Mw+t3G8YhJzo+47rrriIhUnMCn5UjUMiIACT0syypL3OEOn8vlyLIssm2b6urq1PsnTJhAd999N7W3txNRZ8JLLXf6TyOKIioWi+T7PhWLRSoWi7Rw4UICQA0NDaptHMepSAC4rVkEuE3vvvtuIupsxzAMqVAoJLI9RQASenDHtyxL/cxZgjxSAaDRo0fTtddeq+LboyiitrY28n1/MP9NFcPWgOd5VCwWKQxD2rZtG82YMYMMwyDXdatiAcQFgLMuOZPwscceI6LOTEnOHkwaIgAJPmzbViZv19DYyZMn00033UTvvfeeaptCoUC+71OpVEq8AHCH832foiiiQqFARESvvPIKNTY2kmVZlMvllGVUqQCwwGYyGXJdlwzDoGHDhtGLL75IRFT1NOgjhaQDJ4Cu69zx9eq4N3rEiBGYOXMmLr30UsyZM0ft4ZfP51UVHV5LT3qRiyiKytKOgc7/fTabxX333Ycf/OAHqpJQpR57Xj3hZVSOq/A8DxMmTMDatWsxadIkBEGQuDLiqRMA9hC3t7dj1qxZ2Lx584CsEQ80FMvU6ykW3bZttLS04Atf+AJmz56NuXPn4jOf+Yx6PV7CK+4d5/JaSSYeF8D1EAGgUCigrq4OV199Ne6++24MGTJEbZfeH+J7K3CpMB5kcrkc9u/fj9mzZ2PVqlVobGwcsFqRA0XqBIAfjLa2NkyePBkff/zxYF9SxWQyGTQ2NqK5uRlDhgzB2LFjcdppp+Gzn/0sRo4cifHjx6uHjh/Q7kp2pZ1SqaQiGYvFIs477zw899xzR+Tcc+bMweOPP45jjz0WQHJ2D0qlAACdZu9DDz2EPXv2lJlvScFxHDQ0NKCxsRFDhw5FS0sLxo4di+HDhx8yevPaOB2o2puUh6/a0IFqRL7vo66uDu+//z5WrlypKhP1l+6qQMcrM1mWhXw+jwsvvBBTp04dsJLxA0EqBYCDN+KFHdMCZ6PFy4QBnYLBD56uAhDfmZitoFrMa6glkj0R7AZOFuEtnvkBSIoiA1DzWnbWUZftvUzTVLXs0rRVdaXwFMB13bLqytXOaGSfAOcK8DPHWYlJInUWAJvCPAKw8yYptxkvBso/d30dOOgkrFYmXFrg6RA7fgfCImIBYOdjfDOXpP0fUicAgiD0HrEdBUFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFjRAAEQWNEAARBY0QABEFj/h+ueo0XyBHLFAAAAABJRU5ErkJggg==", + Colors: { + Default: "#8a7c72", + DarkRed: "#ba0f0f", + Red: "#f55c5c", + Green: "#32a852", + Yellow: "#ffb01f" + }, + Permissions: 2205281600, + mongoURI: process.env.mongoURI || "mongodb://localhost:27017", + dbo: process.env.dbo || "knoldus", + Presence: { + type: PresenceTypes.Watching, + name: "DayZ Logs", // What message you want after type + status: PresenceStatus.Online + }, +} diff --git a/src/database/armbands.js b/src/database/armbands.js new file mode 100644 index 0000000..c298faf --- /dev/null +++ b/src/database/armbands.js @@ -0,0 +1,164 @@ +module.exports = { + Armbands: [ + { + name: "Black", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/8/82/ArmbandBlack.png/revision/latest?cb=20161127174754" + }, + { + name: "Blue", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/b/bd/ArmbandBlue.png/revision/latest?cb=20161127174803" + }, + { + name: "Green", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/ce/ArmbandGreen.png/revision/latest?cb=20161127174812" + }, + { + name: "Orange", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/e6/ArmbandOrange.png/revision/latest?cb=20161127174846" + }, + { + name: "Pink", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/f/f7/ArmbandPink.png/revision/latest?cb=20161127174854" + }, + { + name: "Red", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/1/14/Armband.png/revision/latest?cb=20161127174901" + }, + { + name: "Yellow", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/8/81/ArmbandYellow.png/revision/latest?cb=20161127174918" + }, + { + name: "White", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/c7/Armband_White.png/revision/latest?cb=20161127174926" + }, + { + name: "Altis", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/ee/Flag_alti_co.png/revision/latest?cb=20200820222622" + }, + { + name: "Asiain Pacific Alliance (APA)", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/c2/Flag_apa_co.png/revision/latest?cb=20200820222623" + }, + { + name: "Bear", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/e1/Flag_bear_co.png/revision/latest?cb=20200820222626" + }, + { + name: "Bohemia Interactive", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/ee/Flag_bi_co.png/revision/latest?cb=20200820222627" + }, + { + name: "Brain", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/7/7d/Flag_brain_co.png/revision/latest?cb=20200820222628" + }, + { + name: "Chernarussian Defence Forces (CDF)", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/d/d6/Flag_cdf_co.png/revision/latest?cb=20200820222629" + }, + { + name: "Chedaki (CHED)", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/9/96/Flag_ched_co.png/revision/latest?cb=20200820222630" + }, + { + name: "CHEL", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/9/98/Flag_chel_co.png/revision/latest?cb=20200820222631" + }, + { + name: "Chernarus", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/ef/Flag_chern_co.png/revision/latest?cb=20200820222632" + }, + { + name: "Chernarus Mining Corporation (CMC)", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/d/da/Flag_cmc_co.png/revision/latest?cb=20200820222634" + }, + { + name: "Rooster", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/4/44/Flag_cock_co.png/revision/latest?cb=20200820222635" + }, + { + name: "DayZ", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/b/b2/Flag_dayz_co.png/revision/latest?cb=20200820222636" + }, + { + name: "North Sahrani (DROS)", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/2/24/Flag_dros_co.png/revision/latest?cb=20200820222637" + }, + { + name: "Fawn", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/d/d2/Flag_fawn_co.png/revision/latest/scale-to-width-down/1000?cb=20200820222639" + }, + { + name: "Pirates", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/a/ab/Flag_jolly_co.png/revision/latest?cb=20200820222643" + }, + { + name: "Cannibals", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/4/42/Flag_jolly_c_co.png/revision/latest?cb=20200820222641" + }, + { + name: "South Sahrani (KOS)", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/a/a1/Flag_kos_co.png/revision/latest?cb=20200820222644" + }, + { + name: "Livonia Army (LDF)", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/c1/Flag_ldf_co.png/revision/latest?cb=20200820222645" + }, + { + name: "Livonia", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/e6/Flag_livo_co.png/revision/latest?cb=20200820222647" + }, + { + name: "NAPA", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/e4/Flag_napa_co.png/revision/latest?cb=20200820222648" + }, + { + name: "Livonia Police", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/6/63/Flag_police_co.png/revision/latest?cb=20200820222649" + }, + { + name: "TEC", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/ea/Flag_tec_co.png/revision/latest?cb=20200820222650" + }, + { + name: "United Earth Coalition (UEC)", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/ca/Flag_uec_co.png/revision/latest?cb=20200820222651" + }, + { + name: "Wolf", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/b/b2/Flag_wolf_co.png/revision/latest?cb=20200820222653" + }, + { + name: "Zenit Radio Station", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/0/05/Flag_zenit_co.png/revision/latest?cb=20200820222654" + }, + { + name: "Zombie Hunters", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/9/97/Flag_zhunters_co.png/revision/latest?cb=20200820222621" + }, + { + name: "RSTA", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/2/20/Flag_rsta_co.png/revision/latest/scale-to-width-down/1000?cb=20210216191221" + }, + { + name: "Refuge", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/8/8e/Flag_refuge_co.png/revision/latest/scale-to-width-down/1000?cb=20210216191205" + }, + { + name: "Snake", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/5/54/Flag_snake_co.png/revision/latest/scale-to-width-down/1000?cb=20210216191234" + }, + { + name: "Zagorky", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/7/75/Flag_zagorky_co.png/revision/latest/scale-to-width-down/1000?cb=20230619164704" + }, + { + name: "Crook", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/c8/Flag_crook_co.png/revision/latest/scale-to-width-down/1000?cb=20230619164705" + }, + { + name: "Rex", + url: "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/c5/Flag_rex_co.png/revision/latest/scale-to-width-down/1000?cb=20230619164706" + }, + ] +} diff --git a/src/database/destinations.js b/src/database/destinations.js new file mode 100644 index 0000000..172a593 --- /dev/null +++ b/src/database/destinations.js @@ -0,0 +1,684 @@ +const { calculateVector } = require("../util/Vector"); + +module.exports = { + Missions: { + "dayzOffline.chernarusplus": "Chernarus", + "dayzOffline.enoch": "Livonia", + "dayzOffline.sakhal": "Sakhal", + }, + + // Calculates the nearest location to a given coordinate + nearest: (pos, mission) => { + let tempDest; + let lastDist = 1000000; + let destination_dir; + for (let i = 0; i < destinations[mission].length; i++) { + let { distance, theta, dir } = calculateVector(pos, destinations[mission][i].coord); + if (distance < lastDist) { + tempDest = destinations[mission][i].name; + lastDist = distance; + destination_dir = dir; + } + } + return lastDist > 500 ? `${destination_dir} of ${tempDest}` : `Near ${tempDest}`; + } +} + +// A curated list of destinations across DayZ Chernarus and Livonia +const destinations = { + Chernarus: [ + { + name: "Sinystok", + coord: [1481.47, 11933.38], + }, { + name: "Novaya Petrovka", + coord: [3437.31, 13010.46], + }, { + name: "Zaprundoe", + coord: [5171.52, 12753.83], + }, { + name: "Ratnoe", + coord: [6174.72, 12722.72], + }, { + name: "Severograd", + coord: [7986.69, 12699.39], + }, { + name: "Svergino", + coord: [9464.27, 13718.14], + }, { + name: "West Novodmitrovsk", + coord: [10988.51, 14344.17], + }, { + name: "East Novodmitrovsk", + coord: [12143.35, 14336.39], + }, { + name: "North Novodmitrovsk", + coord: [11544.55, 14764.11], + }, { + name: "Cernaya Polyana", + coord: [12112.25, 13760.91], + }, { + name: "Turovo", + coord: [13585.94, 14060.32], + }, { + name: "Karmanovka", + coord: [12679.95, 14678.56], + }, { + name: "Dobroe", + coord: [12956.02, 15051.85], + }, { + name: "Belaya Polyana", + coord: [14161.41, 14942.97], + }, { + name: "Svetlojarsk", + coord: [14001.99, 13251.54], + }, { + name: "Olsha", + coord: [13348.75, 12897.70], + }, { + name: "Black Lake", + coord: [13438.18, 12127.80], + }, { + name: "Krasno Airfield", + coord: [12018.93, 12586.63], + }, { + name: "Krasnostav", + coord: [11163.49, 12248.34], + }, { + name: "Rify", + coord: [13811.46, 11210.15], + }, { + name: "Khelmn", + coord: [12287.22, 10840.75], + }, { + name: "North Berezino", + coord: [12905.47, 10059.19], + }, { + name: "Central Berezino", + coord: [12423.31, 9600.36], + }, { + name: "South Berezino", + coord: [11968.38, 9079.32], + }, { + name: "Dubrovka", + coord: [10362.48, 9837.55], + }, { + name: "Vyshnaya Dubrovka", + coord: [9891.99, 10432.47], + }, { + name: "North Solnichniy", + coord: [13123.22, 7100.15] + }, { + name: "Solnichniy", + coord: [13418.74, 6248.60], + }, { + name: "Orlovets", + coord: [12201.68, 7275.12], + }, { + name: "Polana", + coord: [10743.54, 8134.45], + }, { + name: "Gorka", + coord: [9487.60, 8811.03], + }, { + name: "Radio Zenit", + coord: [8128.62, 9230.97], + }, { + name: "Dolina", + coord: [11276.25, 6594.66], + }, { + name: "Devil\"s Castle", + coord: [6890.18, 11439.56], + }, { + name: "Zolotar Castle (Black Mountain)", + coord: [10189.45, 12038.37], + }, { + name: "Kamensk", + coord: [6684.09, 14410.27], + }, { + name: "MB Kamensk", + coord: [7862.27, 14698.01], + }, { + name: "Quarry", + coord: [8614.66, 13333.19], + }, { + name: "Nagornoe", + coord: [9262.08, 14620.24], + }, { + name: "Stary Yar", + coord: [4965.44, 15028.52], + }, { + name: "Tisy", + coord: [3425.65, 14783.55], + }, { + name: "MB Tisy", + coord: [1543.68, 14052.54], + }, { + name: "Topolniki", + coord: [2834.62, 12388.32], + }, { + name: "North NWAF", + coord: [4024.45, 11738.96], + }, { + name: "Central NWAF", + coord: [4249.98, 10766.87], + }, { + name: "South NWAF", + coord: [4864.34, 9588.70], + }, { + name: "Grishino", + coord: [5976.41, 10300.27], + }, { + name: "Kabanino", + coord: [5284.28, 8604.94], + }, { + name: "Stary Sobor", + coord: [6058.07, 7792.28], + }, { + name: "Novy Sobor", + coord: [7088.48, 7648.41], + }, { + name: "MB VMC", + coord: [4483.28, 8286.10], + }, { + name: "Vybor", + coord: [3814.48, 8904.35], + }, { + name: "Pustoshka", + coord: [3060.14, 7905.04], + }, { + name: "Lopatino", + coord: [2725.74, 10016.42], + }, { + name: "Vavilovo", + coord: [2228.03, 11039.06], + }, { + name: "Kalinka", + coord: [3301.22, 11249.03], + }, { + name: "Biathlon Arena", + coord: [493.82, 11093.50], + }, { + name: "Krona Castle", + coord: [1395.92, 9246.52], + }, { + name: "Myshkino", + coord: [2010.28, 7317.90], + }, { + name: "Polesovo", + coord: [5929.75, 13523.72], + }, { + name: "Kalinovka", + coord: [7516.20, 13457.62], + }, { + name: "Skalisty Island", + coord: [13620.93, 3040.70], + }, { + name: "Kamyshovo", + coord: [12061.70, 3526.74], + }, { + name: "Elektrozavodsk", + coord: [10273.05, 2010.28], + }, { + name: "Cherno. Prigorodki", + coord: [7733.95, 3182.62], + }, { + name: "Chernogorsk", + coord: [6573.28, 2544.93], + }, { + name: "Cherno. Dubovo", + coord: [6672.43, 3616.18], + }, { + name: "Cherno. Vysotovo", + coord: [5686.73, 2552.71], + }, { + name: "Cherno. Novoselki", + coord: [6139.72, 3239.01], + }, { + name: "Balota Airfield", + coord: [5054.87, 2344.68], + }, { + name: "Balota", + coord: [4463.84, 2441.89], + }, { + name: "Komarovo", + coord: [3670.61, 2457.44], + }, { + name: "Prison Island", + coord: [2702.41, 1296.77], + }, { + name: "Kamenka", + coord: [1905.30, 2231.92], + }, { + name: "MB Pavlovo", + coord: [2130.82, 3363.43], + }, { + name: "Pavlovo", + coord: [1675.88, 3845.59], + }, { + name: "Bor", + coord: [3324.55, 3985.57], + }, { + name: "Nadezhdino", + coord: [5867.54, 4790.46], + }, { + name: "Mogilevka", + coord: [7570.64, 5140.41], + }, { + name: "Pusta", + coord: [9192.09, 3861.14], + }, { + name: "Staroye", + coord: [10136.96, 5443.71], + }, { + name: "MSTA", + coord: [11334.57, 5486.48], + }, { + name: "Tulga", + coord: [12753.83, 4405.51], + }, { + name: "Guglovo", + coord: [8437.74, 6680.21], + }, { + name: "Vyshnoye", + coord: [6586.88, 6054.18], + }, { + name: "Rogovo", + coord: [4763.24, 6765.75], + }, { + name: "Pulkovo", + coord: [4969.33, 5614.79], + }, { + name: "Green Mountain", + coord: [3707.55, 6003.63], + }, { + name: "Zelenogorsk", + coord: [2581.87, 5190.96], + }, { + name: "Sosnovka", + coord: [2527.43, 6369.14], + }, { + name: "Plotina Tishina Damn", + coord: [1193.73, 6363.30], + }, { + name: "Zvir", + coord: [571.59, 5294.00], + }, { + name: "Shakhovka", + coord: [9658.69, 6555.78], + }, { + name: "Black Forrest", + coord: [9021.00, 7792.28], + }, { + name: "Nizhneye", + coord: [12971.57, 8142.23], + }, { + name: "Rog Castle", + coord: [11249.03, 4281.09], + }, { + name: "Krasnoe", + coord: [6400.24, 15012.96], + }, { + name: "Zub Castle", + coord: [6538.28, 5595.35], + }, { + name: "Pogorevka", + coord: [4417.18, 6400.24], + }, { + name: "Kozlovka", + coord: [4389.96, 4693.25], + }, { + name: "Logging Yard", + coord: [940.98, 7660.07], + }, { + name: "Zabolotye", + coord: [1193.73, 10020.31], + }, { + name: "Ski Resort Peak", + coord: [250.80, 11867.28], + }, + ], + Livonia: [ + { + name: "Lukow", + coord: [3575.00, 11925.00], + }, { + name: "Brena", + coord: [6518.75, 11228.13], + }, { + name: "Kolembrody", + coord: [8406.25, 11968.75], + }, { + name: "Grabin", + coord: [10756.25, 11062.50], + }, { + name: "Sitnik", + coord: [11440.63, 9543.75], + }, { + name: "Tarnow", + coord: [9275.00, 10921.88], + }, { + name: "Sobatka", + coord: [6250.00, 10193.75], + }, { + name: "Gliniska", + coord: [5012.50, 9881.25], + }, { + name: "Gliniska Airfield", + coord: [3968.75, 10278.13] + }, { + name: "Kopa", + coord: [5545.31, 8748.44], + }, { + name: "Olszanka", + coord: [4856.25, 7571.88], + }, { + name: "Radacz", + coord: [4006.25, 7972.66], + }, { + name: "Topolin", + coord: [1665.62, 7378.13], + }, { + name: "Bielawa", + coord: [1525.00, 9700.00], + }, { + name: "Adamow", + coord: [3081.25, 6793.75], + }, { + name: "Muratyn", + coord: [4587.50, 6387.50], + }, { + name: "Lipina", + coord: [5943.75, 6787.50], + }, { + name: "Nidek", + coord: [6118.75, 8056.25], + }, { + name: "Zapadlisko", + coord: [8093.75, 8710.94], + }, { + name: "Krsnik Military", + coord: [7841.02, 10075.39], + }, { + name: "Zalesie", + coord: [878.12, 5512.50], + }, { + name: "Borek Military", + coord: [9807.81, 8500.00], + }, { + name: "Polkrabiec", + coord: [11878.13, 6571.09], + }, { + name: "Lembork", + coord: [8825.00, 6628.13], + }, { + name: "Karlin", + coord: [10064.39, 6924.93], + }, { + name: "Radunin", + coord: [7301.89, 6418.68], + }, { + name: "Roztoka", + coord: [7650.00, 5246.88], + }, { + name: "Sarnowek", + coord: [3287.50, 5009.38], + }, { + name: "Huta", + coord: [5154.69, 5520.31], + }, { + name: "Drewniki", + coord: [5834.38, 5084.38], + }, { + name: "Nadbor", + coord: [6056.25, 4103.13], + }, { + name: "Nadbor Military", + coord: [5625.00, 3787.50], + }, { + name: "Max", + coord: [6448.44, 4732.81], + }, { + name: "Wrzeszcz", + coord: [9042.19, 4385.94], + }, { + name: "Gieraltow", + coord: [11243.75, 4332.81], + }, { + name: "Konopki", + coord: [11460.16, 2889.84], + }, { + name: "Swarog Military", + coord: [5017.19, 2146.88], + }, { + name: "Hedrykow", + coord: [4487.50, 4825.00], + }, { + name: "Polana", + coord: [3296.87, 2043.75], + }, { + name: "Dambog", + coord: [597.27, 1138.67], + }, { + name: "Dolnik", + coord: [11410.94, 578.12], + }, { + name: "Widok", + coord: [10234.38, 2165.63], + }, + ], + Sakhal: [ + { + name: "Tochka", + coord: [3731.25, 14404.69], + }, + { + name: "Utes", + coord: [5396.25, 14539.69], + }, + { + name: "Sputnik", + coord: [7738.13, 14820.00], + }, + { + name: "West Uzhki", + coord: [10501.88, 14588.44], + }, + { + name: "East Uzhki", + coord: [11251.88, 14420.63], + }, + { + name: "Tungar", + coord: [12673.13, 14116.88], + }, + { + name: "Jasnomorsk", + coord: [6953.44, 13388.44], + }, + { + name: "Jevai", + coord: [7937.81, 13541.25], + }, + { + name: "Tumanovo", + coord: [8444.06, 13693.13], + }, + { + name: "Severomorsk", + coord: [9570.94, 13525.31], + }, + { + name: "Orlovo", + coord: [10369.69, 13320.94], + }, + { + name: "Podgornoe", + coord: [10984.69, 13170.94], + }, + { + name: "Rybnoe", + coord: [12423.75, 12722.81], + }, + { + name: "Rudnogorsk", + coord: [13573.13, 11874.38], + }, + { + name: "Matrosovo", + coord: [14266.88, 11621.25], + }, + { + name: "Vajkovo", + coord: [14555.63, 9804.38], + }, + { + name: "Sumnoe", + coord: [14385.00, 8866.88], + }, + { + name: "Vostok", + coord: [13908.75, 8362.50], + }, + { + name: "Aniva", + coord: [12823.13, 7370.63], + }, + { + name: "Juznoe", + coord: [10950.00, 6313.13], + }, + { + name: "Taranay", + coord: [9703.13, 6547.50], + }, + { + name: "Nogovo", + coord: [7681.88, 7848.75], + }, + { + name: "Airfield", + coord: [7104.38, 7325.63], + }, + { + name: "Dudino", + coord: [6133.13, 7286.25], + }, + { + name: "Bolotnoe", + coord: [5083.13, 8660.63], + }, + { + name: "South Petropavlovsk-Sachalsky", + coord: [5443.13, 10001.25], + }, + { + name: "North Petropavlovsk-Sachalsky", + coord: [5585.63, 11197.50], + }, + { + name: "Zupanovo", + coord: [5747.81, 12585.94], + }, + { + name: "Sovetskoe", + coord: [6398.44, 12825.00], + }, + { + name: "Neran", + coord: [2685.00, 9251.25], + }, + { + name: "Tugar", + coord: [1742.81, 6121.88], + }, + { + name: "Cerny Mys", + coord: [5173.13, 3828.75], + }, + { + name: "Kekra", + coord: [7066.88, 4280.63], + }, + { + name: "Slomanyy", + coord: [6333.75, 6453.75], + }, + { + name: "Utichy", + coord: [8563.13, 5079.38], + }, + { + name: "Elizarovo", + coord: [13395.00, 5175.00], + }, + { + name: "Solisko", + coord: [12693.75, 2291.25], + }, + { + name: "Mrak", + coord: [8480.63, 1313.44], + }, + { + name: "Ketoj", + coord: [5626.88, 1991.25], + }, + { + name: "Urup", + coord: [1680.00, 870.00], + }, + { + name: "Ayan", + coord: [1018.12, 2891.25], + }, + { + name: "Cerepacha", + coord: [813.75, 11287.50], + }, + { + name: "Odinokij Vulkan", + coord: [10020.00, 12008.44], + }, + { + name: "Pik Bolcij", + coord: [8195.63, 11675.63], + }, + { + name: "Sakhalskaj GeoES", + coord: [8366.25, 10274.06], + }, + { + name: "Dolinovka", + coord: [9823.13, 9838.13], + }, + { + name: "Lesogorovka", + coord: [11006.25, 9729.38], + }, + { + name: "Sachalag Military", + coord: [12140.63, 9757.50], + }, + { + name: "Goriachevo", + coord: [8887.50, 10018.13], + }, + { + name: "Yasnaya Polyana", + coord: [8128.13, 9150.00], + }, + { + name: "Tichoe", + coord: [6245.63, 8655.00], + }, + { + name: "Ledanoj Greben Military", + coord: [10378.13, 8555.63], + }, + { + name: "Vysokoe", + coord: [11165.63, 7910.63], + }, + ], +} \ No newline at end of file diff --git a/src/database/guild.js b/src/database/guild.js new file mode 100644 index 0000000..898c6cb --- /dev/null +++ b/src/database/guild.js @@ -0,0 +1,102 @@ +module.exports = { + GetGuild: async (client, GuildId) => { + let guild = undefined; + if (client.databaseConnected) guild = await client.dbo.collection("guilds").findOne({ "server.serverID": GuildId }).then(guild => guild); + + // If guild not found, generate guild default + if (!guild) { + guild = {} + guild.server = module.exports.getDefaultSettings(GuildId); + guild.Nitrado = undefined; + if (client.databaseConnected) { + client.dbo.collection("guilds").insertOne(guild, (err, res) => { + if (err) client.error(`GetGuild Insert Error: ${err}`); + }); + } + } + + return { + serverID: GuildId, + Nitrado: guild.Nitrado, + lastLog: guild.server.lastLog, + serverName: guild.server.serverName, + autoRestart: guild.server.autoRestart, + showKillfeedCoords: guild.server.showKillfeedCoords, + showKillfeedWeapon: guild.server.showKillfeedWeapon, + purchaseUAV: guild.server.purchaseUAV, + purchaseEMP: guild.server.purchaseEMP, + allowedChannels: guild.server.allowedChannels, + customChannelStatus: guild.server.allowedChannels.length > 0 ? true : false, + hasBotAdmin: guild.server.botAdminRoles.length > 0 ? true : false, + + killfeedChannel: guild.server.killfeedChannel, + connectionLogsChannel: guild.server.connectionLogsChannel, + activePlayersChannel: guild.server.activePlayersChannel, + welcomeChannel: guild.server.welcomeChannel, + + factionArmbands: guild.server.factionArmbands, + usedArmbands: guild.server.usedArmbands, + excludedRoles: guild.server.excludedRoles, + hasExcludedRoles: guild.server.excludedRoles.length > 0 ? true : false, + botAdminRoles: guild.server.botAdminRoles, + + alarms: guild.server.alarms, + events: guild.server.events, + uavs: guild.server.uavs, + + incomeRoles: guild.server.incomeRoles, + incomeLimiter: guild.server.incomeLimiter, + + startingBalance: guild.server.startingBalance, + uavPrice: guild.server.uavPrice, + empPrice: guild.server.empPrice, + + linkedGamertagRole: guild.server.linkedGamertagRole, + memberRole: guild.server.memberRole, + adminRole: guild.server.adminRole, + + combatLogTimer: guild.server.combatLogTimer, + }; + }, + + getDefaultSettings(GuildId) { + return { + serverID: GuildId, + lastLog: null, + serverName: "our server!", + autoRestart: 0, + showKillfeedCoords: 0, + showKillfeedWeapon: 0, + purchaseUAV: 1, // Allow/Disallow purchase of UAVs + purchaseEMP: 1, // Allow/Disallow purchase of EMPs + allowedChannels: [], + + killfeedChannel: "", + connectionLogsChannel: "", + activePlayersChannel: "", + welcomeChannel: "", + + factionArmbands: {}, + usedArmbands: [], + excludedRoles: [], + botAdminRoles: [], + + 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/src/database/player.js b/src/database/player.js new file mode 100644 index 0000000..adb3db9 --- /dev/null +++ b/src/database/player.js @@ -0,0 +1,131 @@ +const { weapons } = require("./weapons"); + +// Creates a copy of an object to prevent mutation of parent (i.e BodyParts, createWeaponsObject) +const copy = (obj) => JSON.parse(JSON.stringify(obj)); + +const BodyParts = { + Head: 0, + Torso: 0, + RightArm: 0, + LeftArm: 0, + RightLeg: 0, + LeftLeg: 0, +}; + +const createWeaponsObject = (value) => { + const defaultWeapons = {}; + for (const [_, weaponNames] of Object.entries(weapons)) { + for (const [name, _] of Object.entries(weaponNames)) { + defaultWeapons[name] = value; + } + } + return copy(defaultWeapons); +}; + +module.exports = { + UpdatePlayer: async (client, player, interaction = null) => { + /* Wrapping this function in a promise solves some bugs */ + return new Promise(resolve => { + client.dbo.collection("players").updateOne( + { "playerID": player.playerID }, + { $set: { ...player } }, + { upsert: true }, // Create player stat document if it does not exist + (err, _) => { + if (err) { + if (interaction == null) return client.error(`UpdatePlayer Error: ${err}`); + else return client.sendInternalError(interaction, `UpdatePlayer Error: ${err}`); + } else resolve(); + } + ); + }); + }, + + getDefaultPlayer(gamertag, playerId, nitradoServerId) { + return { + // Identifiers + gamertag: gamertag, + playerID: playerId, + discordID: "", + nitradoServerID: nitradoServerId, + + // General PVP Stats + KDR: 0.00, + kills: 0, + deaths: 0, + killStreak: 0, + bestKillStreak: 0, + longestKill: 0, + deathStreak: 0, + worstDeathStreak: 0, + + // In depth PVP Stats + shotsLanded: 0, + timesShot: 0, + shotsLandedPerBodyPart: copy(BodyParts), + timesShotPerBodyPart: copy(BodyParts), + weaponStats: createWeaponsObject({ + kills: 0, + deaths: 0, + shotsLanded: 0, + timesShot: 0, + shotsLandedPerBodyPart: copy(BodyParts), + timesShotPerBodyPart: copy(BodyParts), + }), + combatRating: 800, + highestCombatRating: 800, + lowestCombatRating: 800, + combatRatingHistory: [800], + + // General Session Data + lastConnectionDate: null, + lastDisconnectionDate: null, + lastDamageDate: null, + lastDeathDate: null, + lastHitBy: null, + connected: false, + pos: [], + lastPos: [], + time: null, + lastTime: null, + + // Session Stats + totalSessionTime: 0, + lastSessionTime: 0, + longestSessionTime: 0, + connections: 0, + + // Other + bounties: [], + bountiesLength: 0, + } + }, + + insertPVPstats(player) { + player.shotsLanded = 0; + player.timesShot = 0; + player.shotsLandedPerBodyPart = copy(BodyParts); + player.timesShotPerBodyPart = copy(BodyParts); + player.weaponStats = createWeaponsObject({ + kills: 0, + deaths: 0, + shotsLanded: 0, + timesShot: 0, + shotsLandedPerBodyPart: copy(BodyParts), + timesShotPerBodyPart: copy(BodyParts), + }); + return player; + }, + + // If a new weapon is not in the existing weaponStats, this will add it. + createWeaponStats(player, weapon) { + player.weaponStats[weapon] = { + kills: 0, + deaths: 0, + shotsLanded: 0, + timesShot: 0, + shotsLandedPerBodyPart: copy(BodyParts), + timesShotPerBodyPart: copy(BodyParts), + } + return player; + } +} diff --git a/src/database/user.js b/src/database/user.js new file mode 100644 index 0000000..e97b2ba --- /dev/null +++ b/src/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/src/database/weapons.js b/src/database/weapons.js new file mode 100644 index 0000000..dda8977 --- /dev/null +++ b/src/database/weapons.js @@ -0,0 +1,77 @@ +module.exports = { + weapons: { + handguns: { + "CR-75": "https://static.wikia.nocookie.net/dayz_gamepedia/images/4/40/CZ75.png/revision/latest/scale-to-width-down/112?cb=20210505021307", + "Deagle": "https://static.wikia.nocookie.net/dayz_gamepedia/images/6/62/Deagle.png/revision/latest/scale-to-width-down/127?cb=20210512003023", + "Derringer": "https://static.wikia.nocookie.net/dayz_gamepedia/images/9/9f/Derringer_Black.png/revision/latest/scale-to-width-down/105?cb=20220521175445", + "FX-45": "https://static.wikia.nocookie.net/dayz_gamepedia/images/f/fd/FNX45.png/revision/latest/scale-to-width-down/104?cb=20210505025055", + "IJ-70": "https://static.wikia.nocookie.net/dayz_gamepedia/images/2/26/MakarovIJ70.png/revision/latest/scale-to-width-down/92?cb=20210209000551", + "Kolt 1911": "https://static.wikia.nocookie.net/dayz_gamepedia/images/f/f9/Colt1911.png/revision/latest/scale-to-width-down/112?cb=20210505030200", + "Longhorn": "https://static.wikia.nocookie.net/dayz_gamepedia/images/7/79/Longhorn.png/revision/latest/scale-to-width-down/222?cb=20220324214533", + "MK II": "https://static.wikia.nocookie.net/dayz_gamepedia/images/0/0d/MKII.png/revision/latest/scale-to-width-down/171?cb=20210210153348", + "Mlock-91": "https://static.wikia.nocookie.net/dayz_gamepedia/images/9/9b/Glock19.png/revision/latest/scale-to-width-down/121?cb=20210505024259", + "P1": "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/cc/P1.png/revision/latest/scale-to-width-down/120?cb=20220518204515", + "Revolver": "https://static.wikia.nocookie.net/dayz_gamepedia/images/6/6d/Revolver.png/revision/latest/scale-to-width-down/148?cb=20210208232303", + "Signal Pistol": "https://static.wikia.nocookie.net/dayz_gamepedia/images/a/a7/Flaregun.png/revision/latest/scale-to-width-down/107?cb=20210501150913", + }, + shotguns: { + "BK-12": "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/cb/Izh18Shotgun.png/revision/latest/scale-to-width-down/256?cb=20220922184507", + "BK-133": "https://static.wikia.nocookie.net/dayz_gamepedia/images/5/5c/MP-133-Shotgun.png/revision/latest/scale-to-width-down/256?cb=20210210190104", + "BK-43": "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/c7/Izh43Shotgun.png/revision/latest/scale-to-width-down/256?cb=20210210185835", + "Vaiga": "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/c8/Vaiga.png/revision/latest/scale-to-width-down/256?cb=20220220185225", + }, + subMachineGuns: { + "Bizon": "https://static.wikia.nocookie.net/dayz_gamepedia/images/a/af/PP19.png/revision/latest/scale-to-width-down/251?cb=20220127132305", + "CR-61 Skorpion": "https://static.wikia.nocookie.net/dayz_gamepedia/images/6/63/VZ61Scorpion.png/revision/latest/scale-to-width-down/222?cb=20220518204508", + "SG5-K": "https://static.wikia.nocookie.net/dayz_gamepedia/images/f/fc/MP5-K.png/revision/latest/scale-to-width-down/158?cb=20220221011343", + "USG-45": "https://static.wikia.nocookie.net/dayz_gamepedia/images/d/d7/UMP45.png/revision/latest/scale-to-width-down/153?cb=20220221002354", + }, + assaultRifles: { + "AUR A1": "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/e6/AugShort.png/revision/latest/scale-to-width-down/173?cb=20211104175243", + "AUR AX": "https://static.wikia.nocookie.net/dayz_gamepedia/images/b/be/Aug.png/revision/latest/scale-to-width-down/233?cb=20211104182427", + "KA-101": "https://static.wikia.nocookie.net/dayz_gamepedia/images/f/f2/AK101.png/revision/latest/scale-to-width-down/251?cb=20210207040122", + "KA-74": "https://static.wikia.nocookie.net/dayz_gamepedia/images/8/8b/AK74.png/revision/latest/scale-to-width-down/253?cb=20210505013141", + "KAS-74U": "https://static.wikia.nocookie.net/dayz_gamepedia/images/0/0b/AKS74U.png/revision/latest/scale-to-width-down/191?cb=20210505014222", + "KA-M": "https://static.wikia.nocookie.net/dayz_gamepedia/images/6/6c/AKM.png/revision/latest/scale-to-width-down/244?cb=20210505011614", + "LE-MAS": "https://static.wikia.nocookie.net/dayz_gamepedia/images/2/21/FAMAS.png/revision/latest/scale-to-width-down/197?cb=20210902183114", + "M16-A2": "https://static.wikia.nocookie.net/dayz_gamepedia/images/b/b3/M16-A2.png/revision/latest/scale-to-width-down/256?cb=20220221002601", + "M4-A1": "https://static.wikia.nocookie.net/dayz_gamepedia/images/a/a1/M4A1.png/revision/latest/scale-to-width-down/223?cb=20220330014851", + "SVAL": "https://static.wikia.nocookie.net/dayz_gamepedia/images/3/39/ASVAL.png/revision/latest/scale-to-width-down/256?cb=20210208015731", + "Vikhr": "https://static.wikia.nocookie.net/dayz_gamepedia/images/0/0d/Vikhr.png/revision/latest/scale-to-width-down/173?cb=20240116163108" + }, + battleRifles: { + "LAR": "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/e9/FAL.png/revision/latest/scale-to-width-down/256?cb=20220221001123", + }, + boltActionRifles: { + "CR-527": "https://static.wikia.nocookie.net/dayz_gamepedia/images/f/f0/CR527Wood.png/revision/latest/scale-to-width-down/256?cb=20220518204503 ", + "CR-550 Savanna": "https://static.wikia.nocookie.net/dayz_gamepedia/images/4/44/CR-550_Savanna.png/revision/latest/scale-to-width-down/256?cb=20220518204410", + "M70 Tundra": "https://static.wikia.nocookie.net/dayz_gamepedia/images/6/62/Winchester70.png/revision/latest/scale-to-width-down/256?cb=20220517152918", + "Mosin 91/30": "https://static.wikia.nocookie.net/dayz_gamepedia/images/a/a8/Mosin9130.png/revision/latest/scale-to-width-down/256?cb=20230126021955", + "Pioneer": "https://static.wikia.nocookie.net/dayz_gamepedia/images/6/69/Scout.png/revision/latest/scale-to-width-down/256?cb=20220518204357", + "SSG 82": "https://static.wikia.nocookie.net/dayz_gamepedia/images/1/10/SSG82.png/revision/latest/scale-to-width-down/256?cb=20220922192455", + "VS-89": "https://static.wikia.nocookie.net/dayz_gamepedia/images/e/ea/SV98.png/revision/latest/scale-to-width-down/256?cb=20240424164607", + }, + breakActionRifles: { + "BK-18": "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/cb/IZH18_Rifle.png/revision/latest/scale-to-width-down/256?cb=20220517154121", + "Blaze": "https://static.wikia.nocookie.net/dayz_gamepedia/images/8/8a/Blaze_95_Double_Rifle_Wood.png/revision/latest/scale-to-width-down/256?cb=20220517154129", + }, + leverActionRifles: { + "Repeater Carbine": "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/ce/Repeater.png/revision/latest/scale-to-width-down/256?cb=20220517154151", + }, + marksmanRifles: { + "VSD": "https://static.wikia.nocookie.net/dayz_gamepedia/images/a/a2/SVD_w._PSO-1.png/revision/latest/scale-to-width-down/256?cb=20220220235826", + "VSS": "https://static.wikia.nocookie.net/dayz_gamepedia/images/8/83/VSSVintorez.png/revision/latest/scale-to-width-down/256?cb=20210208202042", + }, + semiAutomaticRifles: { + "DMR": "https://static.wikia.nocookie.net/dayz_gamepedia/images/b/b4/M14.png/revision/latest/scale-to-width-down/350?cb=20231005142636", + "SK 59/66": "https://static.wikia.nocookie.net/dayz_gamepedia/images/f/fe/SKS.png/revision/latest/scale-to-width-down/256?cb=20220517154633", + "Sporter 22": "https://static.wikia.nocookie.net/dayz_gamepedia/images/5/5b/Sporter_22_Wood.png/revision/latest/scale-to-width-down/256?cb=20220518204154", + }, + other: { + "Crossbow": "https://static.wikia.nocookie.net/dayz_gamepedia/images/7/79/Crossbow.png/revision/latest/scale-to-width-down/212?cb=20180121164101", + "M79": "https://static.wikia.nocookie.net/dayz_gamepedia/images/b/b7/M79.png/revision/latest/scale-to-width-down/256?cb=20220521184052", + }, + }, + + weaponClassOf: (weapon) => Object.keys(module.exports.weapons).filter(c => weapon in module.exports.weapons[c])[0], +} diff --git a/src/events/guildCreate.js b/src/events/guildCreate.js new file mode 100644 index 0000000..1e97d97 --- /dev/null +++ b/src/events/guildCreate.js @@ -0,0 +1,3 @@ +module.exports = (client, guild) => { + require("../util/RegisterSlashCommands").RegisterGuildCommands(client, guild.id); +}; \ No newline at end of file diff --git a/src/events/guildMemberAdd.js b/src/events/guildMemberAdd.js new file mode 100644 index 0000000..574c6bb --- /dev/null +++ b/src/events/guildMemberAdd.js @@ -0,0 +1,17 @@ +const { EmbedBuilder } = require("discord.js"); +const { GetGuild } = require("../database/guild"); + +module.exports = async (client, member) => { + + let GuildDB = await GetGuild(client, member.guild.id); + if (!client.exists(GuildDB.welcomeChannel)) return; + const channel = client.GetChannel(GuildDB.welcomeChannel); + + if (GuildDB.serverName == "") GuildDB.serverName = "our server!" + + let embed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`**Welcome** <@${member.user.id}> to **${GuildDB.serverName}**\nUse the command to link your Discord to your gamertag.`); + + channel.send({ content: `<@${member.user.id}>`, embeds: [embed] }); +}; diff --git a/src/events/interactionCreate.js b/src/events/interactionCreate.js new file mode 100644 index 0000000..93e0cda --- /dev/null +++ b/src/events/interactionCreate.js @@ -0,0 +1,21 @@ +const { InteractionType } = require("discord.js"); +const { GetGuild } = require("../database/guild"); + + +module.exports = async (client, interaction) => { + if (interaction.type == InteractionType.ApplicationCommand) return; + /* + This file routes any menu, modal & button interactions + from any command + */ + + let GuildDB = await GetGuild(client, interaction.guildId); + const interactionName = interaction.customId.split("-")[0]; + let interactionHandler = client.interactionHandlers.get(interactionName); + + try { + interactionHandler.run(client, interaction, GuildDB); + } catch (err) { + client.sendInternalError(interaction, err); + } +} \ No newline at end of file diff --git a/src/events/ready.js b/src/events/ready.js new file mode 100644 index 0000000..504e1da --- /dev/null +++ b/src/events/ready.js @@ -0,0 +1,11 @@ +module.exports = async (client) => { + (client.Ready = true), + client.user.setActivity({ + type: client.config.Presence.type, + name: client.config.Presence.name + }); + client.log(`Successfully Logged in as ${client.user.tag}`); + client.log(`Ready to serve in ${client.channels.cache.size} channels on ${client.guilds.cache.size} servers, for a total of ${client.users.cache.size} users.`) + client.RegisterSlashCommands(); + setInterval(client.logsUpdateTimer, client.timer, client); +}; diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..bf507ff --- /dev/null +++ b/src/index.js @@ -0,0 +1,8 @@ +const { ShardingManager } = require("discord.js"); +const config = require("./config/config"); + +const manager = new ShardingManager("./bot.js", { token: config.Token }); + +manager.on("shardCreate", shard => console.log(`Launched shard ${shard.id}`)); + +manager.spawn(); diff --git a/src/util/AdminLogsHandler.js b/src/util/AdminLogsHandler.js new file mode 100644 index 0000000..83d4bfd --- /dev/null +++ b/src/util/AdminLogsHandler.js @@ -0,0 +1,68 @@ +const { EmbedBuilder } = require("discord.js"); +const { nearest } = require("../database/destinations"); +const { GetWebhook, WebhookSend } = require("./WebhookHandler"); + +module.exports = { + + SendConnectionLogs: async (client, guild, data) => { + if (!client.exists(guild.connectionLogsChannel)) return; + const channel = client.GetChannel(guild.connectionLogsChannel); + if (!channel) return; + + let newDt = await client.getDateEST(data.time); + let unixTime = Math.floor(newDt.getTime() / 1000); + + let connectionLog = new EmbedBuilder() + .setColor(data.connected ? client.config.Colors.Green : client.config.Colors.Red) + .setDescription(`**${data.connected ? "Connect" : "Disconnect"} Event - \n${data.player} ${data.connected ? "Connected" : "Disconnected"}**`); + + const NAME = "DayZ.R Admin Logs"; + const webhook = await GetWebhook(client, NAME, guild.connectionLogsChannel); + + if (!data.connected) { + if (data.lastConnectionDate != null) { + 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 }); + } + + // if (client.exists(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; + const channel = client.GetChannel(guild.connectionLogsChannel); + if (!channel) return; // Ensure channel exists + + const newDt = await client.getDateEST(data.time); + const diffSeconds = Math.round((newDt.getTime() - data.lastDamageDate.getTime()) / 1000); + + // If diff is greater than configured time in minutes, not a combat log + // or if death after last combat + if (diffSeconds > (data.combatLogTimer * 60)) return; + if (data.lastDamageDate <= data.lastDeathDate) return; + + // If lastHitBy (attacker) died after shooting this player + // then it does not count as combat logging, (the combat ended due to death) + let attacker = await client.dbo.collection("players").findOne({ "gamertag": data.lastHitBy }); + if (attacker.lastDeathDate > data.lastDamageDate) return; + + let unixTime = Math.floor(newDt.getTime() / 1000); + const destination = nearest(data.pos, guild.Nitrado.Mission); + + 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]})**\n${destination}`); + + const NAME = "DayZ.R Admin Logs"; + const webhook = await GetWebhook(client, NAME, guild.connectionLogsChannel); + + let content = { embeds: [combatLog] }; + if (client.exists(guild.adminRole)) content.content = `<@&${guild.adminRole}>`; + WebhookSend(client, webhook, content); + // return channel.send({ embeds: [combatLog] }); + } +}; diff --git a/src/util/AlarmsHandler.js b/src/util/AlarmsHandler.js new file mode 100644 index 0000000..f4e0700 --- /dev/null +++ b/src/util/AlarmsHandler.js @@ -0,0 +1,249 @@ +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"); + +// 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!**`)] }); + + client.dbo.collection("guilds").updateOne({ "server.serverID": guild.serverID }, { + $pull: { + "server.events": e + } + }, (err, res) => { + if (err) return client.sendError(client.GetChannel(guild.adminLogsChannel), err); + }); +} + +const HandlePlayerTrackEvent = async (client, guild, e) => { + if (!client.exists(e.channel)) return ExpireEvent(client, guild, e); // Expire event since it has invalid channel. + const channel = client.GetChannel(e.channel); + if (!channel) return; + + let player = await client.dbo.collection("players").findOne({ "gamertag": e.gamertag }); + + let newDt = await client.getDateEST(player.time); + let unixTime = Math.floor(newDt.getTime() / 1000); + + const destination = nearest(player.pos, guild.Nitrado.Mission); + + const trackEvent = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`**${e.name} Event**\n${e.gamertag} was located at **[${player.pos[0]}, ${player.pos[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${player.pos[0]};${player.pos[1]})** at \n${destination}`); + + const NAME = "DayZ.R Player Tracker"; + const webhook = await GetWebhook(client, NAME, e.channel); + + let content = { embeds: [trackEvent] }; + if (client.exists(guild.adminRole)) content.content = `<@&${e.role}>`; + WebhookSend(client, webhook, content); + + // if (e.role) channel.send({ content: `<@&${e.role}>`, embeds: [trackEvent] }); + // else channel.send({ embeds: [trackEvent] }); + + let now = new Date(); + let diff = ((now - e.creationDate) / 1000) / 60; + let minutesBetweenDates = Math.abs(Math.round(diff)); + + if (minutesBetweenDates >= e.time) ExpireEvent(client, guild, e); +} + +// Public functions (called externally) + +module.exports = { + + HandleAlarmsAndUAVs: async (client, guild, data) => { + + for (let i = 0; i < guild.alarms.length; i++) { + let alarm = guild.alarms[i]; + let now = new Date(); + if (alarm.uavExpire != null && alarm.uavExpire < now) alarm.disabled = false; + if (alarm.disabled) continue; // ignore if alarm is disabled due to emp + 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 distance = Math.sqrt(Math.pow(diff[0], 2) + Math.pow(diff[1], 2)).toFixed(2) + + if (distance < alarm.radius) { + + let newDt = await client.getDateEST(data.time); + let unixTime = Math.floor(newDt.getTime() / 1000); + + if (!client.alarmPingQueue.get(guild.serverID).has(alarm.channel)) client.alarmPingQueue.get(guild.serverID).set(alarm.channel, new Map()); + let route = alarm.mute ? null : alarm.role; + if (!client.alarmPingQueue.get(guild.serverID).get(alarm.channel).has(route)) client.alarmPingQueue.get(guild.serverID).get(alarm.channel).set(route, []); + + if (alarm.rules.includes["ban_on_entry"]) { + client.alarmPingQueue.get(guild.serverID).get(alarm.channel).get(route).push( + new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`**Zone Ping - **\n**${data.player}** was located within **${distance} meters** of the Zone **${alarm.name}** __and has been banned.__`) + .addFields({ name: "**Location**", value: `**[${data.pos[0]}, ${data.pos[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${data.pos[0]};${data.pos[1]})**`, inline: false }) + ); + + BanPlayer(client, data.player); + return; + } + + client.alarmPingQueue.get(guild.serverID).get(alarm.channel).get(route).push( + new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`**Zone Ping - **\n**${data.player}** was located within **${distance} meters** of the Zone **${alarm.name}**`) + .addFields({ name: "**Location**", value: `**[${data.pos[0]}, ${data.pos[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${data.pos[0]};${data.pos[1]})**`, inline: false }) + ); + + return; + } + } + + for (let i = 0; i < guild.uavs.length; i++) { + let uav = guild.uavs[i]; + + let diff = [Math.round(uav.origin[0] - data.pos[0]), Math.round(uav.origin[1] - data.pos[1])]; + let distance = Math.sqrt(Math.pow(diff[0], 2) + Math.pow(diff[1], 2)).toFixed(2); + + if (distance < uav.radius) { + let newDt = await client.getDateEST(data.time); + let unixTime = Math.floor(newDt.getTime() / 1000); + + const destination = nearest(data.pos, guild.Nitrado.Mission); + + let uavEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`**UAV Detection - **\n**${data.player}** was spotted in the UAV zone at **[${data.pos[0]}, ${data.pos[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${data.pos[0]};${data.pos[1]})\n${destination}**`) + + client.users.fetch(uav.owner, false).then((user) => { + user.send({ embeds: [uavEmbed] }); + }); + } + } + }, + + HandleExpiredUAVs: async (client, guild) => { + let uavs = guild.uavs; + let update = false; + + for (let i = 0; i < uavs.length; i++) { + let uav = uavs[i]; + + let now = new Date(); + let diff = Math.round((now.getTime() - uav.creationDate.getTime()) / 1000 / 60); // diff minutes + + if (diff <= 30) continue; + + uavs.splice(i, 1); + update = true; + + let expired = new EmbedBuilder().setColor(client.config.Colors.Red).setDescription("**Low Battery**\nUAV has run out of battery and is no longer active."); + + client.users.fetch(uav.owner, false).then((user) => { + user.send({ embeds: [expired] }); + }); + } + + if (update) { + client.dbo.collection("guilds").updateOne({ "server.serverID": guild.serverID }, { $set: { "server.uavs": uavs } }, (err, res) => { + if (err) return client.sendError(client.GetChannel(guild.adminLogsChannel), err); + }); + } + }, + + KillInAlarm: async (client, guildId, data) => { + + let guild = await GetGuild(client, guildId); + + for (let i = 0; i < guild.alarms.length; i++) { + let alarm = guild.alarms[i]; + if (alarm.disabled || !alarm.rules.includes("ban_on_kill")) continue; // ignore if alarm is disabled or not ban on kill; + if (alarm.ignoredPlayers.includes(data.killerID)) continue; + + let diff = [Math.round(alarm.origin[0] - data.killerPOS[0]), Math.round(alarm.origin[1] - data.killerPOS[1])]; + let distance = Math.sqrt(Math.pow(diff[0], 2) + Math.pow(diff[1], 2)).toFixed(2) + + if (distance < alarm.radius) { + const channel = client.GetChannel(alarm.channel); + if (!channel) continue; + + let newDt = await client.getDateEST(data.time); + let unixTime = Math.floor(newDt.getTime() / 1000); + + let alarmEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`**Zone Ping - **\n**${data.killer}** was located within **${distance} meters** of the Zone **${alarm.name}** __and has been banned for killing **${data.victim}**.__`) + .addFields({ name: "**Location**", value: `**[${data.killerPOS[0]}, ${data.killerPOS[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${data.killerPOS[0]};${data.killerPOS[1]})**`, inline: false }) + + const NAME = "DayZ.R Zone Alert"; + const webhook = await GetWebhook(client, NAME, alarm.channel); + + let content = { content: `<@&${alarm.role}>`, embeds: [alarmEmbed] }; + WebhookSend(client, webhook, content); + + // channel.send({ content: `<@&${alarm.role}>`, embeds: [alarmEmbed] }); + + BanPlayer(client, data.killer); + break; + } + } + return; + }, + + PlaceFireplaceInAlarm: async (client, guild, line) => { + + let fireplacePlacement = /(.*) \| Player \"(.*)\" \(id=(.*) pos=<(.*)>\) placed Fireplace/g; + let data = [...line.matchAll(fireplacePlacement)][0]; + if (!data) return; + + let info = { + time: data[1], + player: data[2], + playerID: data[3], + playerPOS: data[4].split(", ").map(v => parseFloat(v)), + }; + + for (let i = 0; i < guild.alarms.length; i++) { + let alarm = guild.alarms[i]; + if (alarm.disabled || !alarm.rules.includes("ban_on_fireplace_placement")) continue; + if (alarm.ignoredPlayers.includes(info.playerID)) continue; + + let diff = [Math.round(alarm.origin[0] - info.playerPOS[0]), Math.round(alarm.origin[1] - info.playerPOS[1])]; + let distance = Math.sqrt(Math.pow(diff[0], 2) + Math.pow(diff[1], 2)).toFixed(2); + + if (distance < alarm.radius) { + const channel = client.GetChannel(alarm.channel); + if (!channel) return; + + let newDt = await client.getDateEST(info.time); + let unixTime = Math.floor(newDt.getTime() / 1000); + + let alarmEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`**Zone Ping - **\n**${info.player}** was located within **${distance} meters** of the Zone **${alarm.name}** __and has been banned for **placing a fireplace**.__`) + .addFields({ name: "**Location**", value: `**[${info.playerPOS[0]}, ${info.playerPOS[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${info.playerPOS[0]};${info.playerPOS[1]})**`, inline: false }) + + const NAME = "DayZ.R Zone Alert"; + const webhook = await GetWebhook(client, NAME, alarm.channel); + + let content = { content: `<@&${alarm.role}>`, embeds: [alarmEmbed] }; + WebhookSend(client, webhook, content); + + // channel.send({ content: `<@&${alarm.role}>`, embeds: [alarmEmbed] }); + + BanPlayer(client, info.player); + break; + } + } + return; + }, + + HandleEvents: async (client, guild) => { + for (let i = 0; i < guild.events.length; i++) { + let event = guild.events[i]; + if (event.type == "player-track") HandlePlayerTrackEvent(client, guild, event); + } + }, +} diff --git a/src/util/CombatRatingHandler.js b/src/util/CombatRatingHandler.js new file mode 100644 index 0000000..e15cca5 --- /dev/null +++ b/src/util/CombatRatingHandler.js @@ -0,0 +1,6 @@ +module.exports = { + calculateNewCombatRating: (Ra, Rb, score) => { + const Ea = 1 / (1 + Math.pow(10, ((Rb - Ra) / 400))); + return Math.round(Ra + 32 * (score - Ea)); + }, +} \ No newline at end of file diff --git a/src/util/CommandOptionTypes.js b/src/util/CommandOptionTypes.js new file mode 100644 index 0000000..afa4a82 --- /dev/null +++ b/src/util/CommandOptionTypes.js @@ -0,0 +1,15 @@ +module.exports = { + CommandOptionTypes: { + 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, + } +}; \ No newline at end of file diff --git a/src/util/Cryptic.js b/src/util/Cryptic.js new file mode 100644 index 0000000..ef1b24f --- /dev/null +++ b/src/util/Cryptic.js @@ -0,0 +1,19 @@ +const crypto = require("crypto"); + +module.exports = { + encrypt: (data, EncryptionMethod, Key, EncryptionIV) => { + const cipher = crypto.createCipheriv(EncryptionMethod, Key, EncryptionIV) + return Buffer.from( + cipher.update(data, "utf8", "hex") + cipher.final("hex") + ).toString("base64") // Encrypts data and converts to hex and base64 + }, + + decrypt: (data, EncryptionMethod, Key, EncryptionIV) => { + const buff = Buffer.from(data, "base64") + const decipher = crypto.createDecipheriv(EncryptionMethod, Key, EncryptionIV) + return ( + decipher.update(buff.toString("utf8"), "hex", "utf8") + + decipher.final("utf8") + ) // Decrypts data and converts to utf8 + } +} \ No newline at end of file diff --git a/src/util/KillfeedHandler.js b/src/util/KillfeedHandler.js new file mode 100644 index 0000000..b9c53a9 --- /dev/null +++ b/src/util/KillfeedHandler.js @@ -0,0 +1,290 @@ +const { EmbedBuilder } = require("discord.js"); +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 { weapons, weaponClassOf } = require("../database/weapons"); +const { GetWebhook, WebhookSend } = require("../util/WebhookHandler"); + +const Templates = { + Killed: 1, + HitBy: 2, + HitByAndDead: 3, + Explosion: 4, + LandMine: 5, + Melee: 6, + Vehicle: 7, +}; + +const TemplateExpressions = { + 1: /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\) killed by Player \"(.*)\" \(id=(.*) pos=<(.*)>\) with (.*) from (.*) meters /g, + 2: /(.*) \| Player \"(.*)\" \(id=(.*) pos=<(.*)>\)\[HP\: (.*)\] hit by Player \"(.*)\" \(id=(.*) pos=<(.*)>\) into (.*) for (.*) damage \((.*)\) with (.*) from (.*) meters /g, + 3: /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\)\[HP\: (.*)\] hit by Player \"(.*)\" \(id=(.*) pos=<(.*)>\) into (.*) for (.*) damage \((.*)\) with (.*) from (.*) meters /g, + 4: /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\) killed by with (.*)/g, + 5: /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\) killed by LandMineTrap/g, + 6: /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\)\[HP\: (.*)\] hit by Player \"(.*)\" \(id=(.*) pos=<(.*)>\) into (.*) for (.*) damage \((.*)\) with (.*)/g, + 7: /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\)\[HP\: (.*)\] hit by (.*) with TransportHit/g, +}; + +const Vehicles = { + CivilianSedan: "White Olga", + CivilianSedan_Black: "Black Olga", + CivilianSedan_Wine: "Wine Olga", + + Hatchback_02: "Red Gunter", + Hatchback_02_Black: "Black Gunter", + Hatchback_02_Blue: "Blue Gunter", + + OffroadHatchBack: "Green ADA 4x4", + OffroadHatchBack_Blue: "Blue ADA 4x4", + OffroadHatchBack_White: "White ADA 4x4", + + Sedan_02: "Yellow Sarka", + Sedan_02_Grey: "Grey Sarka", + Sedan_02_Red: "Red Sarka", + + Truck_01_Covered: "Green V3S Truck", + Truck_01_Covered_Blue: "Blue V3S Truck", + Truck_01_Covered_Orange: "Orange V3S Truck", + + Offroad_02: "M1025 Humvee" +}; + +module.exports = { + + // Update last death date for non PVP deaths + UpdateLastDeathDate: async (NitradoServerID, client, line) => { + let killedByZmb = /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\) killed by (.*)/g; + let diedTemplate = /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\) died\. Stats> Water: (.*) Energy: (.*) Bleed sources: (.*)/g; + + let data = line.includes(">) died.") ? [...line.matchAll(diedTemplate)][0] : [...line.matchAll(killedByZmb)][0]; + if (!data) return; + + let info = { + time: data[1], + victim: data[2], + victimID: data[3], + victimPOS: data[4].split(", ").map(v => parseFloat(v)), + }; + + 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); + + victimStat.lastDeathDate = newDt; + + await UpdatePlayer(client, victimStat); + return + }, + + HandleKillfeed: async (NitradoServerID, client, guild, line) => { + + const NAME = "DayZ.R Killfeed"; + const channel = client.GetChannel(guild.killfeedChannel); + + const killedBy = line.includes("hit by Player") && line.includes("(DEAD)") && line.includes("meters") ? Templates.HitByAndDead : + line.includes("hit by Player") && !line.includes("meters") ? Templates.Melee : // Missing meters indicates it was a melee attack. + line.includes("hit by Player") ? Templates.HitBy : + line.includes("killed by Player") ? Templates.Killed : + line.includes("TransportHit") ? Templates.Vehicle : + line.includes("killed by LandMineTrap") ? Templates.LandMine : Templates.Explosion; + + let data = [...line.matchAll(TemplateExpressions[killedBy])][0]; + + if (!data) return; + + // Create base data + let info = { + time: data[1], + victim: data[2], + victimID: data[3], + victimPOS: data[4].split(", ").map(v => parseFloat(v)), + }; + + // Add additional data + if ([Templates.HitBy, Templates.HitByAndDead, Templates.Melee].includes(killedBy)) { + info.killer = data[6]; + info.killerID = data[7]; + info.killerPOS = data[8].split(", ").map(v => parseFloat(v)); + info.bodyPart = data[9]; + info.damage = data[10]; + info.weapon = data[12]; + info.distance = killedBy == Templates.Melee ? 0 : parseFloat(data[13]).toFixed(2); + } else if (killedBy == Templates.Killed) { + info.killer = data[5]; + info.killerID = data[6]; + info.killerPOS = data[7].split(", ").map(v => parseFloat(v)); + info.weapon = data[8]; + info.distance = parseFloat(data[9]).toFixed(2); + } + else if (killedBy == Templates.Vehicle) info.causeOfDeath = data[6]; + else if (killedBy == Templates.Explosion) info.causeOfDeath = data[5]; + else return; // Unknown template; + + 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 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); + victimStat.deaths++; + victimStat.deathStreak++; + victimStat.worstDeathStreak = victimStat.deathStreak > victimStat.worstDeathStreak ? victimStat.deathStreak : victimStat.worstDeathStreak; + victimStat.KDR = victimStat.kills / (victimStat.deaths == 0 ? 1 : victimStat.deaths); // prevent division by 0 + victimStat.killStreak = 0; + victimStat.lastDeathDate = newDt; + + const cod = killedBy == Templates.LandMine ? `Land Mine Trap` : + killedBy == Templates.Vehicle ? Vehicles[info.causeOfDeath] : info.causeOfDeath; + const coord = showCoords ? `\n***Location [${info.victimPOS[0]}, ${info.victimPOS[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${info.victimPOS[0]};${info.victimPOS[1]})***\n${destination}` : ""; + const killMessage = killedBy == Templates.Vehicle ? "run over by" : "blew up from"; + + const killEvent = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`**Death Event** - \n**${info.victim}** ${killMessage} a **${cod}.**${coord}`); + + await UpdatePlayer(client, victimStat); + + if (!channel) return; + const webhook = await GetWebhook(client, NAME, guild.killfeedChannel); + WebhookSend(client, webhook, { embeds: [killEvent] }); + + // if (client.exists(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; + + 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); + + let weapon = info.weapon.includes("Engraved") ? info.weapon.split("Engraved ")[1] : + info.weapon.includes("Sawed-off") ? info.weapon.split("Sawed-off ")[1] : + info.weapon; + + // Update killer stats + killerStat.kills++; + killerStat.killStreak++; + killerStat.bestKillStreak = killerStat.killStreak > killerStat.bestKillStreak ? killerStat.killStreak : killerStat.bestKillStreak; + 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; + killerStat.weaponStats[weapon].kills++; + + // Update victim stats + victimStat.deaths++; + victimStat.deathStreak++; + victimStat.worstDeathStreak = victimStat.deathStreak > victimStat.worstDeathStreak ? victimStat.deathStreak : victimStat.worstDeathStreak; + 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; + 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); + + // 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); + victimStat.combatRating = calculateNewCombatRating(victimStat.combatRating, killerStat.combatRating, 0); + + // Update combat rating records + if (killerStat.combatRating > killerStat.highestCombatRating) killerStat.highestCombatRating = killerStat.combatRating; + if (victimStat.combatRating < victimStat.lowestCombatRating) victimStat.lowestCombatRating = victimStat.combatRating; + if (killerStat.combatRatingHistory.length >= 12) killerStat.combatRatingHistory = killerStat.combatRatingHistory.slice(1); // Remove first element (limits history to length 12) + if (victimStat.combatRatingHistory.length >= 12) victimStat.combatRatingHistory = victimStat.combatRatingHistory.slice(1); // Remove first element (limits history to length 12) + killerStat.combatRatingHistory.push(killerStat.combatRating); + victimStat.combatRatingHistory.push(victimStat.combatRating); + + let kdiff = killerStat.combatRating - killerOldRating; + let vdiff = victimStat.combatRating - victimOldRating; + + let receivedBounty = null; + if (victimStat.bounties.length > 0 && killerStat.discordID != "") { + let totalBounty = 0; + for (let i = 0; i < victimStat.bounties.length; i++) { + totalBounty += victimStat.bounties[i].value; + } + + let banking = await client.dbo.collection("users").findOne({ "user.userID": killerStat.discordID }).then(banking => banking); + + if (!banking) { + banking = await createUser(interaction.member.user.id, guild.serverID, guild.startingBalance, client) + if (!client.exists(banking)) return client.sendInternalError(interaction, err); + } + banking = banking.user; + + if (!client.exists(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"); + } + + const newBalance = banking.guilds[guild.serverID].balance + totalBounty; + + await client.dbo.collection("users").updateOne({ "user.userID": killerStat.discordID }, { + $set: { + [`user.guilds.${guild.serverID}.balance`]: newBalance, + } + }, (err, res) => { + if (err) return client.sendError(client.GetChannel(guild.killfeedChannel), `Killfeed Error: Updating killer bank balance\n${err}`); + }); + + receivedBounty = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`<@${killerStat.discordID}> received **$${totalBounty.toFixed(2).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}** in bounty rewards.`); + + victimStat.bounties = []; // clear bounties after claimed + victimStat.bountiesLength = 0; + } + + await UpdatePlayer(client, victimStat); + await UpdatePlayer(client, killerStat); + + const header = `**Kill Event** - \n**${info.killer}** killed **${info.victim}**`; + const killData = `\n> **__Kill Data__**\n> Weapon: \` ${info.weapon} \`\n> Distance: \` ${info.distance}m \`\n> Body Part: \` ${info.bodyPart != undefined ? info.bodyPart.split("(")[0] : "N/A"} \`\n> Damage: \` ${info.damage != undefined ? info.damage : "N/A"} \``; + const killerStatsView = `\n**Killer Rating** (${kdiff >= 0 ? "+" : ""}${kdiff}) ${killerStat.combatRating}\n${killerStat.KDR.toFixed(2)} K/D - ${killerStat.kills} Kill${(killerStat.kills == 0 || killerStat.kills > 1) ? "s" : ""} - Killstreak: ${killerStat.killStreak}`; + const victimStatsView = `\n**Victim Rating** (${vdiff >= 0 ? "+" : ""}${vdiff}) ${victimStat.combatRating}\n${victimStat.KDR.toFixed(2)} K/D - ${victimStat.deaths} Death${victimStat.deaths == 0 || victimStat.deaths > 1 ? "s" : ""} - Deathstreak: ${victimStat.deathStreak}`; + const coord = showCoords ? `\n***Location [${info.victimPOS[0]}, ${info.victimPOS[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${info.victimPOS[0]};${info.victimPOS[1]})***\n${destination}` : ""; + + let killEvent = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setDescription(`${header}${killData}${killerStatsView}${victimStatsView}${coord}`); + + if (showWeapon) { + let weaponClass = weaponClassOf(weapon); + killEvent.setThumbnail(weapons[weaponClass][weapon]) + } + + if (!channel) return; + + 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 (client.exists(channel)) await channel.send({ embeds: [killEvent] }); + // if (client.exists(receivedBounty) && client.exists(channel)) await channel.send({ content: `<@${killerStat.discordID}>`, embeds: [receivedBounty] }); + + return; + } +} \ No newline at end of file diff --git a/src/util/Logger.js b/src/util/Logger.js new file mode 100644 index 0000000..49adb16 --- /dev/null +++ b/src/util/Logger.js @@ -0,0 +1,40 @@ +const winston = require("winston"); +const colors = require("colors"); + +class Logger { + constructor(LoggingFile) { + this.logger = winston.createLogger({ + transports: [new winston.transports.File({ filename: LoggingFile })], + }); + } + + log(Text) { + let d = new Date(); + this.logger.log({ + level: "info", + message: + `${d.getHours()}:${d.getMinutes()} - ${d.getMonth() + 1}:${d.getDate()}:${d.getFullYear()} | Info: ` + Text + }); + console.log( + colors.green( + `${d.getMonth() + 1}:${d.getDate()}:${d.getFullYear()} - ${d.getHours()}:${d.getMinutes()}` + ) + colors.yellow(" | Info: " + Text) + ); + } + + error(Text) { + let d = new Date(); + this.logger.log({ + level: "error", + message: + `${d.getHours()}:${d.getMinutes()} - ${d.getMonth() + 1}:${d.getDate()}:${d.getFullYear()} | Error: ` + Text + }); + console.log( + colors.green( + `${d.getMonth() + 1}:${d.getDate()}:${d.getFullYear()} - ${d.getHours()}:${d.getMinutes()}` + ) + colors.yellow(" | Error: ") + colors.red(Text) + ); + } +} + +module.exports = Logger; \ No newline at end of file diff --git a/src/util/LogsHandler.js b/src/util/LogsHandler.js new file mode 100644 index 0000000..25fc86c --- /dev/null +++ b/src/util/LogsHandler.js @@ -0,0 +1,265 @@ +const { EmbedBuilder } = require("discord.js"); +const { HandleAlarmsAndUAVs } = require("./AlarmsHandler"); +const { SendConnectionLogs, DetectCombatLog } = require("./AdminLogsHandler"); +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"); + +module.exports = { + + HandlePlayerLogs: async (NitradoServerID, client, GuildDB, line, combatLogTimer = 5) => { + + const connectTemplate = /(.*) \| Player \"(.*)\" is connected \(id=(.*)\)/g; + const disconnectTemplate = /(.*) \| Player \"(.*)\"\(id=(.*)\) has been disconnected/g; + const positionTemplate = /(.*) \| Player \"(.*)\" \(id=(.*) pos=<(.*)>\)/g; + const damageTemplate = /(.*) \| Player \"(.*)\" \(id=(.*) pos=<(.*)>\)\[HP\: (.*)\] hit by Player \"(.*)\" \(id=(.*) pos=<(.*)>\) into (.*) for (.*) damage \((.*)\) with (.*) from (.*) meters /g; + const deadTemplate = /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\)\[HP\: (.*)\] hit by Player \"(.*)\" \(id=(.*) pos=<(.*)>\) into (.*) for (.*) damage \((.*)\) with (.*) from (.*) meters /g; + + if (line.includes(" connected")) { + const data = [...line.matchAll(connectTemplate)][0]; + if (!data) return; + + const info = { + time: data[1], + player: data[2], + playerID: data[3], + }; + + if (!client.exists(info.player) || !client.exists(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); + const newDt = await client.getDateEST(info.time); + + playerStat.lastConnectionDate = newDt; + playerStat.connected = true; + if (!client.exists(playerStat.connections)) playerStat.connections = 0; + playerStat.connections++; + + // Track adjusted sessions this instance has handled (e.g. no bot crashes or restarts). + if (client.playerSessions.get(NitradoServerID).has(info.playerID)) { + // Player is already in a session, update the session"s end time. + const session = client.playerSessions.get(NitradoServerID).get(info.playerID); + session.endTime = newDt; // Update end time. + } else { + // Player is not in a session, create a new session. + const newSession = { + startTime: newDt, + endTime: null, // Initialize end time as null. + }; + client.playerSessions.get(NitradoServerID).set(info.playerID, newSession); + } + + await SendConnectionLogs(client, GuildDB, { + time: info.time, + player: info.player, + connected: true, + lastConnectionDate: null, + }); + + await UpdatePlayer(client, playerStat); + } + + if (line.includes(" disconnected")) { + const data = [...line.matchAll(disconnectTemplate)][0]; + if (!data) return; + + const info = { + time: data[1], + player: data[2], + playerID: data[3], + }; + + if (!client.exists(info.player) || !client.exists(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); + + let oldUnixTime; + let sessionTimeSeconds; + const newDt = await client.getDateEST(info.time); + const unixTime = Math.round(newDt.getTime() / 1000); // Seconds + if (playerStat.lastConnectionDate != null) { + oldUnixTime = Math.round(playerStat.lastConnectionDate.getTime() / 1000); // Seconds + sessionTimeSeconds = unixTime - oldUnixTime; + } else sessionTimeSeconds = 0; + if (!client.exists(playerStat.longestSessionTime)) playerStat.longestSessionTime = 0; + + playerStat.totalSessionTime = playerStat.totalSessionTime + sessionTimeSeconds; + playerStat.lastSessionTime = sessionTimeSeconds; + playerStat.longestSessionTime = sessionTimeSeconds > playerStat.longestSessionTime ? sessionTimeSeconds : playerStat.longestSessionTime; + playerStat.lastDisconnectionDate = newDt; + playerStat.connected = false; + + await SendConnectionLogs(client, GuildDB, { + time: info.time, + player: info.player, + connected: false, + lastConnectionDate: playerStat.lastConnectionDate, + }); + + if (combatLogTimer != 0) { + await DetectCombatLog(client, GuildDB, { + time: info.time, + player: info.player, + pos: playerStat.pos, + lastDamageDate: playerStat.lastDamageDate, + lastHitBy: playerStat.lastHitBy, + lastDeathDate: playerStat.lastDeathDate, + combatLogTimer: combatLogTimer, + }); + } + + await UpdatePlayer(client, playerStat); + } + + if (line.includes("pos=<") && !line.includes("hit by")) { + const data = [...line.matchAll(positionTemplate)][0]; + if (!data) return; + + const info = { + time: data[1], + player: data[2], + playerID: data[3], + pos: data[4].split(", ").map(v => parseFloat(v)) + }; + + if (!client.exists(info.player) || !client.exists(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); + + playerStat.lastPos = playerStat.pos; + playerStat.pos = info.pos; + playerStat.lastTime = playerStat.time; + playerStat.lastDate = playerStat.date; + playerStat.time = `${info.time} EST`; + playerStat.date = await client.getDateEST(info.time); + + if (line.includes("hit by") || line.includes("killed by")) return; // prevent additional information from being fed to Alarms & UAVs + + await HandleAlarmsAndUAVs(client, GuildDB, { + time: info.time, + player: info.player, + playerID: info.playerID, + pos: info.pos, + }); + + await UpdatePlayer(client, playerStat) + } + + if (line.includes("hit by Player")) { + const data = line.includes("(DEAD)") ? [...line.matchAll(deadTemplate)][0] : [...line.matchAll(damageTemplate)][0]; + if (!data) return; + + const info = { + time: data[1], + player: data[2], + playerID: data[3], + attacker: data[6], + attackerID: data[7], + bodyPart: data[9].split("(")[0], + weapon: data[12], + }; + + if (!client.exists(info.player) || !client.exists(info.playerID) || !client.exists(info.attacker) || !client.exists(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); + + 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); + + // Update in depth PVP stats if non Melee weapon + if (info.weapon.includes("Engraved")) info.weapon = info.weapon.split("Engraved ")[1]; + if (info.weapon.includes("Sawed-off")) info.weapon = info.weapon.split("Sawed-off ")[1]; + if (info.weapon in playerStat.weaponStats) { + playerStat.timesShot++; + playerStat.timesShotPerBodyPart[info.bodyPart]++; + if (!client.exists(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); + attackerStat.weaponStats[info.weapon].shotsLanded++; + attackerStat.weaponStats[info.weapon].shotsLandedPerBodyPart[info.bodyPart]++; + } + + await UpdatePlayer(client, playerStat); + await UpdatePlayer(client, attackerStat); + } + + return; + }, + + HandleActivePlayersList: async (nitrado_cred, client, guild) => { + client.activePlayersTick = 0; // reset hour tick + + if (!client.exists(guild.activePlayersChannel)) return; + const channel = client.GetChannel(guild.activePlayersChannel); + if (!channel) return; + + const data = await FetchServerSettings(nitrado_cred, client, "HandleActivePlayersList"); // Fetch server status + const e = data && data !== 1; // Check if data exists + + const hostname = e ? data.data.gameserver.settings.config.hostname : "N/A"; + const map = Missions[data.data.gameserver.settings.config.mission]; + const status = e ? data.data.gameserver.status : "N/A"; + const slots = e ? data.data.gameserver.slots : "N/A"; + const playersOnline = e ? data.data.gameserver.query.player_current : undefined; + + const Statuses = { + "started": { emoji: "🟢", text: "Active" }, + "stopped": { emoji: "🔴", text: "Stopped" }, + "restarting": { emoji: "↻", text: "Restarting" }, + }; + + const emojiStatus = Statuses[status].emoji || "❓"; + const textStatus = Statuses[status].text || "Unknown Status"; + + let activePlayers = await client.dbo.collection("players").find({ "nitradoServerID": nitrado_cred.ServerID }).toArray().filter(player => player.connected); + + let des = activePlayers.length > 0 ? `` : `**No Players Online**`; + for (let i = 0; i < activePlayers.length; i++) { + des += `**- ${activePlayers[i].gamertag}**\n`; + } + + const nodes = activePlayers.length === 0; + const serverEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTitle(`Online List - \` ${playersOnline === undefined ? activePlayers.length : playersOnline} \` Player${playersOnline !== 1 ? "s" : ""} Online`) + .addFields( + { name: "Server:", value: `\` ${hostname} \``, inline: false }, + { name: "Map:", value: `\` ${map} \``, inline: true }, + { name: "Status:", value: `\` ${emojiStatus} ${textStatus} \``, inline: true }, + { name: "Slots:", value: `\` ${slots} \``, inline: true } + ); + + const activePlayersEmbed = new EmbedBuilder() + .setColor(client.config.Colors.Default) + .setTimestamp() + .setTitle(`Players Online:`) + .setDescription(des || (nodes ? "No Players Online :(" : "")); + + const NAME = "DayZ.R Admin Logs"; + const webhook = await GetWebhook(client, NAME, guild.connectionLogsChannel); + + let id = client.playerListMsgIds.get(guild.serverID); + if (id == "") { + id = await WebhookSend(client, webhook, { embeds: [serverEmbed, activePlayersEmbed] }).id; + client.playerListMsgIds.set(guild.serverID, id); + } else { + WebhookMessageEdit(client, webhook, id, { embeds: [serverEmbed, activePlayersEmbed] }); + } + } +}; diff --git a/src/util/NitradoAPI.js b/src/util/NitradoAPI.js new file mode 100644 index 0000000..efde904 --- /dev/null +++ b/src/util/NitradoAPI.js @@ -0,0 +1,311 @@ +const { finished } = require("stream/promises"); +const concat = require("concat-stream"); +const { Readable } = require("stream"); +const FormData = require("form-data"); +const fs = require("fs"); +const maxRetries = 5; +const retryDelay = 5000; // 5 seconds + +// Private functions (only called locally) + +const UploadNitradoFile = async (nitrado_cred, client, remoteDir, remoteFilename, localFileDir) => { + for (let retries = 0; retries <= maxRetries; retries++) { + try { + const res = await fetch(`https://api.nitrado.net/services/${nitrado_cred.ServerID}/gameservers/file_server/upload?` + new URLSearchParams({ + path: remoteDir, + file: remoteFilename + }), { + method: "POST", + headers: { + "Authorization": nitrado_cred.Auth + }, + }).then(response => response.json()); + + let contents = fs.readFileSync(localFileDir, "utf8"); + + const uploadRes = await fetch(res.data.token.url, { + method: "POST", + headers: { + "Content-Type": "application/binary", + token: res.data.token.token + }, + body: contents, + }) + if (!uploadRes.ok) { + client.error(`Failed to upload file to Nitrado (${nitrado_cred.ServerID}): status: ${uploadRes.status}, message: ${res.statusText}: UploadNitradoFile`); + if (retries === 2) return 1; // Return error status on the second failed status code. + } else { + return uploadRes; + } + } catch (error) { + client.error(`UploadNitradoFile: Error connecting to server (${nitrado_cred.ServerID}): ${error.message}`); + if (retries === maxRetries) { + client.error(`UploadNitradoFile: Error connecting to server (${nitrado_cred.ServerID}) after ${maxRetries} retries`); + return 1; + } + } + await new Promise(resolve => setTimeout(resolve, retryDelay)); // Delay before retrying + } +} + +const HandlePlayerBan = async (nitrado_cred, client, gamertag, ban) => { + const data = await module.exports.FetchServerSettings(nitrado_cred, client, "HandlePlayerBan"); // Fetch server status + + if (data && data != 1) { + let bans = data.data.gameserver.settings.general.bans; + if (ban) bans += `\r\n${gamertag}`; + else if (!ban) bans = bans.replace(gamertag, ""); + else client.error("Incorrect Ban Option: HandlePlayerBan"); + + let category = "general"; + let key = "bans"; + return await module.exports.PostServerSettings(nitrado_cred, client, category, key, bans); // returns 1 (failed) or 0 (not failed) + } +} + +const GetRemoteDir = async (nitrado_cred, client, dir = "") => { + const dirParam = client.exists(dir) ? `?dir=${dir}` : ""; + for (let retries = 0; retries <= maxRetries; retries++) { + try { + const res = await fetch(`https://api.nitrado.net/services/${nitrado_cred.ServerID}/gameservers/file_server/list${dirParam}`, { + headers: { + "Authorization": nitrado_cred.Auth + } + }).then(response => + response.json().then(data => data) + ).then(res => res); + + if (res.status === "error") return 1; + + return res.data.entries; + } catch (error) { + client.error(`GetRemoteDir: Error connecting to server (${nitrado_cred.ServerID}): ${error}`); + if (retries == maxRetries) { + client.error(`GetRemoteDir: Error connecting to server (${nitrado_cred.ServerID}) after ${maxRetries} retries`); + return 1; + } + } + await new Promise(resolve => setTimeout(resolve, retryDelay)); // Delay before retrying + } +} + +// Public functions (called externally) + +module.exports = { + + DownloadNitradoFile: async (nitrado_cred, client, filename, outputDir) => { + for (let retries = 0; retries <= maxRetries; retries++) { + try { + const res = await fetch(`https://api.nitrado.net/services/${nitrado_cred.ServerID}/gameservers/file_server/download?file=${filename}`, { + headers: { + "Authorization": nitrado_cred.Auth + } + }).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}": message: ${res.message}: DownloadNitradoFile`); + return 1; + } + const { body } = await fetch(res.data.token.url); + await finished(Readable.fromWeb(body).pipe(stream)); + return 0; + } catch (error) { + client.error(`DownloadNitradoFile: Error connecting to server (${nitrado_cred.ServerID}): ${error.message}`); + if (retries === maxRetries) { + client.error(`DownloadNitradoFile: Error connecting to server (${nitrado_cred.ServerID}) after ${maxRetries} retries`); + return 1; + } + } + await new Promise(resolve => setTimeout(resolve, retryDelay)); // Delay before retrying + } + }, + + /* + Export explicit function names; i.e BanPlayer() & UnbanPlayer() + that call to the private parent function HandlePlayerBan() + rather than write two whole different functions for each. + */ + + BanPlayer: async (nitrado_cred, client, gamertag) => await HandlePlayerBan(nitrado_cred, client, gamertag, true), + UnbanPlayer: async (nitrado_cred, client, gamertag) => await HandlePlayerBan(nitrado_cred, client, gamertag, false), + + RestartServer: async (nitrado_cred, client, restart_message, message) => { + const params = { + restart_message: restart_message, + message: message + }; + for (let retries = 0; retries < maxRetries; retries++) { + try { + const res = await fetch(`https://api.nitrado.net/services/${nitrado_cred.ServerID}/gameservers/restart`, { + method: "POST", + headers: { + "Authorization": nitrado_cred.Auth, + }, + body: JSON.stringify(params) + }); + + if (!res.ok) { + client.error(`Failed to restart Nitrado server (${nitrado_cred.ServerID}): status: ${res.status}, message: ${res.statusText}: RestartServer`); + return 1; // Return error status on failed status code. + } else { + return 0; + } + } catch (error) { + client.error(`RestartServer: Error connecting to server (${nitrado_cred.ServerID}): ${error.message}`); + if (retries === maxRetries) { + client.error(`RestartServer: Error connecting to server (${nitrado_cred.ServerID}) after ${maxRetries} retries`); + return 1; + } + } + await new Promise(resolve => setTimeout(resolve, retryDelay)); // Delay before retrying + } + }, + + FetchServerSettings: async (nitrado_cred, client, fetcher) => { + for (let retries = 0; retries <= maxRetries; retries++) { + try { + // get current status + const res = await fetch(`https://api.nitrado.net/services/${nitrado_cred.ServerID}/gameservers`, { + headers: { + "Authorization": nitrado_cred.Auth + } + }); + + if (!res.ok) { + client.error(`Failed to get Nitrado server stats (${nitrado_cred.ServerID}): status: ${res.status}, message: ${res.statusText}: ${fetcher} via FetchServerSettings`); + if (res.status == 401) return 1; // return immediately if unauthorized + if (retries === 2) return 1; // Return error status on the second failed status code. + } else { + const data = await res.json(); + return data; + } + } catch (error) { + client.error(`${fetcher} via FetchServerSettings: Error connecting to server (${nitrado_cred.ServerID}): ${error.message}`); + if (retries === maxRetries) { + client.error(`${fetcher} via FetchServerSettings: Error connecting to server (${nitrado_cred.ServerID}) after ${maxRetries} retries`); + return 1; + } + } + await new Promise(resolve => setTimeout(resolve, retryDelay)); // Delay before retrying + } + }, + + PostServerSettings: async (nitrado_cred, client, category, key, value) => { + for (let retries = 0; retries <= maxRetries; retries++) { + try { + const formData = new FormData(); + formData.append("category", category); + formData.append("key", key); + formData.append("value", value); + formData.pipe(concat(data => { + async function postData() { + const res = await fetch(`https://api.nitrado.net/services/${nitrado_cred.ServerID}/gameservers/settings`, { + method: "POST", + credentials: "include", + headers: { + ...formData.getHeaders(), + "Authorization": nitrado_cred.Auth + }, + body: data, + }); + if (!res.ok) { + client.error(`Failed to get post Nitrado server settings (${nitrado_cred.ServerID}): status: ${res.status}, message: ${res.statusText}: PostServerSettings`); + if (retries === 2) return 1; // Return error status on the second failed status code. + } else { + const data = await res.json(); + return data; + } + } + postData(); + })); + return 0; + } catch (error) { + client.error(`PostServerSettings: Error connecting to server (${nitrado_cred.ServerID}): ${error.message}`); + if (retries === maxRetries) { + client.error(`PostServerSettings: Error connecting to server (${nitrado_cred.ServerID}) after ${maxRetries} retries`); + return 1; + } + } + await new Promise(resolve => setTimeout(resolve, retryDelay)); // Delay before retrying + } + }, + + CheckServerStatus: async (nitrado_cred, client) => { + const data = await module.exports.FetchServerSettings(nitrado_cred, client, "CheckServerStatus"); // Fetch server status + + if (data && data != 1) { + if (data && data.data.gameserver.status === "stopped") { + client.log(`Restart of Nitrado server ${nitrado_cred.ServerID} has been invoked by the bot, the periodic check showed status of "${data.data.gameserver.status}".`); + // Write optional "restart_message" to set in the Nitrado server logs and send a notice "message" to your server community. + restart_message = "Server being restarted by periodic bot check."; + message = "The server was restarted by periodic bot check!"; + + module.exports.RestartServer(nitrado_cred, client, restart_message, message); + } + } + }, + + DisableBaseDamage: async (nitrado_cred, client, preference) => { + const pref = preference ? "1" : "0"; + const posted = await module.exports.PostServerSettings(nitrado_cred, client, "config", "disableBaseDamage", pref); + if (posted == 1) return 1; + + const remoteDirs = await GetRemoteDir(nitrado_cred, client); + if (remoteDirs == 1) return 1; + const basePath = remoteDirs.filter(dir => dir.type == "dir")[0].path + const remoteDirsFromBase = await GetRemoteDir(nitrado_cred, client, basePath); + if (remoteDirsFromBase == 1) return 1; + const missionPath = remoteDirsFromBase[0].path; + const cfggameplayPath = `${missionPath}/cfggameplay.json`; + + const jsonDir = `./logs/cfggameplay.json`; + await module.exports.DownloadNitradoFile(nitrado_cred, client, cfggameplayPath, jsonDir); + + let gameplay = JSON.parse(fs.readFileSync(jsonDir)); + gameplay.GeneralData.disableBaseDamage = preference; + + // write JSON to file + fs.writeFileSync(jsonDir, JSON.stringify(gameplay, null, 2)); + + const uploaded = await UploadNitradoFile(nitrado_cred, client, missionPath, "cfggameplay.json", jsonDir); + if (uploaded == 1) return 1; + + return 0; + }, + + DisableContainerDamage: async (nitrado_cred, client, preference) => { + const pref = preference ? "1" : "0"; + const posted = await module.exports.PostServerSettings(nitrado_cred, client, "config", "disableContainerDamage", pref); + if (posted == 1) return 1; + + const remoteDirs = await GetRemoteDir(nitrado_cred, client); + if (remoteDirs == 1) return 1; + const basePath = remoteDirs.filter(dir => dir.type == "dir")[0].path + const remoteDirsFromBase = await GetRemoteDir(nitrado_cred, client, basePath); + if (remoteDirsFromBase == 1) return 1; + const missionPath = remoteDirsFromBase[0].path; + const cfggameplayPath = `${missionPath}/cfggameplay.json`; + + const jsonDir = `./logs/cfggameplay.json`; + await module.exports.DownloadNitradoFile(nitrado_cred, client, cfggameplayPath, jsonDir); + + let gameplay = JSON.parse(fs.readFileSync(jsonDir)); + gameplay.GeneralData.disableContainerDamage = preference; + + // write JSON to file + fs.writeFileSync(jsonDir, JSON.stringify(gameplay, null, 2)); + + const uploaded = await UploadNitradoFile(nitrado_cred, client, missionPath, "cfggameplay.json", jsonDir); + if (uploaded == 1) return 1; + + return 0; + }, + + NitradoCredentialStatus: { + FAILED: "FAILED", + OK: "OK", + }, +} diff --git a/src/util/RegisterSlashCommands.js b/src/util/RegisterSlashCommands.js new file mode 100644 index 0000000..e7045a0 --- /dev/null +++ b/src/util/RegisterSlashCommands.js @@ -0,0 +1,68 @@ +const fs = require("fs"); +const path = require("path"); +const { Routes } = require("discord.js"); +const { REST } = require("@discordjs/rest"); + +/** + * Register slash commands for a guild + * @param {require("../structures/DayzRBot")} client + */ +module.exports = { + // Register guild commands + RegisterGuildCommands: async (client, guild) => { + const commands = []; + const commandFiles = fs.readdirSync(path.join(__dirname, "..", "commands")).filter(file => file.endsWith(".js")); + + // Place your client and guild ids here + const clientId = client.application.id; + const guildId = guild; + + for (const file of commandFiles) { + const command = require(`../commands/${file}`); + if (!command.global) commands.push(command); // don"t include global commands + } + + const rest = new REST({ version: "10" }).setToken(client.config.Token); + + try { + client.log(`[${guildId}] Started refreshing guild (/) commands.`); + + await rest.put( + Routes.applicationGuildCommands(clientId, guildId), + { body: commands }, + ); + + client.log(`[${guildId}] Successfully reloaded guild (/) commands.`); + } catch (error) { + client.error(error); + } + }, + + // Register global commands + RegisterGlobalCommands: async (client) => { + const commands = []; + const commandFiles = fs.readdirSync(path.join(__dirname, "..", "commands")).filter(file => file.endsWith(".js")); + + const clientId = client.application.id; + + for (const file of commandFiles) { + const command = require(`../commands/${file}`); + if (command.global) commands.push(command); + } + + const rest = new REST({ version: "10" }).setToken(client.config.Token); + + try { + client.log("[global] Started refreshing global (/) commands."); + + await rest.put( + Routes.applicationCommands(clientId), + { body: commands }, + ); + + client.log("[global] Successfully reloaded global (/) commands."); + } catch (error) { + client.error(error); + } + } +}; \ No newline at end of file diff --git a/src/util/Vector.js b/src/util/Vector.js new file mode 100644 index 0000000..212d4c8 --- /dev/null +++ b/src/util/Vector.js @@ -0,0 +1,12 @@ +module.exports = { + calculateVector: (pos1, pos2) => { + let delta = [Math.round(pos2[0] - pos1[0]), Math.round(pos2[1] - pos1[1])]; + let distance = parseFloat(Math.sqrt(Math.pow(delta[0], 2) + Math.pow(delta[1], 2)).toFixed(0)); + let thetat = Math.round(Math.atan2(delta[0], delta[1]) / Math.PI * 180); + let theta = (thetat < 0) ? (360 + thetat) : thetat; + let compass = ["S", "SW", "W", "NW", "N", "NE", "E", "SE", "S"]; + let dir = compass[Math.round(theta / 45)]; + + return { distance, theta, dir } + } +} \ No newline at end of file diff --git a/src/util/WebhookHandler.js b/src/util/WebhookHandler.js new file mode 100644 index 0000000..a9d1852 --- /dev/null +++ b/src/util/WebhookHandler.js @@ -0,0 +1,56 @@ +const { makeURLSearchParams } = require("@discordjs/rest"); +const { REST } = require("@discordjs/rest"); +const { Routes } = require("discord.js"); + +const createWebhook = async (client, channel_id, name, avatar) => { + const rest = new REST({ version: "10" }).setToken(client.config.Token); + return await rest.post(Routes.channelWebhooks(channel_id), { + body: { + name: name, + avatar: avatar + } + }); +}; + +module.exports = { + GetWebhook: async (client, webhookName, channel_id) => { + // Get all webhooks from configured channel + const rest = new REST({ version: "10" }).setToken(client.config.Token); + const webhooks = await rest.get(Routes.channelWebhooks(channel_id)); + + let webhook = null; + if (webhooks.length == 0) { + // If no webhook exists, create new webhook with given name for this channel + webhook = createWebhook(client, channel_id, webhookName, client.config.AvatarData); + } else { + // Check existing webhooks for one with given name + let exists = false; + for (let i = 0; i < webhooks.length; i++) { + if (webhooks[i].name == webhookName) { + webhook = webhooks[i]; + exists = true; + break; + } + } + + if (!exists) webhook = createWebhook(client, channel_id, webhookName, client.config.AvatarData); + } + + return webhook; + }, + + WebhookSend: async (client, webhook, content) => { + const rest = new REST({ version: "10" }).setToken(client.config.Token); + return await rest.post(Routes.webhook(webhook.id, webhook.token), { + body: content, + query: makeURLSearchParams({ wait: true }) + }); + }, + + WebhookMessageEdit: async (client, webhook, message_id, content) => { + const rest = new REST({ version: "10" }).setToken(client.config.Token); + return rest.patch(Routes.webhookMessage(webhook.id, webhook.token, message_id), { + body: content + }); + } +} diff --git a/util/AdminLogsHandler.js b/util/AdminLogsHandler.js deleted file mode 100644 index b9142d9..0000000 --- a/util/AdminLogsHandler.js +++ /dev/null @@ -1,68 +0,0 @@ -const { EmbedBuilder } = require('discord.js'); -const { nearest } = require('../database/destinations'); -const { GetWebhook, WebhookSend } = require("../util/WebhookHandler"); - -module.exports = { - - SendConnectionLogs: async (client, guild, data) => { - if (!client.exists(guild.connectionLogsChannel)) return; - const channel = client.GetChannel(guild.connectionLogsChannel); - if (!channel) return; - - let newDt = await client.getDateEST(data.time); - let unixTime = Math.floor(newDt.getTime() / 1000); - - let connectionLog = new EmbedBuilder() - .setColor(data.connected ? client.config.Colors.Green : client.config.Colors.Red) - .setDescription(`**${data.connected ? 'Connect' : 'Disconnect'} Event - \n${data.player} ${data.connected ? 'Connected' : 'Disconnected'}**`); - - const NAME = "DayZ.R Admin Logs"; - const webhook = await GetWebhook(client, NAME, guild.connectionLogsChannel); - - if (!data.connected) { - if (data.lastConnectionDate != null) { - 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 }); - } - - // if (client.exists(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; - const channel = client.GetChannel(guild.connectionLogsChannel); - if (!channel) return; // Ensure channel exists - - const newDt = await client.getDateEST(data.time); - const diffSeconds = Math.round((newDt.getTime() - data.lastDamageDate.getTime()) / 1000); - - // If diff is greater than configured time in minutes, not a combat log - // or if death after last combat - if (diffSeconds > (data.combatLogTimer * 60)) return; - if (data.lastDamageDate <= data.lastDeathDate) return; - - // If lastHitBy (attacker) died after shooting this player - // then it does not count as combat logging, (the combat ended due to death) - let attacker = await client.dbo.collection("players").findOne({"gamertag": data.lastHitBy}); - if (attacker.lastDeathDate > data.lastDamageDate) return; - - let unixTime = Math.floor(newDt.getTime() / 1000); - const destination = nearest(data.pos, guild.Nitrado.Mission); - - 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]})**\n${destination}`); - - const NAME = "DayZ.R Admin Logs"; - const webhook = await GetWebhook(client, NAME, guild.connectionLogsChannel); - - let content = { embeds: [combatLog] }; - if (client.exists(guild.adminRole)) content.content = `<@&${guild.adminRole}>`; - WebhookSend(client, webhook, content); - // return channel.send({ embeds: [combatLog] }); - } -}; diff --git a/util/AlarmsHandler.js b/util/AlarmsHandler.js deleted file mode 100644 index 6d704c4..0000000 --- a/util/AlarmsHandler.js +++ /dev/null @@ -1,249 +0,0 @@ -const { BanPlayer, UnbanPlayer } = require('./NitradoAPI'); -const { EmbedBuilder } = require('discord.js'); -const { nearest } = require('../database/destinations'); -const { GetGuild } = require('../database/guild'); -const { GetWebhook, WebhookSend } = require("../util/WebhookHandler"); - -// 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!**`)] }); - - client.dbo.collection("guilds").updateOne({ "server.serverID": guild.serverID }, { - $pull: { - "server.events": e - } - }, (err, res) => { - if (err) return client.sendError(client.GetChannel(guild.adminLogsChannel), err); - }); -} - -const HandlePlayerTrackEvent = async (client, guild, e) => { - if (!client.exists(e.channel)) return ExpireEvent(client, guild, e); // Expire event since it has invalid channel. - const channel = client.GetChannel(e.channel); - if (!channel) return; - - let player = await client.dbo.collection("players").findOne({"gamertag": e.gamertag}); - - let newDt = await client.getDateEST(player.time); - let unixTime = Math.floor(newDt.getTime()/1000); - - const destination = nearest(player.pos, guild.Nitrado.Mission); - - const trackEvent = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`**${e.name} Event**\n${e.gamertag} was located at **[${player.pos[0]}, ${player.pos[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${player.pos[0]};${player.pos[1]})** at \n${destination}`); - - const NAME = "DayZ.R Player Tracker"; - const webhook = await GetWebhook(client, NAME, e.channel); - - let content = { embeds: [trackEvent] }; - if (client.exists(guild.adminRole)) content.content = `<@&${e.role}>`; - WebhookSend(client, webhook, content); - - // if (e.role) channel.send({ content: `<@&${e.role}>`, embeds: [trackEvent] }); - // else channel.send({ embeds: [trackEvent] }); - - let now = new Date(); - let diff = ((now - e.creationDate) / 1000) / 60; - let minutesBetweenDates = Math.abs(Math.round(diff)); - - if (minutesBetweenDates >= e.time) ExpireEvent(client, guild, e); -} - -// Public functions (called externally) - -module.exports = { - - HandleAlarmsAndUAVs: async (client, guild, data) => { - - for (let i = 0; i < guild.alarms.length; i++) { - let alarm = guild.alarms[i]; - let now = new Date(); - if (alarm.uavExpire!=null&&alarm.uavExpire**\n**${data.player}** was located within **${distance} meters** of the Zone **${alarm.name}** __and has been banned.__`) - .addFields({ name: '**Location**', value: `**[${data.pos[0]}, ${data.pos[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${data.pos[0]};${data.pos[1]})**`, inline: false }) - ); - - BanPlayer(client, data.player); - return; - } - - client.alarmPingQueue.get(guild.serverID).get(alarm.channel).get(route).push( - new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`**Zone Ping - **\n**${data.player}** was located within **${distance} meters** of the Zone **${alarm.name}**`) - .addFields({ name: '**Location**', value: `**[${data.pos[0]}, ${data.pos[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${data.pos[0]};${data.pos[1]})**`, inline: false }) - ); - - return; - } - } - - for (let i = 0; i < guild.uavs.length; i++) { - let uav = guild.uavs[i]; - - let diff = [Math.round(uav.origin[0] - data.pos[0]), Math.round(uav.origin[1] - data.pos[1])]; - let distance = Math.sqrt(Math.pow(diff[0], 2) + Math.pow(diff[1], 2)).toFixed(2); - - if (distance < uav.radius) { - let newDt = await client.getDateEST(data.time); - let unixTime = Math.floor(newDt.getTime()/1000); - - const destination = nearest(data.pos, guild.Nitrado.Mission); - - let uavEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`**UAV Detection - **\n**${data.player}** was spotted in the UAV zone at **[${data.pos[0]}, ${data.pos[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${data.pos[0]};${data.pos[1]})\n${destination}**`) - - client.users.fetch(uav.owner, false).then((user) => { - user.send({ embeds: [uavEmbed] }); - }); - } - } - }, - - HandleExpiredUAVs: async (client, guild) => { - let uavs = guild.uavs; - let update = false; - - for (let i = 0; i < uavs.length; i++) { - let uav = uavs[i]; - - let now = new Date(); - let diff = Math.round((now.getTime() - uav.creationDate.getTime()) / 1000 / 60); // diff minutes - - if (diff <= 30) continue; - - uavs.splice(i, 1); - update = true; - - let expired = new EmbedBuilder().setColor(client.config.Colors.Red).setDescription("**Low Battery**\nUAV has run out of battery and is no longer active."); - - client.users.fetch(uav.owner, false).then((user) => { - user.send({ embeds: [expired] }); - }); - } - - if (update) { - client.dbo.collection("guilds").updateOne({ "server.serverID": guild.serverID }, {$set: { "server.uavs": uavs }}, (err, res) => { - if (err) return client.sendError(client.GetChannel(guild.adminLogsChannel), err); - }); - } - }, - - KillInAlarm: async (client, guildId, data) => { - - let guild = await GetGuild(client, guildId); - - for (let i = 0; i < guild.alarms.length; i++) { - let alarm = guild.alarms[i]; - if (alarm.disabled || !alarm.rules.includes('ban_on_kill')) continue; // ignore if alarm is disabled or not ban on kill; - if (alarm.ignoredPlayers.includes(data.killerID)) continue; - - let diff = [Math.round(alarm.origin[0] - data.killerPOS[0]), Math.round(alarm.origin[1] - data.killerPOS[1])]; - let distance = Math.sqrt(Math.pow(diff[0], 2) + Math.pow(diff[1], 2)).toFixed(2) - - if (distance < alarm.radius) { - const channel = client.GetChannel(alarm.channel); - if (!channel) continue; - - let newDt = await client.getDateEST(data.time); - let unixTime = Math.floor(newDt.getTime()/1000); - - let alarmEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`**Zone Ping - **\n**${data.killer}** was located within **${distance} meters** of the Zone **${alarm.name}** __and has been banned for killing **${data.victim}**.__`) - .addFields({ name: '**Location**', value: `**[${data.killerPOS[0]}, ${data.killerPOS[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${data.killerPOS[0]};${data.killerPOS[1]})**`, inline: false }) - - const NAME = "DayZ.R Zone Alert"; - const webhook = await GetWebhook(client, NAME, alarm.channel); - - let content = { content: `<@&${alarm.role}>`, embeds: [alarmEmbed] }; - WebhookSend(client, webhook, content); - - // channel.send({ content: `<@&${alarm.role}>`, embeds: [alarmEmbed] }); - - BanPlayer(client, data.killer); - break; - } - } - return; - }, - - PlaceFireplaceInAlarm: async (client, guild, line) => { - - let fireplacePlacement = /(.*) \| Player \"(.*)\" \(id=(.*) pos=<(.*)>\) placed Fireplace/g; - let data = [...line.matchAll(fireplacePlacement)][0]; - if (!data) return; - - let info = { - time: data[1], - player: data[2], - playerID: data[3], - playerPOS: data[4].split(', ').map(v => parseFloat(v)), - }; - - for (let i = 0; i < guild.alarms.length; i++) { - let alarm = guild.alarms[i]; - if (alarm.disabled || !alarm.rules.includes('ban_on_fireplace_placement')) continue; - if (alarm.ignoredPlayers.includes(info.playerID)) continue; - - let diff = [Math.round(alarm.origin[0] - info.playerPOS[0]), Math.round(alarm.origin[1] - info.playerPOS[1])]; - let distance = Math.sqrt(Math.pow(diff[0], 2) + Math.pow(diff[1], 2)).toFixed(2); - - if (distance < alarm.radius) { - const channel = client.GetChannel(alarm.channel); - if (!channel) return; - - let newDt = await client.getDateEST(info.time); - let unixTime = Math.floor(newDt.getTime()/1000); - - let alarmEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`**Zone Ping - **\n**${info.player}** was located within **${distance} meters** of the Zone **${alarm.name}** __and has been banned for **placing a fireplace**.__`) - .addFields({ name: '**Location**', value: `**[${info.playerPOS[0]}, ${info.playerPOS[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${info.playerPOS[0]};${info.playerPOS[1]})**`, inline: false }) - - const NAME = "DayZ.R Zone Alert"; - const webhook = await GetWebhook(client, NAME, alarm.channel); - - let content = { content: `<@&${alarm.role}>`, embeds: [alarmEmbed] }; - WebhookSend(client, webhook, content); - - // channel.send({ content: `<@&${alarm.role}>`, embeds: [alarmEmbed] }); - - BanPlayer(client, info.player); - break; - } - } - return; - }, - - HandleEvents: async (client, guild) => { - for (let i = 0; i < guild.events.length; i++) { - let event = guild.events[i]; - if (event.type == 'player-track') HandlePlayerTrackEvent(client, guild, event); - } - }, -} diff --git a/util/CombatRatingHandler.js b/util/CombatRatingHandler.js deleted file mode 100644 index 9f7b0ca..0000000 --- a/util/CombatRatingHandler.js +++ /dev/null @@ -1,6 +0,0 @@ -module.exports = { - calculateNewCombatRating: (Ra, Rb, score) => { - const Ea = 1 / (1 + Math.pow(10, ((Rb - Ra) / 400))); - return Math.round(Ra + 32 * (score - Ea)); - }, -} \ No newline at end of file diff --git a/util/CommandOptionTypes.js b/util/CommandOptionTypes.js deleted file mode 100644 index d74fec1..0000000 --- a/util/CommandOptionTypes.js +++ /dev/null @@ -1,15 +0,0 @@ -module.exports = { - CommandOptionTypes: { - 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, - } -}; \ No newline at end of file diff --git a/util/Cryptic.js b/util/Cryptic.js deleted file mode 100644 index 0f32e46..0000000 --- a/util/Cryptic.js +++ /dev/null @@ -1,19 +0,0 @@ -const crypto = require('crypto'); - -module.exports = { - encrypt: (data, EncryptionMethod, Key, EncryptionIV) => { - const cipher = crypto.createCipheriv(EncryptionMethod, Key, EncryptionIV) - return Buffer.from( - cipher.update(data, 'utf8', 'hex') + cipher.final('hex') - ).toString('base64') // Encrypts data and converts to hex and base64 - }, - - decrypt: (data, EncryptionMethod, Key, EncryptionIV) => { - const buff = Buffer.from(data, 'base64') - const decipher = crypto.createDecipheriv(EncryptionMethod, Key, EncryptionIV) - return ( - decipher.update(buff.toString('utf8'), 'hex', 'utf8') + - decipher.final('utf8') - ) // Decrypts data and converts to utf8 - } -} \ No newline at end of file diff --git a/util/KillfeedHandler.js b/util/KillfeedHandler.js deleted file mode 100644 index 82bc5aa..0000000 --- a/util/KillfeedHandler.js +++ /dev/null @@ -1,290 +0,0 @@ -const { EmbedBuilder } = require('discord.js'); -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 { weapons, weaponClassOf } = require('../database/weapons'); -const { GetWebhook, WebhookSend } = require("../util/WebhookHandler"); - -const Templates = { - Killed: 1, - HitBy: 2, - HitByAndDead: 3, - Explosion: 4, - LandMine: 5, - Melee: 6, - Vehicle: 7, -}; - -const TemplateExpressions = { - 1: /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\) killed by Player \"(.*)\" \(id=(.*) pos=<(.*)>\) with (.*) from (.*) meters /g, - 2: /(.*) \| Player \"(.*)\" \(id=(.*) pos=<(.*)>\)\[HP\: (.*)\] hit by Player \"(.*)\" \(id=(.*) pos=<(.*)>\) into (.*) for (.*) damage \((.*)\) with (.*) from (.*) meters /g, - 3: /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\)\[HP\: (.*)\] hit by Player \"(.*)\" \(id=(.*) pos=<(.*)>\) into (.*) for (.*) damage \((.*)\) with (.*) from (.*) meters /g, - 4: /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\) killed by with (.*)/g, - 5: /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\) killed by LandMineTrap/g, - 6: /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\)\[HP\: (.*)\] hit by Player \"(.*)\" \(id=(.*) pos=<(.*)>\) into (.*) for (.*) damage \((.*)\) with (.*)/g, - 7: /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\)\[HP\: (.*)\] hit by (.*) with TransportHit/g, -}; - -const Vehicles = { - CivilianSedan: 'White Olga', - CivilianSedan_Black: 'Black Olga', - CivilianSedan_Wine: 'Wine Olga', - - Hatchback_02: 'Red Gunter', - Hatchback_02_Black: 'Black Gunter', - Hatchback_02_Blue: 'Blue Gunter', - - OffroadHatchBack: 'Green ADA 4x4', - OffroadHatchBack_Blue: 'Blue ADA 4x4', - OffroadHatchBack_White: 'White ADA 4x4', - - Sedan_02: 'Yellow Sarka', - Sedan_02_Grey: 'Grey Sarka', - Sedan_02_Red: 'Red Sarka', - - Truck_01_Covered: 'Green V3S Truck', - Truck_01_Covered_Blue: 'Blue V3S Truck', - Truck_01_Covered_Orange: 'Orange V3S Truck', - - Offroad_02: 'M1025 Humvee' -}; - -module.exports = { - - // Update last death date for non PVP deaths - UpdateLastDeathDate: async (NitradoServerID, client, line) => { - let killedByZmb = /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\) killed by (.*)/g; - let diedTemplate = /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\) died\. Stats> Water: (.*) Energy: (.*) Bleed sources: (.*)/g; - - let data = line.includes('>) died.') ? [...line.matchAll(diedTemplate)][0] : [...line.matchAll(killedByZmb)][0]; - if (!data) return; - - let info = { - time: data[1], - victim: data[2], - victimID: data[3], - victimPOS: data[4].split(', ').map(v => parseFloat(v)), - }; - - 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); - - victimStat.lastDeathDate = newDt; - - await UpdatePlayer(client, victimStat); - return - }, - - HandleKillfeed: async (NitradoServerID, client, guild, line) => { - - const NAME = "DayZ.R Killfeed"; - const channel = client.GetChannel(guild.killfeedChannel); - - const killedBy = line.includes('hit by Player') && line.includes('(DEAD)') && line.includes('meters') ? Templates.HitByAndDead : - line.includes('hit by Player') && !line.includes('meters') ? Templates.Melee : // Missing meters indicates it was a melee attack. - line.includes('hit by Player') ? Templates.HitBy : - line.includes('killed by Player') ? Templates.Killed : - line.includes('TransportHit') ? Templates.Vehicle : - line.includes('killed by LandMineTrap') ? Templates.LandMine : Templates.Explosion; - - let data = [...line.matchAll(TemplateExpressions[killedBy])][0]; - - if (!data) return; - - // Create base data - let info = { - time: data[1], - victim: data[2], - victimID: data[3], - victimPOS: data[4].split(', ').map(v => parseFloat(v)), - }; - - // Add additional data - if ([Templates.HitBy, Templates.HitByAndDead, Templates.Melee].includes(killedBy)) { - info.killer = data[6]; - info.killerID = data[7]; - info.killerPOS = data[8].split(', ').map(v => parseFloat(v)); - info.bodyPart = data[9]; - info.damage = data[10]; - info.weapon = data[12]; - info.distance = killedBy == Templates.Melee ? 0 : parseFloat(data[13]).toFixed(2); - } else if (killedBy == Templates.Killed) { - info.killer = data[5]; - info.killerID = data[6]; - info.killerPOS = data[7].split(', ').map(v => parseFloat(v)); - info.weapon = data[8]; - info.distance = parseFloat(data[9]).toFixed(2); - } - else if (killedBy == Templates.Vehicle) info.causeOfDeath = data[6]; - else if (killedBy == Templates.Explosion) info.causeOfDeath = data[5]; - else return; // Unknown template; - - 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 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); - victimStat.deaths++; - victimStat.deathStreak++; - victimStat.worstDeathStreak = victimStat.deathStreak > victimStat.worstDeathStreak ? victimStat.deathStreak : victimStat.worstDeathStreak; - victimStat.KDR = victimStat.kills / (victimStat.deaths == 0 ? 1 : victimStat.deaths); // prevent division by 0 - victimStat.killStreak = 0; - victimStat.lastDeathDate = newDt; - - const cod = killedBy == Templates.LandMine ? `Land Mine Trap` : - killedBy == Templates.Vehicle ? Vehicles[info.causeOfDeath] : info.causeOfDeath; - const coord = showCoords ? `\n***Location [${info.victimPOS[0]}, ${info.victimPOS[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${info.victimPOS[0]};${info.victimPOS[1]})***\n${destination}` : ''; - const killMessage = killedBy == Templates.Vehicle ? 'run over by' : 'blew up from'; - - const killEvent = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`**Death Event** - \n**${info.victim}** ${killMessage} a **${cod}.**${coord}`); - - await UpdatePlayer(client, victimStat); - - if (!channel) return; - const webhook = await GetWebhook(client, NAME, guild.killfeedChannel); - WebhookSend(client, webhook, { embeds: [killEvent]}); - - // if (client.exists(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; - - 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); - - let weapon = info.weapon.includes("Engraved") ? info.weapon.split("Engraved ")[1] : - info.weapon.includes("Sawed-off") ? info.weapon.split("Sawed-off ")[1] : - info.weapon; - - // Update killer stats - killerStat.kills++; - killerStat.killStreak++; - killerStat.bestKillStreak = killerStat.killStreak > killerStat.bestKillStreak ? killerStat.killStreak : killerStat.bestKillStreak; - 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; - killerStat.weaponStats[weapon].kills++; - - // Update victim stats - victimStat.deaths++; - victimStat.deathStreak++; - victimStat.worstDeathStreak = victimStat.deathStreak > victimStat.worstDeathStreak ? victimStat.deathStreak : victimStat.worstDeathStreak; - 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; - 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); - - // 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); - victimStat.combatRating = calculateNewCombatRating(victimStat.combatRating, killerStat.combatRating, 0); - - // Update combat rating records - if (killerStat.combatRating > killerStat.highestCombatRating) killerStat.highestCombatRating = killerStat.combatRating; - if (victimStat.combatRating < victimStat.lowestCombatRating) victimStat.lowestCombatRating = victimStat.combatRating; - if (killerStat.combatRatingHistory.length >= 12) killerStat.combatRatingHistory = killerStat.combatRatingHistory.slice(1); // Remove first element (limits history to length 12) - if (victimStat.combatRatingHistory.length >= 12) victimStat.combatRatingHistory = victimStat.combatRatingHistory.slice(1); // Remove first element (limits history to length 12) - killerStat.combatRatingHistory.push(killerStat.combatRating); - victimStat.combatRatingHistory.push(victimStat.combatRating); - - let kdiff = killerStat.combatRating - killerOldRating; - let vdiff = victimStat.combatRating - victimOldRating; - - let receivedBounty = null; - if (victimStat.bounties.length > 0 && killerStat.discordID != "") { - let totalBounty = 0; - for (let i = 0; i < victimStat.bounties.length; i++) { - totalBounty += victimStat.bounties[i].value; - } - - let banking = await client.dbo.collection("users").findOne({"user.userID": killerStat.discordID}).then(banking => banking); - - if (!banking) { - banking = await createUser(interaction.member.user.id, guild.serverID, guild.startingBalance, client) - if (!client.exists(banking)) return client.sendInternalError(interaction, err); - } - banking = banking.user; - - if (!client.exists(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'); - } - - const newBalance = banking.guilds[ guild.serverID].balance + totalBounty; - - await client.dbo.collection("users").updateOne({ "user.userID": killerStat.discordID }, { - $set: { - [`user.guilds.${ guild.serverID}.balance`]: newBalance, - } - }, (err, res) => { - if (err) return client.sendError(client.GetChannel(guild.killfeedChannel), `Killfeed Error: Updating killer bank balance\n${err}`); - }); - - receivedBounty = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`<@${killerStat.discordID}> received **$${totalBounty.toFixed(2).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}** in bounty rewards.`); - - victimStat.bounties = []; // clear bounties after claimed - victimStat.bountiesLength = 0; - } - - await UpdatePlayer(client, victimStat); - await UpdatePlayer(client, killerStat); - - const header = `**Kill Event** - \n**${info.killer}** killed **${info.victim}**`; - const killData = `\n> **__Kill Data__**\n> Weapon: \` ${info.weapon} \`\n> Distance: \` ${info.distance}m \`\n> Body Part: \` ${info.bodyPart != undefined ? info.bodyPart.split('(')[0] : 'N/A'} \`\n> Damage: \` ${info.damage != undefined ? info.damage : 'N/A'} \``; - const killerStatsView = `\n**Killer Rating** (${kdiff >= 0 ? '+' : ''}${kdiff}) ${killerStat.combatRating}\n${killerStat.KDR.toFixed(2)} K/D - ${killerStat.kills} Kill${(killerStat.kills == 0 || killerStat.kills > 1) ? 's':''} - Killstreak: ${killerStat.killStreak}`; - const victimStatsView = `\n**Victim Rating** (${vdiff >= 0 ? '+' : ''}${vdiff}) ${victimStat.combatRating}\n${victimStat.KDR.toFixed(2)} K/D - ${victimStat.deaths} Death${victimStat.deaths == 0 || victimStat.deaths>1?'s':''} - Deathstreak: ${victimStat.deathStreak}`; - const coord = showCoords ? `\n***Location [${info.victimPOS[0]}, ${info.victimPOS[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${info.victimPOS[0]};${info.victimPOS[1]})***\n${destination}` : ''; - - let killEvent = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setDescription(`${header}${killData}${killerStatsView}${victimStatsView}${coord}`); - - if (showWeapon) { - let weaponClass = weaponClassOf(weapon); - killEvent.setThumbnail(weapons[weaponClass][weapon]) - } - - if (!channel) return; - - 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 (client.exists(channel)) await channel.send({ embeds: [killEvent] }); - // if (client.exists(receivedBounty) && client.exists(channel)) await channel.send({ content: `<@${killerStat.discordID}>`, embeds: [receivedBounty] }); - - return; - } -} \ No newline at end of file diff --git a/util/Logger.js b/util/Logger.js deleted file mode 100644 index c9420bb..0000000 --- a/util/Logger.js +++ /dev/null @@ -1,38 +0,0 @@ -const winston = require("winston"); -const colors = require("colors"); - -class Logger { - constructor(LoggingFile) { - this.logger = winston.createLogger({ - transports: [new winston.transports.File({ filename: LoggingFile })], - }); - } - - log(Text) { - let d = new Date(); - this.logger.log({ - level: "info", - message: - `${d.getHours()}:${d.getMinutes()} - ${d.getMonth()+1}:${d.getDate()}:${d.getFullYear()} | Info: ` + Text}); - console.log( - colors.green( - `${d.getMonth()+1}:${d.getDate()}:${d.getFullYear()} - ${d.getHours()}:${d.getMinutes()}` - ) + colors.yellow(" | Info: " + Text) - ); - } - - error(Text) { - let d = new Date(); - this.logger.log({ - level: "error", - message: - `${d.getHours()}:${d.getMinutes()} - ${d.getMonth()+1}:${d.getDate()}:${d.getFullYear()} | Error: ` + Text}); - console.log( - colors.green( - `${d.getMonth()+1}:${d.getDate()}:${d.getFullYear()} - ${d.getHours()}:${d.getMinutes()}` - ) + colors.yellow(" | Error: ") + colors.red(Text) - ); - } -} - -module.exports = Logger; \ No newline at end of file diff --git a/util/LogsHandler.js b/util/LogsHandler.js deleted file mode 100644 index 873570b..0000000 --- a/util/LogsHandler.js +++ /dev/null @@ -1,265 +0,0 @@ -const { EmbedBuilder } = require('discord.js'); -const { HandleAlarmsAndUAVs } = require('./AlarmsHandler'); -const { SendConnectionLogs, DetectCombatLog } = require('./AdminLogsHandler'); -const { getDefaultPlayer } = require('../database/player'); -const { FetchServerSettings } = require('../util/NitradoAPI'); -const { UpdatePlayer, insertPVPstats, createWeaponStats } = require('../database/player') -const { Missions } = require('../database/destinations'); -const { GetWebhook, WebhookSend, WebhookMessageEdit } = require("../util/WebhookHandler"); - -module.exports = { - - HandlePlayerLogs: async (NitradoServerID, client, GuildDB, line, combatLogTimer = 5) => { - - const connectTemplate = /(.*) \| Player \"(.*)\" is connected \(id=(.*)\)/g; - const disconnectTemplate = /(.*) \| Player \"(.*)\"\(id=(.*)\) has been disconnected/g; - const positionTemplate = /(.*) \| Player \"(.*)\" \(id=(.*) pos=<(.*)>\)/g; - const damageTemplate = /(.*) \| Player \"(.*)\" \(id=(.*) pos=<(.*)>\)\[HP\: (.*)\] hit by Player \"(.*)\" \(id=(.*) pos=<(.*)>\) into (.*) for (.*) damage \((.*)\) with (.*) from (.*) meters /g; - const deadTemplate = /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\)\[HP\: (.*)\] hit by Player \"(.*)\" \(id=(.*) pos=<(.*)>\) into (.*) for (.*) damage \((.*)\) with (.*) from (.*) meters /g; - - if (line.includes(' connected')) { - const data = [...line.matchAll(connectTemplate)][0]; - if (!data) return; - - const info = { - time: data[1], - player: data[2], - playerID: data[3], - }; - - if (!client.exists(info.player) || !client.exists(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); - const newDt = await client.getDateEST(info.time); - - playerStat.lastConnectionDate = newDt; - playerStat.connected = true; - if (!client.exists(playerStat.connections)) playerStat.connections = 0; - playerStat.connections++; - - // Track adjusted sessions this instance has handled (e.g. no bot crashes or restarts). - if (client.playerSessions.get(NitradoServerID).has(info.playerID)) { - // Player is already in a session, update the session's end time. - const session = client.playerSessions.get(NitradoServerID).get(info.playerID); - session.endTime = newDt; // Update end time. - } else { - // Player is not in a session, create a new session. - const newSession = { - startTime: newDt, - endTime: null, // Initialize end time as null. - }; - client.playerSessions.get(NitradoServerID).set(info.playerID, newSession); - } - - await SendConnectionLogs(client, GuildDB, { - time: info.time, - player: info.player, - connected: true, - lastConnectionDate: null, - }); - - await UpdatePlayer(client, playerStat); - } - - if (line.includes(' disconnected')) { - const data = [...line.matchAll(disconnectTemplate)][0]; - if (!data) return; - - const info = { - time: data[1], - player: data[2], - playerID: data[3], - }; - - if (!client.exists(info.player) || !client.exists(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); - - let oldUnixTime; - let sessionTimeSeconds; - const newDt = await client.getDateEST(info.time); - const unixTime = Math.round(newDt.getTime() / 1000); // Seconds - if (playerStat.lastConnectionDate != null) { - oldUnixTime = Math.round(playerStat.lastConnectionDate.getTime() / 1000); // Seconds - sessionTimeSeconds = unixTime - oldUnixTime; - } else sessionTimeSeconds = 0; - if (!client.exists(playerStat.longestSessionTime)) playerStat.longestSessionTime = 0; - - playerStat.totalSessionTime = playerStat.totalSessionTime + sessionTimeSeconds; - playerStat.lastSessionTime = sessionTimeSeconds; - playerStat.longestSessionTime = sessionTimeSeconds > playerStat.longestSessionTime ? sessionTimeSeconds : playerStat.longestSessionTime; - playerStat.lastDisconnectionDate = newDt; - playerStat.connected = false; - - await SendConnectionLogs(client, GuildDB, { - time: info.time, - player: info.player, - connected: false, - lastConnectionDate: playerStat.lastConnectionDate, - }); - - if (combatLogTimer != 0) { - await DetectCombatLog(client, GuildDB, { - time: info.time, - player: info.player, - pos: playerStat.pos, - lastDamageDate: playerStat.lastDamageDate, - lastHitBy: playerStat.lastHitBy, - lastDeathDate: playerStat.lastDeathDate, - combatLogTimer: combatLogTimer, - }); - } - - await UpdatePlayer(client, playerStat); - } - - if (line.includes('pos=<') && !line.includes('hit by')) { - const data = [...line.matchAll(positionTemplate)][0]; - if (!data) return; - - const info = { - time: data[1], - player: data[2], - playerID: data[3], - pos: data[4].split(', ').map(v => parseFloat(v)) - }; - - if (!client.exists(info.player) || !client.exists(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); - - playerStat.lastPos = playerStat.pos; - playerStat.pos = info.pos; - playerStat.lastTime = playerStat.time; - playerStat.lastDate = playerStat.date; - playerStat.time = `${info.time} EST`; - playerStat.date = await client.getDateEST(info.time); - - if (line.includes('hit by') || line.includes('killed by')) return; // prevent additional information from being fed to Alarms & UAVs - - await HandleAlarmsAndUAVs(client, GuildDB, { - time: info.time, - player: info.player, - playerID: info.playerID, - pos: info.pos, - }); - - await UpdatePlayer(client, playerStat) - } - - if (line.includes('hit by Player')) { - const data = line.includes('(DEAD)') ? [...line.matchAll(deadTemplate)][0] : [...line.matchAll(damageTemplate)][0]; - if (!data) return; - - const info = { - time: data[1], - player: data[2], - playerID: data[3], - attacker: data[6], - attackerID: data[7], - bodyPart: data[9].split("(")[0], - weapon: data[12], - }; - - if (!client.exists(info.player) || !client.exists(info.playerID) || !client.exists(info.attacker) || !client.exists(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); - - 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); - - // Update in depth PVP stats if non Melee weapon - if (info.weapon.includes("Engraved")) info.weapon = info.weapon.split("Engraved ")[1]; - if (info.weapon.includes("Sawed-off")) info.weapon = info.weapon.split("Sawed-off ")[1]; - if (info.weapon in playerStat.weaponStats) { - playerStat.timesShot++; - playerStat.timesShotPerBodyPart[info.bodyPart]++; - if (!client.exists(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); - attackerStat.weaponStats[info.weapon].shotsLanded++; - attackerStat.weaponStats[info.weapon].shotsLandedPerBodyPart[info.bodyPart]++; - } - - await UpdatePlayer(client, playerStat); - await UpdatePlayer(client, attackerStat); - } - - return; - }, - - HandleActivePlayersList: async (nitrado_cred, client, guild) => { - client.activePlayersTick = 0; // reset hour tick - - if (!client.exists(guild.activePlayersChannel)) return; - const channel = client.GetChannel(guild.activePlayersChannel); - if (!channel) return; - - const data = await FetchServerSettings(nitrado_cred, client, 'HandleActivePlayersList'); // Fetch server status - const e = data && data !== 1; // Check if data exists - - const hostname = e ? data.data.gameserver.settings.config.hostname : 'N/A'; - const map = Missions[data.data.gameserver.settings.config.mission]; - const status = e ? data.data.gameserver.status : 'N/A'; - const slots = e ? data.data.gameserver.slots : 'N/A'; - const playersOnline = e ? data.data.gameserver.query.player_current : undefined; - - const Statuses = { - "started": {emoji: "🟢", text: "Active"}, - "stopped": {emoji: "🔴", text: "Stopped"}, - "restarting": {emoji: "↻", text: "Restarting"}, - }; - - const emojiStatus = Statuses[status].emoji || "❓"; - const textStatus = Statuses[status].text || "Unknown Status"; - - let activePlayers = await client.dbo.collection("players").find({"nitradoServerID": nitrado_cred.ServerID}).toArray().filter(player => player.connected); - - let des = activePlayers.length > 0 ? `` : `**No Players Online**`; - for (let i = 0; i < activePlayers.length; i++) { - des += `**- ${activePlayers[i].gamertag}**\n`; - } - - const nodes = activePlayers.length === 0; - const serverEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTitle(`Online List - \` ${playersOnline === undefined ? activePlayers.length : playersOnline} \` Player${playersOnline !== 1 ? 's' : ''} Online`) - .addFields( - { name: 'Server:', value: `\` ${hostname} \``, inline: false }, - { name: 'Map:', value: `\` ${map} \``, inline: true }, - { name: 'Status:', value: `\` ${emojiStatus} ${textStatus} \``, inline: true }, - { name: 'Slots:', value: `\` ${slots} \``, inline: true } - ); - - const activePlayersEmbed = new EmbedBuilder() - .setColor(client.config.Colors.Default) - .setTimestamp() - .setTitle(`Players Online:`) - .setDescription(des || (nodes ? "No Players Online :(" : "")); - - const NAME = "DayZ.R Admin Logs"; - const webhook = await GetWebhook(client, NAME, guild.connectionLogsChannel); - - let id = client.playerListMsgIds.get(guild.serverID); - if (id == "") { - id = await WebhookSend(client, webhook, { embeds: [serverEmbed, activePlayersEmbed] }).id; - client.playerListMsgIds.set(guild.serverID, id); - } else { - WebhookMessageEdit(client, webhook, id, { embeds: [serverEmbed, activePlayersEmbed] }); - } - } -}; diff --git a/util/NitradoAPI.js b/util/NitradoAPI.js deleted file mode 100644 index 350a99d..0000000 --- a/util/NitradoAPI.js +++ /dev/null @@ -1,311 +0,0 @@ -const { finished } = require('stream/promises'); -const concat = require('concat-stream'); -const { Readable } = require('stream'); -const FormData = require('form-data'); -const fs = require('fs'); -const maxRetries = 5; -const retryDelay = 5000; // 5 seconds - -// Private functions (only called locally) - -const UploadNitradoFile = async (nitrado_cred, client, remoteDir, remoteFilename, localFileDir) => { - for (let retries = 0; retries <= maxRetries; retries++) { - try { - const res = await fetch(`https://api.nitrado.net/services/${nitrado_cred.ServerID}/gameservers/file_server/upload?` + new URLSearchParams({ - path: remoteDir, - file: remoteFilename - }), { - method: "POST", - headers: { - "Authorization": nitrado_cred.Auth - }, - }).then(response => response.json()); - - let contents = fs.readFileSync(localFileDir, 'utf8'); - - const uploadRes = await fetch(res.data.token.url, { - method: "POST", - headers: { - 'Content-Type': 'application/binary', - token: res.data.token.token - }, - body: contents, - }) - if (!uploadRes.ok) { - client.error(`Failed to upload file to Nitrado (${nitrado_cred.ServerID}): status: ${uploadRes.status}, message: ${res.statusText}: UploadNitradoFile`); - if (retries === 2) return 1; // Return error status on the second failed status code. - } else { - return uploadRes; - } - } catch (error) { - client.error(`UploadNitradoFile: Error connecting to server (${nitrado_cred.ServerID}): ${error.message}`); - if (retries === maxRetries) { - client.error(`UploadNitradoFile: Error connecting to server (${nitrado_cred.ServerID}) after ${maxRetries} retries`); - return 1; - } - } - await new Promise(resolve => setTimeout(resolve, retryDelay)); // Delay before retrying - } -} - -const HandlePlayerBan = async (nitrado_cred, client, gamertag, ban) => { - const data = await module.exports.FetchServerSettings(nitrado_cred, client, 'HandlePlayerBan'); // Fetch server status - - if (data && data != 1) { - let bans = data.data.gameserver.settings.general.bans; - if (ban) bans += `\r\n${gamertag}`; - else if (!ban) bans = bans.replace(gamertag, ''); - else client.error("Incorrect Ban Option: HandlePlayerBan"); - - let category = 'general'; - let key = 'bans'; - return await module.exports.PostServerSettings(nitrado_cred, client, category, key, bans); // returns 1 (failed) or 0 (not failed) - } -} - -const GetRemoteDir = async (nitrado_cred, client, dir="") => { - const dirParam = client.exists(dir) ? `?dir=${dir}` : ""; - for (let retries = 0; retries <= maxRetries; retries++) { - try { - const res = await fetch(`https://api.nitrado.net/services/${nitrado_cred.ServerID}/gameservers/file_server/list${dirParam}`, { - headers: { - "Authorization": nitrado_cred.Auth - } - }).then(response => - response.json().then(data => data) - ).then(res => res); - - if (res.status === "error") return 1; - - return res.data.entries; - } catch (error) { - client.error(`GetRemoteDir: Error connecting to server (${nitrado_cred.ServerID}): ${error}`); - if (retries == maxRetries) { - client.error(`GetRemoteDir: Error connecting to server (${nitrado_cred.ServerID}) after ${maxRetries} retries`); - return 1; - } - } - await new Promise(resolve => setTimeout(resolve, retryDelay)); // Delay before retrying - } -} - -// Public functions (called externally) - -module.exports = { - - DownloadNitradoFile: async(nitrado_cred, client, filename, outputDir) => { - for (let retries = 0; retries <= maxRetries; retries++) { - try { - const res = await fetch(`https://api.nitrado.net/services/${nitrado_cred.ServerID}/gameservers/file_server/download?file=${filename}`, { - headers: { - "Authorization": nitrado_cred.Auth - } - }).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}": message: ${res.message}: DownloadNitradoFile`); - return 1; - } - const { body } = await fetch(res.data.token.url); - await finished(Readable.fromWeb(body).pipe(stream)); - return 0; - } catch (error) { - client.error(`DownloadNitradoFile: Error connecting to server (${nitrado_cred.ServerID}): ${error.message}`); - if (retries === maxRetries) { - client.error(`DownloadNitradoFile: Error connecting to server (${nitrado_cred.ServerID}) after ${maxRetries} retries`); - return 1; - } - } - await new Promise(resolve => setTimeout(resolve, retryDelay)); // Delay before retrying - } - }, - - /* - Export explicit function names; i.e BanPlayer() & UnbanPlayer() - that call to the private parent function HandlePlayerBan() - rather than write two whole different functions for each. - */ - - BanPlayer: async (nitrado_cred, client, gamertag) => await HandlePlayerBan(nitrado_cred, client, gamertag, true), - UnbanPlayer: async (nitrado_cred, client, gamertag) => await HandlePlayerBan(nitrado_cred, client, gamertag, false), - - RestartServer: async (nitrado_cred, client, restart_message, message) => { - const params = { - restart_message: restart_message, - message: message - }; - for (let retries = 0; retries < maxRetries; retries++) { - try { - const res = await fetch(`https://api.nitrado.net/services/${nitrado_cred.ServerID}/gameservers/restart`, { - method: "POST", - headers: { - "Authorization": nitrado_cred.Auth, - }, - body: JSON.stringify(params) - }); - - if (!res.ok) { - client.error(`Failed to restart Nitrado server (${nitrado_cred.ServerID}): status: ${res.status}, message: ${res.statusText}: RestartServer`); - return 1; // Return error status on failed status code. - } else { - return 0; - } - } catch (error) { - client.error(`RestartServer: Error connecting to server (${nitrado_cred.ServerID}): ${error.message}`); - if (retries === maxRetries) { - client.error(`RestartServer: Error connecting to server (${nitrado_cred.ServerID}) after ${maxRetries} retries`); - return 1; - } - } - await new Promise(resolve => setTimeout(resolve, retryDelay)); // Delay before retrying - } - }, - - FetchServerSettings: async (nitrado_cred, client, fetcher) => { - for (let retries = 0; retries <= maxRetries; retries++) { - try { - // get current status - const res = await fetch(`https://api.nitrado.net/services/${nitrado_cred.ServerID}/gameservers`, { - headers: { - "Authorization": nitrado_cred.Auth - } - }); - - if (!res.ok) { - client.error(`Failed to get Nitrado server stats (${nitrado_cred.ServerID}): status: ${res.status}, message: ${res.statusText}: ${fetcher} via FetchServerSettings`); - if (res.status == 401) return 1; // return immediately if unauthorized - if (retries === 2) return 1; // Return error status on the second failed status code. - } else { - const data = await res.json(); - return data; - } - } catch (error) { - client.error(`${fetcher} via FetchServerSettings: Error connecting to server (${nitrado_cred.ServerID}): ${error.message}`); - if (retries === maxRetries) { - client.error(`${fetcher} via FetchServerSettings: Error connecting to server (${nitrado_cred.ServerID}) after ${maxRetries} retries`); - return 1; - } - } - await new Promise(resolve => setTimeout(resolve, retryDelay)); // Delay before retrying - } - }, - - PostServerSettings: async (nitrado_cred, client, category, key, value) => { - for (let retries = 0; retries <= maxRetries; retries++) { - try { - const formData = new FormData(); - formData.append("category", category); - formData.append("key", key); - formData.append("value", value); - formData.pipe(concat(data => { - async function postData() { - const res = await fetch(`https://api.nitrado.net/services/${nitrado_cred.ServerID}/gameservers/settings`, { - method: "POST", - credentials: 'include', - headers: { - ...formData.getHeaders(), - "Authorization": nitrado_cred.Auth - }, - body: data, - }); - if (!res.ok) { - client.error(`Failed to get post Nitrado server settings (${nitrado_cred.ServerID}): status: ${res.status}, message: ${res.statusText}: PostServerSettings`); - if (retries === 2) return 1; // Return error status on the second failed status code. - } else { - const data = await res.json(); - return data; - } - } - postData(); - })); - return 0; - } catch (error) { - client.error(`PostServerSettings: Error connecting to server (${nitrado_cred.ServerID}): ${error.message}`); - if (retries === maxRetries) { - client.error(`PostServerSettings: Error connecting to server (${nitrado_cred.ServerID}) after ${maxRetries} retries`); - return 1; - } - } - await new Promise(resolve => setTimeout(resolve, retryDelay)); // Delay before retrying - } - }, - - CheckServerStatus: async (nitrado_cred, client) => { - const data = await module.exports.FetchServerSettings(nitrado_cred, client, 'CheckServerStatus'); // Fetch server status - - if (data && data != 1) { - if (data && data.data.gameserver.status === 'stopped') { - client.log(`Restart of Nitrado server ${nitrado_cred.ServerID} has been invoked by the bot, the periodic check showed status of "${data.data.gameserver.status}".`); - // Write optional "restart_message" to set in the Nitrado server logs and send a notice "message" to your server community. - restart_message = 'Server being restarted by periodic bot check.'; - message = 'The server was restarted by periodic bot check!'; - - module.exports.RestartServer(nitrado_cred, client, restart_message, message); - } - } - }, - - DisableBaseDamage: async (nitrado_cred, client, preference) => { - const pref = preference ? '1' : '0'; - const posted = await module.exports.PostServerSettings(nitrado_cred, client, "config", "disableBaseDamage", pref); - if (posted == 1) return 1; - - const remoteDirs = await GetRemoteDir(nitrado_cred, client); - if (remoteDirs == 1) return 1; - const basePath = remoteDirs.filter(dir => dir.type == 'dir')[0].path - const remoteDirsFromBase = await GetRemoteDir(nitrado_cred, client, basePath); - if (remoteDirsFromBase == 1) return 1; - const missionPath = remoteDirsFromBase[0].path; - const cfggameplayPath = `${missionPath}/cfggameplay.json`; - - const jsonDir = `./logs/cfggameplay.json`; - await module.exports.DownloadNitradoFile(nitrado_cred, client, cfggameplayPath, jsonDir); - - let gameplay = JSON.parse(fs.readFileSync(jsonDir)); - gameplay.GeneralData.disableBaseDamage = preference; - - // write JSON to file - fs.writeFileSync(jsonDir, JSON.stringify(gameplay, null, 2)); - - const uploaded = await UploadNitradoFile(nitrado_cred, client, missionPath, 'cfggameplay.json', jsonDir); - if (uploaded == 1) return 1; - - return 0; - }, - - DisableContainerDamage: async (nitrado_cred, client, preference) => { - const pref = preference ? '1' : '0'; - const posted = await module.exports.PostServerSettings(nitrado_cred, client, "config", "disableContainerDamage", pref); - if (posted == 1) return 1; - - const remoteDirs = await GetRemoteDir(nitrado_cred, client); - if (remoteDirs == 1) return 1; - const basePath = remoteDirs.filter(dir => dir.type == 'dir')[0].path - const remoteDirsFromBase = await GetRemoteDir(nitrado_cred, client, basePath); - if (remoteDirsFromBase == 1) return 1; - const missionPath = remoteDirsFromBase[0].path; - const cfggameplayPath = `${missionPath}/cfggameplay.json`; - - const jsonDir = `./logs/cfggameplay.json`; - await module.exports.DownloadNitradoFile(nitrado_cred, client, cfggameplayPath, jsonDir); - - let gameplay = JSON.parse(fs.readFileSync(jsonDir)); - gameplay.GeneralData.disableContainerDamage = preference; - - // write JSON to file - fs.writeFileSync(jsonDir, JSON.stringify(gameplay, null, 2)); - - const uploaded = await UploadNitradoFile(nitrado_cred, client, missionPath, 'cfggameplay.json', jsonDir); - if (uploaded == 1) return 1; - - return 0; - }, - - NitradoCredentialStatus: { - FAILED: "FAILED", - OK: "OK", - }, -} diff --git a/util/RegisterSlashCommands.js b/util/RegisterSlashCommands.js deleted file mode 100644 index a4c0cc0..0000000 --- a/util/RegisterSlashCommands.js +++ /dev/null @@ -1,68 +0,0 @@ -const fs = require("fs"); -const path = require("path"); -const { Routes } = require('discord.js'); -const { REST } = require('@discordjs/rest'); - -/** - * Register slash commands for a guild - * @param {require("../structures/DayzRBot")} client - */ -module.exports = { - // Register guild commands - RegisterGuildCommands: async (client, guild) => { - const commands = []; - const commandFiles = fs.readdirSync(path.join(__dirname, "..", "commands")).filter(file => file.endsWith('.js')); - - // Place your client and guild ids here - const clientId = client.application.id; - const guildId = guild; - - for (const file of commandFiles) { - const command = require(`../commands/${file}`); - if (!command.global) commands.push(command); // don't include global commands - } - - const rest = new REST({ version: '10' }).setToken(client.config.Token); - - try { - client.log(`[${guildId}] Started refreshing guild (/) commands.`); - - await rest.put( - Routes.applicationGuildCommands(clientId, guildId), - { body: commands }, - ); - - client.log(`[${guildId}] Successfully reloaded guild (/) commands.`); - } catch (error) { - client.error(error); - } - }, - - // Register global commands - RegisterGlobalCommands: async (client) => { - const commands = []; - const commandFiles = fs.readdirSync(path.join(__dirname, "..", "commands")).filter(file => file.endsWith('.js')); - - const clientId = client.application.id; - - for (const file of commandFiles) { - const command = require(`../commands/${file}`); - if (command.global) commands.push(command); - } - - const rest = new REST({ version: '10' }).setToken(client.config.Token); - - try { - client.log('[global] Started refreshing global (/) commands.'); - - await rest.put( - Routes.applicationCommands(clientId), - { body: commands }, - ); - - client.log('[global] Successfully reloaded global (/) commands.'); - } catch (error) { - client.error(error); - } - } -}; \ No newline at end of file diff --git a/util/Vector.js b/util/Vector.js deleted file mode 100644 index da6f0a0..0000000 --- a/util/Vector.js +++ /dev/null @@ -1,12 +0,0 @@ -module.exports = { - calculateVector: (pos1, pos2) => { - let delta = [Math.round(pos2[0] - pos1[0]), Math.round(pos2[1] - pos1[1])]; - let distance = parseFloat(Math.sqrt(Math.pow(delta[0], 2) + Math.pow(delta[1], 2)).toFixed(0)); - let thetat = Math.round(Math.atan2(delta[0], delta[1]) / Math.PI * 180); - let theta = (thetat < 0) ? (360 + thetat) : thetat; - let compass = ["S", "SW", "W", "NW", "N", "NE", "E", "SE", "S"]; - let dir = compass[Math.round(theta / 45)]; - - return {distance, theta, dir} - } -} \ No newline at end of file diff --git a/util/WebhookHandler.js b/util/WebhookHandler.js deleted file mode 100644 index bc017d5..0000000 --- a/util/WebhookHandler.js +++ /dev/null @@ -1,56 +0,0 @@ -const { makeURLSearchParams } = require('@discordjs/rest'); -const { REST } = require('@discordjs/rest'); -const { Routes } = require('discord.js'); - -const createWebhook = async (client, channel_id, name, avatar) => { - const rest = new REST({ version: '10' }).setToken(client.config.Token); - return await rest.post(Routes.channelWebhooks(channel_id), { - body: { - name: name, - avatar: avatar - } - }); -}; - -module.exports = { - GetWebhook: async (client, webhookName, channel_id) => { - // Get all webhooks from configured channel - const rest = new REST({ version: '10' }).setToken(client.config.Token); - const webhooks = await rest.get(Routes.channelWebhooks(channel_id)); - - let webhook = null; - if (webhooks.length == 0) { - // If no webhook exists, create new webhook with given name for this channel - webhook = createWebhook(client, channel_id, webhookName, client.config.AvatarData); - } else { - // Check existing webhooks for one with given name - let exists = false; - for (let i = 0; i < webhooks.length; i++) { - if (webhooks[i].name == webhookName) { - webhook = webhooks[i]; - exists = true; - break; - } - } - - if (!exists) webhook = createWebhook(client, channel_id, webhookName, client.config.AvatarData); - } - - return webhook; - }, - - WebhookSend: async (client, webhook, content) => { - const rest = new REST({ version: '10' }).setToken(client.config.Token); - return await rest.post(Routes.webhook(webhook.id, webhook.token), { - body: content, - query: makeURLSearchParams({ wait: true }) - }); - }, - - WebhookMessageEdit: async (client, webhook, message_id, content) => { - const rest = new REST({ version: '10' }).setToken(client.config.Token); - return rest.patch(Routes.webhookMessage(webhook.id, webhook.token, message_id), { - body: content - }); - } -}