fix: updated logging for commands

This commit is contained in:
Marius Begby committed 2023-08-26 17:00:08 +02:00
1 parent 5c8f3353f9
commit a04d0aeb5b
24 files changed
+510 -292

No files matched your search

+5 -1
View File
@@ -52,6 +52,10 @@ module.exports.presenceStatusOptions = {
// Configurations for visual embed messages.
// Includes design elements like colors and custom emojis/symbols.
module.exports.embedOptions = {
info: {
fallbackThumbnailUrl:
'https://raw.githubusercontent.com/mariusbegby/cadence-discord-bot/main/assets/logo-rounded-128px.png'
},
colors: {
success: '#23A55A',
warning: '#F0B232',
@@ -101,7 +105,7 @@ module.exports.embedOptions = {
sourceYouTube: '🎵',
sourceSoundCloud: '🎵',
sourceSpotify: '🎵',
liveTrack: '🔴',
liveTrack: '🔴'
}
};
+2 -2
View File
@@ -20,10 +20,10 @@
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node ./src/index.js",
"start-pretty": "node ./src/index.js | pino-pretty --ignore environment,source,module,action,name,context,err,error,executionId,shardId,guildId",
"start-pretty": "node ./src/index.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,shardId,guildId",
"start-pretty-no-ignore": "node ./src/index.js | pino-pretty",
"deploy": "node ./src/utils/deploySlashCommands.js",
"deploy-pretty": "node ./src/utils/deploySlashCommands.js | pino-pretty --ignore environment,source,module,action,name,context,err,error,executionId,shardId,guildId",
"deploy-pretty": "node ./src/utils/deploySlashCommands.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,shardId,guildId",
"eslint": "eslint ./"
},
"dependencies": {
+10
View File
@@ -10,6 +10,15 @@ module.exports = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
source: 'help.js',
module: 'slashCommand',
name: '/help',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
const commandList = client.commands
.filter((command) => {
// don't include system commands
@@ -34,6 +43,7 @@ module.exports = {
? `${embedOptions.icons.bot} **Enjoying ${botOptions.name}?**\nAdd me to another server: \n**[Click me!](${botOptions.botInviteUrl})**`
: '';
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+19 -1
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { getUptimeFormatted } = require('../../utils/system/getUptimeFormatted');
@@ -15,6 +14,15 @@ module.exports = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
source: 'status.js',
module: 'slashCommand',
name: '/status',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
const uptimeString = await getUptimeFormatted({ executionId });
const usedMemoryInMB = Math.ceil((await osu.mem.info()).usedMemMb).toLocaleString('en-US');
const cpuUsage = await osu.cpu.usage();
@@ -47,6 +55,11 @@ module.exports = {
activeVoiceConnections = queueCountList.reduce((acc, queueAmount) => acc + queueAmount, 0);
totalTracks = trackCountList.reduce((acc, trackAmount) => acc + trackAmount, 0);
totalListeners = listenerCountList.reduce((acc, listenerAmount) => acc + listenerAmount, 0);
logger.debug('Successfully fetched player statistics from shards.');
})
.catch((error) => {
logger.error(error, 'Failed to fetch player statistics from shards.');
});
await client.shard
@@ -58,6 +71,8 @@ module.exports = {
memberCount += guildCache.reduce((acc, guildCache) => acc + guildCache.memberCount, 0);
}
});
logger.debug('Successfully fetched client values from shards.');
})
.catch((error) => {
logger.error(error, 'Failed to fetch client values from shards.');
@@ -78,6 +93,9 @@ module.exports = {
const discordStatusString = `**${client.ws.ping} ms** Discord API latency`;
logger.debug('Transformed status into into embed description.');
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+19 -22
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const ffmpegFilterOptions = config.get('ffmpegFilterOptions');
@@ -23,6 +22,15 @@ module.exports = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'filters.js',
module: 'slashCommand',
name: '/filters',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
@@ -77,6 +85,7 @@ module.exports = {
.setEmoji(embedOptions.icons.disable)
);
logger.debug('Sending info embed with action row components.');
const response = await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -87,9 +96,6 @@ module.exports = {
],
components: [filterActionRow, disableFiltersActionRow]
});
logger.debug(
`[Shard ${interaction.guild.shardId}] Sent embed for command ${interaction.commandName}, awaiting interaction response.`
);
const collectorFilter = (i) => i.user.id === interaction.user.id;
try {
@@ -98,12 +104,10 @@ module.exports = {
time: 300_000
});
logger.debug(
`[Shard ${interaction.guild.shardId}] Received interaction response for command ${interaction.commandName}.`
);
confirmation.deferUpdate();
logger.debug('Received component interaction response.');
queue.filters.ffmpeg.setInputArgs([
'-threads',
ffmpegFilterOptions.threadAmount,
@@ -119,9 +123,11 @@ module.exports = {
// Reset filters before enabling provided filters
if (queue.filters.ffmpeg.filters.length > 0) {
queue.filters.ffmpeg.setFilters(false);
logger.debug('Reset queue filters.');
}
if (confirmation.customId === 'disable-filters' || confirmation.values.length === 0) {
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -148,13 +154,9 @@ module.exports = {
// Enable provided filters
queue.filters.ffmpeg.toggle(confirmation.values);
logger.debug(`Enabled filters ${confirmation.values.join(', ')}.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] Enabled filters ${confirmation.values.join(', ')} for command ${
interaction.commandName
}.`
);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -181,17 +183,12 @@ module.exports = {
});
} catch (error) {
if (error.code === 'InteractionCollectorError') {
logger.debug(
`[Shard ${interaction.guild.shardId}] Interaction response timed out for command ${interaction.commandName}.`
);
logger.debug('Interaction response timed out.');
return;
}
logger.debug(
error,
`[Shard ${interaction.guild.shardId}] Unhandled error while awaiting interaction response for command ${interaction.commandName}, throwing error.`
);
throw error;
logger.error(error, 'Unhandled error while awaiting or handling component interaction.');
return;
}
}
};
+14 -7
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -14,6 +13,15 @@ module.exports = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'leave.js',
module: 'slashCommand',
name: '/leave',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
@@ -21,9 +29,9 @@ module.exports = {
const queue = useQueue(interaction.guild.id);
if (!queue) {
logger.debug(
`User used command ${interaction.commandName} but there was no queue.`
);
logger.debug('There is already no queue.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -41,11 +49,10 @@ module.exports = {
if (!queue.deleted) {
queue.delete();
logger.debug(
`User used command ${interaction.commandName} and deleted the queue.`
);
logger.debug('Deleted the queue.');
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+22 -18
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const botOptions = config.get('botOptions');
@@ -28,6 +27,15 @@ module.exports = {
)
),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'loop.js',
module: 'slashCommand',
name: '/loop',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
@@ -55,10 +63,9 @@ module.exports = {
const currentModeUserString = loopModesFormatted.get(currentMode);
if (!mode && mode !== 0) {
logger.debug(
`User used command ${interaction.commandName} but no mode was provided.`
);
logger.debug('No mode input was provided, responding with current loop mode.');
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -73,10 +80,9 @@ module.exports = {
}
if (mode === currentMode) {
logger.debug(
`User used command ${interaction.commandName} but loop mode was already set to ${modeUserString}.`
);
logger.debug(`Loop mode is already set to ${modeUserString}.`);
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -91,10 +97,11 @@ module.exports = {
queue.setRepeatMode(mode);
if (!queue.repeatMode === mode) {
logger.debug(
`User used command ${interaction.commandName} but failed to change loop mode.`
logger.warn(
'Failed to change loop mode. After setting queue repeat mode, the value was not the same as input.'
);
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -107,10 +114,9 @@ module.exports = {
}
if (queue.repeatMode === 0) {
logger.debug(
`User used command ${interaction.commandName} and disabled loop mode.`
);
logger.debug('Disabled loop mode.');
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -127,10 +133,9 @@ module.exports = {
}
if (queue.repeatMode === 3) {
logger.debug(
`User used command ${interaction.commandName} and enabled autoplay.`
);
logger.debug('Enabled autoplay mode.');
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -146,10 +151,9 @@ module.exports = {
});
}
logger.debug(
`User used command ${interaction.commandName} and enabled loop mode.`
);
logger.debug('Enabled loop mode.');
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+51 -30
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -26,24 +25,27 @@ module.exports = {
.setMaxLength(500)
.setAutocomplete(true)
),
autocomplete: async ({ interaction }) => {
autocomplete: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'lyrics.js',
module: 'slashCommand',
name: '/lyrics',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
const query = interaction.options.getString('query', true);
const { lastQuery, result, timestamp } = recentQueries.get(interaction.user.id) || {};
if (lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - timestamp < 500) {
logger.debug(
{ action: 'autocomplete_responded' },
`Autocomplete search responded with results from lastQuery for query: '${query}'`
);
logger.debug(`Responding with results from lastQuery for query '${query}'`);
return interaction.respond(result);
}
if (query.length < 3) {
logger.debug(
{ action: 'autocomplete_responded' },
`Autocomplete search responded with empty results due to < 3 length for query '${query}'`
);
logger.debug(`Responding with empty results due to < 3 length for query '${query}'`);
return interaction.respond([]);
}
@@ -52,6 +54,7 @@ module.exports = {
let response = [];
if (!lyricsResult) {
logger.debug(`No Genius lyrics found for query '${query}', using player.search() as fallback.`);
const player = useMainPlayer();
const searchResults = await player.search(query);
response = searchResults.tracks.slice(0, 1).map((track) => ({
@@ -62,6 +65,7 @@ module.exports = {
value: track.title.slice(0, 100)
}));
} else {
logger.debug(`Found Genius lyrics for query '${query}'.`);
response = [
{
name: `${lyricsResult.title} [Artist: ${lyricsResult.artist.name}]`.slice(0, 100),
@@ -71,6 +75,7 @@ module.exports = {
}
if (!response || response.length === 0) {
logger.debug(`Responding with empty results for query '${query}'`);
return interaction.respond([]);
}
@@ -80,13 +85,19 @@ module.exports = {
timestamp: Date.now()
});
logger.debug(
{ action: 'autocomplete_responded' },
`Autocomplete search responded for query: '${query}'`
);
logger.debug(`Responding to autocomplete with results for query: '${query}'.`);
return interaction.respond(response);
},
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'lyrics.js',
module: 'slashCommand',
name: '/lyrics',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
const query = interaction.options.getString('query');
const queue = useQueue(interaction.guild.id);
let geniusSearchQuery = '';
@@ -108,19 +119,24 @@ module.exports = {
return;
}
geniusSearchQuery = queue.currentTrack.title.slice(0, 50);
logger.debug(
`No input query provided, using current track. Using query for genius: '${geniusSearchQuery}'`
);
}
let searchResult;
if (query) {
logger.debug(`Query input provided, using query '${query}' for player.search().`);
const player = useMainPlayer();
const searchResults = await player.search(query, {
searchEngine: QueryType.SPOTIFY_SEARCH
});
if (searchResults.tracks.length === 0) {
logger.debug(
`User used command ${interaction.commandName} but there was no search results found.`
);
logger.debug('No search results using player.search() found.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -134,7 +150,7 @@ module.exports = {
searchResult = searchResults.tracks[0];
geniusSearchQuery = searchResults.tracks[0].title;
logger.debug(`Using query for genius: ${geniusSearchQuery}`);
logger.debug(`Using query for genius: '${geniusSearchQuery}'`);
}
// get lyrics
@@ -143,9 +159,15 @@ module.exports = {
// try again with shorter query (some titles just have added info in the end)
if (!lyricsResult && geniusSearchQuery.length > 20) {
logger.debug(
`No Genius lyrics found for query '${geniusSearchQuery}', trying again with shorter query (20 chars).`
);
lyricsResult = await genius.search(geniusSearchQuery.slice(0, 20)).catch(() => null);
}
if (!lyricsResult && geniusSearchQuery.length > 10) {
logger.debug(
`No Genius lyrics found for query '${geniusSearchQuery}', trying again with shorter query (10 chars).`
);
lyricsResult = await genius.search(geniusSearchQuery.slice(0, 10)).catch(() => null);
}
@@ -167,14 +189,14 @@ module.exports = {
!searchResultAuthorSplitIncludesArtist
) {
lyricsResult = null;
logger.debug('Found lyrics but artist name did not match from player result.');
logger.debug('Found Genius lyrics but artist name did not match from player.search() result.');
}
}
if (!lyricsResult || !lyricsResult.lyrics) {
logger.debug(
`User used command ${interaction.commandName} but there was no lyrics found.`
);
logger.debug('No matching lyrics found.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -186,16 +208,17 @@ module.exports = {
});
}
logger.debug(`Successfully found matching Genius lyrics for query '${geniusSearchQuery}'.`);
// If message length is too long, split into multiple messages
if (lyricsResult.lyrics.length > 3800) {
logger.debug('Lyrics too long, splitting into multiple messages.');
logger.debug('Lyrics text too long, splitting into multiple messages.');
const messageCount = Math.ceil(lyricsResult.lyrics.length / 3800);
for (let i = 0; i < messageCount; i++) {
logger.debuf(
`Lyrics, sending message ${i + 1} of ${messageCount}.`
);
logger.debuf(`Lyrics, sending message ${i + 1} of ${messageCount}.`);
const message = lyricsResult.lyrics.slice(i * 3800, (i + 1) * 3800);
if (i === 0) {
logger.debug('Responding with info embed for first message with lyrics.');
await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -210,6 +233,7 @@ module.exports = {
});
continue;
} else {
logger.debug('Sending consecutive message with lyrics.');
await interaction.channel.send({
embeds: [
new EmbedBuilder()
@@ -223,10 +247,7 @@ module.exports = {
return;
}
logger.debug(
`User used command ${interaction.commandName} and retrieved lyrics.`
);
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+33 -28
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const playerOptions = config.get('playerOptions');
@@ -16,6 +15,15 @@ module.exports = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'nowplaying.js',
module: 'slashCommand',
name: '/nowplaying',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
@@ -106,10 +114,9 @@ module.exports = {
const loopModeUserString = loopModesFormatted.get(queue.repeatMode);
logger.debug(
`User used command ${interaction.commandName}, finished intializing data.`
);
logger.debug('Successfully retrieved information about the current track.');
logger.debug('Sending info embed with action row components.');
const response = await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -121,7 +128,7 @@ module.exports = {
(queue.node.isPaused()
? '**Currently Paused**\n'
: `**${embedOptions.icons.audioPlaying} Now Playing**\n`) +
`**[${currentTrack.title}](${currentTrack.url})**` +
`**[${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**` +
`\nRequested by: <@${currentTrack.requestedBy.id}>` +
`\n ${bar}\n\n` +
`${
@@ -145,7 +152,9 @@ module.exports = {
},
{
name: '**Track source**',
value: `**${sourceIcons.get(currentTrack.raw.source)} [${source}](${currentTrack.url})**`,
value: `**${sourceIcons.get(currentTrack.raw.source)} [${source}](${
currentTrack.raw.url ?? currentTrack.url
})**`,
inline: true
}
)
@@ -158,9 +167,7 @@ module.exports = {
components: [nowPlayingActionRow]
});
logger.debug(
`User used command ${interaction.commandName}, finished sending response.`
);
logger.debug(`User used command '${interaction.commandName}', finished sending response.`);
const collectorFilter = (i) => i.user.id === interaction.user.id;
try {
@@ -171,14 +178,14 @@ module.exports = {
confirmation.deferUpdate();
logger.debug('Received component interaction response.');
if (confirmation.customId === 'nowplaying-skip') {
logger.debug(
`User used command ${interaction.commandName}, received skip confirmation.`
);
logger.debug('Received skip confirmation.');
if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) {
logger.debug(
`User used command ${interaction.commandName} and tried skipping but there was no queue.`
);
logger.debug('Tried skipping track but there was no queue.');
logger.debug('Responding with warning embed.');
return await interaction.followUp({
embeds: [
new EmbedBuilder()
@@ -193,8 +200,10 @@ module.exports = {
if (queue.currentTrack !== currentTrack) {
logger.debug(
`User used command ${interaction.commandName} and tried skipping but the track was already removed.`
'Tried skipping track but it is not the current track and therefore already skipped/removed.'
);
logger.debug('Responding with warning embed.');
return await interaction.followUp({
embeds: [
new EmbedBuilder()
@@ -217,12 +226,11 @@ module.exports = {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
queue.node.skip();
logger.debug('Skipped the track.');
const repeatModeUserString = loopModesFormatted.get(queue.repeatMode);
logger.debug(
`User used command ${interaction.commandName} and skipped the track.`
);
logger.debug('Responding with success embed.');
return await interaction.followUp({
embeds: [
new EmbedBuilder()
@@ -231,7 +239,9 @@ module.exports = {
iconURL: interaction.user.avatarURL()
})
.setDescription(
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${skippedTrack.url})**` +
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${
skippedTrack.title
}](${skippedTrack.raw.url ?? skippedTrack.url})**` +
`${
queue.repeatMode === 0
? ''
@@ -250,17 +260,12 @@ module.exports = {
}
} catch (error) {
if (error.code === 'InteractionCollectorError') {
logger.debug(
`User used command ${interaction.commandName} but did not respond to the skip prompt.`
);
logger.debug('Interaction response timed out.');
return;
}
logger.debug(
error,
`User used command ${interaction.commandName} but there was an unhandled error.`
);
throw error;
logger.error(error, 'Unhandled error while awaiting or handling component interaction.');
return;
}
}
};
+14 -7
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -15,6 +14,15 @@ module.exports = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'pause.js',
module: 'slashCommand',
name: '/pause',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
@@ -44,12 +52,9 @@ module.exports = {
// change paused state to opposite of current state
queue.node.setPaused(!queue.node.isPaused());
logger.debug(
`User used command ${
interaction.commandName
} and set paused state to ${queue.node.isPaused()}.`
);
logger.debug(`Set paused state to ${queue.node.isPaused()}.`);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -60,7 +65,9 @@ module.exports = {
.setDescription(
`**${embedOptions.icons.pauseResumed} ${
queue.node.isPaused() ? 'Paused Track' : 'Resumed track'
}**\n**${durationFormat} [${queue.currentTrack.title}](${queue.currentTrack.url})**`
}**\n**${durationFormat} [${queue.currentTrack.title}](${
queue.currentTrack.raw.url ?? queue.currentTrack.url
})**`
)
.setThumbnail(queue.currentTrack.thumbnail)
.setColor(embedOptions.colors.success)
+42 -28
View File
@@ -44,12 +44,12 @@ module.exports = {
const { lastQuery, results, timestamp } = recentQueries.get(interaction.user.id) || {};
if (lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - timestamp < 500) {
logger.debug(`Autocomplete search responded with results from lastQuery for query: '${query}'`);
logger.debug(`Responding with results from lastQuery for query '${query}'`);
return interaction.respond(results);
}
if (query.length < 3) {
logger.debug(`Autocomplete search responded with empty results due to < 3 length for query '${query}'`);
logger.debug(`Responding with empty results due to < 3 length for query '${query}'`);
return interaction.respond([]);
}
const searchResults = await player.search(query);
@@ -76,11 +76,11 @@ module.exports = {
});
if (!response || response.length === 0) {
logger.debug(`Responding with empty results for query '${query}'`);
return interaction.respond([]);
}
logger.debug(`Autocomplete search responded for query: '${query}'`);
logger.debug(`Responding to autocomplete with results for query: '${query}'.`);
return interaction.respond(response);
},
execute: async ({ interaction, executionId }) => {
@@ -88,7 +88,9 @@ module.exports = {
source: 'play.js',
module: 'slashCommand',
name: '/play',
executionId: executionId
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
@@ -116,21 +118,13 @@ module.exports = {
requestedBy: interaction.user
});
} catch (error) {
logger.error(
{
error: {
message: error.message,
type: error.type,
stack: error.stack
}
},
`Failed to search for track with player.search() with query: ${transformedQuery}.`
);
logger.error(error, `Failed to search for track with player.search() with query: ${transformedQuery}.`);
}
if (!searchResult || searchResult.tracks.length === 0) {
logger.debug(`No results found for query: ${query}`);
logger.debug(`No results found for query: '${query}'`);
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -146,8 +140,9 @@ module.exports = {
let queueSize = queue?.size ?? 0;
if ((searchResult.playlist && searchResult.tracks.length) > playerOptions.maxQueueSize - queueSize) {
logger.debug(`Playlist found but too many tracks. Query: ${query}.`);
logger.debug(`Playlist found but would exceed max queue size. Query: '${query}'.`);
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -162,6 +157,7 @@ module.exports = {
let track;
try {
logger.debug(`Attempting to add track with player.play(). Query: '${query}'.`);
({ track } = await player.play(interaction.member.voice.channel, searchResult, {
requestedBy: interaction.user,
nodeOptions: {
@@ -184,11 +180,11 @@ module.exports = {
}
}
}));
logger.debug(`player.play() successful. Query: ${query}.`);
} catch (error) {
if (error.message.includes('Sign in to confirm your age')) {
logger.debug('Found track but failed to retrieve audio due to age confirmation warning.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -202,6 +198,8 @@ module.exports = {
if (error.message.includes('The following content may contain')) {
logger.debug('Found track but failed to retrieve audio due to graphic/mature/sensitive topic warning.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -221,6 +219,7 @@ module.exports = {
) {
logger.debug(error, `Found track but failed to retrieve audio. Query: ${query}.`);
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -235,6 +234,7 @@ module.exports = {
if (error.message === 'Cancelled') {
logger.debug(error, `Operation cancelled. Query: ${query}.`);
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -250,6 +250,7 @@ module.exports = {
// Can happen if /play then /leave before track starts playing
logger.warn(error, 'Found track but failed to play back audio. Voice connection might be unavailable.');
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -261,14 +262,17 @@ module.exports = {
});
}
//logger.error(error, 'Failed to play track with player.play(), unhandled error.');
logger.error(error, 'Failed to play track with player.play(), unhandled error.');
}
logger.debug(`Successfully added track with player.play(). Query: '${query}'.`);
queue = useQueue(interaction.guild.id);
if (!queue) {
logger.warn(`After player.play(), queue is undefined. Query: ${query}.`);
logger.warn(`After player.play(), queue is undefined. Query: '${query}'.`);
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -287,8 +291,10 @@ module.exports = {
track.thumbnail === undefined ||
track.thumbnail === ''
) {
track.thumbnail =
'https://raw.githubusercontent.com/mariusbegby/cadence-discord-bot/main/assets/logo-rounded-128px.png';
logger.debug(
`Track found but source is arbitrary or missing thumbnail. Using fallback thumbnail url. Query: '${query}'.`
);
track.thumbnail = embedOptions.info.fallbackThumbnailUrl;
}
let durationFormat = track.raw.duration === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``;
@@ -300,6 +306,7 @@ module.exports = {
if (searchResult.playlist && searchResult.tracks.length > 1) {
logger.debug(`Playlist found and added with player.play(). Query: '${query}'`);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -310,7 +317,7 @@ module.exports = {
.setDescription(
`**${embedOptions.icons.success} Added playlist to queue**\n**${durationFormat} [${
track.title
}](${track.url})**\n\nAnd **${
}](${track.raw.url ?? track.url})**\n\nAnd **${
searchResult.tracks.length - 1
}** more tracks... **\`/queue\`** to view all.`
)
@@ -321,8 +328,9 @@ module.exports = {
}
if (queue.currentTrack === track && queue.tracks.data.length === 0) {
logger.debug(`Track found and added with player.play(), started playing. Query: ${query}.`);
logger.debug(`Track found and added with player.play(), started playing. Query: '${query}'.`);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -332,7 +340,9 @@ module.exports = {
iconURL: interaction.user.avatarURL()
})
.setDescription(
`**${embedOptions.icons.audioStartedPlaying} Started playing**\n**${durationFormat} [${track.title}](${track.url})**`
`**${embedOptions.icons.audioStartedPlaying} Started playing**\n**${durationFormat} [${
track.title
}](${track.raw.url ?? track.url})**`
)
.setThumbnail(track.thumbnail)
.setColor(embedOptions.colors.success)
@@ -340,7 +350,9 @@ module.exports = {
});
}
logger.debug(`Track found and added with player.play(), added to queue. Query: ${query}.`);
logger.debug(`Track found and added with player.play(), added to queue. Query: '${query}'.`);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -349,7 +361,9 @@ module.exports = {
iconURL: interaction.user.avatarURL()
})
.setDescription(
`${embedOptions.icons.success} **Added to queue**\n**${durationFormat} [${track.title}](${track.url})**`
`${embedOptions.icons.success} **Added to queue**\n**${durationFormat} [${track.title}](${
track.raw.url ?? track.url
})**`
)
.setThumbnail(track.thumbnail)
.setColor(embedOptions.colors.success)
+28 -18
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const playerOptions = config.get('playerOptions');
@@ -16,6 +15,15 @@ module.exports = {
.setNSFW(false)
.addNumberOption((option) => option.setName('page').setDescription('Page number of the queue').setMinValue(1)),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'queue.js',
module: 'slashCommand',
name: '/queue',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
@@ -31,9 +39,9 @@ module.exports = {
if (!queue) {
if (pageIndex >= 1) {
logger.debug(
`User used command ${interaction.commandName} but there was no queue.`
);
logger.debug(`There is no queue and user tried to access page ${pageIndex + 1}.`);
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -47,10 +55,10 @@ module.exports = {
});
}
logger.debug(
`User used command ${interaction.commandName} but there was no queue.`
);
logger.debug('There is no queue, displaying empty queue.');
queueString = 'The queue is empty, add some tracks with **`/play`**!';
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -71,10 +79,9 @@ module.exports = {
const totalPages = Math.ceil(queueLength / 10) || 1;
if (pageIndex > totalPages - 1) {
logger.debug(
`User used command ${interaction.commandName} but page was higher than total pages.`
);
logger.debug('Specified page was higher than total pages.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -89,6 +96,7 @@ module.exports = {
}
if (queue.tracks.data.length === 0) {
logger.debug('Queue exists but with no tracks, displaying empty queue.');
queueString = 'The queue is empty, add some tracks with **`/play`**!';
} else {
queueString = queue.tracks.data
@@ -101,7 +109,9 @@ module.exports = {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
return `**${pageIndex * 10 + index + 1}.** **${durationFormat} [${track.title}](${track.url})**`;
return `**${pageIndex * 10 + index + 1}.** **${durationFormat} [${track.title}](${
track.raw.url ?? track.url
})**`;
})
.join('\n');
}
@@ -126,10 +136,9 @@ module.exports = {
}`;
if (!currentTrack) {
logger.debug(
`User used command ${interaction.commandName} but there was no current track.`
);
logger.debug('Queue exists but there is no current track.');
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -147,6 +156,7 @@ module.exports = {
]
});
} else {
logger.debug('Queue exists with current track, gathering information.');
const timestamp = queue.node.getTimestamp();
let bar = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({
queue: false,
@@ -165,9 +175,7 @@ module.exports = {
bar = `${embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`;
}
logger.debug(
`User used command ${interaction.commandName} and got queue in reply with current track.`
);
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -177,7 +185,9 @@ module.exports = {
})
.setDescription(
`**${embedOptions.icons.audioPlaying} Now playing**\n` +
(currentTrack ? `**[${currentTrack.title}](${currentTrack.url})**` : 'None') +
(currentTrack
? `**[${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**`
: 'None') +
`\nRequested by: <@${currentTrack.requestedBy.id}>` +
`\n ${bar}\n\n` +
`${repeatModeString}` +
+14 -8
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -22,6 +21,15 @@ module.exports = {
.setRequired(true)
),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'remove.js',
module: 'slashCommand',
name: '/remove',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
@@ -39,10 +47,9 @@ module.exports = {
const removeTrackNumber = interaction.options.getNumber('tracknumber');
if (removeTrackNumber > queue.tracks.data.length) {
logger.debug(
`User used command ${interaction.commandName} but track number was higher than total tracks.`
);
logger.debug('Specified track number is higher than total tracks.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -56,6 +63,7 @@ module.exports = {
// Remove specified track number from queue
const removedTrack = queue.node.remove(removeTrackNumber - 1);
logger.debug(`Removed track '${removedTrack.url}' from queue.`);
let durationFormat =
removedTrack.raw.duration === 0 || removedTrack.duration === '0:00' ? '' : `\`${removedTrack.duration}\``;
@@ -63,9 +71,7 @@ module.exports = {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
logger.debug(
`User used command ${interaction.commandName} and removed track.`
);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -74,7 +80,7 @@ module.exports = {
iconURL: interaction.user.avatarURL()
})
.setDescription(
`**${embedOptions.icons.success} Removed track**\n**${durationFormat} [${removedTrack.title}](${removedTrack.url})**`
`**${embedOptions.icons.success} Removed track**\n**${durationFormat} [${removedTrack.title}](${removedTrack.raw.url ?? removedTrack.url})**`
)
.setThumbnail(removedTrack.thumbnail)
.setColor(embedOptions.colors.success)
+21 -16
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -21,6 +20,15 @@ module.exports = {
.setRequired(true)
),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'seek.js',
module: 'slashCommand',
name: '/seek',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
@@ -54,10 +62,9 @@ module.exports = {
}
if (durationArray.length === 0 || durationArray.length > 3) {
logger.debug(
`User used command ${interaction.commandName} but entered an invalid duration.`
);
logger.debug('Invalid duration format input.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -83,9 +90,9 @@ module.exports = {
});
if (!validElements) {
logger.debug(
`User used command ${interaction.commandName} but entered an invalid duration after parsing duration.`
);
logger.debug('Invalid duration after parsing duration input.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -106,10 +113,9 @@ module.exports = {
const isValidDuration = regex.test(durationString);
if (!isValidDuration) {
logger.debug(
`User used command ${interaction.commandName} but entered an invalid duration after regex checks.`
);
logger.debug('Invalid duration after regex checks.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -128,9 +134,9 @@ module.exports = {
const durationInMilliseconds = durationArray[0] * 3600000 + durationArray[1] * 60000 + durationArray[2] * 1000;
if (durationInMilliseconds > currentTrackMaxDurationInMs - 1000) {
logger.debug(
`User used command ${interaction.commandName} but entered a duration longer than the track.`
);
logger.debug('Duration specified is longer than the track duration.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -143,10 +149,9 @@ module.exports = {
}
queue.node.seek(durationInMilliseconds);
logger.debug(`Seeked to '${durationString}' in current track.`);
logger.debug(
`User used command ${interaction.commandName} and seeked to duration.`
);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+11 -5
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -15,6 +14,15 @@ module.exports = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'shuffle.js',
module: 'slashCommand',
name: '/shuffle',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
@@ -34,11 +42,9 @@ module.exports = {
}
queue.tracks.shuffle();
logger.debug('Shuffled queue tracks.');
logger.debug(
`User used command ${interaction.commandName} and shuffled the queue.`
);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+25 -15
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -18,6 +17,15 @@ module.exports = {
option.setName('tracknumber').setDescription('Track number to skip to in the queue.').setMinValue(1)
),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'skip.js',
module: 'slashCommand',
name: '/skip',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
@@ -40,9 +48,9 @@ module.exports = {
if (skipToTrack) {
if (skipToTrack > queue.tracks.data.length) {
logger.debug(
`User used command ${interaction.commandName} but track number was higher than total tracks.`
);
logger.debug('Specified track number was higher than total tracks.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -64,10 +72,9 @@ module.exports = {
}
queue.node.skipTo(skipToTrack - 1);
logger.debug('Skipped to specified track number.');
logger.debug(
`User used command ${interaction.commandName} and skipped to track.`
);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -76,7 +83,9 @@ module.exports = {
iconURL: interaction.user.avatarURL()
})
.setDescription(
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${skippedTrack.url})**`
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${
skippedTrack.title
}](${skippedTrack.raw.url ?? skippedTrack.url})**`
)
.setThumbnail(skippedTrack.thumbnail)
.setColor(embedOptions.colors.success)
@@ -85,9 +94,9 @@ module.exports = {
}
} else {
if (queue.tracks.data.length === 0 && !queue.currentTrack) {
logger.debug(
`User used command ${interaction.commandName} but there was no tracks in queue or current track.`
);
logger.debug('No tracks in queue and no current track.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -109,6 +118,7 @@ module.exports = {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
queue.node.skip();
logger.debug('Skipped current track.');
const loopModesFormatted = new Map([
[0, 'disabled'],
@@ -119,9 +129,7 @@ module.exports = {
const loopModeUserString = loopModesFormatted.get(queue.repeatMode);
logger.debug(
`User used command ${interaction.commandName} and skipped track.`
);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -130,7 +138,9 @@ module.exports = {
iconURL: interaction.user.avatarURL()
})
.setDescription(
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${skippedTrack.url})**` +
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${
skippedTrack.title
}](${skippedTrack.raw.url ?? skippedTrack.url})**` +
`${
queue.repeatMode === 0
? ''
+14 -7
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -14,6 +13,15 @@ module.exports = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'stop.js',
module: 'slashCommand',
name: '/stop',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
@@ -21,9 +29,9 @@ module.exports = {
const queue = useQueue(interaction.guild.id);
if (!queue) {
logger.debug(
`User used command ${interaction.commandName} but there was no queue.`
);
logger.debug('There is no queue.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -43,11 +51,10 @@ module.exports = {
queue.setRepeatMode(0);
queue.clear();
queue.node.stop();
logger.debug(
`User used command ${interaction.commandName} and cleared the queue.`
);
logger.debug('Cleared and stopped the queue.');
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+18 -13
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -22,6 +21,15 @@ module.exports = {
.setMaxValue(100)
),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'volume.js',
module: 'slashCommand',
name: '/volume',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
@@ -41,9 +49,9 @@ module.exports = {
if (!volume && volume !== 0) {
const currentVolume = queue.node.volume;
logger.debug(
`User used command ${interaction.commandName} but no volume was provided, providing info of current volume.`
);
logger.debug('No volume input was provided, showing current volume.');
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -56,9 +64,9 @@ module.exports = {
]
});
} else if (volume > 100 || volume < 0) {
logger.debug(
`User used command ${interaction.commandName} but volume was higher than 100% or lower than 0%.`
);
logger.debug('Volume specified was higher than 100% or lower than 0%.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -70,11 +78,10 @@ module.exports = {
});
} else {
queue.node.setVolume(volume);
logger.debug(`Set volume to ${volume}%.`);
if (volume === 0) {
logger.debug(
`User used command ${interaction.commandName} and muted volume.`
);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -90,9 +97,7 @@ module.exports = {
});
}
logger.debug(
`User used command ${interaction.commandName} and changed volume.`
);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+16 -2
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notValidGuildId } = require('../../utils/validation/systemCommandValidator');
@@ -14,14 +13,23 @@ module.exports = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
source: 'guilds.js',
module: 'slashCommand',
name: '/guilds',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notValidGuildId({ interaction, executionId })) {
logger.debug('Not a valid guild id.');
return;
}
let shardGuilds = [];
let totalGuildCount = 0;
logger.debug('Fetching guilds from all shards.');
await client.shard
.broadcastEval((c) => {
return c.guilds.cache.map((guild) => {
@@ -34,6 +42,8 @@ module.exports = {
totalGuildCount = shardGuilds.length;
logger.debug(`Successfully fetched ${totalGuildCount} guilds.`);
let guildListFormatted = shardGuilds
.map((guild) => {
return {
@@ -54,10 +64,14 @@ module.exports = {
} by member count (${totalGuildCount} total)**\n${guildListFormatted}` +
`\n\n**Total members:** \`${totalMemberCount}\``;
logger.debug('Transformed guild into into embed description.');
if (embedDescription.length >= 4000) {
logger.debug('Embed description is too long, truncating.');
embedDescription = `${embedDescription.slice(0, 3996)}...`;
}
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [new EmbedBuilder().setDescription(embedDescription).setColor(embedOptions.colors.info)]
});
+32 -7
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notValidGuildId } = require('../../utils/validation/systemCommandValidator');
@@ -14,21 +13,46 @@ module.exports = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
source: 'reload.js',
module: 'slashCommand',
name: '/reload',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notValidGuildId({ interaction, executionId })) {
logger.debug('Not a valid guild id.');
return;
}
try {
logger.info('Reloading commands across all shards.');
logger.info(`Execution ID: ${executionId}`);
await client.shard
.broadcastEval((shardClient) => {
shardClient.registerClientCommands(shardClient);
})
.broadcastEval(
async (shardClient, { executionId }) => {
shardClient.registerClientCommands({ client: shardClient, executionId });
},
{ context: { executionId: executionId } }
)
.then(() => {
logger.info('Reloaded commands across all shards.');
logger.info('Successfully reloaded commands across all shards.');
});
} catch (error) {
logger.error(error, 'Failed to reload commands.');
logger.error(error, 'Failed to reload commands across shards.');
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.error} Oops!**\n_Hmm.._ It seems I am unable to reload commands across shards.`
)
.setColor(embedOptions.colors.error)
]
});
}
const commands = client.commands.map((command) => {
@@ -38,6 +62,7 @@ module.exports = {
let embedDescription = `**${embedOptions.icons.bot} Reloaded commands**\n` + commands.join('\n');
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [new EmbedBuilder().setDescription(embedDescription).setColor(embedOptions.colors.success)]
});
+80 -54
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notValidGuildId } = require('../../utils/validation/systemCommandValidator');
@@ -31,70 +30,94 @@ module.exports = {
.addNumberOption((option) => option.setName('page').setDescription('Page number to show').setMinValue(1)),
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
source: 'shards.js',
module: 'slashCommand',
name: '/shards',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notValidGuildId({ interaction, executionId })) {
return;
}
let shardInfoList = [];
await client.shard
.broadcastEval((shardClient) => {
/* eslint-disable no-undef */
let playerStats = player.generateStatistics();
const nodeProcessMemUsageInMb = (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2);
let shardInfo = {
shardId: shardClient.shard.ids[0],
memUsage: nodeProcessMemUsageInMb,
guildCount: shardClient.guilds.cache.size,
guildMemberCount: shardClient.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0),
playerStatistics: {
activeVoiceConnections: playerStats.queues.length,
totalTracks: playerStats.queues.reduce((acc, queue) => acc + queue.tracksCount, 0),
totalListeners: playerStats.queues.reduce((acc, queue) => acc + queue.listeners, 0)
logger.debug('Fetching player statistics and client values from each shard.');
try {
await client.shard
.broadcastEval((shardClient) => {
/* eslint-disable no-undef */
let playerStats = player.generateStatistics();
const nodeProcessMemUsageInMb = (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2);
let shardInfo = {
shardId: shardClient.shard.ids[0],
memUsage: nodeProcessMemUsageInMb,
guildCount: shardClient.guilds.cache.size,
guildMemberCount: shardClient.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0),
playerStatistics: {
activeVoiceConnections: playerStats.queues.length,
totalTracks: playerStats.queues.reduce((acc, queue) => acc + queue.tracksCount, 0),
totalListeners: playerStats.queues.reduce((acc, queue) => acc + queue.listeners, 0)
}
};
return shardInfo;
})
.then((results) => {
shardInfoList = results;
switch (interaction.options.getString('sort')) {
case 'memory':
shardInfoList = shardInfoList.sort((a, b) => b.memUsage - a.memUsage);
break;
case 'connections':
shardInfoList = shardInfoList.sort(
(a, b) =>
b.playerStatistics.activeVoiceConnections -
a.playerStatistics.activeVoiceConnections
);
break;
case 'tracks':
shardInfoList = shardInfoList.sort(
(a, b) => b.playerStatistics.totalTracks - a.playerStatistics.totalTracks
);
break;
case 'listeners':
shardInfoList = shardInfoList.sort(
(a, b) => b.playerStatistics.totalListeners - a.playerStatistics.totalListeners
);
break;
case 'guilds':
shardInfoList = shardInfoList.sort((a, b) => b.guildCount - a.guildCount);
break;
case 'members':
shardInfoList = shardInfoList.sort((a, b) => b.guildMemberCount - a.guildMemberCount);
break;
default:
shardInfoList = shardInfoList.sort((a, b) => a.shardId - b.shardId);
break;
}
};
return shardInfo;
})
.then((results) => {
shardInfoList = results;
logger.debug('Successfully fetched player statistics and client values from shards.');
});
} catch (error) {
logger.error(error, 'Failed to fetch player statistics and client values from shards.');
switch (interaction.options.getString('sort')) {
case 'memory':
shardInfoList = shardInfoList.sort((a, b) => b.memUsage - a.memUsage);
break;
case 'connections':
shardInfoList = shardInfoList.sort(
(a, b) =>
b.playerStatistics.activeVoiceConnections - a.playerStatistics.activeVoiceConnections
);
break;
case 'tracks':
shardInfoList = shardInfoList.sort(
(a, b) => b.playerStatistics.totalTracks - a.playerStatistics.totalTracks
);
break;
case 'listeners':
shardInfoList = shardInfoList.sort(
(a, b) => b.playerStatistics.totalListeners - a.playerStatistics.totalListeners
);
break;
case 'guilds':
shardInfoList = shardInfoList.sort((a, b) => b.guildCount - a.guildCount);
break;
case 'members':
shardInfoList = shardInfoList.sort((a, b) => b.guildMemberCount - a.guildMemberCount);
break;
default:
shardInfoList = shardInfoList.sort((a, b) => a.shardId - b.shardId);
break;
}
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
logger.debug('Fetched shardInfo from each shard.');
})
.catch((error) => {
logger.error(error, 'Failed to fetch client values from shards.');
.setDescription(
`**${embedOptions.icons.error} Oops!**\n_Hmm.._ It seems I am unable to fetch player statistics and client values from shards.`
)
.setColor(embedOptions.colors.error)
]
});
}
const shardCount = shardInfoList.length;
const totalPages = Math.ceil(shardCount / 10) || 1;
@@ -143,6 +166,9 @@ module.exports = {
);
}
logger.debug('Successfully gathered and transformed shard information into embed fields.');
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+17 -1
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notValidGuildId } = require('../../utils/validation/systemCommandValidator');
@@ -17,6 +16,15 @@ module.exports = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
source: 'systemstatus.js',
module: 'slashCommand',
name: '/systemstatus',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notValidGuildId({ interaction, executionId })) {
return;
}
@@ -45,6 +53,7 @@ module.exports = {
const mediaplexVersion = dependencies['mediaplex'];
const distubeYtdlVersion = dependencies['@distube/ytdl-core'];
logger.debug('Fetching player statistics from all shards.');
await client.shard
.broadcastEval(() => {
/* eslint-disable no-undef */
@@ -67,8 +76,11 @@ module.exports = {
activeVoiceConnections = queueCountList.reduce((acc, queueAmount) => acc + queueAmount, 0);
totalTracks = trackCountList.reduce((acc, trackAmount) => acc + trackAmount, 0);
totalListeners = listenerCountList.reduce((acc, listenerAmount) => acc + listenerAmount, 0);
logger.debug('Successfully fetched player statistics from shards.');
});
logger.debug('Fetching client values from all shards.');
await client.shard
.fetchClientValues('guilds.cache')
.then((results) => {
@@ -78,6 +90,7 @@ module.exports = {
memberCount += guildCache.reduce((acc, guildCache) => acc + guildCache.memberCount, 0);
}
});
logger.debug('Successfully fetched client values from shards.');
})
.catch((error) => {
logger.error(error, 'Failed to fetch client values from shards.');
@@ -111,6 +124,9 @@ module.exports = {
const discordStatusString = `**${client.ws.ping} ms** Discord API latency`;
logger.debug('Transformed system status into embed description.');
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+1 -1
View File
@@ -55,7 +55,7 @@ module.exports = {
return;
}
} else if (interaction.isChatInputCommand()) {
logger.debug(`Chat input command interaction created for ${interaction.commandName}.`);
logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`);
try {
await interaction.deferReply();
@@ -23,8 +23,9 @@ exports.notValidGuildId = async ({ interaction, executionId }) => {
.setColor(embedOptions.colors.warning)
]
});
logger.debug(
`User tried to use command ${interaction.commandName} but system command cannot be executed in the specified guild.`
`User tried to use command '${interaction.commandName}' but system command cannot be executed in the specified guild.`
);
return true;
}