fix: annotated the rest of commands

This commit is contained in:
Marius Begby committed 2023-08-27 17:52:49 +02:00
1 parent ef6f7bef80
commit 45d6ffa179
22 files changed
+479 -265

No files matched your search

+1 -1
View File
@@ -114,7 +114,7 @@ module.exports.playerOptions = {
leaveOnEmpty: true, leaveOnEmpty: true,
leaveOnEmptyCooldown: 1_800_000, leaveOnEmptyCooldown: 1_800_000,
leaveOnEnd: true, leaveOnEnd: true,
leaveonEndCooldown: 1_800_000, leaveOnEndCooldown: 1_800_000,
leaveOnStop: true, leaveOnStop: true,
leaveOnStopCooldown: 1_800_000, leaveOnStopCooldown: 1_800_000,
defaultVolume: 50, defaultVolume: 50,
+9 -2
View File
@@ -8,6 +8,8 @@ import { BotOptions, EmbedOptions } from '../../types/configTypes';
const embedOptions: EmbedOptions = config.get('embedOptions'); const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions'); const botOptions: BotOptions = config.get('botOptions');
module.exports = { module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('help') .setName('help')
.setDescription('Show a list of commands and their usage.') .setDescription('Show a list of commands and their usage.')
@@ -19,10 +21,15 @@ module.exports = {
module: 'slashCommand', module: 'slashCommand',
name: '/help', name: '/help',
executionId: executionId, executionId: executionId,
shardId: interaction.guild.shardId, shardId: interaction.guild?.shardId,
guildId: interaction.guild.id guildId: interaction.guild?.id
}); });
if (!client || !client.commands) {
logger.error('Client is undefined or does not have commands property.');
return;
}
const commandList = client.commands const commandList = client.commands
.filter((command) => { .filter((command) => {
// don't include system commands // don't include system commands
+15 -9
View File
@@ -1,5 +1,5 @@
import config from 'config'; import config from 'config';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { Collection, EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js';
import osu from 'node-os-utils'; import osu from 'node-os-utils';
// @ts-ignore // @ts-ignore
@@ -24,8 +24,8 @@ module.exports = {
module: 'slashCommand', module: 'slashCommand',
name: '/status', name: '/status',
executionId: executionId, executionId: executionId,
shardId: interaction.guild.shardId, shardId: interaction.guild?.shardId,
guildId: interaction.guild.id guildId: interaction.guild?.id
}); });
const uptimeString = await getUptimeFormatted({ executionId }); const uptimeString = await getUptimeFormatted({ executionId });
@@ -38,15 +38,20 @@ module.exports = {
let totalTracks = 0; let totalTracks = 0;
let totalListeners = 0; let totalListeners = 0;
if (!client || !client.shard) {
logger.error('Client is undefined or does not have shard property.');
return;
}
await client.shard await client.shard
.broadcastEval(() => { .broadcastEval(() => {
/* eslint-disable no-undef */ /* eslint-disable no-undef */
return player.generateStatistics(); return player.generateStatistics();
}) })
.then((results) => { .then((results) => {
const queueCountList = []; const queueCountList: number[] = [];
const trackCountList = []; const trackCountList: number[] = [];
const listenerCountList = []; const listenerCountList: number[] = [];
results.map((result) => { results.map((result) => {
queueCountList.push(result.queues.length); queueCountList.push(result.queues.length);
if (result.queues.length > 0) { if (result.queues.length > 0) {
@@ -70,10 +75,11 @@ module.exports = {
await client.shard await client.shard
.fetchClientValues('guilds.cache') .fetchClientValues('guilds.cache')
.then((results) => { .then((results) => {
results.map((guildCache) => { const guildCaches = results as Collection<string, Guild>[];
guildCaches.map((guildCache) => {
if (guildCache) { if (guildCache) {
guildCount += guildCache.length; guildCount += guildCache.size;
memberCount += guildCache.reduce((acc, guildCache) => acc + guildCache.memberCount, 0); memberCount += guildCache.reduce((acc, guild) => acc + guild.memberCount, 0);
} }
}); });
+81 -40
View File
@@ -1,17 +1,22 @@
import config from 'config'; import config from 'config';
import { useQueue } from 'discord-player'; import { NodeResolvable, QueueFilters, useQueue } from 'discord-player';
import { import {
ActionRowBuilder, APIActionRowComponent,
APIMessageActionRowComponent,
ButtonBuilder, ButtonBuilder,
ButtonStyle,
ComponentType,
EmbedBuilder, EmbedBuilder,
GuildMember,
Interaction,
SlashCommandBuilder, SlashCommandBuilder,
StringSelectMenuBuilder, StringSelectMenuBuilder,
StringSelectMenuOptionBuilder StringSelectMenuOptionBuilder
} from 'discord.js'; } from 'discord.js';
import loggerModule from '../../services/logger'; import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes'; import { CommandParams, CustomError } from '../../types/commandTypes';
import { EmbedOptions, FFmpegFilterOptions } from '../../types/configTypes'; import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
@@ -31,15 +36,15 @@ module.exports = {
module: 'slashCommand', module: 'slashCommand',
name: '/filters', name: '/filters',
executionId: executionId, executionId: executionId,
shardId: interaction.guild.shardId, shardId: interaction.guild?.shardId,
guildId: interaction.guild.id guildId: interaction.guild?.id
}); });
if (await notInVoiceChannel({ interaction, executionId })) { if (await notInVoiceChannel({ interaction, executionId })) {
return; return;
} }
const queue = useQueue(interaction.guild.id); const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) { if (await queueDoesNotExist({ interaction, queue, executionId })) {
return; return;
@@ -53,12 +58,12 @@ module.exports = {
return; return;
} }
const filterOptions = []; const filterOptions: StringSelectMenuOptionBuilder[] = [];
ffmpegFilterOptions.availableFilters.forEach((filter) => { ffmpegFilterOptions.availableFilters.forEach((filter: FFmpegFilterOption) => {
let isEnabled = false; let isEnabled = false;
if (queue.filters.ffmpeg.filters.includes(filter.value)) { if (queue.filters.ffmpeg.filters.includes(filter.value as keyof QueueFilters)) {
isEnabled = true; isEnabled = true;
} }
@@ -77,31 +82,37 @@ module.exports = {
.setPlaceholder('Select multiple options.') .setPlaceholder('Select multiple options.')
.setMinValues(0) .setMinValues(0)
.setMaxValues(filterOptions.length) .setMaxValues(filterOptions.length)
.addOptions(filterOptions); .addOptions(filterOptions)
.toJSON();
const filterActionRow = new ActionRowBuilder().addComponents(filterSelect); const filterActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
type: ComponentType.ActionRow,
components: [filterSelect]
};
const disableFiltersActionRow = new ActionRowBuilder().addComponents( const disableButton = new ButtonBuilder()
new ButtonBuilder()
.setCustomId('disable-filters') .setCustomId('disable-filters')
.setLabel('Disable all filters') .setLabel('Disable all filters')
.setStyle('Secondary') .setStyle(ButtonStyle.Secondary)
.setEmoji(embedOptions.icons.disable) .setEmoji(embedOptions.icons.disable)
); .toJSON();
const disableFiltersActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
type: ComponentType.ActionRow,
components: [disableButton]
};
logger.debug('Sending info embed with action row components.'); logger.debug('Sending info embed with action row components.');
const response = await interaction.editReply({ const response = await interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setDescription( .setDescription('**Toggle filters**\nEnable or disable audio filters for playback from the menu.')
`**Toggle filters** ${embedOptions.icons.beta}\nEnable or disable audio filters for playback from the menu.`
)
.setColor(embedOptions.colors.info) .setColor(embedOptions.colors.info)
], ],
components: [filterActionRow, disableFiltersActionRow] components: [filterActionRow, disableFiltersActionRow]
}); });
const collectorFilter = (i) => i.user.id === interaction.user.id; const collectorFilter = (i: Interaction) => i.user.id === interaction.user.id;
try { try {
const confirmation = await response.awaitMessageComponent({ const confirmation = await response.awaitMessageComponent({
filter: collectorFilter, filter: collectorFilter,
@@ -130,24 +141,15 @@ module.exports = {
logger.debug('Reset queue filters.'); logger.debug('Reset queue filters.');
} }
if (confirmation.customId === 'disable-filters' || confirmation.values.length === 0) { let authorName: string;
logger.debug('Responding with success embed.');
return await interaction.editReply({ if (interaction.member instanceof GuildMember) {
embeds: [ authorName = interaction.member.nickname || interaction.user.username;
new EmbedBuilder() } else {
.setAuthor({ authorName = interaction.user.username;
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
})
.setDescription(
`**${embedOptions.icons.success} Disabled filters**\nAll audio filters have been disabled.`
)
.setColor(embedOptions.colors.success)
],
components: []
});
} }
if ('values' in confirmation) {
// if bassboost is enabled and not normalizer, also enable normalizer to avoid distrorion // if bassboost is enabled and not normalizer, also enable normalizer to avoid distrorion
if ( if (
(confirmation.values.includes('bassboost_low') || confirmation.values.includes('bassboost')) && (confirmation.values.includes('bassboost_low') || confirmation.values.includes('bassboost')) &&
@@ -157,7 +159,7 @@ module.exports = {
} }
// Enable provided filters // Enable provided filters
queue.filters.ffmpeg.toggle(confirmation.values); queue.filters.ffmpeg.toggle(confirmation.values as (keyof QueueFilters)[]);
logger.debug(`Enabled filters ${confirmation.values.join(', ')}.`); logger.debug(`Enabled filters ${confirmation.values.join(', ')}.`);
logger.debug('Responding with success embed.'); logger.debug('Responding with success embed.');
@@ -165,18 +167,22 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: interaction.member.nickname || interaction.user.username, name: authorName,
iconURL: interaction.user.avatarURL() iconURL: interaction.user.avatarURL() || ''
}) })
.setDescription( .setDescription(
`**${ `**${
embedOptions.icons.success embedOptions.icons.success
} Filters toggled**\nNow using these filters:\n${confirmation.values } Filters toggled**\nNow using these filters:\n${confirmation.values
.map((enabledFilter) => { .map((enabledFilter: string) => {
const filter = ffmpegFilterOptions.availableFilters.find( const filter = ffmpegFilterOptions.availableFilters.find(
(filter) => enabledFilter == filter.value (filter) => enabledFilter == filter.value
); );
if (!filter) {
return enabledFilter;
}
return `- **${filter.emoji} ${filter.label}**`; return `- **${filter.emoji} ${filter.label}**`;
}) })
.join('\n')}` .join('\n')}`
@@ -185,14 +191,49 @@ module.exports = {
], ],
components: [] components: []
}); });
} else if (confirmation.customId === 'disable-filters') {
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.success} Disabled filters**\nAll audio filters have been disabled.`
)
.setColor(embedOptions.colors.success)
],
components: []
});
} else {
logger.warn('Unhandled component interaction response.');
}
} catch (error) { } catch (error) {
if (error instanceof CustomError) {
if (error.code === 'InteractionCollectorError') { if (error.code === 'InteractionCollectorError') {
logger.debug('Interaction response timed out.'); logger.debug('Interaction response timed out.');
return; return;
} }
if (error.message === 'Collector received no interactions before ending with reason: time') {
logger.debug('Interaction response timed out.');
return;
}
logger.error(error, 'Unhandled error while awaiting or handling component interaction.'); logger.error(error, 'Unhandled error while awaiting or handling component interaction.');
return; return;
} else {
if (
error instanceof Error &&
error.message === 'Collector received no interactions before ending with reason: time'
) {
logger.debug('Interaction response timed out.');
return;
}
throw error;
}
} }
} }
}; };
+15 -7
View File
@@ -1,6 +1,6 @@
import config from 'config'; import config from 'config';
import { useQueue } from 'discord-player'; import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger'; import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes'; import { CommandParams } from '../../types/commandTypes';
@@ -22,15 +22,15 @@ module.exports = {
module: 'slashCommand', module: 'slashCommand',
name: '/leave', name: '/leave',
executionId: executionId, executionId: executionId,
shardId: interaction.guild.shardId, shardId: interaction.guild?.shardId,
guildId: interaction.guild.id guildId: interaction.guild?.id
}); });
if (await notInVoiceChannel({ interaction, executionId })) { if (await notInVoiceChannel({ interaction, executionId })) {
return; return;
} }
const queue = useQueue(interaction.guild.id); const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (!queue) { if (!queue) {
logger.debug('There is already no queue.'); logger.debug('There is already no queue.');
@@ -56,13 +56,21 @@ module.exports = {
logger.debug('Deleted the queue.'); logger.debug('Deleted the queue.');
} }
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.'); logger.debug('Responding with success embed.');
return await interaction.editReply({ return await interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: interaction.member.nickname || interaction.user.username, name: authorName,
iconURL: interaction.user.avatarURL() iconURL: interaction.user.avatarURL() || ''
}) })
.setDescription( .setDescription(
`**${embedOptions.icons.success} Leaving channel**\nCleared the track queue and left voice channel.\n\nTo play more music, use the **\`/play\`** command!` `**${embedOptions.icons.success} Leaving channel**\nCleared the track queue and left voice channel.\n\nTo play more music, use the **\`/play\`** command!`
+23 -15
View File
@@ -1,6 +1,6 @@
import config from 'config'; import config from 'config';
import { useQueue } from 'discord-player'; import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger'; import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes'; import { CommandParams } from '../../types/commandTypes';
@@ -36,15 +36,15 @@ module.exports = {
module: 'slashCommand', module: 'slashCommand',
name: '/loop', name: '/loop',
executionId: executionId, executionId: executionId,
shardId: interaction.guild.shardId, shardId: interaction.guild?.shardId,
guildId: interaction.guild.id guildId: interaction.guild?.id
}); });
if (await notInVoiceChannel({ interaction, executionId })) { if (await notInVoiceChannel({ interaction, executionId })) {
return; return;
} }
const queue = useQueue(interaction.guild.id); const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) { if (await queueDoesNotExist({ interaction, queue, executionId })) {
return; return;
@@ -61,7 +61,7 @@ module.exports = {
[3, 'autoplay'] [3, 'autoplay']
]); ]);
const mode = parseInt(interaction.options.getString('mode')); const mode = parseInt(interaction.options.getString('mode')!);
const modeUserString = loopModesFormatted.get(mode); const modeUserString = loopModesFormatted.get(mode);
const currentMode = queue.repeatMode; const currentMode = queue.repeatMode;
const currentModeUserString = loopModesFormatted.get(currentMode); const currentModeUserString = loopModesFormatted.get(currentMode);
@@ -76,7 +76,7 @@ module.exports = {
.setDescription( .setDescription(
`**${ `**${
currentMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop currentMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop
} Current loop mode**\nThe looping mode is currently set to \`${currentModeUserString}\`.` } Current loop mode**\nThe looping mode is currently set to **\`${currentModeUserString}\`**.`
) )
.setColor(embedOptions.colors.info) .setColor(embedOptions.colors.info)
] ]
@@ -91,7 +91,7 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setDescription( .setDescription(
`**${embedOptions.icons.warning} Oops!**\nLoop mode is already \`${modeUserString}\`.` `**${embedOptions.icons.warning} Oops!**\nLoop mode is already **\`${modeUserString}\`**.`
) )
.setColor(embedOptions.colors.warning) .setColor(embedOptions.colors.warning)
] ]
@@ -112,7 +112,7 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setDescription( .setDescription(
`**${embedOptions.icons.error} Uh-oh... Failed to change loop mode!**\nI tried to change the loop mode to \`${modeUserString}\`, but something went wrong.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect or the issue persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` `**${embedOptions.icons.error} Uh-oh... Failed to change loop mode!**\nI tried to change the loop mode to **\`${modeUserString}\`**, but something went wrong.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect or the issue persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
) )
.setColor(embedOptions.colors.error) .setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` }) .setFooter({ text: `Execution ID: ${executionId}` })
@@ -120,6 +120,14 @@ module.exports = {
}); });
} }
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
if (queue.repeatMode === 0) { if (queue.repeatMode === 0) {
logger.debug('Disabled loop mode.'); logger.debug('Disabled loop mode.');
@@ -128,8 +136,8 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: interaction.member.nickname || interaction.user.username, name: authorName,
iconURL: interaction.user.avatarURL() iconURL: interaction.user.avatarURL() || ''
}) })
.setDescription( .setDescription(
`**${embedOptions.icons.success} Loop mode disabled**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nThe ${currentModeUserString} will no longer play on repeat!` `**${embedOptions.icons.success} Loop mode disabled**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nThe ${currentModeUserString} will no longer play on repeat!`
@@ -147,8 +155,8 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: interaction.member.nickname || interaction.user.username, name: authorName,
iconURL: interaction.user.avatarURL() iconURL: interaction.user.avatarURL() || ''
}) })
.setDescription( .setDescription(
`**${embedOptions.icons.autoplaying} Loop mode changed**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nWhen the queue is empty, similar tracks will start playing!` `**${embedOptions.icons.autoplaying} Loop mode changed**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nWhen the queue is empty, similar tracks will start playing!`
@@ -165,8 +173,8 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: interaction.member.nickname || interaction.user.username, name: authorName,
iconURL: interaction.user.avatarURL() iconURL: interaction.user.avatarURL() || ''
}) })
.setDescription( .setDescription(
`**${embedOptions.icons.looping} Loop mode changed**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nThe ${modeUserString} will now play on repeat!` `**${embedOptions.icons.looping} Loop mode changed**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nThe ${modeUserString} will now play on repeat!`
+11 -11
View File
@@ -1,5 +1,5 @@
import config from 'config'; import config from 'config';
import { QueryType, useMainPlayer, useQueue } from 'discord-player'; import { NodeResolvable, QueryType, useMainPlayer, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import { lyricsExtractor } from '@discord-player/extractor'; import { lyricsExtractor } from '@discord-player/extractor';
@@ -39,8 +39,8 @@ module.exports = {
autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => { autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => {
const logger = loggerTemplate.child({ const logger = loggerTemplate.child({
executionId: executionId, executionId: executionId,
shardId: interaction.guild.shardId, shardId: interaction.guild?.shardId,
guildId: interaction.guild.id guildId: interaction.guild?.id
}); });
const query = interaction.options.getString('query', true); const query = interaction.options.getString('query', true);
@@ -63,7 +63,7 @@ module.exports = {
if (!lyricsResult) { if (!lyricsResult) {
logger.debug(`No Genius lyrics found for query '${query}', using player.search() as fallback.`); logger.debug(`No Genius lyrics found for query '${query}', using player.search() as fallback.`);
const player = useMainPlayer(); const player = useMainPlayer()!;
const searchResults = await player.search(query); const searchResults = await player.search(query);
response = searchResults.tracks.slice(0, 1).map((track) => ({ response = searchResults.tracks.slice(0, 1).map((track) => ({
name: name:
@@ -99,12 +99,12 @@ module.exports = {
execute: async ({ interaction, executionId }: CommandParams) => { execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerTemplate.child({ const logger = loggerTemplate.child({
executionId: executionId, executionId: executionId,
shardId: interaction.guild.shardId, shardId: interaction.guild?.shardId,
guildId: interaction.guild.id guildId: interaction.guild?.id
}); });
const query = interaction.options.getString('query'); const query = interaction.options.getString('query');
const queue = useQueue(interaction.guild.id); const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
let geniusSearchQuery = ''; let geniusSearchQuery = '';
if (!query) { if (!query) {
@@ -123,7 +123,7 @@ module.exports = {
if (await queueNoCurrentTrack({ interaction, queue, executionId })) { if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return; return;
} }
geniusSearchQuery = queue.currentTrack.title.slice(0, 50); geniusSearchQuery = queue.currentTrack!.title.slice(0, 50);
logger.debug( logger.debug(
`No input query provided, using current track. Using query for genius: '${geniusSearchQuery}'` `No input query provided, using current track. Using query for genius: '${geniusSearchQuery}'`
@@ -133,7 +133,7 @@ module.exports = {
let searchResult; let searchResult;
if (query) { if (query) {
logger.debug(`Query input provided, using query '${query}' for player.search().`); logger.debug(`Query input provided, using query '${query}' for player.search().`);
const player = useMainPlayer(); const player = useMainPlayer()!;
const searchResults = await player.search(query, { const searchResults = await player.search(query, {
searchEngine: QueryType.SPOTIFY_SEARCH searchEngine: QueryType.SPOTIFY_SEARCH
}); });
@@ -220,7 +220,7 @@ module.exports = {
logger.debug('Lyrics text too long, splitting into multiple messages.'); logger.debug('Lyrics text too long, splitting into multiple messages.');
const messageCount = Math.ceil(lyricsResult.lyrics.length / 3800); const messageCount = Math.ceil(lyricsResult.lyrics.length / 3800);
for (let i = 0; i < messageCount; i++) { for (let i = 0; i < messageCount; i++) {
logger.debuf(`Lyrics, sending message ${i + 1} of ${messageCount}.`); logger.debug(`Lyrics, sending message ${i + 1} of ${messageCount}.`);
const message = lyricsResult.lyrics.slice(i * 3800, (i + 1) * 3800); const message = lyricsResult.lyrics.slice(i * 3800, (i + 1) * 3800);
if (i === 0) { if (i === 0) {
logger.debug('Responding with info embed for first message with lyrics.'); logger.debug('Responding with info embed for first message with lyrics.');
@@ -239,7 +239,7 @@ module.exports = {
continue; continue;
} else { } else {
logger.debug('Sending consecutive message with lyrics.'); logger.debug('Sending consecutive message with lyrics.');
await interaction.channel.send({ await interaction.channel!.send({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setDescription(`\`\`\`fix\n${message}\`\`\``) .setDescription(`\`\`\`fix\n${message}\`\`\``)
+71 -34
View File
@@ -1,9 +1,19 @@
import config from 'config'; import config from 'config';
import { useQueue } from 'discord-player'; import { NodeResolvable, Track, useQueue } from 'discord-player';
import { ActionRowBuilder, ButtonBuilder, EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import {
APIActionRowComponent,
APIMessageActionRowComponent,
ButtonBuilder,
ButtonStyle,
ComponentType,
EmbedBuilder,
GuildMember,
Interaction,
SlashCommandBuilder
} from 'discord.js';
import loggerModule from '../../services/logger'; import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes'; import { CommandParams, TrackMetadata, CustomError } from '../../types/commandTypes';
import { EmbedOptions, PlayerOptions } from '../../types/configTypes'; import { EmbedOptions, PlayerOptions } from '../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
@@ -24,15 +34,15 @@ module.exports = {
module: 'slashCommand', module: 'slashCommand',
name: '/nowplaying', name: '/nowplaying',
executionId: executionId, executionId: executionId,
shardId: interaction.guild.shardId, shardId: interaction.guild?.shardId,
guildId: interaction.guild.id guildId: interaction.guild?.id
}); });
if (await notInVoiceChannel({ interaction, executionId })) { if (await notInVoiceChannel({ interaction, executionId })) {
return; return;
} }
const queue = useQueue(interaction.guild.id); const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) { if (await queueDoesNotExist({ interaction, queue, executionId })) {
return; return;
@@ -62,28 +72,27 @@ module.exports = {
['arbitrary', embedOptions.icons.sourceArbitrary] ['arbitrary', embedOptions.icons.sourceArbitrary]
]); ]);
const currentTrack = queue.currentTrack; const currentTrack: Track = queue.currentTrack!;
let author = currentTrack.author ? currentTrack.author : 'Unavailable'; let author = currentTrack.author ? currentTrack.author : 'Unavailable';
if (author === 'cdn.discordapp.com') { if (author === 'cdn.discordapp.com') {
author = 'Unavailable'; author = 'Unavailable';
} }
let plays = currentTrack.views !== 0 ? currentTrack.views : 0; const plays = currentTrack.views !== 0 ? currentTrack.views : 0;
if ( let displayPlays: string = plays.toLocaleString('en-US');
plays === 0 &&
currentTrack.metadata.bridge && const metadata = currentTrack.metadata as TrackMetadata;
currentTrack.metadata.bridge.views !== 0 &&
currentTrack.metadata.bridge.views !== undefined if (plays === 0 && metadata.bridge && metadata.bridge.views !== 0 && metadata.bridge.views !== undefined) {
) { displayPlays = metadata.bridge.views.toLocaleString('en-US');
plays = currentTrack.metadata.bridge.views;
} else if (plays === 0) { } else if (plays === 0) {
plays = 'Unavailable'; displayPlays = 'Unavailable';
} }
const source = sourceStringsFormatted.get(currentTrack.raw.source) ?? 'Unavailable'; const source = sourceStringsFormatted.get(currentTrack.raw.source!) ?? 'Unavailable';
const queueLength = queue.tracks.data.length; const queueLength = queue.tracks.data.length;
const timestamp = queue.node.getTimestamp(); const timestamp = queue.node.getTimestamp()!;
let bar = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({ let bar = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({
queue: false, queue: false,
length: playerOptions.progressBar.length ?? 12, length: playerOptions.progressBar.length ?? 12,
@@ -93,7 +102,7 @@ module.exports = {
rightChar: playerOptions.progressBar.rightChar ?? '▬' rightChar: playerOptions.progressBar.rightChar ?? '▬'
})} **\`${timestamp.total.label}\`**`; })} **\`${timestamp.total.label}\`**`;
if (currentTrack.raw.duration === 0 || currentTrack.duration === '0:00') { if (Number(currentTrack.raw.duration) === 0 || currentTrack.duration === '0:00') {
bar = '_No duration available._'; bar = '_No duration available._';
} }
@@ -101,13 +110,17 @@ module.exports = {
bar = `${embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`; bar = `${embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`;
} }
const nowPlayingActionRow = new ActionRowBuilder().addComponents( const nowPlayingButton = new ButtonBuilder()
new ButtonBuilder()
.setCustomId('nowplaying-skip') .setCustomId('nowplaying-skip')
.setLabel('Skip track') .setLabel('Skip track')
.setStyle('Secondary') .setStyle(ButtonStyle.Secondary)
.setEmoji(embedOptions.icons.nextTrack) .setEmoji(embedOptions.icons.nextTrack)
); .toJSON(); // Convert the builder to a raw object
const nowPlayingActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
type: ComponentType.ActionRow, // This might vary based on your discord.js version
components: [nowPlayingButton]
};
const loopModesFormatted = new Map([ const loopModesFormatted = new Map([
[0, 'disabled'], [0, 'disabled'],
@@ -125,15 +138,15 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: `Channel: ${queue.channel.name} (${queue.channel.bitrate / 1000}kbps)`, name: `Channel: ${queue.channel!.name} (${queue.channel!.bitrate / 1000}kbps)`,
iconURL: interaction.guild.iconURL() iconURL: interaction.guild!.iconURL() || ''
}) })
.setDescription( .setDescription(
(queue.node.isPaused() (queue.node.isPaused()
? '**Currently Paused**\n' ? '**Currently Paused**\n'
: `**${embedOptions.icons.audioPlaying} Now Playing**\n`) + : `**${embedOptions.icons.audioPlaying} Now Playing**\n`) +
`**[${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**` + `**[${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**` +
`\nRequested by: <@${currentTrack.requestedBy.id}>` + `\nRequested by: <@${currentTrack.requestedBy?.id}>` +
`\n ${bar}\n\n` + `\n ${bar}\n\n` +
`${ `${
queue.repeatMode === 0 queue.repeatMode === 0
@@ -151,12 +164,12 @@ module.exports = {
}, },
{ {
name: '**Plays**', name: '**Plays**',
value: plays.toLocaleString('en-US'), value: displayPlays,
inline: true inline: true
}, },
{ {
name: '**Track source**', name: '**Track source**',
value: `**${sourceIcons.get(currentTrack.raw.source)} [${source}](${ value: `**${sourceIcons.get(currentTrack.raw.source!)} [${source}](${
currentTrack.raw.url ?? currentTrack.url currentTrack.raw.url ?? currentTrack.url
})**`, })**`,
inline: true inline: true
@@ -165,15 +178,15 @@ module.exports = {
.setFooter({ .setFooter({
text: queueLength ? `${queueLength} other tracks in the queue...` : ' ' text: queueLength ? `${queueLength} other tracks in the queue...` : ' '
}) })
.setThumbnail(queue.currentTrack.thumbnail) .setThumbnail(queue.currentTrack!.thumbnail)
.setColor(embedOptions.colors.info) .setColor(embedOptions.colors.info)
], ],
components: [nowPlayingActionRow] components: [nowPlayingActionRow as APIActionRowComponent<APIMessageActionRowComponent>]
}); });
logger.debug('Finished sending response.'); logger.debug('Finished sending response.');
const collectorFilter = (i) => i.user.id === interaction.user.id; const collectorFilter = (i: Interaction) => i.user.id === interaction.user.id;
try { try {
const confirmation = await response.awaitMessageComponent({ const confirmation = await response.awaitMessageComponent({
filter: collectorFilter, filter: collectorFilter,
@@ -222,7 +235,7 @@ module.exports = {
const skippedTrack = queue.currentTrack; const skippedTrack = queue.currentTrack;
let durationFormat = let durationFormat =
skippedTrack.raw.duration === 0 || skippedTrack.duration === '0:00' Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00'
? '' ? ''
: `\`${skippedTrack.duration}\``; : `\`${skippedTrack.duration}\``;
@@ -234,13 +247,21 @@ module.exports = {
const repeatModeUserString = loopModesFormatted.get(queue.repeatMode); const repeatModeUserString = loopModesFormatted.get(queue.repeatMode);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.'); logger.debug('Responding with success embed.');
return await interaction.followUp({ return await interaction.followUp({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: interaction.member.nickname || interaction.user.username, name: authorName,
iconURL: interaction.user.avatarURL() iconURL: interaction.user.avatarURL() || ''
}) })
.setDescription( .setDescription(
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${ `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${
@@ -263,13 +284,29 @@ module.exports = {
}); });
} }
} catch (error) { } catch (error) {
if (error instanceof CustomError) {
if (error.code === 'InteractionCollectorError') { if (error.code === 'InteractionCollectorError') {
logger.debug('Interaction response timed out.'); logger.debug('Interaction response timed out.');
return; return;
} }
if (error.message === 'Collector received no interactions before ending with reason: time') {
logger.debug('Interaction response timed out.');
return;
}
logger.error(error, 'Unhandled error while awaiting or handling component interaction.'); logger.error(error, 'Unhandled error while awaiting or handling component interaction.');
return; return;
} else {
if (
error instanceof Error &&
error.message === 'Collector received no interactions before ending with reason: time'
) {
logger.debug('Interaction response timed out.');
return;
}
throw error;
}
} }
} }
}; };
+24 -16
View File
@@ -1,6 +1,6 @@
import config from 'config'; import config from 'config';
import { useQueue } from 'discord-player'; import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger'; import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes'; import { CommandParams } from '../../types/commandTypes';
@@ -23,15 +23,15 @@ module.exports = {
module: 'slashCommand', module: 'slashCommand',
name: '/pause', name: '/pause',
executionId: executionId, executionId: executionId,
shardId: interaction.guild.shardId, shardId: interaction.guild?.shardId,
guildId: interaction.guild.id guildId: interaction.guild?.id
}); });
if (await notInVoiceChannel({ interaction, executionId })) { if (await notInVoiceChannel({ interaction, executionId })) {
return; return;
} }
const queue = useQueue(interaction.guild.id); const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) { if (await queueDoesNotExist({ interaction, queue, executionId })) {
return; return;
@@ -45,12 +45,14 @@ module.exports = {
return; return;
} }
let durationFormat = const currentTrack = queue.currentTrack!;
queue.currentTrack.raw.duration === 0 || queue.currentTrack.duration === '0:00'
? ''
: `\`${queue.currentTrack.duration}\``;
if (queue.currentTrack.raw.live) { let durationFormat =
Number(currentTrack.raw.duration) === 0 || currentTrack.duration === '0:00'
? ''
: `\`${currentTrack.duration}\``;
if (currentTrack.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
} }
@@ -58,22 +60,28 @@ module.exports = {
queue.node.setPaused(!queue.node.isPaused()); queue.node.setPaused(!queue.node.isPaused());
logger.debug(`Set paused state to ${queue.node.isPaused()}.`); logger.debug(`Set paused state to ${queue.node.isPaused()}.`);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.'); logger.debug('Responding with success embed.');
return await interaction.editReply({ return await interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: interaction.member.nickname || interaction.user.username, name: authorName,
iconURL: interaction.user.avatarURL() iconURL: interaction.user.avatarURL() || ''
}) })
.setDescription( .setDescription(
`**${embedOptions.icons.pauseResumed} ${ `**${embedOptions.icons.pauseResumed} ${
queue.node.isPaused() ? 'Paused Track' : 'Resumed track' queue.node.isPaused() ? 'Paused Track' : 'Resumed track'
}**\n**${durationFormat} [${queue.currentTrack.title}](${ }**\n**${durationFormat} [${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**`
queue.currentTrack.raw.url ?? queue.currentTrack.url
})**`
) )
.setThumbnail(queue.currentTrack.thumbnail) .setThumbnail(currentTrack.thumbnail)
.setColor(embedOptions.colors.success) .setColor(embedOptions.colors.success)
] ]
}); });
+61 -29
View File
@@ -1,6 +1,6 @@
import config from 'config'; import config from 'config';
import { useMainPlayer, useQueue } from 'discord-player'; import { useMainPlayer, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger'; import loggerModule from '../../services/logger';
import { CommandAutocompleteParams, CommandParams } from '../../types/commandTypes'; import { CommandAutocompleteParams, CommandParams } from '../../types/commandTypes';
@@ -40,11 +40,11 @@ module.exports = {
autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => { autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => {
const logger = loggerTemplate.child({ const logger = loggerTemplate.child({
executionId: executionId, executionId: executionId,
shardId: interaction.guild.shardId, shardId: interaction.guild?.shardId,
guildId: interaction.guild.id guildId: interaction.guild?.id
}); });
const player = useMainPlayer(); const player = useMainPlayer()!;
const query = interaction.options.getString('query', true); const query = interaction.options.getString('query', true);
const { lastQuery, results, timestamp } = recentQueries.get(interaction.user.id) || {}; const { lastQuery, results, timestamp } = recentQueries.get(interaction.user.id) || {};
@@ -92,8 +92,8 @@ module.exports = {
execute: async ({ interaction, executionId }: CommandParams) => { execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerTemplate.child({ const logger = loggerTemplate.child({
executionId: executionId, executionId: executionId,
shardId: interaction.guild.shardId, shardId: interaction.guild?.shardId,
guildId: interaction.guild.id guildId: interaction.guild?.id
}); });
if (await notInVoiceChannel({ interaction, executionId })) { if (await notInVoiceChannel({ interaction, executionId })) {
@@ -104,13 +104,13 @@ module.exports = {
return; return;
} }
let queue = useQueue(interaction.guild.id); let queue = useQueue(interaction.guild!.id);
if (queue && (await notInSameVoiceChannel({ interaction, queue, executionId }))) { if (queue && (await notInSameVoiceChannel({ interaction, queue, executionId }))) {
return; return;
} }
const player = useMainPlayer(); const player = useMainPlayer()!;
const query = interaction.options.getString('query'); const query = interaction.options.getString('query')!;
const transformedQuery = await transformQuery({ query, executionId }); const transformedQuery = await transformQuery({ query, executionId });
@@ -132,17 +132,17 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setDescription( .setDescription(
`**${embedOptions.icons.warning} No track found**\nNo results found for \`${transformedQuery}\`.\n\nIf you specified a URL, please make sure it is valid and public.` `**${embedOptions.icons.warning} No track found**\nNo results found for **\`${transformedQuery}\`**.\n\nIf you specified a URL, please make sure it is valid and public.`
) )
.setColor(embedOptions.colors.warning) .setColor(embedOptions.colors.warning)
] ]
}); });
} }
queue = useQueue(interaction.guild.id); queue = useQueue(interaction.guild!.id);
const queueSize = queue?.size ?? 0; const queueSize = queue?.size ?? 0;
if ((searchResult.playlist && searchResult.tracks.length) > playerOptions.maxQueueSize - queueSize) { if ((searchResult.playlist! && searchResult.tracks.length) > playerOptions.maxQueueSize - queueSize) {
logger.debug(`Playlist found but would exceed max queue size. Query: '${query}'.`); logger.debug(`Playlist found but would exceed max queue size. Query: '${query}'.`);
logger.debug('Responding with warning embed.'); logger.debug('Responding with warning embed.');
@@ -162,7 +162,7 @@ module.exports = {
try { try {
logger.debug(`Attempting to add track with player.play(). Query: '${query}'.`); logger.debug(`Attempting to add track with player.play(). Query: '${query}'.`);
({ track } = await player.play(interaction.member.voice.channel, searchResult, { ({ track } = await player.play((interaction.member as GuildMember).voice.channel!, searchResult, {
requestedBy: interaction.user, requestedBy: interaction.user,
nodeOptions: { nodeOptions: {
leaveOnEmpty: playerOptions.leaveOnEmpty ?? true, leaveOnEmpty: playerOptions.leaveOnEmpty ?? true,
@@ -185,6 +185,7 @@ module.exports = {
} }
})); }));
} catch (error) { } catch (error) {
if (error instanceof Error) {
if (error.message.includes('Sign in to confirm your age')) { 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('Found track but failed to retrieve audio due to age confirmation warning.');
@@ -201,7 +202,9 @@ module.exports = {
} }
if (error.message.includes('The following content may contain')) { 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(
'Found track but failed to retrieve audio due to graphic/mature/sensitive topic warning.'
);
logger.debug('Responding with warning embed.'); logger.debug('Responding with warning embed.');
return await interaction.editReply({ return await interaction.editReply({
@@ -216,9 +219,8 @@ module.exports = {
} }
if ( if (
(error.type === 'TypeError' && error.message.includes("Cannot read properties of null (reading 'createStream')") ||
(error.message.includes("Cannot read properties of null (reading 'createStream')") || error.message.includes('Failed to fetch resources for ytdl streaming') ||
error.message.includes('Failed to fetch resources for ytdl streaming'))) ||
error.message.includes('Could not extract stream for this track') error.message.includes('Could not extract stream for this track')
) { ) {
logger.debug(error, `Found track but failed to retrieve audio. Query: ${query}.`); logger.debug(error, `Found track but failed to retrieve audio. Query: ${query}.`);
@@ -254,7 +256,10 @@ module.exports = {
if (error.message === "Cannot read properties of null (reading 'createStream')") { if (error.message === "Cannot read properties of null (reading 'createStream')") {
// Can happen if /play then /leave before track starts playing // 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.warn(
error,
'Found track but failed to play back audio. Voice connection might be unavailable.'
);
logger.debug('Responding with error embed.'); logger.debug('Responding with error embed.');
return await interaction.editReply({ return await interaction.editReply({
@@ -270,13 +275,16 @@ 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.');
} else {
throw error;
}
} }
logger.debug(`Successfully added track with player.play(). Query: '${query}'.`); logger.debug(`Successfully added track with player.play(). Query: '${query}'.`);
queue = useQueue(interaction.guild.id); queue = useQueue(interaction.guild!.id);
if (!queue) { if (!queue || !track) {
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.'); logger.debug('Responding with error embed.');
@@ -295,7 +303,7 @@ module.exports = {
if ( if (
track.source.length === 0 || track.source.length === 0 ||
track.source === 'arbitrary' || track.source === 'arbitrary' ||
track.thumnail === null || track.thumbnail === null ||
track.thumbnail === undefined || track.thumbnail === undefined ||
track.thumbnail === '' track.thumbnail === ''
) { ) {
@@ -305,7 +313,8 @@ module.exports = {
track.thumbnail = embedOptions.info.fallbackThumbnailUrl; track.thumbnail = embedOptions.info.fallbackThumbnailUrl;
} }
let durationFormat = track.raw.duration === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``; let durationFormat =
Number(track.raw.duration) === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``;
if (track.raw.live) { if (track.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
@@ -314,13 +323,21 @@ module.exports = {
if (searchResult.playlist && searchResult.tracks.length > 1) { if (searchResult.playlist && searchResult.tracks.length > 1) {
logger.debug(`Playlist found and added with player.play(). Query: '${query}'`); logger.debug(`Playlist found and added with player.play(). Query: '${query}'`);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.'); logger.debug('Responding with success embed.');
return await interaction.editReply({ return await interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: interaction.member.nickname || interaction.user.username, name: authorName,
iconURL: interaction.user.avatarURL() iconURL: interaction.user.avatarURL() || ''
}) })
.setDescription( .setDescription(
`**${embedOptions.icons.success} Added playlist to queue**\n**${durationFormat} [${ `**${embedOptions.icons.success} Added playlist to queue**\n**${durationFormat} [${
@@ -338,14 +355,21 @@ module.exports = {
if (queue.currentTrack === track && queue.tracks.data.length === 0) { 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}'.`);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.'); logger.debug('Responding with success embed.');
return await interaction.editReply({ return await interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: name: authorName,
interaction.member.nickname || interaction.member.nickname || interaction.user.username, iconURL: interaction.user.avatarURL() || ''
iconURL: interaction.user.avatarURL()
}) })
.setDescription( .setDescription(
`**${embedOptions.icons.audioStartedPlaying} Started playing**\n**${durationFormat} [${ `**${embedOptions.icons.audioStartedPlaying} Started playing**\n**${durationFormat} [${
@@ -360,13 +384,21 @@ 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}'.`);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.'); logger.debug('Responding with success embed.');
return await interaction.editReply({ return await interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: interaction.member.nickname || interaction.user.username, name: authorName,
iconURL: interaction.user.avatarURL() iconURL: interaction.user.avatarURL() || ''
}) })
.setDescription( .setDescription(
`${embedOptions.icons.success} **Added to queue**\n**${durationFormat} [${track.title}](${ `${embedOptions.icons.success} **Added to queue**\n**${durationFormat} [${track.title}](${
+18 -18
View File
@@ -1,5 +1,5 @@
import config from 'config'; import config from 'config';
import { useQueue } from 'discord-player'; import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger'; import loggerModule from '../../services/logger';
@@ -24,15 +24,15 @@ module.exports = {
module: 'slashCommand', module: 'slashCommand',
name: '/queue', name: '/queue',
executionId: executionId, executionId: executionId,
shardId: interaction.guild.shardId, shardId: interaction.guild?.shardId,
guildId: interaction.guild.id guildId: interaction.guild?.id
}); });
if (await notInVoiceChannel({ interaction, executionId })) { if (await notInVoiceChannel({ interaction, executionId })) {
return; return;
} }
const queue = useQueue(interaction.guild.id); const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await notInSameVoiceChannel({ interaction, queue, executionId })) { if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return; return;
@@ -50,9 +50,9 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setDescription( .setDescription(
`**${embedOptions.icons.warning} Oops!**\nPage \`${ `**${embedOptions.icons.warning} Oops!**\nPage **\`${
pageIndex + 1 pageIndex + 1
}\` is not a valid page number.\n\nThe queue is currently empty, first add some tracks with **\`/play\`**!` }\`** is not a valid page number.\n\nThe queue is currently empty, first add some tracks with **\`/play\`**!`
) )
.setColor(embedOptions.colors.warning) .setColor(embedOptions.colors.warning)
] ]
@@ -67,8 +67,8 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: interaction.guild.name, name: interaction.guild!.name,
iconURL: interaction.guild.iconURL() iconURL: interaction.guild!.iconURL() || ''
}) })
.setDescription(`**${embedOptions.icons.queue} Tracks in queue**\n${queueString}`) .setDescription(`**${embedOptions.icons.queue} Tracks in queue**\n${queueString}`)
.setColor(embedOptions.colors.info) .setColor(embedOptions.colors.info)
@@ -90,9 +90,9 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setDescription( .setDescription(
`**${embedOptions.icons.warning} Oops!**\nPage \`${ `**${embedOptions.icons.warning} Oops!**\nPage **\`${
pageIndex + 1 pageIndex + 1
}\` is not a valid page number.\n\nThere are only a total of \`${totalPages}\` pages in the queue.` }\`** is not a valid page number.\n\nThere are only a total of **\`${totalPages}\`** pages in the queue.`
) )
.setColor(embedOptions.colors.warning) .setColor(embedOptions.colors.warning)
] ]
@@ -107,7 +107,7 @@ module.exports = {
.slice(pageIndex * 10, pageIndex * 10 + 10) .slice(pageIndex * 10, pageIndex * 10 + 10)
.map((track, index) => { .map((track, index) => {
let durationFormat = let durationFormat =
track.raw.duration === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``; Number(track.raw.duration) === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``;
if (track.raw.live) { if (track.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
@@ -147,8 +147,8 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: `Channel: ${queue.channel.name} (${queue.channel.bitrate / 1000}kbps)`, name: `Channel: ${queue.channel!.name} (${queue.channel!.bitrate / 1000}kbps)`,
iconURL: interaction.guild.iconURL() iconURL: interaction.guild!.iconURL() || ''
}) })
.setDescription( .setDescription(
`${repeatModeString}` + `**${embedOptions.icons.queue} Tracks in queue**\n${queueString}` `${repeatModeString}` + `**${embedOptions.icons.queue} Tracks in queue**\n${queueString}`
@@ -161,7 +161,7 @@ module.exports = {
}); });
} else { } else {
logger.debug('Queue exists with current track, gathering information.'); logger.debug('Queue exists with current track, gathering information.');
const timestamp = queue.node.getTimestamp(); const timestamp = queue.node.getTimestamp()!;
let bar = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({ let bar = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({
queue: false, queue: false,
length: playerOptions.progressBar.length ?? 12, length: playerOptions.progressBar.length ?? 12,
@@ -171,7 +171,7 @@ module.exports = {
rightChar: playerOptions.progressBar.rightChar ?? '▬' rightChar: playerOptions.progressBar.rightChar ?? '▬'
})} **\`${timestamp.total.label}\`**`; })} **\`${timestamp.total.label}\`**`;
if (currentTrack.raw.duration === 0 || currentTrack.duration === '0:00') { if (Number(currentTrack.raw.duration) === 0 || currentTrack.duration === '0:00') {
bar = '_No duration available._'; bar = '_No duration available._';
} }
@@ -184,15 +184,15 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: `Channel: ${queue.channel.name} (${queue.channel.bitrate / 1000}kbps)`, name: `Channel: ${queue.channel!.name} (${queue.channel!.bitrate / 1000}kbps)`,
iconURL: interaction.guild.iconURL() iconURL: interaction.guild!.iconURL() || ''
}) })
.setDescription( .setDescription(
`**${embedOptions.icons.audioPlaying} Now playing**\n` + `**${embedOptions.icons.audioPlaying} Now playing**\n` +
(currentTrack (currentTrack
? `**[${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**` ? `**[${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**`
: 'None') + : 'None') +
`\nRequested by: <@${currentTrack.requestedBy.id}>` + `\nRequested by: <@${currentTrack.requestedBy?.id}>` +
`\n ${bar}\n\n` + `\n ${bar}\n\n` +
`${repeatModeString}` + `${repeatModeString}` +
`**${embedOptions.icons.queue} Tracks in queue**\n${queueString}` `**${embedOptions.icons.queue} Tracks in queue**\n${queueString}`
+21 -11
View File
@@ -1,6 +1,6 @@
import config from 'config'; import config from 'config';
import { useQueue } from 'discord-player'; import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger'; import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes'; import { CommandParams } from '../../types/commandTypes';
@@ -30,15 +30,15 @@ module.exports = {
module: 'slashCommand', module: 'slashCommand',
name: '/remove', name: '/remove',
executionId: executionId, executionId: executionId,
shardId: interaction.guild.shardId, shardId: interaction.guild?.shardId,
guildId: interaction.guild.id guildId: interaction.guild?.id
}); });
if (await notInVoiceChannel({ interaction, executionId })) { if (await notInVoiceChannel({ interaction, executionId })) {
return; return;
} }
const queue = useQueue(interaction.guild.id); const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) { if (await queueDoesNotExist({ interaction, queue, executionId })) {
return; return;
@@ -48,7 +48,7 @@ module.exports = {
return; return;
} }
const removeTrackNumber = interaction.options.getNumber('tracknumber'); const removeTrackNumber = interaction.options.getNumber('tracknumber')!;
if (removeTrackNumber > queue.tracks.data.length) { if (removeTrackNumber > queue.tracks.data.length) {
logger.debug('Specified track number is higher than total tracks.'); logger.debug('Specified track number is higher than total tracks.');
@@ -58,7 +58,7 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setDescription( .setDescription(
`**${embedOptions.icons.warning} Oops!**\nTrack \`${removeTrackNumber}\` is not a valid track number. There are a total of\`${queue.tracks.data.length}\` tracks in the queue.\n\nView tracks added to the queue with **\`/queue\`**.` `**${embedOptions.icons.warning} Oops!**\nTrack **\`${removeTrackNumber}\`** is not a valid track number. There are a total of **\`${queue.tracks.data.length}\`** tracks in the queue.\n\nView tracks added to the queue with **\`/queue\`**.`
) )
.setColor(embedOptions.colors.warning) .setColor(embedOptions.colors.warning)
] ]
@@ -66,22 +66,32 @@ module.exports = {
} }
// Remove specified track number from queue // Remove specified track number from queue
const removedTrack = queue.node.remove(removeTrackNumber - 1); const removedTrack = queue.node.remove(removeTrackNumber - 1)!;
logger.debug(`Removed track '${removedTrack.url}' from queue.`); logger.debug(`Removed track '${removedTrack.url}' from queue.`);
let durationFormat = let durationFormat =
removedTrack.raw.duration === 0 || removedTrack.duration === '0:00' ? '' : `\`${removedTrack.duration}\``; Number(removedTrack.raw.duration) === 0 || removedTrack.duration === '0:00'
? ''
: `\`${removedTrack.duration}\``;
if (removedTrack.raw.live) { if (removedTrack.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
} }
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.'); logger.debug('Responding with success embed.');
return await interaction.editReply({ return await interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: interaction.member.nickname || interaction.user.username, name: authorName,
iconURL: interaction.user.avatarURL() iconURL: interaction.user.avatarURL() || ''
}) })
.setDescription( .setDescription(
`**${embedOptions.icons.success} Removed track**\n**${durationFormat} [${removedTrack.title}](${ `**${embedOptions.icons.success} Removed track**\n**${durationFormat} [${removedTrack.title}](${
+44 -30
View File
@@ -1,6 +1,6 @@
import config from 'config'; import config from 'config';
import { useQueue } from 'discord-player'; import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger'; import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes'; import { CommandParams } from '../../types/commandTypes';
@@ -29,15 +29,15 @@ module.exports = {
module: 'slashCommand', module: 'slashCommand',
name: '/seek', name: '/seek',
executionId: executionId, executionId: executionId,
shardId: interaction.guild.shardId, shardId: interaction.guild?.shardId,
guildId: interaction.guild.id guildId: interaction.guild?.id
}); });
if (await notInVoiceChannel({ interaction, executionId })) { if (await notInVoiceChannel({ interaction, executionId })) {
return; return;
} }
const queue = useQueue(interaction.guild.id); const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) { if (await queueDoesNotExist({ interaction, queue, executionId })) {
return; return;
@@ -52,7 +52,8 @@ module.exports = {
} }
const durationInput = interaction.options.getString('duration'); const durationInput = interaction.options.getString('duration');
let durationArray = durationInput.split(':');
let durationArray = durationInput!.split(':');
switch (durationArray.length) { switch (durationArray.length) {
case 1: case 1:
@@ -65,6 +66,12 @@ module.exports = {
break; break;
} }
durationArray = durationArray.map((value) => {
return value.padStart(2, '0');
});
const durationString = durationArray.join(':');
if (durationArray.length === 0 || durationArray.length > 3) { if (durationArray.length === 0 || durationArray.length > 3) {
logger.debug('Invalid duration format input.'); logger.debug('Invalid duration format input.');
@@ -73,22 +80,16 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setDescription( .setDescription(
`**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, \`${durationString}\`.\n\nPlease use the format \`HH:mm:ss\`, \`mm:ss\` or \`ss\`, where \`HH\` is hours, \`mm\` is minutes and \`ss\` is seconds.\n\n**Examples:**\n` + `**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` +
'- `/seek` **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' + '- **`/seek`** **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' +
'- `/seek` **`3:27`** - Seek to 3 minutes and 27 seconds.\n' + '- **`/seek`** **`3:27`** - Seek to 3 minutes and 27 seconds.\n' +
'- `/seek` **`42`** - Seek to 42 seconds.' '- **`/seek`** **`42`** - Seek to 42 seconds.'
) )
.setColor(embedOptions.colors.warning) .setColor(embedOptions.colors.warning)
] ]
}); });
} }
durationArray = durationArray.map((value) => {
return value.padStart(2, '0');
});
const durationString = durationArray.join(':');
const validElements = durationArray.every((value) => { const validElements = durationArray.every((value) => {
return value.length === 2; return value.length === 2;
}); });
@@ -101,10 +102,10 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setDescription( .setDescription(
`**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, \`${durationString}\`.\n\nPlease use the format \`HH:mm:ss\`, \`mm:ss\` or \`ss\`, where \`HH\` is hours, \`mm\` is minutes and \`ss\` is seconds.\n\n**Examples:**\n` + `**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` +
'- `/seek` **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' + '- **`/seek`** **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' +
'- `/seek` **`3:27`** - Seek to 3 minutes and 27 seconds.\n' + '- **`/seek`** **`3:27`** - Seek to 3 minutes and 27 seconds.\n' +
'- `/seek` **`42`** - Seek to 42 seconds.' '- **`/seek`** **`42`** - Seek to 42 seconds.'
) )
.setColor(embedOptions.colors.warning) .setColor(embedOptions.colors.warning)
] ]
@@ -124,18 +125,19 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setDescription( .setDescription(
`**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, \`${durationString}\`.\n\nPlease use the format \`HH:mm:ss\`, \`mm:ss\` or \`ss\`, where \`HH\` is hours, \`mm\` is minutes and \`ss\` is seconds.\n\n**Examples:**\n` + `**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` +
'- `/seek` **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' + '- **`/seek`** **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' +
'- `/seek` **`3:27`** - Seek to 3 minutes and 27 seconds.\n' + '- **`/seek`** **`3:27`** - Seek to 3 minutes and 27 seconds.\n' +
'- `/seek` **`42`** - Seek to 42 seconds.' '- **`/seek`** **`42`** - Seek to 42 seconds.'
) )
.setColor(embedOptions.colors.warning) .setColor(embedOptions.colors.warning)
] ]
}); });
} }
const currentTrackMaxDurationInMs = queue.currentTrack.durationMS; const currentTrackMaxDurationInMs = queue.currentTrack!.durationMS;
const durationInMilliseconds = durationArray[0] * 3600000 + durationArray[1] * 60000 + durationArray[2] * 1000; const durationInMilliseconds: number =
Number(durationArray[0]) * 3600000 + Number(durationArray[1]) * 60000 + Number(durationArray[2]) * 1000;
if (durationInMilliseconds > currentTrackMaxDurationInMs - 1000) { if (durationInMilliseconds > currentTrackMaxDurationInMs - 1000) {
logger.debug('Duration specified is longer than the track duration.'); logger.debug('Duration specified is longer than the track duration.');
@@ -145,7 +147,11 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setDescription( .setDescription(
`**${embedOptions.icons.warning} Oops!**\nYou entered **\`${durationString}\`**, which is a duration that is longer than the duration for the current track.\n\nPlease try a duration that is less than the duration of the track (**\`${queue.currentTrack.duration}\`**).` `**${
embedOptions.icons.warning
} Oops!**\nYou entered **\`${durationString}\`**, which is a duration that is longer than the duration for the current track.\n\nPlease try a duration that is less than the duration of the track (**\`${
queue.currentTrack!.duration
}\`**).`
) )
.setColor(embedOptions.colors.warning) .setColor(embedOptions.colors.warning)
] ]
@@ -155,18 +161,26 @@ module.exports = {
queue.node.seek(durationInMilliseconds); queue.node.seek(durationInMilliseconds);
logger.debug(`Seeked to '${durationString}' in current track.`); logger.debug(`Seeked to '${durationString}' in current track.`);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.'); logger.debug('Responding with success embed.');
return await interaction.editReply({ return await interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: interaction.member.nickname || interaction.user.username, name: authorName,
iconURL: interaction.user.avatarURL() iconURL: interaction.user.avatarURL() || ''
}) })
.setDescription( .setDescription(
`**${embedOptions.icons.success} Seeking to duration**\nSeeking to **\`${durationString}\`** in current track.` `**${embedOptions.icons.success} Seeking to duration**\nSeeking to **\`${durationString}\`** in current track.`
) )
.setThumbnail(queue.currentTrack.thumbnail) .setThumbnail(queue.currentTrack!.thumbnail)
.setColor(embedOptions.colors.success) .setColor(embedOptions.colors.success)
] ]
}); });
+15 -7
View File
@@ -1,6 +1,6 @@
import config from 'config'; import config from 'config';
import { useQueue } from 'discord-player'; import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger'; import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes'; import { CommandParams } from '../../types/commandTypes';
@@ -23,15 +23,15 @@ module.exports = {
module: 'slashCommand', module: 'slashCommand',
name: '/shuffle', name: '/shuffle',
executionId: executionId, executionId: executionId,
shardId: interaction.guild.shardId, shardId: interaction.guild?.shardId,
guildId: interaction.guild.id guildId: interaction.guild?.id
}); });
if (await notInVoiceChannel({ interaction, executionId })) { if (await notInVoiceChannel({ interaction, executionId })) {
return; return;
} }
const queue = useQueue(interaction.guild.id); const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) { if (await queueDoesNotExist({ interaction, queue, executionId })) {
return; return;
@@ -48,13 +48,21 @@ module.exports = {
queue.tracks.shuffle(); queue.tracks.shuffle();
logger.debug('Shuffled queue tracks.'); logger.debug('Shuffled queue tracks.');
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.'); logger.debug('Responding with success embed.');
return await interaction.editReply({ return await interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: interaction.member.nickname || interaction.user.username, name: authorName,
iconURL: interaction.user.avatarURL() iconURL: interaction.user.avatarURL() || ''
}) })
.setDescription( .setDescription(
`**${embedOptions.icons.shuffled} Shuffled queue tracks**\nThe **${queue.tracks.data.length}** tracks in the queue has been shuffled.\n\nView the new queue order with **\`/queue\`**.` `**${embedOptions.icons.shuffled} Shuffled queue tracks**\nThe **${queue.tracks.data.length}** tracks in the queue has been shuffled.\n\nView the new queue order with **\`/queue\`**.`
+33 -14
View File
@@ -1,6 +1,6 @@
import config from 'config'; import config from 'config';
import { useQueue } from 'discord-player'; import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger'; import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes'; import { CommandParams } from '../../types/commandTypes';
@@ -26,15 +26,15 @@ module.exports = {
module: 'slashCommand', module: 'slashCommand',
name: '/skip', name: '/skip',
executionId: executionId, executionId: executionId,
shardId: interaction.guild.shardId, shardId: interaction.guild?.shardId,
guildId: interaction.guild.id guildId: interaction.guild?.id
}); });
if (await notInVoiceChannel({ interaction, executionId })) { if (await notInVoiceChannel({ interaction, executionId })) {
return; return;
} }
const queue = useQueue(interaction.guild.id); const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) { if (await queueDoesNotExist({ interaction, queue, executionId })) {
return; return;
@@ -59,15 +59,17 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setDescription( .setDescription(
`**${embedOptions.icons.warning} Oops!**\nThere are only \`${queue.tracks.data.length}\` tracks in the queue. You cannot skip to track \`${skipToTrack}\`.\n\nView tracks added to the queue with **\`/queue\`**.` `**${embedOptions.icons.warning} Oops!**\nThere are only **\`${queue.tracks.data.length}\`** tracks in the queue. You cannot skip to track **\`${skipToTrack}\`**.\n\nView tracks added to the queue with **\`/queue\`**.`
) )
.setColor(embedOptions.colors.warning) .setColor(embedOptions.colors.warning)
] ]
}); });
} else { } else {
const skippedTrack = queue.currentTrack; const skippedTrack = queue.currentTrack!;
logger.debug('Responding with warning embed.');
let durationFormat = let durationFormat =
skippedTrack.raw.duration === 0 || skippedTrack.duration === '0:00' Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00'
? '' ? ''
: `\`${skippedTrack.duration}\``; : `\`${skippedTrack.duration}\``;
@@ -78,13 +80,21 @@ module.exports = {
queue.node.skipTo(skipToTrack - 1); queue.node.skipTo(skipToTrack - 1);
logger.debug('Skipped to specified track number.'); logger.debug('Skipped to specified track number.');
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.'); logger.debug('Responding with success embed.');
return await interaction.editReply({ return await interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: interaction.member.nickname || interaction.user.username, name: authorName,
iconURL: interaction.user.avatarURL() iconURL: interaction.user.avatarURL() || ''
}) })
.setDescription( .setDescription(
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${ `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${
@@ -112,9 +122,10 @@ module.exports = {
}); });
} }
const skippedTrack = queue.currentTrack; const skippedTrack = queue.currentTrack!;
let durationFormat = let durationFormat =
skippedTrack.raw.duration === 0 || skippedTrack.duration === '0:00' Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00'
? '' ? ''
: `\`${skippedTrack.duration}\``; : `\`${skippedTrack.duration}\``;
@@ -133,13 +144,21 @@ module.exports = {
const loopModeUserString = loopModesFormatted.get(queue.repeatMode); const loopModeUserString = loopModesFormatted.get(queue.repeatMode);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.'); logger.debug('Responding with success embed.');
return await interaction.editReply({ return await interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: interaction.member.nickname || interaction.user.username, name: authorName,
iconURL: interaction.user.avatarURL() iconURL: interaction.user.avatarURL() || ''
}) })
.setDescription( .setDescription(
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${ `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${
+15 -7
View File
@@ -1,6 +1,6 @@
import config from 'config'; import config from 'config';
import { useQueue } from 'discord-player'; import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger'; import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes'; import { CommandParams } from '../../types/commandTypes';
@@ -22,15 +22,15 @@ module.exports = {
module: 'slashCommand', module: 'slashCommand',
name: '/stop', name: '/stop',
executionId: executionId, executionId: executionId,
shardId: interaction.guild.shardId, shardId: interaction.guild?.shardId,
guildId: interaction.guild.id guildId: interaction.guild?.id
}); });
if (await notInVoiceChannel({ interaction, executionId })) { if (await notInVoiceChannel({ interaction, executionId })) {
return; return;
} }
const queue = useQueue(interaction.guild.id); const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (!queue) { if (!queue) {
logger.debug('There is no queue.'); logger.debug('There is no queue.');
@@ -58,13 +58,21 @@ module.exports = {
logger.debug('Cleared and stopped the queue.'); logger.debug('Cleared and stopped the queue.');
} }
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.'); logger.debug('Responding with success embed.');
return await interaction.editReply({ return await interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setAuthor({ .setAuthor({
name: interaction.member.nickname || interaction.user.username, name: authorName,
iconURL: interaction.user.avatarURL() iconURL: interaction.user.avatarURL() || ''
}) })
.setDescription( .setDescription(
`**${embedOptions.icons.success} Stopped playing**\nStopped playing audio and cleared the track queue.\n\nTo play more music, use the **\`/play\`** command!` `**${embedOptions.icons.success} Stopped playing**\nStopped playing audio and cleared the track queue.\n\nTo play more music, use the **\`/play\`** command!`
+5 -9
View File
@@ -38,11 +38,7 @@ module.exports = {
return; return;
} }
if (!interaction.guild) { const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
return;
}
const queue: NodeResolvable = useQueue(interaction.guild.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) { if (await queueDoesNotExist({ interaction, queue, executionId })) {
return; return;
@@ -66,7 +62,7 @@ module.exports = {
.setDescription( .setDescription(
`**${ `**${
currentVolume === 0 ? embedOptions.icons.volumeIsMuted : embedOptions.icons.volume currentVolume === 0 ? embedOptions.icons.volumeIsMuted : embedOptions.icons.volume
} Playback volume**\nThe playback volume is currently set to \`${currentVolume}%\`.` } Playback volume**\nThe playback volume is currently set to **\`${currentVolume}%\`**.`
) )
.setColor(embedOptions.colors.info) .setColor(embedOptions.colors.info)
] ]
@@ -79,7 +75,7 @@ module.exports = {
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setDescription( .setDescription(
`**${embedOptions.icons.warning} Oops!**\nYou cannot set the volume to \`${volume}\`, please pick a value betwen \`1\`% and \`100\`%.` `**${embedOptions.icons.warning} Oops!**\nYou cannot set the volume to **\`${volume}%\`**, please pick a value betwen **\`1%\`** and **\`100%\`**.`
) )
.setColor(embedOptions.colors.warning) .setColor(embedOptions.colors.warning)
] ]
@@ -106,7 +102,7 @@ module.exports = {
iconURL: interaction.user.avatarURL() || '' iconURL: interaction.user.avatarURL() || ''
}) })
.setDescription( .setDescription(
`**${embedOptions.icons.volumeMuted} Audio muted**\nPlayback audio has been muted, because volume was set to \`${volume}%\`.` `**${embedOptions.icons.volumeMuted} Audio muted**\nPlayback audio has been muted, because volume was set to **\`${volume}%\`**.`
) )
.setColor(embedOptions.colors.success) .setColor(embedOptions.colors.success)
] ]
@@ -122,7 +118,7 @@ module.exports = {
iconURL: interaction.user.avatarURL() || '' iconURL: interaction.user.avatarURL() || ''
}) })
.setDescription( .setDescription(
`**${embedOptions.icons.volumeChanged} Volume changed**\nPlayback volume has been changed to \`${volume}%\`.` `**${embedOptions.icons.volumeChanged} Volume changed**\nPlayback volume has been changed to **\`${volume}%\`**.`
) )
.setColor(embedOptions.colors.success) .setColor(embedOptions.colors.success)
] ]
+1 -1
View File
@@ -71,7 +71,7 @@ module.exports = {
`**${embedOptions.icons.bot} ${ `**${embedOptions.icons.bot} ${
totalGuildCount < 25 ? `Top ${totalGuildCount} guilds` : 'Top 25 guilds' totalGuildCount < 25 ? `Top ${totalGuildCount} guilds` : 'Top 25 guilds'
} by member count (${totalGuildCount} total)**\n${guildListFormatted}` + } by member count (${totalGuildCount} total)**\n${guildListFormatted}` +
`\n\n**Total members:** \`${totalMemberCount}\``; `\n\n**Total members:** **\`${totalMemberCount}\`**`;
logger.debug('Transformed guild into into embed description.'); logger.debug('Transformed guild into into embed description.');
+3 -2
View File
@@ -3,8 +3,9 @@ import { Client, Collection, SharedNameAndDescription } from 'discord.js';
type RegisterClientCommandsFunction = (params: { client: Client; executionId: string }) => void; type RegisterClientCommandsFunction = (params: { client: Client; executionId: string }) => void;
export interface Command { export interface Command {
isNew: boolean; isNew?: boolean;
isBeta: boolean; isBeta?: boolean;
isSystemCommand?: boolean;
data: { data: {
name: string; name: string;
description: string; description: string;
+11
View File
@@ -25,3 +25,14 @@ export interface ShardInfo {
totalListeners: number; totalListeners: number;
}; };
} }
export interface TrackMetadata {
bridge: {
views: number;
};
}
export class CustomError extends Error {
type?: string;
code?: string;
}
+1 -1
View File
@@ -91,7 +91,7 @@ export interface PlayerOptions {
leaveOnEmpty: boolean; leaveOnEmpty: boolean;
leaveOnEmptyCooldown: number; leaveOnEmptyCooldown: number;
leaveOnEnd: boolean; leaveOnEnd: boolean;
leaveonEndCooldown: number; leaveOnEndCooldown: number;
leaveOnStop: boolean; leaveOnStop: boolean;
leaveOnStopCooldown: number; leaveOnStopCooldown: number;
defaultVolume: number; defaultVolume: number;
@@ -22,7 +22,7 @@ export const notValidGuildId = async ({ interaction, executionId }: NotValidGuil
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setDescription( .setDescription(
`**${embedOptions.icons.warning} Oops!**\nNo permission to execute this command.\n\nThe command \`${interaction.commandName}\` cannot be executed in this server.` `**${embedOptions.icons.warning} Oops!**\nNo permission to execute this command.\n\nThe command **\`/${interaction.commandName}\`** cannot be executed in this server.`
) )
.setColor(embedOptions.colors.warning) .setColor(embedOptions.colors.warning)
] ]