Author SHA1 Message Date
SowinskiBraeden 37b6f3b1e1 fix admin perms access 2026-04-03 19:13:42 -07:00
SowinskiBraeden 71cd1808d9 auto clean whitespace 2026-03-26 10:12:45 -07:00
SowinskiBraeden 8abd3dadd1 update version number 2026-03-26 09:59:38 -07:00
SowinskiBraeden 67116c85be update player gamertags if changed, but same player ID 2026-03-25 15:15:20 -07:00
SowinskiBraeden bf95bba612 fix player online list log 2026-03-25 15:12:09 -07:00
SowinskiBraeden 11432cb262 ensure .adm files are sorted to choose latest 2026-03-25 12:02:22 -07:00
SowinskiBraeden 3b32c65340 update location link based on mission 2026-03-24 17:28:16 -07:00
SowinskiBraeden e8303fc14a fix log file find/download 2026-03-24 15:08:16 -07:00
SowinskiBraeden df6b9140ec fix/killfeed not updating #50 2025-03-15 10:43:28 -07:00
SowinskiBraeden 8249feaf62 fix/critical runaway code 2025-03-05 10:50:30 -08:00
SowinskiBraeden 66955361b0 update dependencies 2025-03-03 07:42:21 -08:00
SowinskiBraeden 316f4d44b6 fix/alarms handler queue undefined server 2025-03-03 07:40:39 -08:00
SowinskiBraeden 15d250eb76 update formatting 2025-02-05 13:54:11 -08:00
SowinskiBraeden 265f0d3f38 fix/player-list not responding on failed request 2025-01-11 15:49:56 -08:00
SowinskiBraeden cd2ae35a1f update 2025-01-11 11:28:34 -08:00
SowinskiBraeden 0abde2d041 Update LICENSE 2024-12-24 18:18:47 -08:00
SowinskiBraeden fff476c725 Merge pull request #48 from SowinskiBraeden/refactor/use-webhooks
Refactor/use webhooks from #25 & #38
2024-11-17 12:52:42 -08:00
SowinskiBraeden 72922dc3a3 fix/update victim stats after explosive death 2024-11-17 12:50:09 -08:00
SowinskiBraeden d1550ff7b5 fix/convert player list to webhooks 2024-11-17 12:40:46 -08:00
SowinskiBraeden dd983cf9f2 fix/convert killfeed to webhooks 2024-11-17 12:20:23 -08:00
SowinskiBraeden dfa36f2e4b fix/convert alarms to webhooks 2024-11-17 12:09:46 -08:00
SowinskiBraeden 8d822a352a fix/convert admin logs to webhooks 2024-11-17 11:47:07 -08:00
SowinskiBraeden eea202e131 update/webhook handlers 2024-11-17 11:23:01 -08:00
SowinskiBraeden 64c3ecf6bc fix/free unused armbands 2024-11-17 09:33:36 -08:00
SowinskiBraeden 5fb88a0a09 fix/handle failed mongo connection 2024-11-17 09:13:02 -08:00
SowinskiBraeden a3a0e978f9 fix/remove debug command 2024-11-17 08:43:41 -08:00
SowinskiBraeden 8274f8e0da fix/remove debug command 2024-11-17 08:43:03 -08:00
SowinskiBraeden 9e1f3ca371 update/help stats display 2024-11-10 19:36:24 -08:00
SowinskiBraeden 360fd450eb update/view excluded roles via config 2024-11-10 19:29:45 -08:00
SowinskiBraeden a536bc1045 fix/bot admin ping role 2024-11-10 18:39:10 -08:00
SowinskiBraeden 5859c07571 update/view bot admin roles via config 2024-11-10 18:35:48 -08:00
SowinskiBraeden 5e0a45554f update/view configured channels via config 2024-11-10 18:16:17 -08:00
SowinskiBraeden d4cf9ec613 update/fix config view command 2024-11-10 18:05:13 -08:00
SowinskiBraeden 35a1dac081 Update FUNDING.yml 2024-11-08 16:52:17 -08:00
SowinskiBraeden 862686bb07 fix/remove deprecated code 2024-11-08 16:38:31 -08:00
SowinskiBraeden b8197e18d2 Merge pull request #47 from SowinskiBraeden/update/nitrado-improvements
Update/nitrado improvements
2024-11-08 13:56:10 -08:00
SowinskiBraeden c0f59cc040 update/embed styles for credential status 2024-11-08 13:54:00 -08:00
SowinskiBraeden caf43aac4e update/add commands to check+reply nitrado credentials status 2024-11-08 13:49:54 -08:00
SowinskiBraeden bbe0fe5961 update/stop if nitrado credentials fail to fetch settings 2024-11-08 13:39:06 -08:00
SowinskiBraeden 2cb409a36a Merge pull request #46 from SowinskiBraeden/feature/disconnect-nitrado-credentials
update/disconnect nitrado credentials command
2024-11-08 12:58:28 -08:00
53 changed files with 1217 additions and 774 deletions

No files matched your search

+2 -2
View File
@@ -6,8 +6,8 @@ mongoURI='Your mongodb URI'
dbo='Your mongodb database' dbo='Your mongodb database'
# Encryption # Encryption
key='Secret Encryption Key', key='Secret Encryption Key'
iv='Secret Initialization Vector', iv='Secret Initialization Vector'
# Other Bot Configuration # Other Bot Configuration
Dev=PROD. # or DEV. Dev=PROD. # or DEV.
+1 -15
View File
@@ -1,15 +1 @@
# These are supported funding model platforms github: SowinskiBraeden
github: SowinskiBraeden # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
polar: # Replace with a single Polar username
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
thanks_dev: # Replace with a single thanks.dev username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+1 -3
View File
@@ -4,12 +4,10 @@ node_modules/*
# Testing/dev related # Testing/dev related
*_test.js *_test.js
dev-*.js dev-*.js
commands/debug.js
# Logs # Logs
logs/* logs/*
# env # env
.env .env
# Admin Script backups
admin/backup/*
+117 -17
View File
@@ -1,21 +1,121 @@
MIT License Creative Commons Legal Code
Copyright (c) 2023 Braeden Sowinski CC0 1.0 Universal
Permission is hereby granted, free of charge, to any person obtaining a copy CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
of this software and associated documentation files (the "Software"), to deal LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
in the Software without restriction, including without limitation the rights ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
copies of the Software, and to permit persons to whom the Software is REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
furnished to do so, subject to the following conditions: PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
The above copyright notice and this permission notice shall be included in all Statement of Purpose
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR The laws of most jurisdictions throughout the world automatically confer
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, exclusive Copyright and Related Rights (defined below) upon the creator
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE and subsequent owner(s) (each and all, an "owner") of an original work of
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER authorship and/or a database (each, a "Work").
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE Certain owners wish to permanently relinquish those rights to a Work for
SOFTWARE. the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.
+1 -1
View File
@@ -13,7 +13,7 @@ process.on('uncaughtException', async (error) => {
// Asynchronously write the error message to a log file using Promises // Asynchronously write the error message to a log file using Promises
await new Promise((resolve, reject) => { 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 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"), 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) => { `{"level":"error","message":"${d.getHours()}:${d.getMinutes()} - ${d.getMonth()+1}:${d.getDate()}:${d.getFullYear()} | uncaughtException: ${error.stack}"}`, (logErr) => {
if (logErr) { if (logErr) {
console.error('Error writing uncaughtException to log file:', logErr); console.error('Error writing uncaughtException to log file:', logErr);
+4 -4
View File
@@ -1,4 +1,4 @@
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder } = require('discord.js'); const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder, PermissionsBitField } = require('discord.js');
const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes;
const bitfieldCalculator = require('discord-bitfield-calculator'); const bitfieldCalculator = require('discord-bitfield-calculator');
const { Armbands } = require('../database/armbands.js'); const { Armbands } = require('../database/armbands.js');
@@ -125,10 +125,10 @@ module.exports = {
*/ */
run: async (client, interaction, args, { GuildDB }) => { run: async (client, interaction, args, { GuildDB }) => {
const permissions = bitfieldCalculator.permissions(interaction.member.permissions); const permissions = new PermissionsBitField(interaction.member.permissions).toArray();
let canUseCommand = false; let canUseCommand = false;
if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; if (permissions.includes("ManageGuild")) canUseCommand = true;
if (GuildDB.hasBotAdmin && interaction.member.roles.filter(e => GuildDB.botAdminRoles.indexOf(e) !== -1).length > 0) 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 (!canUseCommand) return interaction.send({ content: 'You don\'t have the permissions to use this command.' });
@@ -409,4 +409,4 @@ module.exports = {
} }
} }
} }
+18 -18
View File
@@ -1,4 +1,4 @@
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder } = require('discord.js'); const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder, PermissionsBitField } = require('discord.js');
const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes;
const bitfieldCalculator = require('discord-bitfield-calculator'); const bitfieldCalculator = require('discord-bitfield-calculator');
@@ -15,11 +15,11 @@ const generateAlarmMenus = (alarms, customId, placeholder, description) => {
currentAlarmComponents.addOptions({ currentAlarmComponents.addOptions({
label: alarm.name, label: alarm.name,
description: description, description: description,
value: alarm.name, value: alarm.name,
}); });
}); });
alarmComponents.push(new ActionRowBuilder().addComponents(currentAlarmComponents)); alarmComponents.push(new ActionRowBuilder().addComponents(currentAlarmComponents));
id++; id++;
} }
return alarmComponents; return alarmComponents;
@@ -34,7 +34,7 @@ module.exports = {
permissions: { permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: ["MANAGE_GUILD"], member: ["MANAGE_GUILD"],
}, },
options: [ options: [
{ {
name: "create", name: "create",
@@ -229,11 +229,11 @@ module.exports = {
* @param {string[]} args * @param {string[]} args
* @param {*} param3 * @param {*} param3
*/ */
run: async (client, interaction, args, { GuildDB }) => { run: async (client, interaction, args, { GuildDB }) => {
const permissions = bitfieldCalculator.permissions(interaction.member.permissions); const permissions = new PermissionsBitField(interaction.member.permissions).toArray();
let canUseCommand = false; let canUseCommand = false;
if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; if (permissions.includes("ManageGuild")) canUseCommand = true;
if (GuildDB.hasBotAdmin && interaction.member.roles.filter(e => GuildDB.botAdminRoles.indexOf(e) !== -1).length > 0) 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 (!canUseCommand) return interaction.send({ content: 'You don\'t have the permissions to use this command.' });
@@ -293,9 +293,9 @@ module.exports = {
return interaction.send({ components: alarmComponents, flags: (1 << 6) }); return interaction.send({ components: alarmComponents, flags: (1 << 6) });
} else if (args[0].name == 'add-player' || args[0].name == 'remove-player') { } else if (args[0].name == 'add-player' || args[0].name == 'remove-player') {
const add = args[0].name == 'add-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'}.`)] }); 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( const alarmComponents = generateAlarmMenus(
@@ -422,7 +422,7 @@ module.exports = {
if (interaction.customId.split('-')[1] == 'yes') { if (interaction.customId.split('-')[1] == 'yes') {
let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.customId.split('-')[2]); let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.customId.split('-')[2]);
client.dbo.collection('guilds').updateOne({ 'server.serverID': GuildDB.serverID }, { client.dbo.collection('guilds').updateOne({ 'server.serverID': GuildDB.serverID }, {
$pull: { $pull: {
'server.alarms': alarm, 'server.alarms': alarm,
@@ -430,17 +430,17 @@ module.exports = {
}, (err, res) => { }, (err, res) => {
if (err) return client.sendInternalError(interaction, err); if (err) return client.sendInternalError(interaction, err);
}); });
let successEmbed = new EmbedBuilder() let successEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Green) .setColor(client.config.Colors.Green)
.setDescription(`**Success:** Successfully Deleted **${interaction.customId.split('-')[2]}**`); .setDescription(`**Success:** Successfully Deleted **${interaction.customId.split('-')[2]}**`);
return interaction.update({ embeds: [successEmbed], components: [] }); return interaction.update({ embeds: [successEmbed], components: [] });
} else { } else {
let successEmbed = new EmbedBuilder() let successEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Green) .setColor(client.config.Colors.Green)
.setDescription(`The Zone Alarm **${interaction.customId.split('-')[2]}** will not be deleted.`); .setDescription(`The Zone Alarm **${interaction.customId.split('-')[2]}** will not be deleted.`);
return interaction.update({ embeds: [successEmbed], components: []}); return interaction.update({ embeds: [successEmbed], components: []});
} }
} }
@@ -449,14 +449,14 @@ module.exports = {
run: async(client, interaction, GuildDB) => { run: async(client, interaction, GuildDB) => {
let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0]); let alarm = GuildDB.alarms.find(alarm => alarm.name == interaction.values[0]);
let alarmIndex = GuildDB.alarms.indexOf(alarm); let alarmIndex = GuildDB.alarms.indexOf(alarm);
let playerStat = await client.dbo.collection("players").findOne({"gamertag": interaction.customId.split('-')[2]}); let playerStat = await client.dbo.collection("players").findOne({"gamertag": interaction.customId.split('-')[2]});
if (!client.exists(playerStat)) return interaction.update({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription('**Not Found** This player cannot be found, the gamertag may be incorrect or this player has not logged onto the server before.')], components: [] }); if (!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'; let add = interaction.customId.split('-')[1] == 'add';
if (add) alarm.ignoredPlayers.push(playerStat.playerID); if (add) alarm.ignoredPlayers.push(playerStat.playerID);
else alarm.ignoredPlayers = alarm.ignoredPlayers.filter((v) => { else alarm.ignoredPlayers = alarm.ignoredPlayers.filter((v) => {
return v != playerStat.playerID; return v != playerStat.playerID;
}); });
@@ -514,7 +514,7 @@ module.exports = {
value: alarm.rules[i] value: alarm.rules[i]
}); });
} }
const opt = new ActionRowBuilder().addComponents(alarmRules); const opt = new ActionRowBuilder().addComponents(alarmRules);
return interaction.update({ components: [opt], flags: (1 << 6) }); return interaction.update({ components: [opt], flags: (1 << 6) });
@@ -642,5 +642,5 @@ module.exports = {
return interaction.update({ embeds: [successEmbed], components: [] }); return interaction.update({ embeds: [successEmbed], components: [] });
} }
} }
} }
} }
+4 -4
View File
@@ -22,12 +22,12 @@ module.exports = {
*/ */
run: async (client, interaction, args, { GuildDB }) => { run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) 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 interaction.send({ content: `You are not allowed to use the bot in this channel.`, flags: (1 << 6) });
let available = new StringSelectMenuBuilder() let available = new StringSelectMenuBuilder()
.setCustomId(`View-1-${interaction.member.user.id}`) .setCustomId(`View-1-${interaction.member.user.id}`)
.setPlaceholder('View an armband from list 1') .setPlaceholder('View an armband from list 1')
let availableNext = new StringSelectMenuBuilder() let availableNext = new StringSelectMenuBuilder()
.setCustomId(`View-2-${interaction.member.user.id}`) .setCustomId(`View-2-${interaction.member.user.id}`)
.setPlaceholder('View an armband from list 2') .setPlaceholder('View an armband from list 2')
@@ -55,7 +55,7 @@ module.exports = {
if (tracker > 25) { if (tracker > 25) {
opt2 = new ActionRowBuilder().addComponents(availableNext); opt2 = new ActionRowBuilder().addComponents(availableNext);
compList.push(opt2); compList.push(opt2);
} }
return interaction.send({ components: compList, flags: (1 << 6) }); return interaction.send({ components: compList, flags: (1 << 6) });
}, },
+4 -4
View File
@@ -64,7 +64,7 @@ module.exports = {
} }
let banking = await client.dbo.collection("users").findOne({"user.userID": interaction.member.user.id}).then(banking => banking); let banking = await client.dbo.collection("users").findOne({"user.userID": interaction.member.user.id}).then(banking => banking);
if (!banking) { if (!banking) {
banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client) banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client)
if (!client.exists(banking)) return client.sendInternalError(interaction, err); if (!client.exists(banking)) return client.sendInternalError(interaction, err);
@@ -91,7 +91,7 @@ module.exports = {
if (!client.exists(banking)) return client.sendInternalError(interaction, err); if (!client.exists(banking)) return client.sendInternalError(interaction, err);
} }
targetUserBanking = targetUserBanking.user; targetUserBanking = targetUserBanking.user;
if (!client.exists(targetUserBanking.guilds[GuildDB.serverID])) { if (!client.exists(targetUserBanking.guilds[GuildDB.serverID])) {
const success = addUser(banking.guilds, GuildDB.serverID, targetUserID, client, GuildDB.startingBalance); const success = addUser(banking.guilds, GuildDB.serverID, targetUserID, client, GuildDB.startingBalance);
if (!success) return client.sendInternalError(interaction, 'Failed to add bank'); if (!success) return client.sendInternalError(interaction, 'Failed to add bank');
@@ -141,7 +141,7 @@ module.exports = {
if (!client.exists(banking)) return client.sendInternalError(interaction, err); if (!client.exists(banking)) return client.sendInternalError(interaction, err);
} }
targetUserBanking = targetUserBanking.user; targetUserBanking = targetUserBanking.user;
if (!client.exists(targetUserBanking.guilds[GuildDB.serverID])) { if (!client.exists(targetUserBanking.guilds[GuildDB.serverID])) {
const success = addUser(banking.guilds, GuildDB.serverID, targetUserID, client, GuildDB.startingBalance); const success = addUser(banking.guilds, GuildDB.serverID, targetUserID, client, GuildDB.startingBalance);
if (!success) return client.sendInternalError(interaction, 'Failed to add bank'); if (!success) return client.sendInternalError(interaction, 'Failed to add bank');
@@ -162,4 +162,4 @@ module.exports = {
} }
}, },
}, },
} }
+11 -11
View File
@@ -70,7 +70,7 @@ module.exports = {
let banking; let banking;
if (args[0].name == 'set' || args[0].name == 'pay') { 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); banking = await client.dbo.collection("users").findOne({"user.userID": interaction.member.user.id}).then(banking => banking);
if (!banking) { if (!banking) {
banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client) banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client)
if (!client.exists(banking)) return client.sendInternalError(interaction, err); if (!client.exists(banking)) return client.sendInternalError(interaction, err);
@@ -87,7 +87,7 @@ module.exports = {
let playerStat = await client.dbo.collection("players").findOne({"gamertag": args[0].options[0].value}); 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 (!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) { if (args[0].options[1].value > banking.guilds[GuildDB.serverID].balance) {
let nsf = new EmbedBuilder() let nsf = new EmbedBuilder()
.setDescription('**Bank Notice:** NSF. Non sufficient funds') .setDescription('**Bank Notice:** NSF. Non sufficient funds')
@@ -97,7 +97,7 @@ module.exports = {
} }
const newBalance = banking.guilds[GuildDB.serverID].balance - args[0].options[1].value; const newBalance = banking.guilds[GuildDB.serverID].balance - args[0].options[1].value;
client.dbo.collection("users").updateOne({ "user.userID": interaction.member.user.id }, { client.dbo.collection("users").updateOne({ "user.userID": interaction.member.user.id }, {
$set: { $set: {
[`user.guilds.${GuildDB.serverID}.balance`]: newBalance, [`user.guilds.${GuildDB.serverID}.balance`]: newBalance,
@@ -115,24 +115,24 @@ module.exports = {
playerStat.bountiesLength = playerStat.bounties.length; // Will ensure bounties length = # of bounties, even if bountiesLength does not exists in player stat. 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); await UpdatePlayer(client, playerStat, interaction);
const successEmbed = new EmbedBuilder() const successEmbed = new EmbedBuilder()
.setTitle('Success') .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 </bounty view:1086786904671924267>`) .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 </bounty view:1086786904671924267>`)
.setColor(client.config.Colors.Green); .setColor(client.config.Colors.Green);
return interaction.send({ embeds: [successEmbed], flags: (1 << 6) }); return interaction.send({ embeds: [successEmbed], flags: (1 << 6) });
} else if (args[0].name == 'pay') { } else if (args[0].name == 'pay') {
let playerStat = await client.dbo.collection("players").findOne({"discordID": interaction.member.user.id}); 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 (!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) { if (playerStat.bounties.length == 0) {
const noBounty = new EmbedBuilder() const noBounty = new EmbedBuilder()
.setColor(client.config.Colors.Yellow) .setColor(client.config.Colors.Yellow)
.setDescription(`You have no bounties to pay off.`) .setDescription(`You have no bounties to pay off.`)
return interaction.send({ embeds: [noBounty] }); return interaction.send({ embeds: [noBounty] });
} }
@@ -150,14 +150,14 @@ module.exports = {
} }
const newBalance = banking.guilds[GuildDB.serverID].balance - (totalBounty * 2); 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) => { 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); if (err) return client.sendInternalError(interaction, err);
}); });
playerStat.bounties = []; playerStat.bounties = [];
playerStat.bountiesLength = 0; playerStat.bountiesLength = 0;
await UpdatePlayer(client, playerStat, interaction); await UpdatePlayer(client, playerStat, interaction);
const payedOff = new EmbedBuilder() const payedOff = new EmbedBuilder()
@@ -171,7 +171,7 @@ module.exports = {
const activeBounties = await client.dbo.collection("players").find({ const activeBounties = await client.dbo.collection("players").find({
"bountiesLength": { $gt: 0 } "bountiesLength": { $gt: 0 }
}).toArray(); }).toArray();
let bountiesEmbed = new EmbedBuilder() let bountiesEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Default) .setColor(client.config.Colors.Default)
.setDescription('**Active Boutnies**'); .setDescription('**Active Boutnies**');
@@ -187,4 +187,4 @@ module.exports = {
} }
}, },
}, },
} }
+9 -9
View File
@@ -52,7 +52,7 @@ module.exports = {
const warnArmbadChange = new EmbedBuilder() const warnArmbadChange = new EmbedBuilder()
.setColor(client.config.Colors.Yellow) .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?`) .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() const opt = new ActionRowBuilder()
.addComponents( .addComponents(
new ButtonBuilder() new ButtonBuilder()
@@ -71,7 +71,7 @@ module.exports = {
let available = new StringSelectMenuBuilder() let available = new StringSelectMenuBuilder()
.setCustomId(`Claim-${args[0].value}-1-${interaction.member.user.id}`) .setCustomId(`Claim-${args[0].value}-1-${interaction.member.user.id}`)
.setPlaceholder('Select an armband from list 1 to claim') .setPlaceholder('Select an armband from list 1 to claim')
let availableNext = new StringSelectMenuBuilder() let availableNext = new StringSelectMenuBuilder()
.setCustomId(`Claim-${args[0].value}-2-${interaction.member.user.id}`) .setCustomId(`Claim-${args[0].value}-2-${interaction.member.user.id}`)
.setPlaceholder('Select an armband from list 2 to claim') .setPlaceholder('Select an armband from list 2 to claim')
@@ -98,7 +98,7 @@ module.exports = {
if (tracker > 25) { if (tracker > 25) {
opt2 = new ActionRowBuilder().addComponents(availableNext); opt2 = new ActionRowBuilder().addComponents(availableNext);
compList.push(opt2); compList.push(opt2);
} }
return interaction.send({ components: compList }); return interaction.send({ components: compList });
}, },
@@ -106,7 +106,7 @@ module.exports = {
Interactions: { Interactions: {
Claim: { Claim: {
run: async (client, interaction, GuildDB) => { run: async (client, interaction, GuildDB) => {
if (!interaction.customId.endsWith(interaction.member.user.id)) if (!interaction.customId.endsWith(interaction.member.user.id))
return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) }); return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) });
let factionID = interaction.customId.split('-')[1]; let factionID = interaction.customId.split('-')[1];
@@ -134,7 +134,7 @@ module.exports = {
if (err) return client.sendInternalError(interaction, err); if (err) return client.sendInternalError(interaction, err);
}) })
} }
client.dbo.collection("guilds").updateOne({'server.serverID': GuildDB.serverID}, query, (err, res) => { client.dbo.collection("guilds").updateOne({'server.serverID': GuildDB.serverID}, query, (err, res) => {
if (err) return client.sendInternalError(interaction, err); if (err) return client.sendInternalError(interaction, err);
}) })
@@ -159,14 +159,14 @@ module.exports = {
ChangeArmband: { ChangeArmband: {
run: async (client, interaction, GuildDB) => { run: async (client, interaction, GuildDB) => {
if (!interaction.customId.endsWith(interaction.member.user.id)) if (!interaction.customId.endsWith(interaction.member.user.id))
return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) }); return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) });
if (interaction.customId.split('-')[1]=='yes') { if (interaction.customId.split('-')[1]=='yes') {
let available = new StringSelectMenuBuilder() let available = new StringSelectMenuBuilder()
.setCustomId(`Claim-${interaction.customId.split('-')[2]}-update-1-${interaction.member.user.id}`) .setCustomId(`Claim-${interaction.customId.split('-')[2]}-update-1-${interaction.member.user.id}`)
.setPlaceholder('Select an armband from list 1 to claim') .setPlaceholder('Select an armband from list 1 to claim')
let availableNext = new StringSelectMenuBuilder() let availableNext = new StringSelectMenuBuilder()
.setCustomId(`Claim-${interaction.customId.split('-')[2]}-update-2-${interaction.member.user.id}`) .setCustomId(`Claim-${interaction.customId.split('-')[2]}-update-2-${interaction.member.user.id}`)
.setPlaceholder('Select an armband from list 2 to claim') .setPlaceholder('Select an armband from list 2 to claim')
@@ -193,9 +193,9 @@ module.exports = {
if (tracker > 25) { if (tracker > 25) {
opt2 = new ActionRowBuilder().addComponents(availableNext); opt2 = new ActionRowBuilder().addComponents(availableNext);
compList.push(opt2); compList.push(opt2);
} }
return interaction.update({ embeds: [], components: compList }); return interaction.update({ embeds: [], components: compList });
} else { } else {
const cancel = new EmbedBuilder() const cancel = new EmbedBuilder()
+5 -5
View File
@@ -22,7 +22,7 @@ module.exports = {
*/ */
run: async (client, interaction, args, { GuildDB }) => { run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) { 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 interaction.send({ content: `You are not allowed to use the bot in this channel.`, flags: (1 << 6) });
} }
const hasIncomeRole = GuildDB.incomeRoles.some(data => { const hasIncomeRole = GuildDB.incomeRoles.some(data => {
@@ -41,7 +41,7 @@ module.exports = {
let banking = await client.dbo.collection("users").findOne({"user.userID": interaction.member.user.id}).then(banking => banking); let banking = await client.dbo.collection("users").findOne({"user.userID": interaction.member.user.id}).then(banking => banking);
if (!banking) { if (!banking) {
banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client) banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client)
if (!client.exists(banking)) return client.sendInternalError(interaction, err); if (!client.exists(banking)) return client.sendInternalError(interaction, err);
@@ -54,7 +54,7 @@ module.exports = {
} }
if (!client.exists(banking.guilds[GuildDB.serverID].lastIncome)) banking.guilds[GuildDB.serverID].lastIncome = new Date('2000-01-01T00:00:00'); 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 now = new Date();
let diff = (now - banking.guilds[GuildDB.serverID].lastIncome) / 1000; let diff = (now - banking.guilds[GuildDB.serverID].lastIncome) / 1000;
diff /= (60 * 60); diff /= (60 * 60);
@@ -96,7 +96,7 @@ module.exports = {
date.setHours(date.getHours() + GuildDB.incomeLimiter); date.setHours(date.getHours() + GuildDB.incomeLimiter);
diff = (date - now) / 1000; diff = (date - now) / 1000;
let timeTillIncome = client.secondsToDhms(diff); let timeTillIncome = client.secondsToDhms(diff);
const error = new EmbedBuilder() const error = new EmbedBuilder()
.setColor(client.config.Colors.Red) .setColor(client.config.Colors.Red)
.setDescription(`You've already collected your income this week. Wait **${timeTillIncome}** to collect again.`); .setDescription(`You've already collected your income this week. Wait **${timeTillIncome}** to collect again.`);
@@ -105,4 +105,4 @@ module.exports = {
} }
}, },
}, },
} }
+4 -4
View File
@@ -53,7 +53,7 @@ module.exports = {
let comp; let comp;
if (discord) comp = leaderboard.find(s => s.discordID == discord); if (discord) comp = leaderboard.find(s => s.discordID == discord);
if (gamertag) comp = leaderboard.find(s => s.gamertag == gamertag); if (gamertag) comp = leaderboard.find(s => s.gamertag == gamertag);
let self = leaderboard.find(s => s.discordID == interaction.member.user.id); 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(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.`)] });
@@ -90,7 +90,7 @@ module.exports = {
const diff = Math.abs(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 (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))); if (compData.length < selfData.length) compData.unshift(...(new Array(diff).fill(null, 0, diff)));
const chart = { const chart = {
type: 'line', type: 'line',
data: { data: {
@@ -131,7 +131,7 @@ module.exports = {
}, },
}, },
}; };
const encodedChart = encodeURIComponent(JSON.stringify(chart)); const encodedChart = encodeURIComponent(JSON.stringify(chart));
const chartURL = `https://quickchart.io/chart?c=${encodedChart}&bkg=${encodeURIComponent("#ded8d7")}`; const chartURL = `https://quickchart.io/chart?c=${encodedChart}&bkg=${encodeURIComponent("#ded8d7")}`;
@@ -140,4 +140,4 @@ module.exports = {
return interaction.send({ embeds: [statsEmbed] }); return interaction.send({ embeds: [statsEmbed] });
}, },
}, },
} }
+278 -122
View File
@@ -1,6 +1,6 @@
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js'); const { PermissionsBitField, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js');
const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes;
const bitfieldCalculator = require('discord-bitfield-calculator'); // const bitfieldCalculator = require('discord-bitfield-calculator');
const { getDefaultSettings } = require('../database/guild'); const { getDefaultSettings } = require('../database/guild');
module.exports = { module.exports = {
@@ -12,7 +12,7 @@ module.exports = {
permissions: { permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: ["MANAGE_GUILD"], member: ["MANAGE_GUILD"],
}, },
options: [ options: [
{ {
name: "killfeed", name: "killfeed",
@@ -99,7 +99,13 @@ module.exports = {
name: "clear", name: "clear",
description: "Clears all configured channels", description: "Clears all configured channels",
value: "clear", value: "clear",
type: CommandOptions.SubCommand, type: CommandOptions.SubCommand,
},
{
name: "view",
description: "View configured allowed channels",
value: "view",
type: CommandOptions.SubCommand,
} }
] ]
}, },
@@ -160,31 +166,46 @@ module.exports = {
name: "bot_admin_role", name: "bot_admin_role",
description: "Set/remove bot admin role", description: "Set/remove bot admin role",
value: "bot_admin_role", value: "bot_admin_role",
type: CommandOptions.SubCommand, type: CommandOptions.SubCommandGroup,
options: [ options: [
{ {
name: "action", name: "add",
description: "Set or remove a role to be a bot administrator", description: "Configure role to be bot admin",
value: "action", value: "add",
type: CommandOptions.String, type: CommandOptions.SubCommand,
choices: [ options: [{
{ name: 'add', value: 'add' }, { name: 'remove', value: 'remove' }, name: "role",
], description: "Role to confiure",
required: true, value: "role",
type: CommandOptions.Role,
required: true,
}]
}, },
{ {
name: "role", name: "remove",
description: "Role to configure", description: "Remove configured role as bot admin",
value: "role", value: "remove",
type: CommandOptions.Role, type: CommandOptions.SubCommand,
required: true, 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_role", name: "admin_ping_role",
description: "Admin role to ping in admin logs channel", description: "Admin role to ping in admin logs channel",
value: "admin_role", value: "admin_ping_role",
type: CommandOptions.SubCommand, type: CommandOptions.SubCommand,
options: [{ options: [{
name: "role", name: "role",
@@ -196,26 +217,41 @@ module.exports = {
}, },
{ {
name: "exclude", name: "exclude",
description: "Exclude roles that users can use to claim an armband", description: "Exclude roles that can be used to claim armbands",
value: "exclude", value: "exclude",
type: CommandOptions.SubCommand, type: CommandOptions.SubCommandGroup,
options: [ options: [
{ {
name: "action", name: "add",
description: "Add or remove a role from the exclude list.", description: "Configure role to be excluded",
value: "action", value: "add",
type: CommandOptions.String, type: CommandOptions.SubCommand,
choices: [ options: [{
{ name: 'add', value: 'add' }, { name: 'remove', value: 'remove' }, name: "role",
], description: "Role to confiure",
required: true, value: "role",
type: CommandOptions.Role,
required: true,
}]
}, },
{ {
name: "role", name: "remove",
description: "The role to manage", description: "Remove configured role thats excluded",
value: "role", value: "remove",
type: CommandOptions.Role, type: CommandOptions.SubCommand,
required: true, 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,
}, },
] ]
}, },
@@ -383,7 +419,7 @@ module.exports = {
required: true, required: true,
}] }]
} }
], ],
SlashCommand: { SlashCommand: {
/** /**
* *
@@ -392,11 +428,12 @@ module.exports = {
* @param {string[]} args * @param {string[]} args
* @param {*} param3 * @param {*} param3
*/ */
run: async (client, interaction, args, { GuildDB }) => { run: async (client, interaction, args, { GuildDB }) => {
const permissions = bitfieldCalculator.permissions(interaction.member.permissions); // const permissions = new PermissionsBitField(interaction.member.permissions).toArray();
const permissions = new PermissionsBitField(interaction.member.permissions).toArray();
let canUseCommand = false; let canUseCommand = false;
if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; if (permissions.includes("ManageGuild")) canUseCommand = true;
if (GuildDB.hasBotAdmin && interaction.member.roles.filter(e => GuildDB.botAdminRoles.indexOf(e) !== -1).length > 0) 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 (!canUseCommand) return interaction.send({ content: 'You don\'t have the permissions to use this command.' });
@@ -415,7 +452,7 @@ module.exports = {
if (!channelAdd) {error=true;newChannelErrorEmbed.setDescription(`**Error Notice:** Cannot find that channel.`);} 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 (channelAdd.type=="voice") {error=true;newChannelErrorEmbed.setDescription(`**Error Notice:** Cannot add voice channel to allowed channels.`);}
if (error) return interaction.send({ embeds: [newChannelErrorEmbed] }); if (error) return interaction.send({ embeds: [newChannelErrorEmbed] });
client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID}, {$push:{"server.allowedChannels": channelid}}, (err, res) => { client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID}, {$push:{"server.allowedChannels": channelid}}, (err, res) => {
if (err) return client.sendInternalError(interaction, err); if (err) return client.sendInternalError(interaction, err);
}); });
@@ -450,7 +487,7 @@ module.exports = {
) )
return interaction.send({ embeds: [promptRemoveChannel], components: [optRemoveChannel], flags: (1 << 6) }); return interaction.send({ embeds: [promptRemoveChannel], components: [optRemoveChannel], flags: (1 << 6) });
} else if (channels_config == 'clear') { } else if (channels_config == 'clear') {
const errorNoAllowedChannels = new EmbedBuilder() const errorNoAllowedChannels = new EmbedBuilder()
@@ -476,25 +513,50 @@ module.exports = {
) )
return interaction.send({ embeds: [promptClearChannels], components: [optClearChannels], flags: (1 << 6) }); 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': case 'bot_admin_role':
if (args[0].options[0].value == 'add') { const bot_admin_config = args[0].options[0].name;
const botAdminRoleId = args[0].options[1].value; 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) => { client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID},{$push: {"server.botAdminRoles": botAdminRoleId}}, (err, res) => {
if (err) return client.sendInternalError(interaction, err); if (err) return client.sendInternalError(interaction, err);
}); });
const successSetBotAdminRoleEmbed = new EmbedBuilder() const successSetBotAdminRoleEmbed = new EmbedBuilder()
.setDescription(`Successfully added <@&${botAdminRoleId}> as a bot admin role.\nUsers with this role can use restricted commands.`) .setDescription(`Successfully added <@&${botAdminRoleId}> as a bot admin role.\nUsers with this role can use restricted commands.`)
.setColor(client.config.Colors.Green); .setColor(client.config.Colors.Green);
return interaction.send({ embeds: [successSetBotAdminRoleEmbed] });
} else if (args[0].options[0].value== 'remove') { return interaction.send({ embeds: [successSetBotAdminRoleEmbed] });
} else if (bot_admin_config == 'remove') {
if (!GuildDB.botAdminRoles.includes(botAdminRoleId)) { if (!GuildDB.botAdminRoles.includes(botAdminRoleId)) {
const nonAdminRoleEmbed = new EmbedBuilder() const nonAdminRoleEmbed = new EmbedBuilder()
@@ -521,41 +583,92 @@ module.exports = {
) )
return interaction.send({ embeds: [promptRemoveAdminRole], components: [optRemoveAdminRole], flags: (1 << 6) }); 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_role': case 'admin_ping_role':
client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID},{$set: {"server.adminRole": args[0].options[0].value}}, (err, res) => { 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); if (err) return client.sendInternalError(interaction, err);
}); });
const successSetAdminRoleEmbed = new EmbedBuilder() const successSetAdminRoleEmbed = new EmbedBuilder()
.setDescription(`Successfully set <@&${args[0].options[0].value}> as the server admin role..`) .setDescription(`Successfully set <@&${args[0].options[0].value}> as the server admin role..`)
.setColor(client.config.Colors.Green); .setColor(client.config.Colors.Green);
return interaction.send({ embeds: [successSetAdminRoleEmbed] }); return interaction.send({ embeds: [successSetAdminRoleEmbed] });
case 'exclude': case 'exclude':
if (args[0].options[0].value == 'add') { const exclude_config = args[0].options[0].name;
client.dbo.collection('guilds').updateOne({'server.serverID': GuildDB.serverID}, {$push: {'server.excludedRoles': args[0].options[1].value}}, (err, res) => { 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); if (err) return client.sendInternalError(interaction, err);
}) })
const successExcludeEmbed = new EmbedBuilder() const successExcludeEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Green) .setColor(client.config.Colors.Green)
.setDescription(`**Done!**\n> Successfully added <@&${args[0].options[1].value}> to list of excluded roles.`) .setDescription(`**Done!**\n> Successfully added <@&${exclude_roleid}> to list of excluded roles.`)
return interaction.send({ embeds: [successExcludeEmbed] }); return interaction.send({ embeds: [successExcludeEmbed] });
} else if (args[0].options[0].value == 'remove') { } else if (exclude_config == 'remove') {
client.dbo.collection('guilds').updateOne({'server.serverID': GuildDB.serverID}, {$pull: {'server.excludedRoles': args[0].options[1].value}}, (err, res) => { client.dbo.collection('guilds').updateOne({'server.serverID': GuildDB.serverID}, {$pull: {'server.excludedRoles': exclude_roleid}}, (err, res) => {
if (err) return client.sendInternalError(interaction, err); if (err) return client.sendInternalError(interaction, err);
}) })
const successRemoveExcludeEmbed = new EmbedBuilder() const successRemoveExcludeEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Green) .setColor(client.config.Colors.Green)
.setDescription(`**Done!**\n> Successfully removed <@&${args[0].options[1].value}> to list of excluded roles.`) .setDescription(`**Done!**\n> Successfully removed <@&${exclude_roleid}> to list of excluded roles.`)
return interaction.send({ embeds: [successRemoveExcludeEmbed] }); 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': case 'reset':
@@ -577,26 +690,69 @@ module.exports = {
) )
return interaction.send({ embeds: [promptReset], components: [optReset], flags: (1 << 6) }); return interaction.send({ embeds: [promptReset], components: [optReset], flags: (1 << 6) });
case 'view':
const channelsInfo = GuildDB.customChannelStatus ? '\n╚➤ \`/channels\` to view' : '';
const channelColor = GuildDB.customChannelStatus ? '+ ' : '- ';
let botAdminRoles = '';
for (let i = 0; i < GuildDB.botAdminRoles.length; i++) {
botAdminRoles += `\n╚➤ <@&${GuildDB.botAdminRoles[i]}>`;
}
const botAdminRoleColor = GuildDB.hasBotAdmin ? `+ ` : '- ';
const excludedRolesColor = GuildDB.excludedRoles.length > 0 ? `+ ` : '- ';
const excludedRolesInfo = GuildDB.excludedRoles.length > 0 ? '\n╚➤ \`/excluded\` to view' : '';
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 ? '\`</channels:1225869620813107246>\` 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() const settingsEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Default) .setColor(client.config.Colors.Default)
.setTitle('Current Guild Configurations') .setTitle('Current Guild Configurations')
.addFields( .addFields(
{ name: 'Guild ID', value: `\`\`\`arm\n${GuildDB.serverID}\`\`\``, inline: true }, { name: 'Guild ID', value: `${w}${f}${GuildDB.serverID}${w}`, inline: true },
{ name: 'Has Allowed Channels?', value: `\`\`\`diff\n${channelColor}${GuildDB.customChannelStatus}\`\`\`${channelsInfo}`, inline: true }, { name: 'Server Name', value: `${w}${f}${GuildDB.serverName}${w}`, inline: true },
{ name: 'Has bot admin role?', value: `\`\`\`diff\n${botAdminRoleColor}${client.exists(GuildDB.botAdmin)}\`\`\`${botAdminRoles}`, inline: true }, { name: 'Auto Restart', value: `${w}${a}${autoRestart}${w}`, inline: true },
{ name: 'Excluded roles?', value: `\`\`\`diff\n${excludedRolesColor}${GuildDB.excludedRoles.length > 0}\`\`\`${excludedRolesInfo}` }, { 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] }); return interaction.send({ embeds: [settingsEmbed] });
@@ -608,50 +764,50 @@ module.exports = {
client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID},{$set: {[`server.${channelType}`]: channel}}, (err, res) => { client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID},{$set: {[`server.${channelType}`]: channel}}, (err, res) => {
if (err) return client.sendInternalError(interaction, err); if (err) return client.sendInternalError(interaction, err);
}); });
const successSetChannelEmbed = new EmbedBuilder() const successSetChannelEmbed = new EmbedBuilder()
.setDescription(`Successfully set <#${channel}> as the ${channelType} channel.`) .setDescription(`Successfully set <#${channel}> as the ${channelType} channel.`)
.setColor(client.config.Colors.Green); .setColor(client.config.Colors.Green);
return interaction.send({ embeds: [successSetChannelEmbed] }); return interaction.send({ embeds: [successSetChannelEmbed] });
case 'linked_gt_role': case 'linked_gt_role':
const linked_gt_role = args[0].options[0].value; 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) => { client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID},{$set: {"server.linkedGamertagRole": linked_gt_role}}, (err, res) => {
if (err) return client.sendInternalError(interaction, err); if (err) return client.sendInternalError(interaction, err);
}); });
const successLinkedGTRoleEmbed = new EmbedBuilder() const successLinkedGTRoleEmbed = new EmbedBuilder()
.setDescription(`Successfully set <@&${linked_gt_role}> to give to users who link their gamertag.`) .setDescription(`Successfully set <@&${linked_gt_role}> to give to users who link their gamertag.`)
.setColor(client.config.Colors.Green); .setColor(client.config.Colors.Green);
return interaction.send({ embeds: [successLinkedGTRoleEmbed] }); return interaction.send({ embeds: [successLinkedGTRoleEmbed] });
case 'member_role': case 'member_role':
const member_role = args[0].options[0].value; const member_role = args[0].options[0].value;
client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID},{$set: {"server.memberRole": member_role}}, (err, res) => { client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID},{$set: {"server.memberRole": member_role}}, (err, res) => {
if (err) return client.sendInternalError(interaction, err); if (err) return client.sendInternalError(interaction, err);
}); });
const successMemberRoleEmbed = new EmbedBuilder() const successMemberRoleEmbed = new EmbedBuilder()
.setDescription(`Successfully set <@&${member_role}> to give to users who link they join.`) .setDescription(`Successfully set <@&${member_role}> to give to users who link they join.`)
.setColor(client.config.Colors.Green); .setColor(client.config.Colors.Green);
return interaction.send({ embeds: [successMemberRoleEmbed] }); return interaction.send({ embeds: [successMemberRoleEmbed] });
case 'starting_balance': case 'starting_balance':
client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set: {"server.startingBalance":args[0].options[0].value}}, (err, res) => { 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); if (err) return client.sendInternalError(interaction, err);
}); });
let successSetStartingBalanceEmbed = new EmbedBuilder() let successSetStartingBalanceEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Green) .setColor(client.config.Colors.Green)
.setDescription(`Successfully set $${args[0].options[0].value.toFixed(2)} as starting balance`); .setDescription(`Successfully set $${args[0].options[0].value.toFixed(2)} as starting balance`);
return interaction.send({ embeds: [successSetStartingBalanceEmbed] }); return interaction.send({ embeds: [successSetStartingBalanceEmbed] });
case 'income_role': case 'income_role':
if (args[0].options[0].name== 'set') { if (args[0].options[0].name== 'set') {
const incomeRoleId = args[0].options[0].options[0].value const incomeRoleId = args[0].options[0].options[0].value
@@ -660,17 +816,17 @@ module.exports = {
let errorIncomeAmount = new EmbedBuilder() let errorIncomeAmount = new EmbedBuilder()
.setDescription('**Error Notice:** Amount cannot be $0 or less than $0.') .setDescription('**Error Notice:** Amount cannot be $0 or less than $0.')
.setColor(client.config.Colors.Red); .setColor(client.config.Colors.Red);
return interaction.send({ embeds: [errorIncomeAmount] }); return interaction.send({ embeds: [errorIncomeAmount] });
} }
const searchIndex = GuildDB.incomeRoles.findIndex((role) => role.role==incomeRoleId); const searchIndex = GuildDB.incomeRoles.findIndex((role) => role.role==incomeRoleId);
if (searchIndex == -1) { if (searchIndex == -1) {
const newIncome = { const newIncome = {
role: incomeRoleId, role: incomeRoleId,
income: args[0].options[0].options[1].value, income: args[0].options[0].options[1].value,
} }
client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID}, {$push: {"server.incomeRoles":newIncome}}, (err, res) => { client.dbo.collection("guilds").updateOne({"server.serverID":GuildDB.serverID}, {$push: {"server.incomeRoles":newIncome}}, (err, res) => {
if (err) return client.sendInternalError(interaction, err); if (err) return client.sendInternalError(interaction, err);
}); });
@@ -688,12 +844,12 @@ module.exports = {
}); });
} }
const perform = searchIndex == -1 ? 'set' : 'updated'; const perform = searchIndex == -1 ? 'set' : 'updated';
const successIncomeRoleEmbed = new EmbedBuilder() const successIncomeRoleEmbed = new EmbedBuilder()
.setDescription(`Successfully ${perform} <@&${incomeRoleId}>'s income to $${args[0].options[0].options[1].value}`) .setDescription(`Successfully ${perform} <@&${incomeRoleId}>'s income to $${args[0].options[0].options[1].value}`)
.setColor(client.config.Colors.Green); .setColor(client.config.Colors.Green);
return interaction.send({ embeds: [successIncomeRoleEmbed] }); return interaction.send({ embeds: [successIncomeRoleEmbed] });
} else if (args[0].options[0].name== 'remove') { } else if (args[0].options[0].name== 'remove') {
const searchIndex = GuildDB.incomeRoles.findIndex((role) => role.role==incomeRoleId); const searchIndex = GuildDB.incomeRoles.findIndex((role) => role.role==incomeRoleId);
@@ -702,7 +858,7 @@ module.exports = {
.setDescription('**Error Notice:** Role not found') .setDescription('**Error Notice:** Role not found')
.setColor(client.config.Colors.Red); .setColor(client.config.Colors.Red);
return interaction.send({ embeds: [errorIncomeNotFoundEmbed] }); return interaction.send({ embeds: [errorIncomeNotFoundEmbed] });
} else { } else {
const promptRemoveIncomeRole = new EmbedBuilder() const promptRemoveIncomeRole = new EmbedBuilder()
.setTitle(`Are you sure you want to remove this role as an income?`) .setTitle(`Are you sure you want to remove this role as an income?`)
@@ -723,45 +879,45 @@ module.exports = {
return interaction.send({ embeds: [promptRemoveIncomeRole], components: [optRemoveIncomeRole], flags: (1 << 6) }); return interaction.send({ embeds: [promptRemoveIncomeRole], components: [optRemoveIncomeRole], flags: (1 << 6) });
} }
} }
case 'income_limiter': case 'income_limiter':
client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set: {"server.incomeLimiter":args[0].options[0].value}}, (err, res) => { 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); if (err) return client.sendInternalError(interaction, err);
}); });
let successIncomeLimiterEmbed = new EmbedBuilder() let successIncomeLimiterEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Green) .setColor(client.config.Colors.Green)
.setDescription(`Successfully set **${args[0].options[0].value} hours** as the wait time to collect income.`); .setDescription(`Successfully set **${args[0].options[0].value} hours** as the wait time to collect income.`);
return interaction.send({ embeds: [successIncomeLimiterEmbed] }); return interaction.send({ embeds: [successIncomeLimiterEmbed] });
case 'uav-price': case 'uav-price':
client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set: {"server.uavPrice":args[0].options[0].value}}, (err, res) => { 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); if (err) return client.sendInternalError(interaction, err);
}); });
let successUAVPriceEmbed = new EmbedBuilder() let successUAVPriceEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Green) .setColor(client.config.Colors.Green)
.setDescription(`Successfully set $${args[0].options[0].value.toFixed(2)} as UAV price`); .setDescription(`Successfully set $${args[0].options[0].value.toFixed(2)} as UAV price`);
return interaction.send({ embeds: [successUAVPriceEmbed] }); return interaction.send({ embeds: [successUAVPriceEmbed] });
case 'emp-price': case 'emp-price':
client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set: {"server.empPrice":args[0].options[0].value}}, (err, res) => { 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); if (err) return client.sendInternalError(interaction, err);
}); });
let successEMPPriceEmbed = new EmbedBuilder() let successEMPPriceEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Green) .setColor(client.config.Colors.Green)
.setDescription(`Successfully set $${args[0].options[0].value.toFixed(2)} as EMP price`); .setDescription(`Successfully set $${args[0].options[0].value.toFixed(2)} as EMP price`);
return interaction.send({ embeds: [successEMPPriceEmbed] }); return interaction.send({ embeds: [successEMPPriceEmbed] });
case 'combat-log-timer': case 'combat-log-timer':
client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set: {"server.combatLogTimer":args[0].options[0].value}}, (err, res) => { 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); if (err) return client.sendInternalError(interaction, err);
}); });
let successCobatLogTimerEmbed = new EmbedBuilder() let successCobatLogTimerEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Green) .setColor(client.config.Colors.Green)
.setDescription(`Successfully set combat log timer to **${args[0].options[0].value.toFixed(0)} minutes.**`); .setDescription(`Successfully set combat log timer to **${args[0].options[0].value.toFixed(0)} minutes.**`);
@@ -769,12 +925,12 @@ module.exports = {
return interaction.send({ embeds: [successCobatLogTimerEmbed] }); return interaction.send({ embeds: [successCobatLogTimerEmbed] });
case 'toggle-uav-purchase': case 'toggle-uav-purchase':
const togggleUAVpurchase = args[0].options[0].value ? 1 : 0; const togggleUAVpurchase = args[0].options[0].value ? 1 : 0;
client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set: {"server.purchaseUAV": togggleUAVpurchase}}, (err, res) => { client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set: {"server.purchaseUAV": togggleUAVpurchase}}, (err, res) => {
if (err) return client.sendInternalError(interaction, err); if (err) return client.sendInternalError(interaction, err);
}); });
let successToggleUAVpurchaseEmbed = new EmbedBuilder() let successToggleUAVpurchaseEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Green) .setColor(client.config.Colors.Green)
.setDescription(`Users can ${togggleUAVpurchase ? 'now' : 'no longer'} purchase UAVs.`); .setDescription(`Users can ${togggleUAVpurchase ? 'now' : 'no longer'} purchase UAVs.`);
@@ -782,12 +938,12 @@ module.exports = {
return interaction.send({ embeds: [successToggleUAVpurchaseEmbed] }); return interaction.send({ embeds: [successToggleUAVpurchaseEmbed] });
case 'toggle-emp-purchase': case 'toggle-emp-purchase':
const togggleEMPpurchase = args[0].options[0].value ? 1 : 0; const togggleEMPpurchase = args[0].options[0].value ? 1 : 0;
client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set: {"server.purchaseEMP": togggleEMPpurchase}}, (err, res) => { client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set: {"server.purchaseEMP": togggleEMPpurchase}}, (err, res) => {
if (err) return client.sendInternalError(interaction, err); if (err) return client.sendInternalError(interaction, err);
}); });
let successToggleEMPpurchaseEmbed = new EmbedBuilder() let successToggleEMPpurchaseEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Green) .setColor(client.config.Colors.Green)
.setDescription(`Users can ${togggleUAVpurchase ? 'now' : 'no longer'} purchase EMPs.`); .setDescription(`Users can ${togggleUAVpurchase ? 'now' : 'no longer'} purchase EMPs.`);
@@ -860,7 +1016,7 @@ module.exports = {
}, },
Interactions: { Interactions: {
RemoveAllowedChannels: { RemoveAllowedChannels: {
run: async (client, interaction, GuildDB) => { run: async (client, interaction, GuildDB) => {
if (!interaction.customId.endsWith(interaction.member.user.id)) { if (!interaction.customId.endsWith(interaction.member.user.id)) {
@@ -876,11 +1032,11 @@ module.exports = {
if (err) return client.sendInternalError(interaction, err); if (err) return client.sendInternalError(interaction, err);
}); });
} else if (interaction.customId.split('-')[1]=='no') action = 'kept'; } else if (interaction.customId.split('-')[1]=='no') action = 'kept';
const successEmbed = new EmbedBuilder() const successEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Green) .setColor(client.config.Colors.Green)
.setTitle(`**Success**\n> Successfullly ${action} the channel.`) .setTitle(`**Success**\n> Successfullly ${action} the channel.`)
return interaction.update({ embeds: [successEmbed], components: [] }); return interaction.update({ embeds: [successEmbed], components: [] });
} }
}, },
@@ -890,12 +1046,12 @@ module.exports = {
if (!interaction.customId.endsWith(interaction.member.user.id)) { if (!interaction.customId.endsWith(interaction.member.user.id)) {
return interaction.reply({ return interaction.reply({
content: "This buttpm is not for you", content: "This buttpm is not for you",
flags: (1 << 6) flags: (1 << 6)
}); });
} }
let action; let action;
if (interaction.customId.split('-')[1] == 'yes') { if (interaction.customId.split('-')[1] == 'yes') {
action = 'cleared'; action = 'cleared';
client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set:{"server.allowedChannels":[]}}, (err, res) => { client.dbo.collection("guilds").updateOne({"server.serverID": GuildDB.serverID}, {$set:{"server.allowedChannels":[]}}, (err, res) => {
if (err) return client.sendInternalError(interaction, err); if (err) return client.sendInternalError(interaction, err);
}) })
@@ -925,11 +1081,11 @@ module.exports = {
if (err) return client.sendInternalError(interaction, err); if (err) return client.sendInternalError(interaction, err);
}); });
} else if (interaction.customId.split('-')[1]=='no') action = 'kept'; } else if (interaction.customId.split('-')[1]=='no') action = 'kept';
const successEmbed = new EmbedBuilder() const successEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Green) .setColor(client.config.Colors.Green)
.setDescription(`**Successfully ${action} <@&${roleId}> as the bot admin role.**`) .setDescription(`**Successfully ${action} <@&${roleId}> as the bot admin role.**`)
return interaction.update({ embeds: [successEmbed], components: [] }); return interaction.update({ embeds: [successEmbed], components: [] });
} }
}, },
@@ -951,11 +1107,11 @@ module.exports = {
if (err) return client.sendInternalError(interaction, err); if (err) return client.sendInternalError(interaction, err);
}); });
} else if (interaction.customId.split('-')[1]=='no') action = 'kept'; } else if (interaction.customId.split('-')[1]=='no') action = 'kept';
const successEmbed = new EmbedBuilder() const successEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Green) .setColor(client.config.Colors.Green)
.setDescription(`**Successfully ${action} <@&${roleId}> as an income role.**`) .setDescription(`**Successfully ${action} <@&${roleId}> as an income role.**`)
return interaction.update({ embeds: [successEmbed], components: [] }); return interaction.update({ embeds: [successEmbed], components: [] });
} }
}, },
@@ -976,13 +1132,13 @@ module.exports = {
if (err) return client.sendInternalError(interaction, err); if (err) return client.sendInternalError(interaction, err);
}); });
} else if (interaction.customId.split('-')[1]=='no') action = 'kept'; } else if (interaction.customId.split('-')[1]=='no') action = 'kept';
const successEmbed = new EmbedBuilder() const successEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Green) .setColor(client.config.Colors.Green)
.setTitle(`Successfully ${action} guild configurations.`) .setTitle(`Successfully ${action} guild configurations.`)
return interaction.update({ embeds: [successEmbed], components: [] }); return interaction.update({ embeds: [successEmbed], components: [] });
} }
} }
} }
} }
-30
View File
@@ -1,30 +0,0 @@
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js');
const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes;
module.exports = {
name: "debug",
debug: true,
global: false,
description: "debugging...",
usage: "",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [],
SlashCommand: {
/**
*
* @param {require("../structures/QuarksBot")} client
* @param {import("discord.js").Message} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (!client.config.Admins.includes(interaction.member.user.id)) return interaction.send({ content: 'Only developers can access this command.', flags: (1 << 6) })
return interaction.send({ content: `Hello ${interaction.member.user.id}, you are my creator!!` })
},
},
Interactions: {}
}
+8 -8
View File
@@ -1,4 +1,4 @@
const { EmbedBuilder, ActionRowBuilder, StringSelectMenuBuilder } = require('discord.js'); const { EmbedBuilder, ActionRowBuilder, StringSelectMenuBuilder, PermissionsBitField } = require('discord.js');
const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes;
const bitfieldCalculator = require('discord-bitfield-calculator'); const bitfieldCalculator = require('discord-bitfield-calculator');
@@ -31,7 +31,7 @@ module.exports = {
type: CommandOptions.Integer, type: CommandOptions.Integer,
required: true, required: true,
choices: [ choices: [
{ name: '10-minutes', value: 10 }, { name: '15-minutes', value: 15 }, { name: '20-minutes', value: 20 }, { name: '25-minutes', value: 25 }, { 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: '30-minutes', value: 30 }, { name: '60-minutes', value: 60 }, { name: '90-minutes', value: 90 }, { name: '120-minutes', value: 120 },
] ]
}, },
@@ -80,10 +80,10 @@ module.exports = {
return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) });
} }
const permissions = bitfieldCalculator.permissions(interaction.member.permissions); const permissions = new PermissionsBitField(interaction.member.permissions).toArray();
let canUseCommand = false; let canUseCommand = false;
if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; if (permissions.includes("ManageGuild")) canUseCommand = true;
if (GuildDB.hasBotAdmin && interaction.member.roles.filter(e => GuildDB.botAdminRoles.indexOf(e) !== -1).length > 0) 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 (!canUseCommand) return interaction.send({ content: 'You don\'t have the permissions to use this command.' });
@@ -134,7 +134,7 @@ module.exports = {
value: GuildDB.events[i].name value: GuildDB.events[i].name
}); });
} }
const eventsOptions = new ActionRowBuilder().addComponents(events); const eventsOptions = new ActionRowBuilder().addComponents(events);
return interaction.send({ components: [eventsOptions], flags: (1 << 6) }); return interaction.send({ components: [eventsOptions], flags: (1 << 6) });
@@ -146,7 +146,7 @@ module.exports = {
DeleteEvent: { DeleteEvent: {
run: async(client, interaction, GuildDB) => { run: async(client, interaction, GuildDB) => {
if (!interaction.customId.endsWith(interaction.member.user.id)) if (!interaction.customId.endsWith(interaction.member.user.id))
return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) }); return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) });
let event = GuildDB.events.find(e => e.name == interaction.values[0]); let event = GuildDB.events.find(e => e.name == interaction.values[0]);
@@ -162,9 +162,9 @@ module.exports = {
let successEmbed = new EmbedBuilder() let successEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Green) .setColor(client.config.Colors.Green)
.setDescription(`**Success:** Successfully Deleted **${event.name} Event**`); .setDescription(`**Success:** Successfully Deleted **${event.name} Event**`);
return interaction.update({ embeds: [successEmbed], components: [] }); return interaction.update({ embeds: [successEmbed], components: [] });
} }
} }
} }
} }
+1 -1
View File
@@ -24,7 +24,7 @@ module.exports = {
let noExcludes = new EmbedBuilder() let noExcludes = new EmbedBuilder()
.setColor(client.config.Colors.Default) .setColor(client.config.Colors.Default)
.setTitle('Excluded Roles') .setTitle('Excluded Roles')
.setDescription('> There have been no configured channels'); .setDescription('> There have been no excluded roles');
return interaction.send({ embeds: [noExcludes] }); return interaction.send({ embeds: [noExcludes] });
} }
+5 -5
View File
@@ -29,15 +29,15 @@ module.exports = {
*/ */
run: async (client, interaction, args, { GuildDB }) => { run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) 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 interaction.send({ content: `You are not allowed to use the bot in this channel.`, flags: (1 << 6) });
// Return list of factions and their armband. // Return list of factions and their armband.
if (!args) { if (!args) {
let factions = new EmbedBuilder() let factions = new EmbedBuilder()
.setColor(client.config.Colors.Default) .setColor(client.config.Colors.Default)
.setTitle('Factions & Armbands') .setTitle('Factions & Armbands')
let description = ''; let description = '';
if (GuildDB.usedArmbands.length == 0) { if (GuildDB.usedArmbands.length == 0) {
@@ -48,9 +48,9 @@ module.exports = {
else description += `\n> <@&${factionID}> - *${data.armband}*`; else description += `\n> <@&${factionID}> - *${data.armband}*`;
} }
} }
factions.setDescription(description); factions.setDescription(description);
return interaction.send({ embeds: [factions] }); return interaction.send({ embeds: [factions] });
} }
+6 -6
View File
@@ -44,7 +44,7 @@ module.exports = {
const warnGTOverwrite = new EmbedBuilder() const warnGTOverwrite = new EmbedBuilder()
.setColor(client.config.Colors.Yellow) .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?`) .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() const opt = new ActionRowBuilder()
.addComponents( .addComponents(
new ButtonBuilder() new ButtonBuilder()
@@ -61,7 +61,7 @@ module.exports = {
} }
playerStat.discordID = interaction.member.user.id; playerStat.discordID = interaction.member.user.id;
await UpdatePlayer(client, playerStat, interaction); await UpdatePlayer(client, playerStat, interaction);
let member = interaction.guild.members.cache.get(interaction.member.user.id); let member = interaction.guild.members.cache.get(interaction.member.user.id);
@@ -87,14 +87,14 @@ module.exports = {
OverwriteGamertag: { OverwriteGamertag: {
run: async(client, interaction, GuildDB) => { run: async(client, interaction, GuildDB) => {
if (!interaction.customId.endsWith(interaction.member.user.id)) if (!interaction.customId.endsWith(interaction.member.user.id))
return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) }); return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) });
if (interaction.customId.split('-')[1]=='yes') { if (interaction.customId.split('-')[1]=='yes') {
let playerStat = await client.dbo.collection("players").findOne({"gamertag": interaction.customId.split('-')[2]}); let playerStat = await client.dbo.collection("players").findOne({"gamertag": interaction.customId.split('-')[2]});
playerStat.discordID = interaction.member.user.id; playerStat.discordID = interaction.member.user.id;
await UpdatePlayer(client, playerStat, interaction); await UpdatePlayer(client, playerStat, interaction);
let member = interaction.guild.members.cache.get(interaction.member.user.id); let member = interaction.guild.members.cache.get(interaction.member.user.id);
@@ -123,6 +123,6 @@ module.exports = {
} }
} }
} }
} }
} }
+4 -4
View File
@@ -35,7 +35,7 @@ module.exports = {
const warnGTOverwrite = new EmbedBuilder() const warnGTOverwrite = new EmbedBuilder()
.setColor(client.config.Colors.Yellow) .setColor(client.config.Colors.Yellow)
.setDescription(`**Notice:**\n> Are you sure you want to unlink your gamertag? This will limit some automatic features.`); .setDescription(`**Notice:**\n> Are you sure you want to unlink your gamertag? This will limit some automatic features.`);
const opt = new ActionRowBuilder() const opt = new ActionRowBuilder()
.addComponents( .addComponents(
new ButtonBuilder() new ButtonBuilder()
@@ -56,14 +56,14 @@ module.exports = {
UnlinkGamertag: { UnlinkGamertag: {
run: async(client, interaction, GuildDB) => { run: async(client, interaction, GuildDB) => {
if (!interaction.customId.endsWith(interaction.member.user.id)) if (!interaction.customId.endsWith(interaction.member.user.id))
return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) }); return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) });
if (interaction.customId.split('-')[1]=='yes') { if (interaction.customId.split('-')[1]=='yes') {
let playerStat = await client.dbo.collection("players").findOne({"discordID": interaction.member.user.id}); let playerStat = await client.dbo.collection("players").findOne({"discordID": interaction.member.user.id});
playerStat.discordID = ""; playerStat.discordID = "";
await UpdatePlayer(client, playerStat, interaction); await UpdatePlayer(client, playerStat, interaction);
let connectedEmbed = new EmbedBuilder() let connectedEmbed = new EmbedBuilder()
@@ -82,4 +82,4 @@ module.exports = {
} }
} }
} }
} }
+18 -19
View File
@@ -32,7 +32,7 @@ module.exports = {
value: "support", value: "support",
type: CommandOptions.SubCommand, type: CommandOptions.SubCommand,
}, },
{ {
name: "credits", name: "credits",
description: "DayZ.R Bot Credits", description: "DayZ.R Bot Credits",
value: "credits", value: "credits",
@@ -58,15 +58,15 @@ module.exports = {
if (args[0].name == 'commands') { if (args[0].name == 'commands') {
let Commands = client.commands.filter((cmd) => { let Commands = client.commands.filter((cmd) => {
return !cmd.debug return !cmd.debug
}).map((cmd) => }).map((cmd) =>
`\`/${cmd.name}${cmd.usage ? " " + cmd.usage : ""}\` - ${cmd.description}` `\`/${cmd.name}${cmd.usage ? " " + cmd.usage : ""}\` - ${cmd.description}`
); );
let Embed = new EmbedBuilder() let Embed = new EmbedBuilder()
.setTitle('Commands') .setTitle('Commands')
.setColor(client.config.Colors.Default) .setColor(client.config.Colors.Default)
.setDescription(`${Commands.join("\n")} .setDescription(`${Commands.join("\n")}
DayZR Bot Version: v${client.config.Version}`); DayZR Bot Version: v${client.config.Version}`);
if (!args[0].options[0]) return interaction.send({ embeds: [Embed] }); if (!args[0].options[0]) return interaction.send({ embeds: [Embed] });
else { else {
@@ -77,7 +77,7 @@ module.exports = {
); );
if (!cmd) if (!cmd)
return interaction.send({ content: `❌ | Unable to find that command.` }); return interaction.send({ content: `❌ | Unable to find that command.` });
let embed = new EmbedBuilder() let embed = new EmbedBuilder()
.setDescription(cmd.description) .setDescription(cmd.description)
.setColor(client.config.Colors.Green) .setColor(client.config.Colors.Green)
@@ -85,7 +85,7 @@ module.exports = {
if (cmd.SlashCommand.options && cmd.SlashCommand.options[0].type == 1) { if (cmd.SlashCommand.options && cmd.SlashCommand.options[0].type == 1) {
let description = `${cmd.description}\n\n**Usage**\n`; let description = `${cmd.description}\n\n**Usage**\n`;
for (let i = 0; i < cmd.SlashCommand.options.length; i++) { for (let i = 0; i < cmd.SlashCommand.options.length; i++) {
if (cmd.SlashCommand.options[i].type == 1) { if (cmd.SlashCommand.options[i].type == 1) {
let param = ''; let param = '';
@@ -107,7 +107,7 @@ module.exports = {
const supportEmbed = new EmbedBuilder() const supportEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Default) .setColor(client.config.Colors.Default)
.setDescription(`**__DayZ.R Bot Support__** .setDescription(`**__DayZ.R Bot Support__**
Are you experiencing troubles with the DayZ.R Bot? Are you experiencing troubles with the DayZ.R Bot?
Do you have questions or concerns? Do you have questions or concerns?
Do you require help to use the bot? Do you require help to use the bot?
@@ -126,37 +126,36 @@ module.exports = {
.setDescription(` .setDescription(`
**Bot Author:** mcdazzzled **Bot Author:** mcdazzzled
**Github:** https://github.com/SowinskiBraeden/dayz-reforger **Github:** https://github.com/SowinskiBraeden/dayz-reforger
${client.config.SupportServer} ${client.config.SupportServer}
`); `);
return interaction.send({ embeds: [creditsEmbed] }) return interaction.send({ embeds: [creditsEmbed] })
} else if (args[0].name == 'stats') { } else if (args[0].name == 'stats') {
const end = new Date().getTime(); const end = new Date().getTime();
const totalGuilds = await client.shard.fetchClientValues("guilds.cache.size").then(results => { const totalGuilds = await client.shard.fetchClientValues("guilds.cache.size").then(results => {
return results.reduce((acc, guildCount) => acc + guildCount, 0); return results.reduce((acc, guildCount) => acc + guildCount, 0);
}); });
const totalUsers = await client.shard.broadcastEval(c => { const totalUsers = await client.shard.broadcastEval(c => {
c.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0); c.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0);
}).then(data => data.reduce((acc, memberCount) => acc + memberCount, 0)); }).then(data => data.reduce((acc, memberCount) => acc + memberCount, 0));
const stats = new EmbedBuilder() const stats = new EmbedBuilder()
.setColor(client.config.Colors.Default) .setColor(client.config.Colors.Default)
.setTitle('DayZ Reforger Bot Statistics') .setTitle('DayZ Reforger Bot Statistics')
.addFields( .addFields(
{ name: 'Guilds', value: `${totalGuilds}`, inline: false }, { name: 'Guilds', value: `\`\`\`${totalGuilds}\`\`\``, inline: true },
{ name: 'Users', value: `${totalUsers}`, inline: false }, { name: 'Users', value: `\`\`\`${totalUsers}\`\`\``, inline: true },
{ name: 'Latency', value: `${end - start}ms`, inline: false }, { name: 'Latency', value: `\`\`\`${end - start}ms\`\`\``, inline: true },
{ name: 'Uptime', value: `${client.secondsToDhms(process.uptime().toFixed(2))}`, inline: false }, { name: 'Uptime', value: `\`\`\`${client.secondsToDhms(process.uptime().toFixed(2))}\`\`\``, inline: true },
{ name: 'Bot Version', value: `${client.config.Dev} v${client.config.Version}`, inline: false }, { name: 'Bot Version', value: `\`\`\`${client.config.Dev} v${client.config.Version}\`\`\``, inline: true },
{ name: 'Discord Version', value: `Discord.js ${package.dependencies["discord.js"]}`, inline: false }, { name: 'Discord Version', value: `\`\`\`Discord.js ${package.dependencies["discord.js"]}\`\`\``, inline: true },
{ name: 'MongoDB Version', value: `MongoDB ${package.dependencies.mongodb}`, inline: false },
); );
return interaction.send({ embeds: [stats] }) return interaction.send({ embeds: [stats] })
} }
}, },
}, },
}; };
+22 -22
View File
@@ -21,7 +21,7 @@ module.exports = {
{ name: "Money", value: "money" }, { name: "Money", value: "money" },
{ name: "Total Time Played", value: "totalSessionTime" }, { name: "Total Time Played", value: "totalSessionTime" },
{ name: "Longest Game Session", value: "longestSessionTime" }, { name: "Longest Game Session", value: "longestSessionTime" },
{ name: "Kills", value: "kills" }, { name: "Kills", value: "kills" },
{ name: "Kill Streak", value: "killStreak" }, { name: "Kill Streak", value: "killStreak" },
{ name: "Best Kill Streak", value: "bestKillStreak" }, { name: "Best Kill Streak", value: "bestKillStreak" },
{ name: "Deaths", value: "deaths" }, { name: "Deaths", value: "deaths" },
@@ -60,7 +60,7 @@ module.exports = {
return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) });
} }
const category = args[0].value; const category = args[0].value;
const limit = args[1].value; const limit = args[1].value;
@@ -72,28 +72,28 @@ module.exports = {
]).toArray(); ]).toArray();
} else { } else {
leaderboard = await client.dbo.collection("players").aggregate([ leaderboard = await client.dbo.collection("players").aggregate([
{ $sort: { [`${category}`]: -1 } } { $sort: { [`${category}`]: -1 } }
]).toArray(); ]).toArray();
} }
let leaderboardEmbed = new EmbedBuilder() let leaderboardEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Default); .setColor(client.config.Colors.Default);
let title = category == 'kills' ? "Total Kills Leaderboard" : let title = category == 'kills' ? "Total Kills Leaderboard" :
category == 'killStreak' ? "Current Killstreak Leaderboard" : category == 'killStreak' ? "Current Killstreak Leaderboard" :
category == 'bestKillStreak' ? "Best Killstreak Leaderboard" : category == 'bestKillStreak' ? "Best Killstreak Leaderboard" :
category == 'deaths' ? "Total Deaths Leaderboard" : category == 'deaths' ? "Total Deaths Leaderboard" :
category == 'deathStreak' ? "Current Deathstreak Leaderboard" : category == 'deathStreak' ? "Current Deathstreak Leaderboard" :
category == 'worstDeathStreak' ? "Worst Deathstreak Leaderboard" : category == 'worstDeathStreak' ? "Worst Deathstreak Leaderboard" :
category == 'longestKill' ? "Longest Kill Leaderboard" : category == 'longestKill' ? "Longest Kill Leaderboard" :
category == 'money' ? "Money Leaderboard" : category == 'money' ? "Money Leaderboard" :
category == 'totalSessionTime' ? "Total Time Played" : category == 'totalSessionTime' ? "Total Time Played" :
category == 'longestSessionTime' ? "Longest Game Session" : category == 'longestSessionTime' ? "Longest Game Session" :
category == 'KDR' ? "Kill Death Ratio" : category == 'KDR' ? "Kill Death Ratio" :
category == 'connections' ? "Times Connected" : category == 'connections' ? "Times Connected" :
category == 'shotsLanded' ? "Shots Landed" : category == 'shotsLanded' ? "Shots Landed" :
category == 'timesShot' ? "Times Shot" : category == 'timesShot' ? "Times Shot" :
category == 'combatRating' ? "Combat Rating" : 'N/A Error'; category == 'combatRating' ? "Combat Rating" : 'N/A Error';
@@ -103,21 +103,21 @@ module.exports = {
let des = ``; let des = ``;
for (let i = 0; i < limit; i++) { for (let i = 0; i < limit; i++) {
if (leaderboard.length < limit && i == leaderboard.length) break; 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':''}` : 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 == 'killStreak' ? `${leaderboard[i].killStreak} Player Killstreak` :
category == 'bestKillStreak' ? `${leaderboard[i].bestKillStreak} 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 == 'deaths' ? `${leaderboard[i].deaths} Death${leaderboard[i].deaths>1||leaderboard[i].deaths==0?'s':''}` :
category == 'deathStreak' ? `${leaderboard[i].deathStreak} Deathstreak` : category == 'deathStreak' ? `${leaderboard[i].deathStreak} Deathstreak` :
category == 'worstDeathstreak' ? `${leaderboard[i].worstDeathStreak} Deathstreak` : category == 'worstDeathstreak' ? `${leaderboard[i].worstDeathStreak} Deathstreak` :
category == 'longestKill' ? `${leaderboard[i].longestKill}m` : category == 'longestKill' ? `${leaderboard[i].longestKill}m` :
category == 'money' ? `$${(leaderboard[i].user.guilds[GuildDB.serverID].balance).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}` : 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 == '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 == 'longestSessionTime' ? `**Longest Game Session:** ${client.secondsToDhms(leaderboard[i].longestSessionTime)}` :
category == 'KDR' ? `**KDR: ${leaderboard[i].KDR.toFixed(2)}**` : category == 'KDR' ? `**KDR: ${leaderboard[i].KDR.toFixed(2)}**` :
category == 'connection' ? `**Connections: ${leaderboard[i].connections}**` : category == 'connection' ? `**Connections: ${leaderboard[i].connections}**` :
category == 'combatRating' ? `**Combat Rating:** ${leaderboard[i].combatRating}` : category == 'combatRating' ? `**Combat Rating:** ${leaderboard[i].combatRating}` :
category == 'shotsLanded' ? `**Shots Landed:** ${leaderboard[i].shotsLanded}` : category == 'shotsLanded' ? `**Shots Landed:** ${leaderboard[i].shotsLanded}` :
category == 'timesShot' ? `**Times Shot:** ${leaderboard[i].timesShot}` : 'N/A Error'; category == 'timesShot' ? `**Times Shot:** ${leaderboard[i].timesShot}` : 'N/A Error';
if (category == 'money') des += `**${i+1}.** <@${leaderboard[i].user.userID}> - **${stats}**\n` if (category == 'money') des += `**${i+1}.** <@${leaderboard[i].user.userID}> - **${stats}**\n`
@@ -128,7 +128,7 @@ module.exports = {
} }
if (['money', 'totalSessionTime', 'longestSessionTime', 'combatRating'].includes(category)) leaderboardEmbed.setDescription(des); if (['money', 'totalSessionTime', 'longestSessionTime', 'combatRating'].includes(category)) leaderboardEmbed.setDescription(des);
return interaction.send({ embeds: [leaderboardEmbed] }); return interaction.send({ embeds: [leaderboardEmbed] });
}, },
}, },
+4 -4
View File
@@ -37,14 +37,14 @@ module.exports = {
let newDt = await client.getDateEST(playerStat.time); let newDt = await client.getDateEST(playerStat.time);
let unixTime = Math.floor(newDt.getTime()/1000); let unixTime = Math.floor(newDt.getTime()/1000);
const destination = nearest(playerStat.pos, GuildDB.Nitrado.Mission); const destination = nearest(playerStat.pos, GuildDB.Nitrado.Mission);
let lastLocation = new EmbedBuilder() let lastLocation = new EmbedBuilder()
.setColor(client.config.Colors.Default) .setColor(client.config.Colors.Default)
.setDescription(`**Location - <t:${unixTime}>**\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}`) .setDescription(`**Location - <t:${unixTime}>**\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) }); return interaction.send({ embeds: [lastLocation], flags: (1 << 6) });
}, },
}, },
} }
+90 -90
View File
@@ -1,90 +1,90 @@
const { EmbedBuilder } = require('discord.js'); const { EmbedBuilder } = require('discord.js');
const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes;
module.exports = { module.exports = {
name: "lookup", name: "lookup",
debug: false, debug: false,
global: false, global: false,
description: "Search for a user's Discord or Gamertag", description: "Search for a user's Discord or Gamertag",
usage: "[option] [parameter]", usage: "[option] [parameter]",
permissions: { permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [], member: [],
}, },
options: [{ options: [{
name: "discord", name: "discord",
description: "Find a Discord user from a Gamertag", description: "Find a Discord user from a Gamertag",
value: "discord", value: "discord",
type: CommandOptions.SubCommand, type: CommandOptions.SubCommand,
options: [{ options: [{
name: "gamertag", name: "gamertag",
description: "Gamertag of player", description: "Gamertag of player",
value: "gamertag", value: "gamertag",
type: CommandOptions.String, type: CommandOptions.String,
required: true, required: true,
}] }]
}, { }, {
name: "gamertag", name: "gamertag",
description: "Find a Gamertag from a Discord user", description: "Find a Gamertag from a Discord user",
value: "gamertag", value: "gamertag",
type: CommandOptions.SubCommand, type: CommandOptions.SubCommand,
options: [{ options: [{
name: "user", name: "user",
description: "Discord User", description: "Discord User",
value: "user", value: "user",
type: CommandOptions.User, type: CommandOptions.User,
required: true, required: true,
}] }]
}], }],
SlashCommand: { SlashCommand: {
/** /**
* *
* @param {require("../structures/DayzRBot")} client * @param {require("../structures/DayzRBot")} client
* @param {import("discord.js").Message} message * @param {import("discord.js").Message} message
* @param {string[]} args * @param {string[]} args
* @param {*} param3 * @param {*} param3
*/ */
run: async (client, interaction, args, { GuildDB }) => { run: async (client, interaction, args, { GuildDB }) => {
if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) {
const warnNitradoNotInitialized = new EmbedBuilder() const warnNitradoNotInitialized = new EmbedBuilder()
.setColor(client.config.Colors.Yellow) .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."); .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) }); return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) });
} }
if (args[0].name == 'discord') { if (args[0].name == 'discord') {
let playerStat = await client.dbo.collection("players").findOne({"gamertag": args[0].options[0].value}); 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 (playerStat == undefined) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** This gamertag \` ${args[0].options[0].value} \` cannot be found, the gamertag may be incorrect or this player has not logged onto the server before for at least \` 5 minutes \`.`)] });
if (client.exists(playerStat.discordID)) { if (client.exists(playerStat.discordID)) {
const found = new EmbedBuilder() const found = new EmbedBuilder()
.setColor(client.config.Colors.Yellow) .setColor(client.config.Colors.Yellow)
.setDescription(`**Record Found**\n> The gamertag \` ${playerStat.gamertag} \` is currently linked to <@${playerStat.discordID}>.`) .setDescription(`**Record Found**\n> The gamertag \` ${playerStat.gamertag} \` is currently linked to <@${playerStat.discordID}>.`)
return interaction.send({ embeds: [found] }); return interaction.send({ embeds: [found] });
} }
let notFound = new EmbedBuilder() let notFound = new EmbedBuilder()
.setColor(client.config.Colors.Default) .setColor(client.config.Colors.Default)
.setDescription(`**Record Not Found**\n The gamertag \` ${playerStat.gamertag} \` currently has no linked Discord account.`); .setDescription(`**Record Not Found**\n The gamertag \` ${playerStat.gamertag} \` currently has no linked Discord account.`);
return interaction.send({ embeds: [notFound] }) return interaction.send({ embeds: [notFound] })
} else if (args[0].name == 'gamertag') { } else if (args[0].name == 'gamertag') {
let playerStat = await client.dbo.collection("players").findOne({"discordID": args[0].options[0].value}); 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.`)] }); 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() const found = new EmbedBuilder()
.setColor(client.config.Colors.Yellow) .setColor(client.config.Colors.Yellow)
.setDescription(`**Record Found**\n> The user <@${playerStat.discordID}> has linked the gamertag \` ${playerStat.gamertag} \`.`) .setDescription(`**Record Found**\n> The user <@${playerStat.discordID}> has linked the gamertag \` ${playerStat.gamertag} \`.`)
return interaction.send({ embeds: [found] }); return interaction.send({ embeds: [found] });
} }
}, },
}, },
} }
+11 -10
View File
@@ -12,7 +12,7 @@ module.exports = {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [], member: [],
}, },
options: [], options: [],
SlashCommand: { SlashCommand: {
/** /**
* *
@@ -31,15 +31,16 @@ module.exports = {
return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) });
} }
const data = await FetchServerSettings(GuildDB.Nitrado, client, 'commands/player-list.js'); // Fetch server status 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 e = data && data !== 1; // Check if data exists
const hostname = e ? data.data.gameserver.settings.config.hostname : 'N/A'; const hostname = e ? data.data.gameserver.settings.config.hostname : 'N/A';
const map = Missions[data.data.gameserver.settings.config.mission]; const map = e ? Missions[data.data.gameserver.settings.config.mission] : 'N/A';
const status = e ? data.data.gameserver.status : 'N/A'; const status = e ? data.data.gameserver.status : 'N/A';
const slots = e ? data.data.gameserver.slots : 'N/A'; const slots = e ? data.data.gameserver.slots : 'N/A';
const playersOnline = data.data.gameserver.query.player_current; const playersOnline = e ? data.data.gameserver.query.player_current : 'N/A';
const Statuses = { const Statuses = {
"started": {emoji: "🟢", text: "Active"}, "started": {emoji: "🟢", text: "Active"},
@@ -47,8 +48,8 @@ module.exports = {
"restarting": {emoji: "↻", text: "Restarting"}, "restarting": {emoji: "↻", text: "Restarting"},
}; };
const emojiStatus = Statuses[status].emoji || "❓"; const emojiStatus = e ? Statuses[status].emoji : "❓";
const textStatus = Statuses[status].text || "Unknown Status"; const textStatus = e ? Statuses[status].text : "Unknown Status";
let activePlayers = await client.dbo.collection("players").find({"connected": true}).toArray(); let activePlayers = await client.dbo.collection("players").find({"connected": true}).toArray();
@@ -56,7 +57,7 @@ module.exports = {
for (let i = 0; i < activePlayers.length; i++) { for (let i = 0; i < activePlayers.length; i++) {
des += `**- ${activePlayers[i].gamertag}**\n`; des += `**- ${activePlayers[i].gamertag}**\n`;
} }
const nodes = activePlayers.length === 0; const nodes = activePlayers.length === 0;
const serverEmbed = new EmbedBuilder() const serverEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Default) .setColor(client.config.Colors.Default)
@@ -74,7 +75,7 @@ module.exports = {
.setTitle(`Players Online:`) .setTitle(`Players Online:`)
.setDescription(des || (nodes ? "No Players Online :(" : "")); .setDescription(des || (nodes ? "No Players Online :(" : ""));
return interaction.send({ embeds: [serverEmbed, activePlayersEmbed] }); return interaction.editReply({ embeds: [serverEmbed, activePlayersEmbed] });
}, },
}, },
} }
+24 -24
View File
@@ -22,7 +22,7 @@ module.exports = {
{ name: "Money", value: "money" }, { name: "Money", value: "money" },
{ name: "Total Time Played", value: "totalSessionTime" }, { name: "Total Time Played", value: "totalSessionTime" },
{ name: "Longest Game Session", value: "longestSessionTime" }, { name: "Longest Game Session", value: "longestSessionTime" },
{ name: "Kills", value: "kills" }, { name: "Kills", value: "kills" },
{ name: "Kill Streak", value: "killStreak" }, { name: "Kill Streak", value: "killStreak" },
{ name: "Best Kill Streak", value: "bestKillStreak" }, { name: "Best Kill Streak", value: "bestKillStreak" },
{ name: "Deaths", value: "deaths" }, { name: "Deaths", value: "deaths" },
@@ -56,7 +56,7 @@ module.exports = {
* @param {*} param3 * @param {*} param3
*/ */
run: async (client, interaction, args, { GuildDB }, start) => { run: async (client, interaction, args, { GuildDB }, start) => {
if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) {
const warnNitradoNotInitialized = new EmbedBuilder() const warnNitradoNotInitialized = new EmbedBuilder()
.setColor(client.config.Colors.Yellow) .setColor(client.config.Colors.Yellow)
@@ -69,7 +69,7 @@ module.exports = {
let discord = args[1] && args[1].name == 'discord' ? args[1].value : undefined; 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 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 self = !discord && !gamertag; // searching for self if both discord and gamertag are undefined;
let query; let query;
let leaderboard; let leaderboard;
let leaderboardPos; let leaderboardPos;
@@ -88,7 +88,7 @@ module.exports = {
leaderboardPos = leaderboard.indexOf(query); leaderboardPos = leaderboard.indexOf(query);
} else { } else {
leaderboard = await client.dbo.collection("players").aggregate([ leaderboard = await client.dbo.collection("players").aggregate([
{ $sort: { [`${category}`]: -1 } } { $sort: { [`${category}`]: -1 } }
]).toArray(); ]).toArray();
@@ -108,13 +108,13 @@ module.exports = {
category == 'bestkillStreak' ? "Best Killstreak" : category == 'bestkillStreak' ? "Best Killstreak" :
category == 'deaths' ? "Total Deaths" : category == 'deaths' ? "Total Deaths" :
category == 'deathStreak' ? "Current Deathstreak" : category == 'deathStreak' ? "Current Deathstreak" :
category == 'worstDeathStreak' ? "Worst Deathstreak" : category == 'worstDeathStreak' ? "Worst Deathstreak" :
category == 'longestKill' ? "Longest Kill" : category == 'longestKill' ? "Longest Kill" :
category == 'money' ? "Total Money" : category == 'money' ? "Total Money" :
category == 'totalSessionTime' ? "Total Time Played" : category == 'totalSessionTime' ? "Total Time Played" :
category == 'longestSessionTime' ? "Longest Game Session" : category == 'longestSessionTime' ? "Longest Game Session" :
category == 'KDR' ? "Kill Death Ratio" : category == 'KDR' ? "Kill Death Ratio" :
category == 'connections' ? "Times Connected" : category == 'connections' ? "Times Connected" :
category == 'shotsLanded' ? "Shots Landed" : category == 'shotsLanded' ? "Shots Landed" :
category == 'timesShot' ? "Times Shot" : category == 'timesShot' ? "Times Shot" :
category == 'combatRating' ? "Combat Rating" : 'N/A Error'; category == 'combatRating' ? "Combat Rating" : 'N/A Error';
@@ -134,14 +134,14 @@ module.exports = {
category == 'deaths' ? `${query.deaths} Death${query.deaths>1||query.deaths==0?'s':''}` : category == 'deaths' ? `${query.deaths} Death${query.deaths>1||query.deaths==0?'s':''}` :
category == 'deathStreak' ? `${query.deathStreak} Deathstreak` : category == 'deathStreak' ? `${query.deathStreak} Deathstreak` :
category == 'worstDeathStreak' ? `${query.worstDeathStreak} Deathstreak` : category == 'worstDeathStreak' ? `${query.worstDeathStreak} Deathstreak` :
category == 'longestKill' ? `${query.longestKill}m` : category == 'longestKill' ? `${query.longestKill}m` :
category == 'money' ? `$${(query.user.guilds[GuildDB.serverID].balance).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}` : category == 'money' ? `$${(query.user.guilds[GuildDB.serverID].balance).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}` :
category == 'KDR' ? `${query.KDR.toFixed(2)} KDR` : category == 'KDR' ? `${query.KDR.toFixed(2)} KDR` :
category == 'connections' ? `${query.connections} connections` : category == 'connections' ? `${query.connections} connections` :
category == 'combatRating' ? `${query.combatRating}` : 'N/A Error'; category == 'combatRating' ? `${query.combatRating}` : 'N/A Error';
statsEmbed.addFields({ name: 'Leaderboard Position', value: `# ${leaderboardPos}`, inline: true }); statsEmbed.addFields({ name: 'Leaderboard Position', value: `# ${leaderboardPos}`, inline: true });
if ((category == 'shotsLanded' || category == 'timesShot') && !client.exists(query.shotsLanded)) query = insertPVPstats(query); if ((category == 'shotsLanded' || category == 'timesShot') && !client.exists(query.shotsLanded)) query = insertPVPstats(query);
if (category == 'totalSessionTime') { if (category == 'totalSessionTime') {
@@ -154,11 +154,11 @@ module.exports = {
{ name: 'Longest Game Session', value: client.secondsToDhms(query.longestSessionTime), inline: true }, { name: 'Longest Game Session', value: client.secondsToDhms(query.longestSessionTime), inline: true },
{ name: 'Last Session Time', value: client.secondsToDhms(query.lastSessionTime), inline: true } { name: 'Last Session Time', value: client.secondsToDhms(query.lastSessionTime), inline: true }
); );
} else if (category == 'shotsLanded') { } else if (category == 'shotsLanded') {
statsEmbed.addFields( statsEmbed.addFields(
{ name: 'Total Shots Landed', value: `${query.shotsLanded}`, inline: true }, { name: 'Total Shots Landed', value: `${query.shotsLanded}`, inline: true },
{ name: 'View Weapon stats', value: `</weapon-stats:1169369568104415262>`, inline: true } { name: 'View Weapon stats', value: `</weapon-stats:1169369568104415262>`, inline: true }
); );
const chart = { const chart = {
type: 'bar', type: 'bar',
@@ -189,18 +189,18 @@ module.exports = {
}, },
}, },
}; };
const encodedChart = encodeURIComponent(JSON.stringify(chart)); const encodedChart = encodeURIComponent(JSON.stringify(chart));
const chartURL = `https://quickchart.io/chart?bkg=${encodeURIComponent("#ded8d7")}&c=${encodedChart}`; const chartURL = `https://quickchart.io/chart?bkg=${encodeURIComponent("#ded8d7")}&c=${encodedChart}`;
statsEmbed.setImage(chartURL); statsEmbed.setImage(chartURL);
} else if (category == 'timesShot') { } else if (category == 'timesShot') {
statsEmbed.addFields( statsEmbed.addFields(
{ name: 'Total Times Shot', value: `${query.timesShot}`, inline: true }, { name: 'Total Times Shot', value: `${query.timesShot}`, inline: true },
{ name: 'View Weapon stats', value: `</weapon-stats:1169369568104415262>`, inline: true }, { name: 'View Weapon stats', value: `</weapon-stats:1169369568104415262>`, inline: true },
); );
const chart = { const chart = {
type: 'bar', type: 'bar',
data: { data: {
@@ -230,12 +230,12 @@ module.exports = {
}, },
}, },
}; };
const encodedChart = encodeURIComponent(JSON.stringify(chart)); const encodedChart = encodeURIComponent(JSON.stringify(chart));
const chartURL = `https://quickchart.io/chart?bkg=${encodeURIComponent("#ded8d7")}&c=${encodedChart}`; const chartURL = `https://quickchart.io/chart?bkg=${encodeURIComponent("#ded8d7")}&c=${encodedChart}`;
statsEmbed.setImage(chartURL); statsEmbed.setImage(chartURL);
} else if (category == 'combatRating') { } else if (category == 'combatRating') {
let data = query.combatRatingHistory; let data = query.combatRatingHistory;
@@ -318,8 +318,8 @@ module.exports = {
statsEmbed.setImage(chartURL); statsEmbed.setImage(chartURL);
} else statsEmbed.addFields({ name: title, value: stats, inline: true }); } else statsEmbed.addFields({ name: title, value: stats, inline: true });
return interaction.send({ embeds: [statsEmbed] }); return interaction.send({ embeds: [statsEmbed] });
}, },
}, },
} }
+5 -5
View File
@@ -11,7 +11,7 @@ module.exports = {
permissions: { permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"], channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: ["MANAGE_GUILD"], member: ["MANAGE_GUILD"],
}, },
options: [{ options: [{
name: "duration", name: "duration",
description: "Select the duration of the emp (30 or 60 minutes)", description: "Select the duration of the emp (30 or 60 minutes)",
@@ -32,7 +32,7 @@ module.exports = {
* @param {*} param3 * @param {*} param3
*/ */
run: async (client, interaction, args, { GuildDB }) => { run: async (client, interaction, args, { GuildDB }) => {
if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) {
const warnNitradoNotInitialized = new EmbedBuilder() const warnNitradoNotInitialized = new EmbedBuilder()
.setColor(client.config.Colors.Yellow) .setColor(client.config.Colors.Yellow)
@@ -45,7 +45,7 @@ module.exports = {
const duration = args[0].value; const duration = args[0].value;
let banking = await client.dbo.collection("users").findOne({"user.userID": interaction.member.user.id}).then(banking => banking); let banking = await client.dbo.collection("users").findOne({"user.userID": interaction.member.user.id}).then(banking => banking);
if (!banking) { if (!banking) {
banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client) banking = await createUser(interaction.member.user.id, GuildDB.serverID, GuildDB.startingBalance, client)
if (!client.exists(banking)) return client.sendInternalError(interaction, err); if (!client.exists(banking)) return client.sendInternalError(interaction, err);
@@ -67,13 +67,13 @@ module.exports = {
const price = duration == 30 ? GuildDB.empPrice : GuildDB.empPrice * 2; const price = duration == 30 ? GuildDB.empPrice : GuildDB.empPrice * 2;
const newBalance = banking.guilds[GuildDB.serverID].balance - price; 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) }); 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) => { 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); if (err) return client.sendInternalError(interaction, err);
}); });
let alarms = new StringSelectMenuBuilder() let alarms = new StringSelectMenuBuilder()
.setCustomId(`EMPAlarmSelect-${interaction.member.user.id}`) .setCustomId(`EMPAlarmSelect-${interaction.member.user.id}`)
.setPlaceholder(`Select an Alarm to EMP.`) .setPlaceholder(`Select an Alarm to EMP.`)
+2 -2
View File
@@ -39,7 +39,7 @@ module.exports = {
* @param {*} param3 * @param {*} param3
*/ */
run: async (client, interaction, args, { GuildDB }) => { run: async (client, interaction, args, { GuildDB }) => {
if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) { if (!client.exists(GuildDB.Nitrado) || !client.exists(GuildDB.Nitrado.ServerID) || !client.exists(GuildDB.Nitrado.UserID) || !client.exists(GuildDB.Nitrado.Auth)) {
const warnNitradoNotInitialized = new EmbedBuilder() const warnNitradoNotInitialized = new EmbedBuilder()
.setColor(client.config.Colors.Yellow) .setColor(client.config.Colors.Yellow)
@@ -72,7 +72,7 @@ module.exports = {
} }
const newBalance = banking.guilds[GuildDB.serverID].balance - GuildDB.uavPrice; 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) => { 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); if (err) return client.sendInternalError(interaction, err);
}); });
+7 -7
View File
@@ -1,4 +1,4 @@
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js'); const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, PermissionsBitField } = require('discord.js');
const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes;
const { addUser } = require('../database/user'); const { addUser } = require('../database/user');
const bitfieldCalculator = require('discord-bitfield-calculator'); const bitfieldCalculator = require('discord-bitfield-calculator');
@@ -29,10 +29,10 @@ module.exports = {
* @param {*} param3 * @param {*} param3
*/ */
run: async (client, interaction, args, { GuildDB }) => { run: async (client, interaction, args, { GuildDB }) => {
const permissions = bitfieldCalculator.permissions(interaction.member.permissions); const permissions = new PermissionsBitField(interaction.member.permissions).toArray();
let canUseCommand = false; let canUseCommand = false;
if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; if (permissions.includes("ManageGuild")) canUseCommand = true;
if (client.exists(GuildDB.botAdmin) && interaction.member.roles.includes(GuildDB.botAdmin)) 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.' }); if (!canUseCommand) return interaction.send({ content: 'You don\'t have the permissions to use this command.' });
@@ -56,7 +56,7 @@ module.exports = {
) )
return interaction.send({ embeds: [prompt], components: [opt], flags: (1 << 6) }); return interaction.send({ embeds: [prompt], components: [opt], flags: (1 << 6) });
}, },
}, },
@@ -66,7 +66,7 @@ module.exports = {
run: async (client, interaction, GuildDB) => { run: async (client, interaction, GuildDB) => {
const choice = interaction.customId.split('-')[1]; const choice = interaction.customId.split('-')[1];
const targetUserID = interaction.customId.split('-')[2]; const targetUserID = interaction.customId.split('-')[2];
if (!interaction.customId.endsWith(interaction.member.user.id)) { if (!interaction.customId.endsWith(interaction.member.user.id)) {
return interaction.reply({ return interaction.reply({
content: "This button is not for you", content: "This button is not for you",
@@ -79,7 +79,7 @@ module.exports = {
.setTitle('Successfully reset user\'s data') .setTitle('Successfully reset user\'s data')
let banking = await client.dbo.collection("users").findOne({"user.userID": interaction.member.user.id}).then(banking => banking); let banking = await client.dbo.collection("users").findOne({"user.userID": interaction.member.user.id}).then(banking => banking);
let bankingReset = false; let bankingReset = false;
if (!banking) bankingReset = true if (!banking) bankingReset = true
else banking = banking.user else banking = banking.user
@@ -108,4 +108,4 @@ module.exports = {
} }
} }
} }
} }
+54 -17
View File
@@ -1,7 +1,7 @@
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, ModalBuilder, TextInputBuilder, TextInputStyle } = require('discord.js'); const { PermissionsBitField, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, ModalBuilder, TextInputBuilder, TextInputStyle } = require('discord.js');
const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes; const CommandOptions = require('../util/CommandOptionTypes').CommandOptionTypes;
const bitfieldCalculator = require('discord-bitfield-calculator'); const bitfieldCalculator = require('discord-bitfield-calculator');
const { BanPlayer, UnbanPlayer, RestartServer, CheckServerStatus, DisableBaseDamage, DisableContainerDamage } = require('../util/NitradoAPI'); const { BanPlayer, UnbanPlayer, RestartServer, CheckServerStatus, DisableBaseDamage, DisableContainerDamage, NitradoCredentialStatus } = require('../util/NitradoAPI');
const { encrypt, decrypt } = require('../util/Cryptic'); const { encrypt, decrypt } = require('../util/Cryptic');
module.exports = { module.exports = {
@@ -26,6 +26,18 @@ module.exports = {
value: "disconnect", value: "disconnect",
type: CommandOptions.SubCommand, 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", name: "ban-player",
description: "Ban a player from the DayZ server", description: "Ban a player from the DayZ server",
@@ -96,10 +108,10 @@ module.exports = {
*/ */
run: async (client, interaction, args, { GuildDB }) => { run: async (client, interaction, args, { GuildDB }) => {
const permissions = bitfieldCalculator.permissions(interaction.member.permissions); const permissions = new PermissionsBitField(interaction.member.permissions).toArray();
let canUseCommand = false; let canUseCommand = false;
if (permissions.includes("MANAGE_GUILD")) canUseCommand = true; if (permissions.includes("ManageGuild")) canUseCommand = true;
if (GuildDB.hasBotAdmin && interaction.member.roles.filter(e => GuildDB.botAdminRoles.indexOf(e) !== -1).length > 0) 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 (!canUseCommand) return interaction.send({ content: 'You don\'t have the permissions to use this command.' });
@@ -177,10 +189,34 @@ module.exports = {
return interaction.send({ embeds: [prompt], components: [opt], flags: (1 << 6) }); 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 </server initialize:1166877457559851011>`)] }); 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 </server initialize:1166877457559851011>`)] });
if (args[0].name == 'ban-player') { 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); let data = await BanPlayer(GuildDB.Nitrado, client, args[0].options[0].value);
@@ -227,7 +263,7 @@ module.exports = {
} else if (args[0].name == "auto-restart") { } else if (args[0].name == "auto-restart") {
let msg = 'Auto server restart periodic check enabled.'; let msg = 'Auto server restart periodic check enabled.';
let pref = 0; let pref = 0;
// Enable/Disable a 10min periodic server status check. // Enable/Disable a 10min periodic server status check.
if (!client.arIntervalIds.has(GuildDB.serverID)) { if (!client.arIntervalIds.has(GuildDB.serverID)) {
client.arIntervalIds.set(GuildDB.serverID, setInterval(CheckServerStatus, client.arInterval, GuildDB.Nitrado, client)); client.arIntervalIds.set(GuildDB.serverID, setInterval(CheckServerStatus, client.arInterval, GuildDB.Nitrado, client));
@@ -247,7 +283,7 @@ module.exports = {
}); });
return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(msg)], flags: (1 << 6) }); return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(msg)], flags: (1 << 6) });
} else if (args[0].name == 'disable-base-damage') { } else if (args[0].name == 'disable-base-damage') {
const preference = args[0].options[0].value; const preference = args[0].options[0].value;
await interaction.deferReply({ flags: (1 << 6) }); await interaction.deferReply({ flags: (1 << 6) });
@@ -256,7 +292,7 @@ module.exports = {
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) }); 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) }); 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') { } else if (args[0].name == 'disable-container-damage') {
const preference = args[0].options[0].value; const preference = args[0].options[0].value;
await interaction.deferReply({ flags: (1 << 6) }); await interaction.deferReply({ flags: (1 << 6) });
@@ -265,16 +301,16 @@ module.exports = {
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) }); 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) }); 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: { Interactions: {
NitradoCredentials: { NitradoCredentials: {
run: async(client, interaction, GuildDB) => { run: async(client, interaction, GuildDB) => {
if (!interaction.customId.endsWith(interaction.member.user.id)) if (!interaction.customId.endsWith(interaction.member.user.id))
return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) }); return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) });
const Nitrado = { const Nitrado = {
@@ -286,6 +322,7 @@ module.exports = {
client.key, client.key,
client.encryptionIV client.encryptionIV
), // Encrypt the Authentication Token ), // 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) => { await client.dbo.collection('guilds').updateOne({ "server.serverID": GuildDB.serverID }, { $set: { "Nitrado": Nitrado } }, (err, res) => {
@@ -307,21 +344,21 @@ module.exports = {
const NitradoCredentials = new ModalBuilder() const NitradoCredentials = new ModalBuilder()
.setTitle('Connect your Nitrado Server') .setTitle('Connect your Nitrado Server')
.setCustomId(`NitradoCredentials-${interaction.member.user.id}`); .setCustomId(`NitradoCredentials-${interaction.member.user.id}`);
const ServerID = new ActionRowBuilder().addComponents(new TextInputBuilder() const ServerID = new ActionRowBuilder().addComponents(new TextInputBuilder()
.setCustomId('ServerIDInput') .setCustomId('ServerIDInput')
.setLabel('Your Nitrado Server ID') .setLabel('Your Nitrado Server ID')
.setStyle(TextInputStyle.Short) .setStyle(TextInputStyle.Short)
.setRequired(true) .setRequired(true)
); );
const UserID = new ActionRowBuilder().addComponents(new TextInputBuilder() const UserID = new ActionRowBuilder().addComponents(new TextInputBuilder()
.setCustomId('UserIDInput') .setCustomId('UserIDInput')
.setLabel('Your Nitrado User ID') .setLabel('Your Nitrado User ID')
.setStyle(TextInputStyle.Short) .setStyle(TextInputStyle.Short)
.setRequired(true) .setRequired(true)
); );
const Auth = new ActionRowBuilder().addComponents(new TextInputBuilder() const Auth = new ActionRowBuilder().addComponents(new TextInputBuilder()
.setCustomId('AuthInput') .setCustomId('AuthInput')
.setLabel('Your Nitrado Authentication Token') .setLabel('Your Nitrado Authentication Token')
@@ -329,9 +366,9 @@ module.exports = {
.setStyle(TextInputStyle.Short) .setStyle(TextInputStyle.Short)
.setRequired(true) .setRequired(true)
); );
NitradoCredentials.addComponents(ServerID, UserID, Auth); NitradoCredentials.addComponents(ServerID, UserID, Auth);
// TODO: Figure out how to remove the prompt buttons and the embed. // TODO: Figure out how to remove the prompt buttons and the embed.
return interaction.showModal(NitradoCredentials); return interaction.showModal(NitradoCredentials);
} else { } else {
+8 -8
View File
@@ -61,7 +61,7 @@ module.exports = {
return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) }); return interaction.send({ embeds: [warnNitradoNotInitialized], flags: (1 << 6) });
} }
let discord = args[1] && args[1].name == 'discord' ? args[1].value : undefined; 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 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 self = !discord && !gamertag; // searching for self if both discord and gamertag are undefined
@@ -71,13 +71,13 @@ module.exports = {
// Searching by Discord // Searching by Discord
if (discord) query = await client.dbo.collection("players").findOne({"discordID": discord}); if (discord) query = await client.dbo.collection("players").findOne({"discordID": discord});
// Searching by Gamertag // Searching by Gamertag
if (gamertag) query = await client.dbo.collection("players").findOne({"gamertag": gamertag}); if (gamertag) query = await client.dbo.collection("players").findOne({"gamertag": gamertag});
// Searching for self // Searching for self
if (self) query = await client.dbo.collection("players").findOne({"discordID": interaction.member.user.id}); if (self) query = await client.dbo.collection("players").findOne({"discordID": interaction.member.user.id});
if (!client.exists(query)) return interaction.send({ embeds: [new EmbedBuilder().setColor(client.config.Colors.Yellow).setDescription(`**Not Found** Unable to find any records with the gamertag or user provided.`)] }); if (!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() let weaponSelect = new StringSelectMenuBuilder()
@@ -103,7 +103,7 @@ module.exports = {
run: async(client, interaction, GuildDB) => { run: async(client, interaction, GuildDB) => {
if (!interaction.customId.endsWith(interaction.member.user.id)) if (!interaction.customId.endsWith(interaction.member.user.id))
return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) }); return interaction.reply({ content: 'This interaction is not for you', flags: (1 << 6) });
const weapon = interaction.values[0].split("_")[1]; const weapon = interaction.values[0].split("_")[1];
const weaponClass = interaction.values[0].split("_")[0]; const weaponClass = interaction.values[0].split("_")[0];
const playerID = interaction.customId.split('-')[1]; const playerID = interaction.customId.split('-')[1];
@@ -163,12 +163,12 @@ module.exports = {
}, },
}, },
}; };
const encodedChart = encodeURIComponent(JSON.stringify(chart)); const encodedChart = encodeURIComponent(JSON.stringify(chart));
const chartURL = `https://quickchart.io/chart?bkg=${encodeURIComponent("#ded8d7")}&c=${encodedChart}`; const chartURL = `https://quickchart.io/chart?bkg=${encodeURIComponent("#ded8d7")}&c=${encodedChart}`;
stats.setImage(chartURL); stats.setImage(chartURL);
return interaction.update({ components: [], embeds: [stats] }); return interaction.update({ components: [], embeds: [stats] });
} }
} }
+3 -2
View File
File diff suppressed because one or more lines are too long.
+94 -94
View File
@@ -32,286 +32,286 @@ const destinations = {
coord: [1481.47, 11933.38], coord: [1481.47, 11933.38],
}, { }, {
name: 'Novaya Petrovka', name: 'Novaya Petrovka',
coord: [3437.31, 13010.46], coord: [3437.31, 13010.46],
}, { }, {
name: 'Zaprundoe', name: 'Zaprundoe',
coord: [5171.52, 12753.83], coord: [5171.52, 12753.83],
}, { }, {
name: 'Ratnoe', name: 'Ratnoe',
coord: [6174.72, 12722.72], coord: [6174.72, 12722.72],
}, { }, {
name: 'Severograd', name: 'Severograd',
coord: [7986.69, 12699.39], coord: [7986.69, 12699.39],
}, { }, {
name: 'Svergino', name: 'Svergino',
coord: [9464.27, 13718.14], coord: [9464.27, 13718.14],
}, { }, {
name: 'West Novodmitrovsk', name: 'West Novodmitrovsk',
coord: [10988.51, 14344.17], coord: [10988.51, 14344.17],
}, { }, {
name: 'East Novodmitrovsk', name: 'East Novodmitrovsk',
coord: [12143.35, 14336.39], coord: [12143.35, 14336.39],
}, { }, {
name: 'North Novodmitrovsk', name: 'North Novodmitrovsk',
coord: [11544.55, 14764.11], coord: [11544.55, 14764.11],
}, { }, {
name: 'Cernaya Polyana', name: 'Cernaya Polyana',
coord: [12112.25, 13760.91], coord: [12112.25, 13760.91],
}, { }, {
name: 'Turovo', name: 'Turovo',
coord: [13585.94, 14060.32], coord: [13585.94, 14060.32],
}, { }, {
name: 'Karmanovka', name: 'Karmanovka',
coord: [12679.95, 14678.56], coord: [12679.95, 14678.56],
}, { }, {
name: 'Dobroe', name: 'Dobroe',
coord: [12956.02, 15051.85], coord: [12956.02, 15051.85],
}, { }, {
name: 'Belaya Polyana', name: 'Belaya Polyana',
coord: [14161.41, 14942.97], coord: [14161.41, 14942.97],
}, { }, {
name: 'Svetlojarsk', name: 'Svetlojarsk',
coord: [14001.99, 13251.54], coord: [14001.99, 13251.54],
}, { }, {
name: 'Olsha', name: 'Olsha',
coord: [13348.75, 12897.70], coord: [13348.75, 12897.70],
}, { }, {
name: 'Black Lake', name: 'Black Lake',
coord: [13438.18, 12127.80], coord: [13438.18, 12127.80],
}, { }, {
name: 'Krasno Airfield', name: 'Krasno Airfield',
coord: [12018.93, 12586.63], coord: [12018.93, 12586.63],
}, { }, {
name: 'Krasnostav', name: 'Krasnostav',
coord: [11163.49, 12248.34], coord: [11163.49, 12248.34],
}, { }, {
name: 'Rify', name: 'Rify',
coord: [13811.46, 11210.15], coord: [13811.46, 11210.15],
}, { }, {
name: 'Khelmn', name: 'Khelmn',
coord: [12287.22, 10840.75], coord: [12287.22, 10840.75],
}, { }, {
name: 'North Berezino', name: 'North Berezino',
coord: [12905.47, 10059.19], coord: [12905.47, 10059.19],
}, { }, {
name: 'Central Berezino', name: 'Central Berezino',
coord: [12423.31, 9600.36], coord: [12423.31, 9600.36],
}, { }, {
name: 'South Berezino', name: 'South Berezino',
coord: [11968.38, 9079.32], coord: [11968.38, 9079.32],
}, { }, {
name: 'Dubrovka', name: 'Dubrovka',
coord: [10362.48, 9837.55], coord: [10362.48, 9837.55],
}, { }, {
name: 'Vyshnaya Dubrovka', name: 'Vyshnaya Dubrovka',
coord: [9891.99, 10432.47], coord: [9891.99, 10432.47],
}, { }, {
name: 'North Solnichniy', name: 'North Solnichniy',
coord: [13123.22, 7100.15] coord: [13123.22, 7100.15]
}, { }, {
name: 'Solnichniy', name: 'Solnichniy',
coord: [13418.74, 6248.60], coord: [13418.74, 6248.60],
}, { }, {
name: 'Orlovets', name: 'Orlovets',
coord: [12201.68, 7275.12], coord: [12201.68, 7275.12],
}, { }, {
name: 'Polana', name: 'Polana',
coord: [10743.54, 8134.45], coord: [10743.54, 8134.45],
}, { }, {
name: 'Gorka', name: 'Gorka',
coord: [9487.60, 8811.03], coord: [9487.60, 8811.03],
}, { }, {
name: 'Radio Zenit', name: 'Radio Zenit',
coord: [8128.62, 9230.97], coord: [8128.62, 9230.97],
}, { }, {
name: 'Dolina', name: 'Dolina',
coord: [11276.25, 6594.66], coord: [11276.25, 6594.66],
}, { }, {
name: 'Devil\'s Castle', name: 'Devil\'s Castle',
coord: [6890.18, 11439.56], coord: [6890.18, 11439.56],
}, { }, {
name: 'Zolotar Castle (Black Mountain)', name: 'Zolotar Castle (Black Mountain)',
coord: [10189.45, 12038.37], coord: [10189.45, 12038.37],
}, { }, {
name: 'Kamensk', name: 'Kamensk',
coord: [6684.09, 14410.27], coord: [6684.09, 14410.27],
}, { }, {
name: 'MB Kamensk', name: 'MB Kamensk',
coord: [7862.27, 14698.01], coord: [7862.27, 14698.01],
}, { }, {
name: 'Quarry', name: 'Quarry',
coord: [8614.66, 13333.19], coord: [8614.66, 13333.19],
}, { }, {
name: 'Nagornoe', name: 'Nagornoe',
coord: [9262.08, 14620.24], coord: [9262.08, 14620.24],
}, { }, {
name: 'Stary Yar', name: 'Stary Yar',
coord: [4965.44, 15028.52], coord: [4965.44, 15028.52],
}, { }, {
name: 'Tisy', name: 'Tisy',
coord: [3425.65, 14783.55], coord: [3425.65, 14783.55],
}, { }, {
name: 'MB Tisy', name: 'MB Tisy',
coord: [1543.68, 14052.54], coord: [1543.68, 14052.54],
}, { }, {
name: 'Topolniki', name: 'Topolniki',
coord: [2834.62, 12388.32], coord: [2834.62, 12388.32],
}, { }, {
name: 'North NWAF', name: 'North NWAF',
coord: [4024.45, 11738.96], coord: [4024.45, 11738.96],
}, { }, {
name: 'Central NWAF', name: 'Central NWAF',
coord: [4249.98, 10766.87], coord: [4249.98, 10766.87],
}, { }, {
name: 'South NWAF', name: 'South NWAF',
coord: [4864.34, 9588.70], coord: [4864.34, 9588.70],
}, { }, {
name: 'Grishino', name: 'Grishino',
coord: [5976.41, 10300.27], coord: [5976.41, 10300.27],
}, { }, {
name: 'Kabanino', name: 'Kabanino',
coord: [5284.28, 8604.94], coord: [5284.28, 8604.94],
}, { }, {
name: 'Stary Sobor', name: 'Stary Sobor',
coord: [6058.07, 7792.28], coord: [6058.07, 7792.28],
}, { }, {
name: 'Novy Sobor', name: 'Novy Sobor',
coord: [7088.48, 7648.41], coord: [7088.48, 7648.41],
}, { }, {
name: 'MB VMC', name: 'MB VMC',
coord: [4483.28, 8286.10], coord: [4483.28, 8286.10],
}, { }, {
name: 'Vybor', name: 'Vybor',
coord: [3814.48, 8904.35], coord: [3814.48, 8904.35],
}, { }, {
name: 'Pustoshka', name: 'Pustoshka',
coord: [3060.14, 7905.04], coord: [3060.14, 7905.04],
}, { }, {
name: 'Lopatino', name: 'Lopatino',
coord: [2725.74, 10016.42], coord: [2725.74, 10016.42],
}, { }, {
name: 'Vavilovo', name: 'Vavilovo',
coord: [2228.03, 11039.06], coord: [2228.03, 11039.06],
}, { }, {
name: 'Kalinka', name: 'Kalinka',
coord: [3301.22, 11249.03], coord: [3301.22, 11249.03],
}, { }, {
name: 'Biathlon Arena', name: 'Biathlon Arena',
coord: [493.82, 11093.50], coord: [493.82, 11093.50],
}, { }, {
name: 'Krona Castle', name: 'Krona Castle',
coord: [1395.92, 9246.52], coord: [1395.92, 9246.52],
}, { }, {
name: 'Myshkino', name: 'Myshkino',
coord: [2010.28, 7317.90], coord: [2010.28, 7317.90],
}, { }, {
name: 'Polesovo', name: 'Polesovo',
coord: [5929.75, 13523.72], coord: [5929.75, 13523.72],
}, { }, {
name: 'Kalinovka', name: 'Kalinovka',
coord: [7516.20, 13457.62], coord: [7516.20, 13457.62],
}, { }, {
name: 'Skalisty Island', name: 'Skalisty Island',
coord: [13620.93, 3040.70], coord: [13620.93, 3040.70],
}, { }, {
name: 'Kamyshovo', name: 'Kamyshovo',
coord: [12061.70, 3526.74], coord: [12061.70, 3526.74],
}, { }, {
name: 'Elektrozavodsk', name: 'Elektrozavodsk',
coord: [10273.05, 2010.28], coord: [10273.05, 2010.28],
}, { }, {
name: 'Cherno. Prigorodki', name: 'Cherno. Prigorodki',
coord: [7733.95, 3182.62], coord: [7733.95, 3182.62],
}, { }, {
name: 'Chernogorsk', name: 'Chernogorsk',
coord: [6573.28, 2544.93], coord: [6573.28, 2544.93],
}, { }, {
name: 'Cherno. Dubovo', name: 'Cherno. Dubovo',
coord: [6672.43, 3616.18], coord: [6672.43, 3616.18],
}, { }, {
name: 'Cherno. Vysotovo', name: 'Cherno. Vysotovo',
coord: [5686.73, 2552.71], coord: [5686.73, 2552.71],
}, { }, {
name: 'Cherno. Novoselki', name: 'Cherno. Novoselki',
coord: [6139.72, 3239.01], coord: [6139.72, 3239.01],
}, { }, {
name: 'Balota Airfield', name: 'Balota Airfield',
coord: [5054.87, 2344.68], coord: [5054.87, 2344.68],
}, { }, {
name: 'Balota', name: 'Balota',
coord: [4463.84, 2441.89], coord: [4463.84, 2441.89],
}, { }, {
name: 'Komarovo', name: 'Komarovo',
coord: [3670.61, 2457.44], coord: [3670.61, 2457.44],
}, { }, {
name: 'Prison Island', name: 'Prison Island',
coord: [2702.41, 1296.77], coord: [2702.41, 1296.77],
}, { }, {
name: 'Kamenka', name: 'Kamenka',
coord: [1905.30, 2231.92], coord: [1905.30, 2231.92],
}, { }, {
name: 'MB Pavlovo', name: 'MB Pavlovo',
coord: [2130.82, 3363.43], coord: [2130.82, 3363.43],
}, { }, {
name: 'Pavlovo', name: 'Pavlovo',
coord: [1675.88, 3845.59], coord: [1675.88, 3845.59],
}, { }, {
name: 'Bor', name: 'Bor',
coord: [3324.55, 3985.57], coord: [3324.55, 3985.57],
}, { }, {
name: 'Nadezhdino', name: 'Nadezhdino',
coord: [5867.54, 4790.46], coord: [5867.54, 4790.46],
}, { }, {
name: 'Mogilevka', name: 'Mogilevka',
coord: [7570.64, 5140.41], coord: [7570.64, 5140.41],
}, { }, {
name: 'Pusta', name: 'Pusta',
coord: [9192.09, 3861.14], coord: [9192.09, 3861.14],
}, { }, {
name: 'Staroye', name: 'Staroye',
coord: [10136.96, 5443.71], coord: [10136.96, 5443.71],
}, { }, {
name: 'MSTA', name: 'MSTA',
coord: [11334.57, 5486.48], coord: [11334.57, 5486.48],
}, { }, {
name: 'Tulga', name: 'Tulga',
coord: [12753.83, 4405.51], coord: [12753.83, 4405.51],
}, { }, {
name: 'Guglovo', name: 'Guglovo',
coord: [8437.74, 6680.21], coord: [8437.74, 6680.21],
}, { }, {
name: 'Vyshnoye', name: 'Vyshnoye',
coord: [6586.88, 6054.18], coord: [6586.88, 6054.18],
}, { }, {
name: 'Rogovo', name: 'Rogovo',
coord: [4763.24, 6765.75], coord: [4763.24, 6765.75],
}, { }, {
name: 'Pulkovo', name: 'Pulkovo',
coord: [4969.33, 5614.79], coord: [4969.33, 5614.79],
}, { }, {
name: 'Green Mountain', name: 'Green Mountain',
coord: [3707.55, 6003.63], coord: [3707.55, 6003.63],
}, { }, {
name: 'Zelenogorsk', name: 'Zelenogorsk',
coord: [2581.87, 5190.96], coord: [2581.87, 5190.96],
}, { }, {
name: 'Sosnovka', name: 'Sosnovka',
coord: [2527.43, 6369.14], coord: [2527.43, 6369.14],
}, { }, {
name: 'Plotina Tishina Damn', name: 'Plotina Tishina Damn',
coord: [1193.73, 6363.30], coord: [1193.73, 6363.30],
}, { }, {
name: 'Zvir', name: 'Zvir',
coord: [571.59, 5294.00], coord: [571.59, 5294.00],
}, { }, {
name: 'Shakhovka', name: 'Shakhovka',
coord: [9658.69, 6555.78], coord: [9658.69, 6555.78],
}, { }, {
name: 'Black Forrest', name: 'Black Forrest',
coord: [9021.00, 7792.28], coord: [9021.00, 7792.28],
}, { }, {
name: 'Nizhneye', name: 'Nizhneye',
coord: [12971.57, 8142.23], coord: [12971.57, 8142.23],
}, { }, {
name: 'Rog Castle', name: 'Rog Castle',
coord: [11249.03, 4281.09], coord: [11249.03, 4281.09],
@@ -681,4 +681,4 @@ const destinations = {
coord: [11165.63, 7910.63], coord: [11165.63, 7910.63],
}, },
], ],
} }
+14 -13
View File
@@ -28,32 +28,33 @@ module.exports = {
allowedChannels: guild.server.allowedChannels, allowedChannels: guild.server.allowedChannels,
customChannelStatus: guild.server.allowedChannels.length > 0 ? true : false, customChannelStatus: guild.server.allowedChannels.length > 0 ? true : false,
hasBotAdmin: guild.server.botAdminRoles.length > 0 ? true : false, hasBotAdmin: guild.server.botAdminRoles.length > 0 ? true : false,
killfeedChannel: guild.server.killfeedChannel, killfeedChannel: guild.server.killfeedChannel,
connectionLogsChannel: guild.server.connectionLogsChannel, connectionLogsChannel: guild.server.connectionLogsChannel,
activePlayersChannel: guild.server.activePlayersChannel, activePlayersChannel: guild.server.activePlayersChannel,
welcomeChannel: guild.server.welcomeChannel, welcomeChannel: guild.server.welcomeChannel,
factionArmbands: guild.server.factionArmbands, factionArmbands: guild.server.factionArmbands,
usedArmbands: guild.server.usedArmbands, usedArmbands: guild.server.usedArmbands,
excludedRoles: guild.server.excludedRoles, excludedRoles: guild.server.excludedRoles,
hasExcludedRoles: guild.server.excludedRoles.length > 0 ? true : false,
botAdminRoles: guild.server.botAdminRoles, botAdminRoles: guild.server.botAdminRoles,
alarms: guild.server.alarms, alarms: guild.server.alarms,
events: guild.server.events, events: guild.server.events,
uavs: guild.server.uavs, uavs: guild.server.uavs,
incomeRoles: guild.server.incomeRoles, incomeRoles: guild.server.incomeRoles,
incomeLimiter: guild.server.incomeLimiter, incomeLimiter: guild.server.incomeLimiter,
startingBalance: guild.server.startingBalance, startingBalance: guild.server.startingBalance,
uavPrice: guild.server.uavPrice, uavPrice: guild.server.uavPrice,
empPrice: guild.server.empPrice, empPrice: guild.server.empPrice,
linkedGamertagRole: guild.server.linkedGamertagRole, linkedGamertagRole: guild.server.linkedGamertagRole,
memberRole: guild.server.memberRole, memberRole: guild.server.memberRole,
adminRole: guild.server.adminRole, adminRole: guild.server.adminRole,
combatLogTimer: guild.server.combatLogTimer, combatLogTimer: guild.server.combatLogTimer,
}; };
}, },
@@ -74,27 +75,27 @@ module.exports = {
connectionLogsChannel: "", connectionLogsChannel: "",
activePlayersChannel: "", activePlayersChannel: "",
welcomeChannel: "", welcomeChannel: "",
factionArmbands: {}, factionArmbands: {},
usedArmbands: [], usedArmbands: [],
excludedRoles: [], excludedRoles: [],
botAdminRoles: [], botAdminRoles: [],
alarms: [], alarms: [],
events: [], events: [],
uavs: [], uavs: [],
incomeRoles: [], incomeRoles: [],
incomeLimiter: 168, // # of hours in 7 days incomeLimiter: 168, // # of hours in 7 days
startingBalance: 500, startingBalance: 500,
uavPrice: 50000, uavPrice: 50000,
empPrice: 500000, empPrice: 500000,
linkedGamertagRole: "", linkedGamertagRole: "",
memberRole: "", memberRole: "",
adminRole: "", adminRole: "",
combatLogTimer: 5, // minutes combatLogTimer: 5, // minutes
} }
} }
+4 -4
View File
@@ -57,7 +57,7 @@ module.exports = {
longestKill: 0, longestKill: 0,
deathStreak: 0, deathStreak: 0,
worstDeathStreak: 0, worstDeathStreak: 0,
// In depth PVP Stats // In depth PVP Stats
shotsLanded: 0, shotsLanded: 0,
timesShot: 0, timesShot: 0,
@@ -75,7 +75,7 @@ module.exports = {
highestCombatRating: 800, highestCombatRating: 800,
lowestCombatRating: 800, lowestCombatRating: 800,
combatRatingHistory: [800], combatRatingHistory: [800],
// General Session Data // General Session Data
lastConnectionDate: null, lastConnectionDate: null,
lastDisconnectionDate: null, lastDisconnectionDate: null,
@@ -87,13 +87,13 @@ module.exports = {
lastPos: [], lastPos: [],
time: null, time: null,
lastTime: null, lastTime: null,
// Session Stats // Session Stats
totalSessionTime: 0, totalSessionTime: 0,
lastSessionTime: 0, lastSessionTime: 0,
longestSessionTime: 0, longestSessionTime: 0,
connections: 0, connections: 0,
// Other // Other
bounties: [], bounties: [],
bountiesLength: 0, bountiesLength: 0,
+2 -2
View File
@@ -15,7 +15,7 @@ module.exports = {
"Signal Pistol": "https://static.wikia.nocookie.net/dayz_gamepedia/images/a/a7/Flaregun.png/revision/latest/scale-to-width-down/107?cb=20210501150913", "Signal Pistol": "https://static.wikia.nocookie.net/dayz_gamepedia/images/a/a7/Flaregun.png/revision/latest/scale-to-width-down/107?cb=20210501150913",
}, },
shotguns: { 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-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-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", "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", "Vaiga": "https://static.wikia.nocookie.net/dayz_gamepedia/images/c/c8/Vaiga.png/revision/latest/scale-to-width-down/256?cb=20220220185225",
@@ -65,7 +65,7 @@ module.exports = {
semiAutomaticRifles: { semiAutomaticRifles: {
"DMR": "https://static.wikia.nocookie.net/dayz_gamepedia/images/b/b4/M14.png/revision/latest/scale-to-width-down/350?cb=20231005142636", "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", "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", "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: { other: {
"Crossbow": "https://static.wikia.nocookie.net/dayz_gamepedia/images/7/79/Crossbow.png/revision/latest/scale-to-width-down/212?cb=20180121164101", "Crossbow": "https://static.wikia.nocookie.net/dayz_gamepedia/images/7/79/Crossbow.png/revision/latest/scale-to-width-down/212?cb=20180121164101",
+1 -1
View File
@@ -1,3 +1,3 @@
module.exports = (client, guild) => { module.exports = (client, guild) => {
require("../util/RegisterSlashCommands").RegisterGuildCommands(client, guild.id); require("../util/RegisterSlashCommands").RegisterGuildCommands(client, guild.id);
}; };
+2 -2
View File
@@ -8,7 +8,7 @@ module.exports = async (client, interaction) => {
This file routes any menu, modal & button interactions This file routes any menu, modal & button interactions
from any command from any command
*/ */
let GuildDB = await GetGuild(client, interaction.guildId); let GuildDB = await GetGuild(client, interaction.guildId);
const interactionName = interaction.customId.split("-")[0]; const interactionName = interaction.customId.split("-")[0];
let interactionHandler = client.interactionHandlers.get(interactionName); let interactionHandler = client.interactionHandlers.get(interactionName);
@@ -18,4 +18,4 @@ module.exports = async (client, interaction) => {
} catch (err) { } catch (err) {
client.sendInternalError(interaction, err); client.sendInternalError(interaction, err);
} }
} }
+1 -1
View File
@@ -5,4 +5,4 @@ const manager = new ShardingManager('./bot.js', { token: config.Token });
manager.on('shardCreate', shard => console.log(`Launched shard ${shard.id}`)); manager.on('shardCreate', shard => console.log(`Launched shard ${shard.id}`));
manager.spawn(); manager.spawn();
+68 -31
View File
@@ -1,12 +1,12 @@
{ {
"name": "dayzr-bot", "name": "dayzr-bot",
"version": "12.7.1", "version": "13.3.25",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "dayzr-bot", "name": "dayzr-bot",
"version": "12.7.1", "version": "13.3.25",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@discordjs/rest": "^1.1.0", "@discordjs/rest": "^1.1.0",
@@ -1604,10 +1604,18 @@
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
}, },
"node_modules/ip": { "node_modules/ip-address": {
"version": "2.0.1", "version": "9.0.5",
"resolved": "https://registry.npmjs.org/ip/-/ip-2.0.1.tgz", "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-9.0.5.tgz",
"integrity": "sha512-lJUL9imLTNi1ZfXT+DU6rBBdbiKGBuay9B6xGSPVjUeQwaH1RIGqef8RZkUtHioLmSNpPR5M4HVKJGm1j8FWVQ==" "integrity": "sha512-zHtQzGojZXTwZTHQqra+ETKd4Sn3vgi7uBmlPoXVWZqYvuKmtI0l/VZTjqGmJY9x88GGOaZ9+G9ES8hC4T4X8g==",
"license": "MIT",
"dependencies": {
"jsbn": "1.1.0",
"sprintf-js": "^1.1.3"
},
"engines": {
"node": ">= 12"
}
}, },
"node_modules/is-arrayish": { "node_modules/is-arrayish": {
"version": "0.3.2", "version": "0.3.2",
@@ -1625,6 +1633,12 @@
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
}, },
"node_modules/jsbn": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/jsbn/-/jsbn-1.1.0.tgz",
"integrity": "sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A==",
"license": "MIT"
},
"node_modules/kuler": { "node_modules/kuler": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz", "resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz",
@@ -1809,15 +1823,16 @@
} }
}, },
"node_modules/socks": { "node_modules/socks": {
"version": "2.7.1", "version": "2.8.3",
"resolved": "https://registry.npmjs.org/socks/-/socks-2.7.1.tgz", "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.3.tgz",
"integrity": "sha512-7maUZy1N7uo6+WVEX6psASxtNlKaNVMlGQKkG/63nEDdLOWNbiUMoLK7X4uYoLhQstau72mLgfEWcXcwsaHbYQ==", "integrity": "sha512-l5x7VUUWbjVFbafGLxPWkYsHIhEvmF85tbIeFZWc8ZPtoMyybuEhL7Jye/ooC4/d48FgOjSJXgsF/AJPYCW8Zw==",
"license": "MIT",
"dependencies": { "dependencies": {
"ip": "^2.0.0", "ip-address": "^9.0.5",
"smart-buffer": "^4.2.0" "smart-buffer": "^4.2.0"
}, },
"engines": { "engines": {
"node": ">= 10.13.0", "node": ">= 10.0.0",
"npm": ">= 3.0.0" "npm": ">= 3.0.0"
} }
}, },
@@ -1830,6 +1845,12 @@
"memory-pager": "^1.0.2" "memory-pager": "^1.0.2"
} }
}, },
"node_modules/sprintf-js": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",
"integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==",
"license": "BSD-3-Clause"
},
"node_modules/stack-trace": { "node_modules/stack-trace": {
"version": "0.0.10", "version": "0.0.10",
"resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz",
@@ -1921,9 +1942,10 @@
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==" "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA=="
}, },
"node_modules/undici": { "node_modules/undici": {
"version": "5.28.3", "version": "5.28.5",
"resolved": "https://registry.npmjs.org/undici/-/undici-5.28.3.tgz", "resolved": "https://registry.npmjs.org/undici/-/undici-5.28.5.tgz",
"integrity": "sha512-3ItfzbrhDlINjaP0duwnNsKpDQk3acHI3gVJ1z4fmwMK31k5G9OVIAMLSIaP6w4FaGkaAkN6zaQO9LUvZ1t7VA==", "integrity": "sha512-zICwjrDrcrUE0pyyJc1I2QzBkLM8FINsgOrt6WjA+BgajVq9Nxu2PbFFXUrAggLfDXlZGZBVZYw7WNV5KiBiBA==",
"license": "MIT",
"dependencies": { "dependencies": {
"@fastify/busboy": "^2.0.0" "@fastify/busboy": "^2.0.0"
}, },
@@ -1999,9 +2021,10 @@
} }
}, },
"node_modules/ws": { "node_modules/ws": {
"version": "8.13.0", "version": "8.18.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz", "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz",
"integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==", "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==",
"license": "MIT",
"engines": { "engines": {
"node": ">=10.0.0" "node": ">=10.0.0"
}, },
@@ -3323,10 +3346,14 @@
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
}, },
"ip": { "ip-address": {
"version": "2.0.1", "version": "9.0.5",
"resolved": "https://registry.npmjs.org/ip/-/ip-2.0.1.tgz", "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-9.0.5.tgz",
"integrity": "sha512-lJUL9imLTNi1ZfXT+DU6rBBdbiKGBuay9B6xGSPVjUeQwaH1RIGqef8RZkUtHioLmSNpPR5M4HVKJGm1j8FWVQ==" "integrity": "sha512-zHtQzGojZXTwZTHQqra+ETKd4Sn3vgi7uBmlPoXVWZqYvuKmtI0l/VZTjqGmJY9x88GGOaZ9+G9ES8hC4T4X8g==",
"requires": {
"jsbn": "1.1.0",
"sprintf-js": "^1.1.3"
}
}, },
"is-arrayish": { "is-arrayish": {
"version": "0.3.2", "version": "0.3.2",
@@ -3338,6 +3365,11 @@
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",
"integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==" "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="
}, },
"jsbn": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/jsbn/-/jsbn-1.1.0.tgz",
"integrity": "sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A=="
},
"kuler": { "kuler": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz", "resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz",
@@ -3470,11 +3502,11 @@
"integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==" "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg=="
}, },
"socks": { "socks": {
"version": "2.7.1", "version": "2.8.3",
"resolved": "https://registry.npmjs.org/socks/-/socks-2.7.1.tgz", "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.3.tgz",
"integrity": "sha512-7maUZy1N7uo6+WVEX6psASxtNlKaNVMlGQKkG/63nEDdLOWNbiUMoLK7X4uYoLhQstau72mLgfEWcXcwsaHbYQ==", "integrity": "sha512-l5x7VUUWbjVFbafGLxPWkYsHIhEvmF85tbIeFZWc8ZPtoMyybuEhL7Jye/ooC4/d48FgOjSJXgsF/AJPYCW8Zw==",
"requires": { "requires": {
"ip": "^2.0.0", "ip-address": "^9.0.5",
"smart-buffer": "^4.2.0" "smart-buffer": "^4.2.0"
} }
}, },
@@ -3487,6 +3519,11 @@
"memory-pager": "^1.0.2" "memory-pager": "^1.0.2"
} }
}, },
"sprintf-js": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",
"integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="
},
"stack-trace": { "stack-trace": {
"version": "0.0.10", "version": "0.0.10",
"resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz",
@@ -3558,9 +3595,9 @@
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==" "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA=="
}, },
"undici": { "undici": {
"version": "5.28.3", "version": "5.28.5",
"resolved": "https://registry.npmjs.org/undici/-/undici-5.28.3.tgz", "resolved": "https://registry.npmjs.org/undici/-/undici-5.28.5.tgz",
"integrity": "sha512-3ItfzbrhDlINjaP0duwnNsKpDQk3acHI3gVJ1z4fmwMK31k5G9OVIAMLSIaP6w4FaGkaAkN6zaQO9LUvZ1t7VA==", "integrity": "sha512-zICwjrDrcrUE0pyyJc1I2QzBkLM8FINsgOrt6WjA+BgajVq9Nxu2PbFFXUrAggLfDXlZGZBVZYw7WNV5KiBiBA==",
"requires": { "requires": {
"@fastify/busboy": "^2.0.0" "@fastify/busboy": "^2.0.0"
} }
@@ -3618,9 +3655,9 @@
} }
}, },
"ws": { "ws": {
"version": "8.13.0", "version": "8.18.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz", "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz",
"integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==", "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==",
"requires": {} "requires": {}
} }
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "dayzr-bot", "name": "dayzr-bot",
"version": "13.3.2", "version": "13.4.3",
"description": "A General Purpose Discord Bot for DayZ Nitrado Servers.", "description": "A General Purpose Discord Bot for DayZ Nitrado Servers.",
"main": "index.js", "main": "index.js",
"nodemonConfig": { "nodemonConfig": {
+62 -37
View File
@@ -6,11 +6,12 @@ const Logger = require("../util/Logger");
const crypto = require('crypto'); const crypto = require('crypto');
// custom util imports // custom util imports
const { DownloadNitradoFile, CheckServerStatus, FetchServerSettings, PostServerSettings } = require('../util/NitradoAPI'); const { DownloadNitradoFile, CheckServerStatus, FetchServerSettings, PostServerSettings, NitradoCredentialStatus, GetRemoteDir } = require('../util/NitradoAPI');
const { HandlePlayerLogs, HandleActivePlayersList } = require('../util/LogsHandler'); const { HandlePlayerLogs, HandleActivePlayersList } = require('../util/LogsHandler');
const { HandleKillfeed, UpdateLastDeathDate } = require('../util/KillfeedHandler'); const { HandleKillfeed, UpdateLastDeathDate } = require('../util/KillfeedHandler');
const { HandleExpiredUAVs, HandleEvents, PlaceFireplaceInAlarm } = require('../util/AlarmsHandler'); const { HandleExpiredUAVs, HandleEvents, PlaceFireplaceInAlarm } = require('../util/AlarmsHandler');
const { decrypt } = require('../util/Cryptic'); const { decrypt } = require('../util/Cryptic');
const { GetWebhook, WebhookSend } = require("../util/WebhookHandler");
// Data structures imports // Data structures imports
const { getDefaultPlayer, UpdatePlayer } = require('../database/player'); const { getDefaultPlayer, UpdatePlayer } = require('../database/player');
@@ -66,12 +67,15 @@ class DayzRBot extends Client {
this.db; this.db;
this.dbo; this.dbo;
this.databaseConnected = false; this.databaseConnected = false;
this.arInterval = arInterval; this.arInterval = arInterval;
this.arIntervalIds = new Map(); this.arIntervalIds = new Map();
this.playerSessions = new Map(); this.playerSessions = new Map();
this.logHistory = new Map(); this.logHistory = new Map();
this.alarmPingQueue = new Map(); this.alarmPingQueue = new Map();
this.playerListMsgIds = new Map();
this.initialize(); this.initialize();
this.LoadCommandsAndInteractionHandlers(); this.LoadCommandsAndInteractionHandlers();
this.LoadEvents(); this.LoadEvents();
@@ -99,18 +103,16 @@ class DayzRBot extends Client {
// Free unused armbands for related commands // Free unused armbands for related commands
if (['armbands', 'claim', 'factions'].includes(command)) { if (['armbands', 'claim', 'factions'].includes(command)) {
for (const [factionID, data] of Object.entries(GuildDB.factionArmbands)) { for (const [factionID, data] of Object.entries(GuildDB.factionArmbands)) {
const guild = client.guilds.cache.get(GuildDB.serverID); const guild = this.guilds.cache.get(GuildDB.serverID);
const role = guild.roles.cache.find(role => role.id == factionID); const role = guild.roles.cache.find(role => role.id == factionID);
if (!role) { if (!role) {
let query = { let query = {
$pull: { 'server.usedArmbands': data.armband }, $pull: { 'server.usedArmbands': data.armband },
$unset: { [`server.factionArmbands.${factionID}`]: "" }, $unset: { [`server.factionArmbands.${factionID}`]: "" },
}; };
await client.dbo.collection("guilds").updateOne({ 'server.serverID': GuildDB.serverID }, query, (err, res) => { this.dbo.collection("guilds").updateOne({ 'server.serverID': GuildDB.serverID }, query, (err, res) => {
if (err) return client.sendInternalError(interaction, err); if (err) return this.sendInternalError(interaction, err);
}); });
} else {
newFactionArmbands[`${factionID}`] = data;
} }
} }
} }
@@ -118,7 +120,7 @@ class DayzRBot extends Client {
this.log(`Interaction [${interaction.guild_id}] - ${command}`); this.log(`Interaction [${interaction.guild_id}] - ${command}`);
const rest = new REST({ version: '10' }).setToken(this.config.Token); const rest = new REST({ version: '10' }).setToken(this.config.Token);
// Easy to send response so ;) // Easy to send response so ;)
interaction.guild = await this.guilds.fetch(interaction.guild_id); interaction.guild = await this.guilds.fetch(interaction.guild_id);
const handleCallback = async (interactionType, message) => { const handleCallback = async (interactionType, message) => {
@@ -134,7 +136,7 @@ class DayzRBot extends Client {
interaction.send = async (message) => handleCallback(InteractionResponseType.ChannelMessageWithSource, message); interaction.send = async (message) => handleCallback(InteractionResponseType.ChannelMessageWithSource, message);
interaction.deferReply = async (message) => handleCallback(InteractionResponseType.DeferredChannelMessageWithSource, message); interaction.deferReply = async (message) => handleCallback(InteractionResponseType.DeferredChannelMessageWithSource, message);
interaction.showModal = async (message) => handleCallback(InteractionResponseType.Modal, message); interaction.showModal = async (message) => handleCallback(InteractionResponseType.Modal, message);
interaction.editReply = async (message) => { interaction.editReply = async (message) => {
return await rest.patch(Routes.webhookMessage(this.application.id, interaction.token), { return await rest.patch(Routes.webhookMessage(this.application.id, interaction.token), {
body: message, body: message,
@@ -185,7 +187,7 @@ class DayzRBot extends Client {
if (this.playerSessions.get(guild.Nitrado.ServerID).size === 0) { 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 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. .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++) { for (let i = 0; i < players.length; i++) {
await UpdatePlayer(this, players[i]) await UpdatePlayer(this, players[i])
} }
@@ -201,7 +203,7 @@ class DayzRBot extends Client {
if (lines[i].includes('connected') || lines[i].includes('pos=<')) await HandlePlayerLogs(guild.Nitrado.ServerID, this, guild, lines[i], guild.combatLogTimer); 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('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]); if (lines[i].includes(') placed Fireplace')) await PlaceFireplaceInAlarm(this, guild, lines[i]);
// Handle killfeed logs // Handle killfeed logs
if ( if (
(lines[i].includes('killed by with') || lines[i].includes('killed by LandMineTrap')) || // Handle explosive deaths (lines[i].includes('killed by with') || lines[i].includes('killed by LandMineTrap')) || // Handle explosive deaths
@@ -215,17 +217,25 @@ class DayzRBot extends Client {
const maxEmbed = 10; const maxEmbed = 10;
this.alarmPingQueue.forEach(queue => { this.alarmPingQueue.forEach(queue => {
queue.forEach((data, channel_id) => { queue.forEach(async (data, channel_id) => {
const channel = this.GetChannel(channel_id); const channel = this.GetChannel(channel_id);
if (!channel) return; if (!channel) return;
data.forEach((embeds, role) => {
const NAME = "DayZ.R Zone Alert";
const webhook = await GetWebhook(this, NAME, channel_id);
data.forEach(async (embeds, role) => {
let embedArrays = []; let embedArrays = [];
while (embeds.length > 0); while (embeds.length > 0)
embedArrays.push(embeds.splice(0, maxEmbed)); embedArrays.push(embeds.splice(0, maxEmbed));
for (let i = 0; i < embedArrays.length; i++) { for (let i = 0; i < embedArrays.length; i++) {
if (role == '-no-role-ping-') channel.send({ embeds: embedArrays[i] }); let content = { embeds: embedArrays[i] };
else channel.send({ content: `<@&${role}>`, 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] });
} }
}); });
}); });
@@ -256,7 +266,7 @@ class DayzRBot extends Client {
if (!this.exists(info.player) || !this.exists(info.playerID)) continue; // Skip this player if the player does not exist. 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); lastDetectedTime = await this.getDateEST(info.time);
let playerStat = await this.dbo.collection("players").findOne({"playerID": info.playerID}); 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 (!this.exists(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, guild.Nitrado.ServerID);
@@ -301,47 +311,55 @@ class DayzRBot extends Client {
c.guilds.cache.forEach(async (guild) => { c.guilds.cache.forEach(async (guild) => {
let GuildDB = await GetGuild(c, guild.id); let GuildDB = await GetGuild(c, guild.id);
/* /*
Note to self: Note to self:
return statements do not prematurely exit out of a forEach loop like it does in a for loop. 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 (!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 = { const NitradoCred = {
ServerID: GuildDB.Nitrado.ServerID, ServerID: GuildDB.Nitrado.ServerID,
UserID: GuildDB.Nitrado.UserID, UserID: GuildDB.Nitrado.UserID,
Auth: decrypt( Auth: decrypt(
GuildDB.Nitrado.Auth, GuildDB.Nitrado.Auth,
c.config.EncryptionMethod, c.config.EncryptionMethod,
c.key, c.key,
c.encryptionIV c.encryptionIV
) ),
}; };
const response = await FetchServerSettings(NitradoCred, c, "logsUpdateTimer").then(res => res); const response = await FetchServerSettings(NitradoCred, c, "logsUpdateTimer").then(res => res);
if (response == 1) return; 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; const settings = response.data.gameserver;
// Update Nitrado DayZ Mission if change is detected // Update Nitrado DayZ Mission if change is detected
if (GuildDB.Nitrado.Mission !== Missions[settings.settings.config.mission]) { 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) => { 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 [${guild.serverID}] for nitrado server [${guild.Nitrado.ServerID}]`); 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]; 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 let filenames = await GetRemoteDir(NitradoCred, c, `${settings.game_specific.path}config`);
const filename = settings.game_specific.log_files.sort((a, b) => a.length - b.length)[0]; filenames = filenames.sort((a, b) => a.modified_at - b.modified_at)
const path = `${settings.game_specific.path.slice(0, -1)}${filename.split(settings.game)[1]}`; filenames = filenames.filter(path => path.path.includes(".ADM"))
filenames = filenames.map(path => path.path)
const filename = filenames[filenames.length - 1];
// Ensure Player List is logged for next update // Ensure Player List is logged for next update
const playerListEnabled = parseInt(settings.settings.config.adminLogPlayerList) const playerListEnabled = parseInt(settings.settings.config.adminLogPlayerList)
if (!playerListEnabled) PostServerSettings(NitradoCred, c, "config", "adminLogPlayerList", '1') if (!playerListEnabled) PostServerSettings(NitradoCred, c, "config", "adminLogPlayerList", '1')
await DownloadNitradoFile(NitradoCred, c, path, `./logs/${NitradoCred.ServerID}-logs.ADM`).then(async (status) => { await DownloadNitradoFile(NitradoCred, c, filename, `./logs/${NitradoCred.ServerID}-logs.ADM`).then(async (status) => {
if (status == 1) return c.error(`Failed to Download Nitrado Log Files - [${NitradoCred.ServerID}]`); if (status == 1) return c.error(`Failed to Download Nitrado Log Files - [${NitradoCred.ServerID}]`);
await c.readLogs(GuildDB).then(async () => { await c.readLogs(GuildDB).then(async () => {
HandleExpiredUAVs(c, GuildDB); HandleExpiredUAVs(c, GuildDB);
@@ -381,7 +399,9 @@ class DayzRBot extends Client {
this.databaseConnected = true; this.databaseConnected = true;
} catch (err) { } catch (err) {
databaselogs.attempts++; databaselogs.attempts++;
let db = (mongoURI.includes("@") ? mongoURI.split("@")[1] : mongoURI.split("//")[1]).endsWith("/") ? mongoURI.slice(0, -1) : mongoURI; 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}`); this.error(`Failed to connect to mongodb (mongodb://${db}/${dbo}): attempt ${databaselogs.attempts} - ${err}`);
failed = true; failed = true;
} }
@@ -395,9 +415,10 @@ class DayzRBot extends Client {
async initialize() { async initialize() {
// Wait for MongoDB to connect // Wait for MongoDB to connect
await this.connectMongo(this.config.mongoURI, this.config.dbo); await this.connectMongo(this.config.mongoURI, this.config.dbo);
if (!this.databaseConnected) return;
let guilds = await this.dbo.collection("guilds").find({}).toArray(); let guilds = await this.dbo.collection("guilds").find({}).toArray();
/* /*
Initialize auto restart for enabled servers Initialize auto restart for enabled servers
Initialize last logs Initialize last logs
@@ -407,7 +428,7 @@ class DayzRBot extends Client {
if (!this.exists(guilds[i].Nitrado)) continue; if (!this.exists(guilds[i].Nitrado)) continue;
if (guilds[i].server.autoRestart) { if (guilds[i].server.autoRestart) {
const NitradoCred = { const NitradoCred = {
ServerID: guilds[i].Nitrado.ServerID, ServerID: guilds[i].Nitrado.ServerID,
UserID: guilds[i].Nitrado.UserID, UserID: guilds[i].Nitrado.UserID,
Auth: decrypt( Auth: decrypt(
guilds[i].Nitrado.Auth, guilds[i].Nitrado.Auth,
@@ -420,7 +441,9 @@ class DayzRBot extends Client {
} }
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.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.playerSessions.set(guilds[i].Nitrado.ServerID, new Map()); // Same reason here as named above.
this.log(`[${guilds[i].server.serverID}] Initialized existing Nitrado`); 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})`);
} }
} }
@@ -430,11 +453,13 @@ class DayzRBot extends Client {
if (guild.autoRestart) this.arIntervalIds.set(guildId, setInterval(CheckServerStatus, this.arInterval, Nitrado, this)) if (guild.autoRestart) this.arIntervalIds.set(guildId, setInterval(CheckServerStatus, this.arInterval, Nitrado, this))
this.logHistory.set(Nitrado.ServerID, guild.lastLog); this.logHistory.set(Nitrado.ServerID, guild.lastLog);
this.playerSessions.set(Nitrado.ServerID, new Map()); this.playerSessions.set(Nitrado.ServerID, new Map());
this.log(`[${guild.serverID}] Initialized new Nitrado`); 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 } exists(n) { return typeof(n) == 'number' ? !isNaN(n) : null != n && undefined != n && "" != n }
secondsToDhms(seconds) { secondsToDhms(seconds) {
seconds = Number(seconds); seconds = Number(seconds);
const d = Math.floor(seconds / (3600 * 24)); const d = Math.floor(seconds / (3600 * 24));
+17 -8
View File
@@ -1,11 +1,13 @@
const { EmbedBuilder } = require('discord.js'); const { EmbedBuilder } = require('discord.js');
const { nearest } = require('../database/destinations'); const { nearest } = require('../database/destinations');
const { GetWebhook, WebhookSend } = require("../util/WebhookHandler");
module.exports = { module.exports = {
SendConnectionLogs: async (client, guild, data) => { SendConnectionLogs: async (client, guild, data) => {
if (!client.exists(guild.connectionLogsChannel)) return; if (!client.exists(guild.connectionLogsChannel)) return;
const channel = client.GetChannel(guild.connectionLogsChannel); const channel = client.GetChannel(guild.connectionLogsChannel);
if (!channel) return;
let newDt = await client.getDateEST(data.time); let newDt = await client.getDateEST(data.time);
let unixTime = Math.floor(newDt.getTime() / 1000); let unixTime = Math.floor(newDt.getTime() / 1000);
@@ -14,6 +16,9 @@ module.exports = {
.setColor(data.connected ? client.config.Colors.Green : client.config.Colors.Red) .setColor(data.connected ? client.config.Colors.Green : client.config.Colors.Red)
.setDescription(`**${data.connected ? 'Connect' : 'Disconnect'} Event - <t:${unixTime}>\n${data.player} ${data.connected ? 'Connected' : 'Disconnected'}**`); .setDescription(`**${data.connected ? 'Connect' : 'Disconnect'} Event - <t:${unixTime}>\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.connected) {
if (data.lastConnectionDate != null) { if (data.lastConnectionDate != null) {
let oldUnixTime = Math.floor(data.lastConnectionDate.getTime() / 1000); let oldUnixTime = Math.floor(data.lastConnectionDate.getTime() / 1000);
@@ -22,17 +27,20 @@ module.exports = {
} else connectionLog.addFields({ name: '**Session Time**', value: `**Unknown**`, inline: false }); } else connectionLog.addFields({ name: '**Session Time**', value: `**Unknown**`, inline: false });
} }
if (client.exists(channel)) await channel.send({ embeds: [connectionLog] }); // if (client.exists(channel)) await channel.send({ embeds: [connectionLog] });
await WebhookSend(client, webhook, {embeds: [connectionLog]});
}, },
DetectCombatLog: async (client, guild, data) => { DetectCombatLog: async (client, guild, data) => {
if (!client.exists(data.lastDamageDate)) return; if (!client.exists(data.lastDamageDate)) return;
if (!client.exists(guild.connectionLogsChannel)) 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 newDt = await client.getDateEST(data.time);
const diffSeconds = Math.round((newDt.getTime() - data.lastDamageDate.getTime()) / 1000); const diffSeconds = Math.round((newDt.getTime() - data.lastDamageDate.getTime()) / 1000);
// If diff is greater than 5 minutes, not a combat log // If diff is greater than configured time in minutes, not a combat log
// or if death after last combat // or if death after last combat
if (diffSeconds > (data.combatLogTimer * 60)) return; if (diffSeconds > (data.combatLogTimer * 60)) return;
if (data.lastDamageDate <= data.lastDeathDate) return; if (data.lastDamageDate <= data.lastDeathDate) return;
@@ -40,10 +48,7 @@ module.exports = {
// If lastHitBy (attacker) died after shooting this player // If lastHitBy (attacker) died after shooting this player
// then it does not count as combat logging, (the combat ended due to death) // 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}); let attacker = await client.dbo.collection("players").findOne({"gamertag": data.lastHitBy});
if (attacker.lastDeathDate > data.lastDamageDate) return; if (attacker.lastDeathDate > data.lastDamageDate) return;
const channel = client.GetChannel(guild.connectionLogsChannel);
if (!channel) return;
let unixTime = Math.floor(newDt.getTime() / 1000); let unixTime = Math.floor(newDt.getTime() / 1000);
const destination = nearest(data.pos, guild.Nitrado.Mission); const destination = nearest(data.pos, guild.Nitrado.Mission);
@@ -52,8 +57,12 @@ module.exports = {
.setColor(client.config.Colors.Red) .setColor(client.config.Colors.Red)
.setDescription(`**NOTICE:**\n**${data.player}** has combat logged at <t:${unixTime}> 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}`); .setDescription(`**NOTICE:**\n**${data.player}** has combat logged at <t:${unixTime}> 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}`);
if (client.exists(guild.adminRole)) channel.send({ content: `<@&${guild.adminRole}>` }); const NAME = "DayZ.R Admin Logs";
const webhook = await GetWebhook(client, NAME, guild.connectionLogsChannel);
return channel.send({ embeds: [combatLog] }); let content = { embeds: [combatLog] };
if (client.exists(guild.adminRole)) content.content = `<@&${guild.adminRole}>`;
WebhookSend(client, webhook, content);
// return channel.send({ embeds: [combatLog] });
} }
}; };
+39 -15
View File
@@ -2,6 +2,7 @@ const { BanPlayer, UnbanPlayer } = require('./NitradoAPI');
const { EmbedBuilder } = require('discord.js'); const { EmbedBuilder } = require('discord.js');
const { nearest } = require('../database/destinations'); const { nearest } = require('../database/destinations');
const { GetGuild } = require('../database/guild'); const { GetGuild } = require('../database/guild');
const { GetWebhook, WebhookSend } = require("../util/WebhookHandler");
// Private functions (only called locally) // Private functions (only called locally)
@@ -20,6 +21,10 @@ const ExpireEvent = async(client, guild, e) => {
} }
const HandlePlayerTrackEvent = async (client, guild, e) => { const HandlePlayerTrackEvent = async (client, guild, e) => {
if (!client.exists(e.channel)) return ExpireEvent(client, guild, e); // Expire event since it has invalid channel.
const channel = client.GetChannel(e.channel);
if (!channel) return;
let player = await client.dbo.collection("players").findOne({"gamertag": e.gamertag}); let player = await client.dbo.collection("players").findOne({"gamertag": e.gamertag});
let newDt = await client.getDateEST(player.time); let newDt = await client.getDateEST(player.time);
@@ -31,10 +36,15 @@ const HandlePlayerTrackEvent = async (client, guild, e) => {
.setColor(client.config.Colors.Default) .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 <t:${unixTime}>\n${destination}`); .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 <t:${unixTime}>\n${destination}`);
if (!client.exists(e.channel)) return ExpireEvent(client, guild, e); // Expire event since it has invalid channel. const NAME = "DayZ.R Player Tracker";
const channel = client.GetChannel(e.channel); const webhook = await GetWebhook(client, NAME, e.channel);
if (e.role) channel.send({ content: `<@&${e.role}>`, embeds: [trackEvent] });
else channel.send({ embeds: [trackEvent] }); 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 now = new Date();
let diff = ((now - e.creationDate) / 1000) / 60; let diff = ((now - e.creationDate) / 1000) / 60;
@@ -86,7 +96,7 @@ module.exports = {
.setDescription(`**Zone Ping - <t:${unixTime}>**\n**${data.player}** was located within **${distance} meters** of the Zone **${alarm.name}**`) .setDescription(`**Zone Ping - <t:${unixTime}>**\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 }) .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; return;
} }
} }
@@ -106,7 +116,7 @@ module.exports = {
let uavEmbed = new EmbedBuilder() let uavEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Default) .setColor(client.config.Colors.Default)
.setDescription(`**UAV Detection - <t:${unixTime}>**\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}**`) .setDescription(`**UAV Detection - <t:${unixTime}>**\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) => { client.users.fetch(uav.owner, false).then((user) => {
user.send({ embeds: [uavEmbed] }); user.send({ embeds: [uavEmbed] });
}); });
@@ -123,9 +133,9 @@ module.exports = {
let now = new Date(); let now = new Date();
let diff = Math.round((now.getTime() - uav.creationDate.getTime()) / 1000 / 60); // diff minutes let diff = Math.round((now.getTime() - uav.creationDate.getTime()) / 1000 / 60); // diff minutes
if (diff <= 30) continue; if (diff <= 30) continue;
uavs.splice(i, 1); uavs.splice(i, 1);
update = true; update = true;
@@ -144,9 +154,9 @@ module.exports = {
}, },
KillInAlarm: async (client, guildId, data) => { KillInAlarm: async (client, guildId, data) => {
let guild = await GetGuild(client, guildId); let guild = await GetGuild(client, guildId);
for (let i = 0; i < guild.alarms.length; i++) { for (let i = 0; i < guild.alarms.length; i++) {
let alarm = guild.alarms[i]; let alarm = guild.alarms[i];
if (alarm.disabled || !alarm.rules.includes('ban_on_kill')) continue; // ignore if alarm is disabled or not ban on kill; if (alarm.disabled || !alarm.rules.includes('ban_on_kill')) continue; // ignore if alarm is disabled or not ban on kill;
@@ -157,6 +167,7 @@ module.exports = {
if (distance < alarm.radius) { if (distance < alarm.radius) {
const channel = client.GetChannel(alarm.channel); const channel = client.GetChannel(alarm.channel);
if (!channel) continue;
let newDt = await client.getDateEST(data.time); let newDt = await client.getDateEST(data.time);
let unixTime = Math.floor(newDt.getTime()/1000); let unixTime = Math.floor(newDt.getTime()/1000);
@@ -165,11 +176,17 @@ module.exports = {
.setColor(client.config.Colors.Default) .setColor(client.config.Colors.Default)
.setDescription(`**Zone Ping - <t:${unixTime}>**\n**${data.killer}** was located within **${distance} meters** of the Zone **${alarm.name}** __and has been banned for killing **${data.victim}**.__`) .setDescription(`**Zone Ping - <t:${unixTime}>**\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 }) .addFields({ name: '**Location**', value: `**[${data.killerPOS[0]}, ${data.killerPOS[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${data.killerPOS[0]};${data.killerPOS[1]})**`, inline: false })
channel.send({ content: `<@&${alarm.role}>`, embeds: [alarmEmbed] }); 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); BanPlayer(client, data.killer);
break; break;
} }
} }
return; return;
@@ -198,6 +215,7 @@ module.exports = {
if (distance < alarm.radius) { if (distance < alarm.radius) {
const channel = client.GetChannel(alarm.channel); const channel = client.GetChannel(alarm.channel);
if (!channel) return;
let newDt = await client.getDateEST(info.time); let newDt = await client.getDateEST(info.time);
let unixTime = Math.floor(newDt.getTime()/1000); let unixTime = Math.floor(newDt.getTime()/1000);
@@ -206,8 +224,14 @@ module.exports = {
.setColor(client.config.Colors.Default) .setColor(client.config.Colors.Default)
.setDescription(`**Zone Ping - <t:${unixTime}>**\n**${info.player}** was located within **${distance} meters** of the Zone **${alarm.name}** __and has been banned for **placing a fireplace**.__`) .setDescription(`**Zone Ping - <t:${unixTime}>**\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 }) .addFields({ name: '**Location**', value: `**[${info.playerPOS[0]}, ${info.playerPOS[1]}](https://www.izurvive.com/chernarusplussatmap/#location=${info.playerPOS[0]};${info.playerPOS[1]})**`, inline: false })
channel.send({ content: `<@&${alarm.role}>`, embeds: [alarmEmbed] }); 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); BanPlayer(client, info.player);
break; break;
+1 -1
View File
@@ -12,4 +12,4 @@ module.exports = {
Float: 10, // AKA Number in Discord's Documentation Float: 10, // AKA Number in Discord's Documentation
Attachment: 11, Attachment: 11,
} }
}; };
+1 -1
View File
@@ -16,4 +16,4 @@ module.exports = {
decipher.final('utf8') decipher.final('utf8')
) // Decrypts data and converts to utf8 ) // Decrypts data and converts to utf8
} }
} }
+51 -27
View File
@@ -5,6 +5,7 @@ const { nearest } = require('../database/destinations');
const { getDefaultPlayer, UpdatePlayer } = require('../database/player'); const { getDefaultPlayer, UpdatePlayer } = require('../database/player');
const { calculateNewCombatRating } = require('./CombatRatingHandler'); const { calculateNewCombatRating } = require('./CombatRatingHandler');
const { weapons, weaponClassOf } = require('../database/weapons'); const { weapons, weaponClassOf } = require('../database/weapons');
const { GetWebhook, WebhookSend } = require("../util/WebhookHandler");
const Templates = { const Templates = {
Killed: 1, Killed: 1,
@@ -30,19 +31,19 @@ const Vehicles = {
CivilianSedan: 'White Olga', CivilianSedan: 'White Olga',
CivilianSedan_Black: 'Black Olga', CivilianSedan_Black: 'Black Olga',
CivilianSedan_Wine: 'Wine Olga', CivilianSedan_Wine: 'Wine Olga',
Hatchback_02: 'Red Gunter', Hatchback_02: 'Red Gunter',
Hatchback_02_Black: 'Black Gunter', Hatchback_02_Black: 'Black Gunter',
Hatchback_02_Blue: 'Blue Gunter', Hatchback_02_Blue: 'Blue Gunter',
OffroadHatchBack: 'Green ADA 4x4', OffroadHatchBack: 'Green ADA 4x4',
OffroadHatchBack_Blue: 'Blue ADA 4x4', OffroadHatchBack_Blue: 'Blue ADA 4x4',
OffroadHatchBack_White: 'White ADA 4x4', OffroadHatchBack_White: 'White ADA 4x4',
Sedan_02: 'Yellow Sarka', Sedan_02: 'Yellow Sarka',
Sedan_02_Grey: 'Grey Sarka', Sedan_02_Grey: 'Grey Sarka',
Sedan_02_Red: 'Red Sarka', Sedan_02_Red: 'Red Sarka',
Truck_01_Covered: 'Green V3S Truck', Truck_01_Covered: 'Green V3S Truck',
Truck_01_Covered_Blue: 'Blue V3S Truck', Truck_01_Covered_Blue: 'Blue V3S Truck',
Truck_01_Covered_Orange: 'Orange V3S Truck', Truck_01_Covered_Orange: 'Orange V3S Truck',
@@ -51,12 +52,12 @@ const Vehicles = {
}; };
module.exports = { module.exports = {
// Update last death date for non PVP deaths // Update last death date for non PVP deaths
UpdateLastDeathDate: async (NitradoServerID, client, line) => { UpdateLastDeathDate: async (NitradoServerID, client, line) => {
let killedByZmb = /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\) killed by (.*)/g; let killedByZmb = /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\) killed by (.*)/g;
let diedTemplate = /(.*) \| Player \"(.*)\" \(DEAD\) \(id=(.*) pos=<(.*)>\) died\. Stats> Water: (.*) Energy: (.*) Bleed sources: (.*)/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]; let data = line.includes('>) died.') ? [...line.matchAll(diedTemplate)][0] : [...line.matchAll(killedByZmb)][0];
if (!data) return; if (!data) return;
@@ -79,20 +80,21 @@ module.exports = {
}, },
HandleKillfeed: async (NitradoServerID, client, guild, line) => { HandleKillfeed: async (NitradoServerID, client, guild, line) => {
const NAME = "DayZ.R Killfeed";
const channel = client.GetChannel(guild.killfeedChannel); const channel = client.GetChannel(guild.killfeedChannel);
const killedBy = line.includes('hit by Player') && line.includes('(DEAD)') && line.includes('meters') ? Templates.HitByAndDead : 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') && !line.includes('meters') ? Templates.Melee : // Missing meters indicates it was a melee attack.
line.includes('hit by Player') ? Templates.HitBy : line.includes('hit by Player') ? Templates.HitBy :
line.includes('killed by Player') ? Templates.Killed : line.includes('killed by Player') ? Templates.Killed :
line.includes('TransportHit') ? Templates.Vehicle : line.includes('TransportHit') ? Templates.Vehicle :
line.includes('killed by LandMineTrap') ? Templates.LandMine : Templates.Explosion; line.includes('killed by LandMineTrap') ? Templates.LandMine : Templates.Explosion;
let data = [...line.matchAll(TemplateExpressions[killedBy])][0]; let data = [...line.matchAll(TemplateExpressions[killedBy])][0];
if (!data) return; if (!data) return;
// Create base data // Create base data
let info = { let info = {
time: data[1], time: data[1],
@@ -133,9 +135,14 @@ module.exports = {
if (killedBy == Templates.LandMine || killedBy == Templates.Explosion || killedBy == Templates.Vehicle) { if (killedBy == Templates.LandMine || killedBy == Templates.Explosion || killedBy == Templates.Vehicle) {
let victimStat = await client.dbo.collection("players").findOne({"playerID": info.victimID}); let victimStat = await client.dbo.collection("players").findOne({"playerID": info.victimID});
if (!client.exists(victimStat)) victimStat = getDefaultPlayer(info.victim, info.victimID, NitradoServerID); 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; victimStat.lastDeathDate = newDt;
const cod = killedBy == Templates.LandMine ? `Land Mine Trap` : const cod = killedBy == Templates.LandMine ? `Land Mine Trap` :
killedBy == Templates.Vehicle ? Vehicles[info.causeOfDeath] : info.causeOfDeath; 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 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 killMessage = killedBy == Templates.Vehicle ? 'run over by' : 'blew up from';
@@ -144,9 +151,14 @@ module.exports = {
.setColor(client.config.Colors.Default) .setColor(client.config.Colors.Default)
.setDescription(`**Death Event** - <t:${unixTime}>\n**${info.victim}** ${killMessage} a **${cod}.**${coord}`); .setDescription(`**Death Event** - <t:${unixTime}>\n**${info.victim}** ${killMessage} a **${cod}.**${coord}`);
if (client.exists(channel)) await channel.send({ embeds: [killEvent] });
await UpdatePlayer(client, victimStat); await UpdatePlayer(client, victimStat);
return
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 KillInAlarm(client, guild.serverID, info); // check if kill happened in a no kill zone
@@ -171,7 +183,7 @@ module.exports = {
killerStat.deathStreak = 0; killerStat.deathStreak = 0;
if (!client.exists(killerStat.weaponStats[weapon].kills)) killerStat.weaponStats[weapon].kills = 0; if (!client.exists(killerStat.weaponStats[weapon].kills)) killerStat.weaponStats[weapon].kills = 0;
killerStat.weaponStats[weapon].kills++; killerStat.weaponStats[weapon].kills++;
// Update victim stats // Update victim stats
victimStat.deaths++; victimStat.deaths++;
victimStat.deathStreak++; victimStat.deathStreak++;
@@ -181,7 +193,7 @@ module.exports = {
victimStat.lastDeathDate = newDt; victimStat.lastDeathDate = newDt;
if (!client.exists(victimStat.weaponStats[weapon].deaths)) victimStat.weaponStats[weapon].death = 0; if (!client.exists(victimStat.weaponStats[weapon].deaths)) victimStat.weaponStats[weapon].death = 0;
victimStat.weaponStats[weapon].deaths++; victimStat.weaponStats[weapon].deaths++;
// Create defaults for non-existing ratings // Create defaults for non-existing ratings
if (!client.exists(killerStat.combatRating)) killerStat.combatRating = 800; if (!client.exists(killerStat.combatRating)) killerStat.combatRating = 800;
if (!client.exists(victimStat.combatRating)) victimStat.combatRating = 800; if (!client.exists(victimStat.combatRating)) victimStat.combatRating = 800;
@@ -189,13 +201,13 @@ module.exports = {
if (!client.exists(victimStat.combatRatingHistory)) victimStat.combatRatingHistory = [800]; if (!client.exists(victimStat.combatRatingHistory)) victimStat.combatRatingHistory = [800];
if (!client.exists(killerStat.highestCombatRating)) killerStat.highestCombatRating = Math.max(...killerStat.combatRatingHistory); if (!client.exists(killerStat.highestCombatRating)) killerStat.highestCombatRating = Math.max(...killerStat.combatRatingHistory);
if (!client.exists(victimStat.lowestCombatRating)) victimStat.lowestCombatRating = Math.min(...victimStat.combatRatingHistory); if (!client.exists(victimStat.lowestCombatRating)) victimStat.lowestCombatRating = Math.min(...victimStat.combatRatingHistory);
// Calculate new ratings // Calculate new ratings
let killerOldRating = killerStat.combatRating; let killerOldRating = killerStat.combatRating;
let victimOldRating = victimStat.combatRating; let victimOldRating = victimStat.combatRating;
killerStat.combatRating = calculateNewCombatRating(killerStat.combatRating, victimStat.combatRating, client.exists(info.bodyPart) && info.bodyPart.includes('Head') ? 1.25 : 1); killerStat.combatRating = calculateNewCombatRating(killerStat.combatRating, victimStat.combatRating, client.exists(info.bodyPart) && info.bodyPart.includes('Head') ? 1.25 : 1);
victimStat.combatRating = calculateNewCombatRating(victimStat.combatRating, killerStat.combatRating, 0); victimStat.combatRating = calculateNewCombatRating(victimStat.combatRating, killerStat.combatRating, 0);
// Update combat rating records // Update combat rating records
if (killerStat.combatRating > killerStat.highestCombatRating) killerStat.highestCombatRating = killerStat.combatRating; if (killerStat.combatRating > killerStat.highestCombatRating) killerStat.highestCombatRating = killerStat.combatRating;
if (victimStat.combatRating < victimStat.lowestCombatRating) victimStat.lowestCombatRating = victimStat.combatRating; if (victimStat.combatRating < victimStat.lowestCombatRating) victimStat.lowestCombatRating = victimStat.combatRating;
@@ -203,7 +215,7 @@ module.exports = {
if (victimStat.combatRatingHistory.length >= 12) victimStat.combatRatingHistory = victimStat.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); killerStat.combatRatingHistory.push(killerStat.combatRating);
victimStat.combatRatingHistory.push(victimStat.combatRating); victimStat.combatRatingHistory.push(victimStat.combatRating);
let kdiff = killerStat.combatRating - killerOldRating; let kdiff = killerStat.combatRating - killerOldRating;
let vdiff = victimStat.combatRating - victimOldRating; let vdiff = victimStat.combatRating - victimOldRating;
@@ -215,7 +227,7 @@ module.exports = {
} }
let banking = await client.dbo.collection("users").findOne({"user.userID": killerStat.discordID}).then(banking => banking); let banking = await client.dbo.collection("users").findOne({"user.userID": killerStat.discordID}).then(banking => banking);
if (!banking) { if (!banking) {
banking = await createUser(interaction.member.user.id, guild.serverID, guild.startingBalance, client) banking = await createUser(interaction.member.user.id, guild.serverID, guild.startingBalance, client)
if (!client.exists(banking)) return client.sendInternalError(interaction, err); if (!client.exists(banking)) return client.sendInternalError(interaction, err);
@@ -228,14 +240,14 @@ module.exports = {
} }
const newBalance = banking.guilds[ guild.serverID].balance + totalBounty; const newBalance = banking.guilds[ guild.serverID].balance + totalBounty;
await client.dbo.collection("users").updateOne({ "user.userID": killerStat.discordID }, { await client.dbo.collection("users").updateOne({ "user.userID": killerStat.discordID }, {
$set: { $set: {
[`user.guilds.${ guild.serverID}.balance`]: newBalance, [`user.guilds.${ guild.serverID}.balance`]: newBalance,
} }
}, (err, res) => { }, (err, res) => {
if (err) return client.sendError(client.GetChannel(guild.killfeedChannel), `Killfeed Error: Updating killer bank balance\n${err}`); if (err) return client.sendError(client.GetChannel(guild.killfeedChannel), `Killfeed Error: Updating killer bank balance\n${err}`);
}); });
receivedBounty = new EmbedBuilder() receivedBounty = new EmbedBuilder()
.setColor(client.config.Colors.Default) .setColor(client.config.Colors.Default)
@@ -247,12 +259,17 @@ module.exports = {
await UpdatePlayer(client, victimStat); await UpdatePlayer(client, victimStat);
await UpdatePlayer(client, killerStat); await UpdatePlayer(client, killerStat);
const header = `**Kill Event** - <t:${unixTime}>\n**${info.killer}** killed **${info.victim}**`; const header = `**Kill Event** - <t:${unixTime}>\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 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 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 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}` : '';
const map = guild.Nitrado.Mission == "Chernarus" ? "chernarusplus" :
guild.Nitrado.Mission == "Livonia" ? "livonia" :
"sakhal";
const coord = showCoords ? `\n***Location [${info.victimPOS[0]}, ${info.victimPOS[1]}](https://www.izurvive.com/${map}/#location=${info.victimPOS[0]};${info.victimPOS[1]})***\n${destination}` : '';
let killEvent = new EmbedBuilder() let killEvent = new EmbedBuilder()
.setColor(client.config.Colors.Default) .setColor(client.config.Colors.Default)
@@ -263,9 +280,16 @@ module.exports = {
killEvent.setThumbnail(weapons[weaponClass][weapon]) killEvent.setThumbnail(weapons[weaponClass][weapon])
} }
if (client.exists(channel)) await channel.send({ embeds: [killEvent] }); if (!channel) return;
if (client.exists(receivedBounty) && client.exists(channel)) await channel.send({ content: `<@${killerStat.discordID}>`, embeds: [receivedBounty] });
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; return;
} }
} }
+1 -1
View File
@@ -35,4 +35,4 @@ class Logger {
} }
} }
module.exports = Logger; module.exports = Logger;
+23 -11
View File
@@ -5,8 +5,7 @@ const { getDefaultPlayer } = require('../database/player');
const { FetchServerSettings } = require('../util/NitradoAPI'); const { FetchServerSettings } = require('../util/NitradoAPI');
const { UpdatePlayer, insertPVPstats, createWeaponStats } = require('../database/player') const { UpdatePlayer, insertPVPstats, createWeaponStats } = require('../database/player')
const { Missions } = require('../database/destinations'); const { Missions } = require('../database/destinations');
const { GetWebhook, WebhookSend, WebhookMessageEdit } = require("../util/WebhookHandler");
let lastSendMessage;
module.exports = { module.exports = {
@@ -34,11 +33,12 @@ module.exports = {
if (!client.exists(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, NitradoServerID); if (!client.exists(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, NitradoServerID);
const newDt = await client.getDateEST(info.time); const newDt = await client.getDateEST(info.time);
playerStat.gamertag = info.player; // update username if changed
playerStat.lastConnectionDate = newDt; playerStat.lastConnectionDate = newDt;
playerStat.connected = true; playerStat.connected = true;
if (!client.exists(playerStat.connections)) playerStat.connections = 0; if (!client.exists(playerStat.connections)) playerStat.connections = 0;
playerStat.connections++; playerStat.connections++;
// Track adjusted sessions this instance has handled (e.g. no bot crashes or restarts). // Track adjusted sessions this instance has handled (e.g. no bot crashes or restarts).
if (client.playerSessions.get(NitradoServerID).has(info.playerID)) { if (client.playerSessions.get(NitradoServerID).has(info.playerID)) {
// Player is already in a session, update the session's end time. // Player is already in a session, update the session's end time.
@@ -77,7 +77,7 @@ module.exports = {
let playerStat = await client.dbo.collection("players").findOne({"playerID": info.playerID}); 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)) playerStat = getDefaultPlayer(info.player, info.playerID, NitradoServerID);
let oldUnixTime; let oldUnixTime;
let sessionTimeSeconds; let sessionTimeSeconds;
const newDt = await client.getDateEST(info.time); const newDt = await client.getDateEST(info.time);
@@ -88,6 +88,7 @@ module.exports = {
} else sessionTimeSeconds = 0; } else sessionTimeSeconds = 0;
if (!client.exists(playerStat.longestSessionTime)) playerStat.longestSessionTime = 0; if (!client.exists(playerStat.longestSessionTime)) playerStat.longestSessionTime = 0;
playerStat.gamertag = info.player; // update username if changed
playerStat.totalSessionTime = playerStat.totalSessionTime + sessionTimeSeconds; playerStat.totalSessionTime = playerStat.totalSessionTime + sessionTimeSeconds;
playerStat.lastSessionTime = sessionTimeSeconds; playerStat.lastSessionTime = sessionTimeSeconds;
playerStat.longestSessionTime = sessionTimeSeconds > playerStat.longestSessionTime ? sessionTimeSeconds : playerStat.longestSessionTime; playerStat.longestSessionTime = sessionTimeSeconds > playerStat.longestSessionTime ? sessionTimeSeconds : playerStat.longestSessionTime;
@@ -133,6 +134,7 @@ module.exports = {
if (!client.exists(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, NitradoServerID); if (!client.exists(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, NitradoServerID);
if (!client.exists(playerStat.lastConnectionDate)) playerStat.lastConnectionDate = await client.getDateEST(info.time); if (!client.exists(playerStat.lastConnectionDate)) playerStat.lastConnectionDate = await client.getDateEST(info.time);
playerStat.gamertag = info.player; // update username if changed
playerStat.lastPos = playerStat.pos; playerStat.lastPos = playerStat.pos;
playerStat.pos = info.pos; playerStat.pos = info.pos;
playerStat.lastTime = playerStat.time; playerStat.lastTime = playerStat.time;
@@ -173,9 +175,12 @@ module.exports = {
if (!client.exists(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, NitradoServerID); if (!client.exists(playerStat)) playerStat = getDefaultPlayer(info.player, info.playerID, NitradoServerID);
if (!client.exists(attackerStat)) attackerStat = getDefaultPlayer(info.attacker, info.attackerID, NitradoServerID); if (!client.exists(attackerStat)) attackerStat = getDefaultPlayer(info.attacker, info.attackerID, NitradoServerID);
playerStat.gamertag = info.player; // update username if changed
playerStat.lastDamageDate = await client.getDateEST(info.time); playerStat.lastDamageDate = await client.getDateEST(info.time);
playerStat.lastHitBy = info.attacker; playerStat.lastHitBy = info.attacker;
attackerStat.gamertag = info.attacker; // update username if changed
if (!client.exists(playerStat.shotsLanded)) playerStat = insertPVPstats(playerStat); if (!client.exists(playerStat.shotsLanded)) playerStat = insertPVPstats(playerStat);
if (!client.exists(attackerStat.shotsLanded)) attackerStat = insertPVPstats(attackerStat); if (!client.exists(attackerStat.shotsLanded)) attackerStat = insertPVPstats(attackerStat);
@@ -208,10 +213,11 @@ module.exports = {
if (!client.exists(guild.activePlayersChannel)) return; if (!client.exists(guild.activePlayersChannel)) return;
const channel = client.GetChannel(guild.activePlayersChannel); const channel = client.GetChannel(guild.activePlayersChannel);
if (!channel) return;
const data = await FetchServerSettings(nitrado_cred, client, 'HandleActivePlayersList'); // Fetch server status const data = await FetchServerSettings(nitrado_cred, client, 'HandleActivePlayersList'); // Fetch server status
const e = data && data !== 1; // Check if data exists const e = data && data !== 1; // Check if data exists
const hostname = e ? data.data.gameserver.settings.config.hostname : 'N/A'; const hostname = e ? data.data.gameserver.settings.config.hostname : 'N/A';
const map = Missions[data.data.gameserver.settings.config.mission]; const map = Missions[data.data.gameserver.settings.config.mission];
const status = e ? data.data.gameserver.status : 'N/A'; const status = e ? data.data.gameserver.status : 'N/A';
@@ -227,13 +233,14 @@ module.exports = {
const emojiStatus = Statuses[status].emoji || "❓"; const emojiStatus = Statuses[status].emoji || "❓";
const textStatus = Statuses[status].text || "Unknown Status"; 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 activePlayers = await client.dbo.collection("players").find({ "nitradoServerID": parseInt(nitrado_cred.ServerID) }).toArray();
activePlayers = activePlayers.filter(player => player.connected);
let des = activePlayers.length > 0 ? `` : `**No Players Online**`; let des = activePlayers.length > 0 ? `` : `**No Players Online**`;
for (let i = 0; i < activePlayers.length; i++) { for (let i = 0; i < activePlayers.length; i++) {
des += `**- ${activePlayers[i].gamertag}**\n`; des += `**- ${activePlayers[i].gamertag}**\n`;
} }
const nodes = activePlayers.length === 0; const nodes = activePlayers.length === 0;
const serverEmbed = new EmbedBuilder() const serverEmbed = new EmbedBuilder()
.setColor(client.config.Colors.Default) .setColor(client.config.Colors.Default)
@@ -251,10 +258,15 @@ module.exports = {
.setTitle(`Players Online:`) .setTitle(`Players Online:`)
.setDescription(des || (nodes ? "No Players Online :(" : "")); .setDescription(des || (nodes ? "No Players Online :(" : ""));
if (lastSendMessage) lastSendMessage.delete().catch(error => client.sendError(channel, `HandleActivePlayersList Error: \n${error}`)); // Remove previous message before reprinting const NAME = "DayZ.R Admin Logs";
const webhook = await GetWebhook(client, NAME, guild.activePlayersChannel);
return channel.send({ embeds: [serverEmbed, activePlayersEmbed] }).then(sentMessage => let id = client.playerListMsgIds.get(guild.serverID);
lastSendMessage = sentMessage 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] });
}
} }
}; };
+42 -35
View File
@@ -22,7 +22,7 @@ const UploadNitradoFile = async (nitrado_cred, client, remoteDir, remoteFilename
}).then(response => response.json()); }).then(response => response.json());
let contents = fs.readFileSync(localFileDir, 'utf8'); let contents = fs.readFileSync(localFileDir, 'utf8');
const uploadRes = await fetch(res.data.token.url, { const uploadRes = await fetch(res.data.token.url, {
method: "POST", method: "POST",
headers: { headers: {
@@ -63,36 +63,37 @@ const HandlePlayerBan = async (nitrado_cred, client, gamertag, ban) => {
} }
} }
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) // Public functions (called externally)
module.exports = { module.exports = {
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
}
},
DownloadNitradoFile: async(nitrado_cred, client, filename, outputDir) => { DownloadNitradoFile: async(nitrado_cred, client, filename, outputDir) => {
for (let retries = 0; retries <= maxRetries; retries++) { for (let retries = 0; retries <= maxRetries; retries++) {
try { try {
@@ -100,7 +101,7 @@ module.exports = {
headers: { headers: {
"Authorization": nitrado_cred.Auth "Authorization": nitrado_cred.Auth
} }
}).then(response => }).then(response =>
response.json().then(data => data) response.json().then(data => data)
).then(res => res); ).then(res => res);
@@ -124,8 +125,8 @@ module.exports = {
}, },
/* /*
Export explicit function names; i.e BanPlayer() & UnbanPlayer() Export explicit function names; i.e BanPlayer() & UnbanPlayer()
that call to the private parent function HandlePlayerBan() that call to the private parent function HandlePlayerBan()
rather than write two whole different functions for each. rather than write two whole different functions for each.
*/ */
@@ -176,6 +177,7 @@ module.exports = {
if (!res.ok) { if (!res.ok) {
client.error(`Failed to get Nitrado server stats (${nitrado_cred.ServerID}): status: ${res.status}, message: ${res.statusText}: ${fetcher} via FetchServerSettings`); 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. if (retries === 2) return 1; // Return error status on the second failed status code.
} else { } else {
const data = await res.json(); const data = await res.json();
@@ -260,7 +262,7 @@ module.exports = {
const missionPath = remoteDirsFromBase[0].path; const missionPath = remoteDirsFromBase[0].path;
const cfggameplayPath = `${missionPath}/cfggameplay.json`; const cfggameplayPath = `${missionPath}/cfggameplay.json`;
const jsonDir = `./logs/cfggameplay.json`; const jsonDir = `./logs/cfggameplay.json`;
await module.exports.DownloadNitradoFile(nitrado_cred, client, cfggameplayPath, jsonDir); await module.exports.DownloadNitradoFile(nitrado_cred, client, cfggameplayPath, jsonDir);
let gameplay = JSON.parse(fs.readFileSync(jsonDir)); let gameplay = JSON.parse(fs.readFileSync(jsonDir));
@@ -271,7 +273,7 @@ module.exports = {
const uploaded = await UploadNitradoFile(nitrado_cred, client, missionPath, 'cfggameplay.json', jsonDir); const uploaded = await UploadNitradoFile(nitrado_cred, client, missionPath, 'cfggameplay.json', jsonDir);
if (uploaded == 1) return 1; if (uploaded == 1) return 1;
return 0; return 0;
}, },
@@ -288,7 +290,7 @@ module.exports = {
const missionPath = remoteDirsFromBase[0].path; const missionPath = remoteDirsFromBase[0].path;
const cfggameplayPath = `${missionPath}/cfggameplay.json`; const cfggameplayPath = `${missionPath}/cfggameplay.json`;
const jsonDir = `./logs/cfggameplay.json`; const jsonDir = `./logs/cfggameplay.json`;
await module.exports.DownloadNitradoFile(nitrado_cred, client, cfggameplayPath, jsonDir); await module.exports.DownloadNitradoFile(nitrado_cred, client, cfggameplayPath, jsonDir);
let gameplay = JSON.parse(fs.readFileSync(jsonDir)); let gameplay = JSON.parse(fs.readFileSync(jsonDir));
@@ -299,7 +301,12 @@ module.exports = {
const uploaded = await UploadNitradoFile(nitrado_cred, client, missionPath, 'cfggameplay.json', jsonDir); const uploaded = await UploadNitradoFile(nitrado_cred, client, missionPath, 'cfggameplay.json', jsonDir);
if (uploaded == 1) return 1; if (uploaded == 1) return 1;
return 0; return 0;
} },
NitradoCredentialStatus: {
FAILED: "FAILED",
OK: "OK",
},
} }
+3 -3
View File
@@ -8,7 +8,7 @@ const { REST } = require('@discordjs/rest');
* @param {require("../structures/DayzRBot")} client * @param {require("../structures/DayzRBot")} client
*/ */
module.exports = { module.exports = {
// Register guild commands // Register guild commands
RegisterGuildCommands: async (client, guild) => { RegisterGuildCommands: async (client, guild) => {
const commands = []; const commands = [];
const commandFiles = fs.readdirSync(path.join(__dirname, "..", "commands")).filter(file => file.endsWith('.js')); const commandFiles = fs.readdirSync(path.join(__dirname, "..", "commands")).filter(file => file.endsWith('.js'));
@@ -50,7 +50,7 @@ module.exports = {
if (command.global) commands.push(command); if (command.global) commands.push(command);
} }
const rest = new REST({ version: '10' }).setToken(client.config.Token); const rest = new REST({ version: '10' }).setToken(client.config.Token);
try { try {
client.log('[global] Started refreshing global (/) commands.'); client.log('[global] Started refreshing global (/) commands.');
@@ -65,4 +65,4 @@ module.exports = {
client.error(error); client.error(error);
} }
} }
}; };
+3 -3
View File
@@ -6,7 +6,7 @@ module.exports = {
let theta = (thetat < 0) ? (360 + thetat) : thetat; let theta = (thetat < 0) ? (360 + thetat) : thetat;
let compass = ["S", "SW", "W", "NW", "N", "NE", "E", "SE", "S"]; let compass = ["S", "SW", "W", "NW", "N", "NE", "E", "SE", "S"];
let dir = compass[Math.round(theta / 45)]; let dir = compass[Math.round(theta / 45)];
return {distance, theta, dir} return {distance, theta, dir}
} }
} }
+56
View File
@@ -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
});
}
}