mirror of
https://github.com/darksaid98/cadence-discord-bot.git
synced 2026-12-03 14:38:49 +00:00
organize command files into one folder
This commit is contained in:
1 parent
e85cd4dfc2
commit
676c915e6e
26 files changed
+158
-168
No files matched your search
@@ -0,0 +1,150 @@
|
||||
import { GuildQueue, GuildQueueHistory, Track, useHistory, useQueue } from 'discord-player';
|
||||
import { ChatInputCommandInteraction, EmbedBuilder, SlashCommandBuilder } from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkHistoryExists, checkQueueCurrentTrack } from '../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { Logger } from 'pino';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { TFunction } from 'i18next';
|
||||
import { formatSlashCommand } from '../../common/formattingUtils';
|
||||
|
||||
class BackCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(
|
||||
new SlashCommandBuilder()
|
||||
.setName('back')
|
||||
.addIntegerOption((option) => option.setName('position').setMinValue(1))
|
||||
);
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const history: GuildQueueHistory = useHistory(interaction.guild!.id)!;
|
||||
|
||||
await this.runValidators({ interaction, history, executionId }, [
|
||||
checkInVoiceChannel,
|
||||
checkSameVoiceChannel,
|
||||
checkHistoryExists,
|
||||
checkQueueCurrentTrack
|
||||
]);
|
||||
|
||||
const backToTrackInput: number = interaction.options.getInteger('position')!;
|
||||
|
||||
if (backToTrackInput) {
|
||||
return await this.handleBackToTrackPosition(logger, interaction, history, backToTrackInput, translator);
|
||||
} else {
|
||||
return await this.handleBackToPreviousTrack(logger, interaction, history, translator);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleBackToTrackPosition(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
history: GuildQueueHistory,
|
||||
backtoTrackPosition: number,
|
||||
translator: TFunction
|
||||
) {
|
||||
if (backtoTrackPosition > history.tracks.data.length) {
|
||||
return await this.handleTrackPositionHigherThanHistoryLength(
|
||||
backtoTrackPosition,
|
||||
history,
|
||||
logger,
|
||||
interaction,
|
||||
translator
|
||||
);
|
||||
} else {
|
||||
await history.back();
|
||||
const recoveredTrack: Track = history.currentTrack! ?? history.tracks.data[backtoTrackPosition - 1];
|
||||
logger.debug('Went back to specified track position in history.');
|
||||
return await this.respondWithSuccessEmbed(recoveredTrack, interaction, translator);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleTrackPositionHigherThanHistoryLength(
|
||||
backToTrackPosition: number,
|
||||
history: GuildQueueHistory,
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
translator: TFunction
|
||||
) {
|
||||
logger.debug('Specified track position was higher than total tracks.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.back.trackPositionHigherThanHistoryLength', {
|
||||
icon: this.embedOptions.icons.warning,
|
||||
count: history.tracks.data.length,
|
||||
backPosition: backToTrackPosition,
|
||||
historyCommand: formatSlashCommand('history', translator)
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async handleBackToPreviousTrack(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
history: GuildQueueHistory,
|
||||
translator: TFunction
|
||||
) {
|
||||
if (history.tracks.data.length === 0) {
|
||||
return await this.handleNoTracksInHistory(logger, interaction, translator);
|
||||
}
|
||||
|
||||
await history.back();
|
||||
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
const currentTrack: Track = queue.currentTrack!;
|
||||
logger.debug('Recovered track from history.');
|
||||
return await this.respondWithSuccessEmbed(currentTrack, interaction, translator);
|
||||
}
|
||||
private async handleNoTracksInHistory(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
translator: TFunction
|
||||
) {
|
||||
logger.debug('No tracks in history.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.back.trackHistoryEmpty', {
|
||||
icon: this.embedOptions.icons.warning,
|
||||
playCommand: formatSlashCommand('play', translator)
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async respondWithSuccessEmbed(
|
||||
recoveredTrack: Track,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
translator: TFunction
|
||||
) {
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(
|
||||
translator('commands.back.trackReplayed', {
|
||||
icon: this.embedOptions.icons.back,
|
||||
track: this.getDisplayTrackDurationAndUrl(recoveredTrack, translator)
|
||||
})
|
||||
)
|
||||
.setThumbnail(this.getTrackThumbnailUrl(recoveredTrack))
|
||||
.setColor(this.embedOptions.colors.success)
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default new BackCommand();
|
||||
@@ -0,0 +1,265 @@
|
||||
import config from 'config';
|
||||
import { GuildQueue, QueueFilters, useQueue } from 'discord-player';
|
||||
import {
|
||||
APIActionRowComponent,
|
||||
APIButtonComponent,
|
||||
APIMessageActionRowComponent,
|
||||
APIStringSelectComponent,
|
||||
ButtonBuilder,
|
||||
ButtonStyle,
|
||||
ChatInputCommandInteraction,
|
||||
ComponentType,
|
||||
EmbedBuilder,
|
||||
Message,
|
||||
SlashCommandBuilder,
|
||||
StringSelectMenuBuilder,
|
||||
StringSelectMenuOptionBuilder
|
||||
} from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import {
|
||||
BiquadFilterOptions,
|
||||
EqualizerFilterOptions,
|
||||
FFmpegFilterOptions,
|
||||
FilterOption
|
||||
} from '../../types/configTypes';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { TFunction } from 'i18next';
|
||||
|
||||
const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions');
|
||||
const biquadFilterOptions: BiquadFilterOptions = config.get('biquadFilterOptions');
|
||||
const equalizerFilterOptions: EqualizerFilterOptions = config.get('equalizerFilterOptions');
|
||||
|
||||
class FiltersCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
// TODO: Implement system for localized filter names and descriptions
|
||||
const data = localizeCommand(
|
||||
new SlashCommandBuilder()
|
||||
.setName('filters')
|
||||
.addStringOption((option) =>
|
||||
option
|
||||
.setName('type')
|
||||
.setRequired(false)
|
||||
.addChoices(
|
||||
{ value: 'ffmpeg', name: ' ' },
|
||||
{ value: 'biquad', name: ' ' },
|
||||
{ value: 'equalizer', name: ' ' },
|
||||
{ value: 'disable', name: ' ' }
|
||||
)
|
||||
)
|
||||
);
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
|
||||
await this.runValidators({ interaction, queue, executionId }, [
|
||||
checkInVoiceChannel,
|
||||
checkSameVoiceChannel,
|
||||
checkQueueExists,
|
||||
checkQueueCurrentTrack
|
||||
]);
|
||||
|
||||
const filterProvider: string = interaction.options.getString('type') || 'ffmpeg';
|
||||
|
||||
switch (filterProvider) {
|
||||
case 'ffmpeg':
|
||||
return await this.handleFfmpegFilters(logger, interaction, queue, translator);
|
||||
case 'biquad':
|
||||
return await this.handleBiquadFilters(logger, interaction, queue, translator);
|
||||
case 'equalizer':
|
||||
return await this.handleEqualizerFilters(logger, interaction, translator);
|
||||
case 'disable':
|
||||
return await this.disableAllFiltersAndRespondWithSuccess(logger, interaction, queue, translator);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleFfmpegFilters(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue<unknown>,
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
logger.debug('Handling ffmpeg filters.');
|
||||
const filterOptions: StringSelectMenuOptionBuilder[] = [];
|
||||
|
||||
ffmpegFilterOptions.availableFilters.forEach((filter: FilterOption) => {
|
||||
let isEnabled: boolean = false;
|
||||
|
||||
if (queue.filters.ffmpeg.filters.includes(filter.value as keyof QueueFilters)) {
|
||||
isEnabled = true;
|
||||
}
|
||||
|
||||
filterOptions.push(
|
||||
new StringSelectMenuOptionBuilder()
|
||||
.setLabel(filter.label)
|
||||
.setDescription(filter.description)
|
||||
.setValue(filter.value)
|
||||
.setEmoji(filter.emoji)
|
||||
.setDefault(isEnabled)
|
||||
);
|
||||
});
|
||||
|
||||
return await this.sendFiltersEmbed(logger, interaction, 'ffmpeg', filterOptions, translator);
|
||||
}
|
||||
|
||||
private async handleBiquadFilters(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue<unknown>,
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
logger.debug('Handling biquad filters.');
|
||||
const filterOptions: StringSelectMenuOptionBuilder[] = [];
|
||||
|
||||
biquadFilterOptions.availableFilters.forEach((filter: FilterOption) => {
|
||||
let isEnabled: boolean = false;
|
||||
if (queue.filters.biquad!.biquadFilter === (filter.value as keyof BiquadFilterType)) {
|
||||
isEnabled = true;
|
||||
}
|
||||
|
||||
filterOptions.push(
|
||||
new StringSelectMenuOptionBuilder()
|
||||
.setLabel(filter.label)
|
||||
.setDescription(filter.description)
|
||||
.setValue(filter.value)
|
||||
.setEmoji(filter.emoji)
|
||||
.setDefault(isEnabled)
|
||||
);
|
||||
});
|
||||
|
||||
return await this.sendFiltersEmbed(logger, interaction, 'biquad', filterOptions, translator);
|
||||
}
|
||||
|
||||
private async handleEqualizerFilters(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
logger.debug('Handling biquad filters.');
|
||||
const filterOptions: StringSelectMenuOptionBuilder[] = [];
|
||||
|
||||
equalizerFilterOptions.availableFilters.forEach((filter: FilterOption) => {
|
||||
filterOptions.push(
|
||||
new StringSelectMenuOptionBuilder()
|
||||
.setLabel(filter.label)
|
||||
.setDescription(filter.description)
|
||||
.setValue(filter.value)
|
||||
.setEmoji(filter.emoji)
|
||||
.setDefault(false)
|
||||
);
|
||||
});
|
||||
|
||||
return await this.sendFiltersEmbed(logger, interaction, 'equalizer', filterOptions, translator);
|
||||
}
|
||||
|
||||
private async sendFiltersEmbed(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
filterProvider: string,
|
||||
filterOptions: StringSelectMenuOptionBuilder[],
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
const actionRows = this.buildFilterActionRows(filterOptions, filterProvider, translator);
|
||||
|
||||
logger.debug('Sending info embed with action row components.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.filters.toggleFilterInstructions', {
|
||||
provider: filterProvider
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
],
|
||||
components: actionRows
|
||||
});
|
||||
}
|
||||
|
||||
private buildFilterActionRows(
|
||||
filterOptions: StringSelectMenuOptionBuilder[],
|
||||
filterProvider: string,
|
||||
translator: TFunction
|
||||
): APIActionRowComponent<APIMessageActionRowComponent>[] {
|
||||
const filterSelect: APIStringSelectComponent = new StringSelectMenuBuilder()
|
||||
.setCustomId(`filters-select-menu_${filterProvider}`)
|
||||
.setPlaceholder(
|
||||
filterProvider === 'ffmpeg'
|
||||
? translator('commands.filters.selectFilterPlaceholderMany')
|
||||
: translator('commands.filters.selectFilterPlaceholder')
|
||||
)
|
||||
.setMinValues(0)
|
||||
.setMaxValues(filterProvider === 'ffmpeg' ? ffmpegFilterOptions.maxFilters : 1)
|
||||
.addOptions(filterOptions)
|
||||
.toJSON();
|
||||
|
||||
const filterActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
|
||||
type: ComponentType.ActionRow,
|
||||
components: [filterSelect]
|
||||
};
|
||||
|
||||
const disableButton: APIButtonComponent = new ButtonBuilder()
|
||||
.setCustomId('filters-disable-button')
|
||||
.setStyle(ButtonStyle.Secondary)
|
||||
.setEmoji(this.embedOptions.icons.disable)
|
||||
.toJSON();
|
||||
|
||||
if (this.embedOptions.components.showButtonLabels) {
|
||||
disableButton.label = translator('commands.filters.disableAllFiltersButton');
|
||||
}
|
||||
|
||||
const disableFiltersActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
|
||||
type: ComponentType.ActionRow,
|
||||
components: [disableButton]
|
||||
};
|
||||
|
||||
return [filterActionRow, disableFiltersActionRow];
|
||||
}
|
||||
|
||||
private async disableAllFiltersAndRespondWithSuccess(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
if (queue.filters.ffmpeg.filters.length > 0) {
|
||||
queue.filters.ffmpeg.setFilters(false);
|
||||
}
|
||||
|
||||
if (queue.filters.biquad) {
|
||||
queue.filters.biquad.disable();
|
||||
}
|
||||
|
||||
if (queue.filters.equalizer) {
|
||||
queue.filters.equalizer.disable();
|
||||
}
|
||||
|
||||
logger.debug('Reset queue filters.');
|
||||
|
||||
logger.debug('Responding with success embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(
|
||||
translator('commands.filters.allFiltersDisabled', {
|
||||
icon: this.embedOptions.icons.success
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.success)
|
||||
],
|
||||
components: []
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default new FiltersCommand();
|
||||
@@ -0,0 +1,135 @@
|
||||
import {
|
||||
APIActionRowComponent,
|
||||
APIButtonComponent,
|
||||
APIMessageActionRowComponent,
|
||||
ButtonBuilder,
|
||||
ButtonStyle,
|
||||
ChatInputCommandInteraction,
|
||||
Collection,
|
||||
ComponentType,
|
||||
LocaleString,
|
||||
EmbedBuilder,
|
||||
SlashCommandBuilder,
|
||||
SlashCommandNumberOption,
|
||||
SlashCommandStringOption
|
||||
} from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { CommandMetadata, localizeCommand, translatorInstance, useServerTranslator } from '../../common/localeUtil';
|
||||
import { ExtendedClient } from '../../types/clientTypes';
|
||||
|
||||
class HelpCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(new SlashCommandBuilder().setName('help'));
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, client, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const commandEmbedString = await this.getCommandEmbedString(client!, interaction);
|
||||
|
||||
const components: APIMessageActionRowComponent[] = [];
|
||||
|
||||
if (this.botOptions.serverInviteUrl && this.botOptions.serverInviteUrl !== '') {
|
||||
const supportServerButton: APIButtonComponent = new ButtonBuilder()
|
||||
.setURL(this.botOptions.serverInviteUrl)
|
||||
.setStyle(ButtonStyle.Link)
|
||||
.setEmoji(this.embedOptions.icons.support)
|
||||
.setLabel(translator('commands.help.supportServerButton'))
|
||||
.toJSON();
|
||||
components.push(supportServerButton);
|
||||
}
|
||||
|
||||
if (this.botOptions.botInviteUrl && this.botOptions.botInviteUrl !== '') {
|
||||
const addBotButton: APIButtonComponent = new ButtonBuilder()
|
||||
.setURL(this.botOptions.botInviteUrl)
|
||||
.setStyle(ButtonStyle.Link)
|
||||
.setEmoji(this.embedOptions.icons.bot)
|
||||
.setLabel(translator('commands.help.addBotButton'))
|
||||
.toJSON();
|
||||
components.push(addBotButton);
|
||||
}
|
||||
|
||||
const embedActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
|
||||
type: ComponentType.ActionRow,
|
||||
components
|
||||
};
|
||||
|
||||
logger.debug('Responding with info embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.help.listTitle', {
|
||||
icon: this.embedOptions.icons.rule
|
||||
}) +
|
||||
'\n' +
|
||||
commandEmbedString
|
||||
)
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
],
|
||||
components: components.length > 0 ? [embedActionRow] : []
|
||||
});
|
||||
}
|
||||
|
||||
private getNonSystemCommands(client: ExtendedClient): Collection<string, BaseSlashCommandInteraction> {
|
||||
const clientSlashCommands = client.slashCommandInteractions;
|
||||
const nonSystemCommands = clientSlashCommands?.filter((command) => !command.isSystemCommand);
|
||||
|
||||
if (!nonSystemCommands) {
|
||||
throw new Error('No non-system commands found.');
|
||||
}
|
||||
|
||||
return nonSystemCommands;
|
||||
}
|
||||
|
||||
private async getCommandEmbedString(
|
||||
client: ExtendedClient,
|
||||
interaction: ChatInputCommandInteraction
|
||||
): Promise<string> {
|
||||
const commandCollection = this.getNonSystemCommands(client!);
|
||||
|
||||
const locale = interaction.guildLocale ?? 'en-US';
|
||||
const commandStringList = commandCollection.map((command: BaseSlashCommandInteraction) => {
|
||||
return this.getCommandString(command, locale);
|
||||
});
|
||||
|
||||
const commandString = commandStringList.join('\n');
|
||||
return commandString;
|
||||
}
|
||||
|
||||
private getCommandString(command: BaseSlashCommandInteraction, locale: LocaleString): string {
|
||||
const commandName = command.data.name;
|
||||
const metadataKey = `commands.${commandName}.metadata`;
|
||||
let translatedData: CommandMetadata | undefined = undefined;
|
||||
translatedData = translatorInstance.getResource(locale, 'bot', metadataKey) as CommandMetadata | undefined;
|
||||
|
||||
const commandParams: string = this.getCommandParams(command, locale);
|
||||
|
||||
const beta: string = command.isBeta ? `${this.embedOptions.icons.beta} ` : '';
|
||||
const newCommand: string = command.isNew ? `${this.embedOptions.icons.new} ` : '';
|
||||
|
||||
return `- **\`/${translatedData?.name ?? command.data.name}\`** ${commandParams}- ${beta}${newCommand}${
|
||||
translatedData?.description ?? command.data.description
|
||||
}`;
|
||||
}
|
||||
|
||||
private getCommandParams(command: BaseSlashCommandInteraction, locale: LocaleString): string {
|
||||
const commandName = command.data.name;
|
||||
const option = command.data.options[0];
|
||||
|
||||
if (option instanceof SlashCommandNumberOption || option instanceof SlashCommandStringOption) {
|
||||
const metadataKey = `commands.${commandName}.metadata.options.${option.name}`;
|
||||
let translatedData: CommandMetadata | undefined = undefined;
|
||||
translatedData = translatorInstance.getResource(locale, 'bot', metadataKey) as CommandMetadata | undefined;
|
||||
return `**\`${translatedData?.name ?? option.name}\`** `;
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
export default new HelpCommand();
|
||||
@@ -0,0 +1,253 @@
|
||||
import { GuildQueue, GuildQueueHistory, Track, useHistory, useQueue } from 'discord-player';
|
||||
import {
|
||||
APIActionRowComponent,
|
||||
APIButtonComponent,
|
||||
APIMessageActionRowComponent,
|
||||
ButtonBuilder,
|
||||
ButtonStyle,
|
||||
ChatInputCommandInteraction,
|
||||
ComponentType,
|
||||
EmbedBuilder,
|
||||
EmbedFooterData,
|
||||
SlashCommandBuilder
|
||||
} from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkHistoryExists } from '../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { TFunction } from 'i18next';
|
||||
import { formatRepeatModeDetailed, formatSlashCommand } from '../../common/formattingUtils';
|
||||
|
||||
class HistoryCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(
|
||||
new SlashCommandBuilder()
|
||||
.setName('history')
|
||||
.addIntegerOption((option) => option.setName('page').setMinValue(1))
|
||||
);
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const history: GuildQueueHistory = useHistory(interaction.guild!.id)!;
|
||||
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
|
||||
await this.runValidators({ interaction, history, executionId }, [
|
||||
checkInVoiceChannel,
|
||||
checkSameVoiceChannel,
|
||||
checkHistoryExists
|
||||
]);
|
||||
|
||||
const pageIndex: number = this.getPageIndex(interaction);
|
||||
const totalPages: number = this.getTotalPages(history);
|
||||
|
||||
if (pageIndex > totalPages - 1) {
|
||||
return await this.handleInvalidPage(logger, interaction, pageIndex, totalPages, translator);
|
||||
}
|
||||
|
||||
const historyTracksListString: string = this.getHistoryTracksListString(history, pageIndex, translator);
|
||||
|
||||
const currentTrack: Track = history.currentTrack!;
|
||||
if (currentTrack) {
|
||||
return await this.handleCurrentTrack(
|
||||
logger,
|
||||
interaction,
|
||||
queue,
|
||||
history,
|
||||
currentTrack,
|
||||
historyTracksListString,
|
||||
translator
|
||||
);
|
||||
}
|
||||
|
||||
return await this.handleNoCurrentTrack(
|
||||
logger,
|
||||
interaction,
|
||||
queue,
|
||||
history,
|
||||
historyTracksListString,
|
||||
translator
|
||||
);
|
||||
}
|
||||
|
||||
private async handleCurrentTrack(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
history: GuildQueueHistory,
|
||||
currentTrack: Track,
|
||||
historyTracksListString: string,
|
||||
translator: TFunction
|
||||
) {
|
||||
logger.debug('History exists with current track, gathering information.');
|
||||
|
||||
const components: APIMessageActionRowComponent[] = [];
|
||||
|
||||
const previousButton: APIButtonComponent = new ButtonBuilder()
|
||||
.setDisabled(queue.history.tracks.data.length > 0 ? false : true)
|
||||
.setCustomId(`action-previous-button_${currentTrack.id}`)
|
||||
.setStyle(ButtonStyle.Secondary)
|
||||
.setEmoji(this.embedOptions.icons.previousTrack)
|
||||
.toJSON();
|
||||
components.push(previousButton);
|
||||
|
||||
const playPauseButton: APIButtonComponent = new ButtonBuilder()
|
||||
.setCustomId(`action-pauseresume-button_${currentTrack.id}`)
|
||||
.setStyle(ButtonStyle.Secondary)
|
||||
.setEmoji(this.embedOptions.icons.pauseResumeTrack)
|
||||
.toJSON();
|
||||
components.push(playPauseButton);
|
||||
|
||||
const skipButton: APIButtonComponent = new ButtonBuilder()
|
||||
.setCustomId(`action-skip-button_${currentTrack.id}`)
|
||||
.setStyle(ButtonStyle.Secondary)
|
||||
.setEmoji(this.embedOptions.icons.nextTrack)
|
||||
.toJSON();
|
||||
components.push(skipButton);
|
||||
|
||||
if (this.embedOptions.components.showButtonLabels) {
|
||||
previousButton.label = translator('musicPlayerCommon.controls.previous');
|
||||
playPauseButton.label = queue.node.isPaused()
|
||||
? translator('musicPlayerCommon.controls.resume')
|
||||
: translator('musicPlayerCommon.controls.pause');
|
||||
skipButton.label = translator('musicPlayerCommon.controls.skip');
|
||||
}
|
||||
|
||||
const embedActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
|
||||
type: ComponentType.ActionRow,
|
||||
components
|
||||
};
|
||||
|
||||
logger.debug('Responding with info embed.');
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedQueueAuthor(interaction, queue, translator))
|
||||
.setDescription(
|
||||
this.getDisplayTrackPlayingStatus(queue, translator) +
|
||||
'\n' +
|
||||
`${this.getFormattedTrackUrl(currentTrack, translator)}\n` +
|
||||
`${translator('musicPlayerCommon.requestedBy', {
|
||||
user: this.getDisplayTrackRequestedBy(currentTrack, translator)
|
||||
})}\n` +
|
||||
`${this.getDisplayQueueProgressBar(queue, translator)}\n` +
|
||||
`${formatRepeatModeDetailed(queue.repeatMode, this.embedOptions, translator)}\n` +
|
||||
`${translator('commands.history.tracksInHistoryTitle', {
|
||||
icon: this.embedOptions.icons.queue
|
||||
})}\n` +
|
||||
historyTracksListString
|
||||
)
|
||||
.setThumbnail(this.getTrackThumbnailUrl(currentTrack))
|
||||
.setFooter(this.getDisplayFullFooterInfo(interaction, history, translator))
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
],
|
||||
components: [embedActionRow]
|
||||
});
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
private getDisplayTrackPlayingStatus = (queue: GuildQueue, translator: TFunction): string => {
|
||||
return queue.node.isPaused()
|
||||
? translator('musicPlayerCommon.nowPausedTitle', { icon: this.embedOptions.icons.paused })
|
||||
: translator('musicPlayerCommon.nowPlayingTitle', { icon: this.embedOptions.icons.audioPlaying });
|
||||
};
|
||||
|
||||
private async handleNoCurrentTrack(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
history: GuildQueueHistory,
|
||||
historyTracksListString: string,
|
||||
translator: TFunction
|
||||
) {
|
||||
logger.debug('History exists but there is no current track.');
|
||||
|
||||
logger.debug('Responding with info embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedQueueAuthor(interaction, queue, translator))
|
||||
.setDescription(
|
||||
translator('commands.history.tracksInHistoryTitle', {
|
||||
icon: this.embedOptions.icons.queue
|
||||
}) +
|
||||
'\n' +
|
||||
historyTracksListString
|
||||
)
|
||||
.setFooter(this.getDisplayFullFooterInfo(interaction, history, translator))
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async handleInvalidPage(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
pageIndex: number,
|
||||
totalPages: number,
|
||||
translator: TFunction
|
||||
) {
|
||||
logger.debug('Specified page was higher than total pages.');
|
||||
|
||||
logger.debug('Responding with warning embed.');
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.history.invalidPageNumber', {
|
||||
icon: this.embedOptions.icons.warning,
|
||||
page: pageIndex + 1,
|
||||
count: totalPages
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
private getPageIndex(interaction: ChatInputCommandInteraction): number {
|
||||
return (interaction.options.getInteger('page') || 1) - 1;
|
||||
}
|
||||
|
||||
private getTotalPages(history: GuildQueueHistory): number {
|
||||
return Math.ceil(history.tracks.data.length / 10) || 1;
|
||||
}
|
||||
|
||||
private getHistoryTracksListString(history: GuildQueueHistory, pageIndex: number, translator: TFunction): string {
|
||||
if (!history || history.tracks.data.length === 0) {
|
||||
return translator('commands.history.emptyHistory', {
|
||||
playCommand: formatSlashCommand('play', translator)
|
||||
});
|
||||
}
|
||||
|
||||
return history.tracks.data
|
||||
.slice(pageIndex * 10, pageIndex * 10 + 10)
|
||||
.map((track, index) => {
|
||||
return `**${pageIndex * 10 + index + 1}.** ${this.getDisplayTrackDurationAndUrl(track, translator)}`;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
private getDisplayFullFooterInfo(
|
||||
interaction: ChatInputCommandInteraction,
|
||||
history: GuildQueueHistory,
|
||||
translator: TFunction
|
||||
): EmbedFooterData {
|
||||
const pagination = this.getFooterDisplayPageInfo(interaction, history, translator);
|
||||
|
||||
const fullFooterData = {
|
||||
text: `${pagination.text}`
|
||||
};
|
||||
|
||||
return fullFooterData;
|
||||
}
|
||||
}
|
||||
|
||||
export default new HistoryCommand();
|
||||
@@ -0,0 +1,133 @@
|
||||
import { GuildQueue, useMainPlayer, useQueue } from 'discord-player';
|
||||
import { ChatInputCommandInteraction, EmbedBuilder, GuildMember, Message, SlashCommandBuilder } from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { checkVoicePermissionJoinAndTalk } from '../../utils/validation/permissionValidator';
|
||||
import { Logger } from 'pino';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { formatSlashCommand } from '../../common/formattingUtils';
|
||||
import { TFunction } from 'i18next';
|
||||
|
||||
class JoinCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(new SlashCommandBuilder().setName('join'));
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
await this.runValidators({ interaction, executionId }, [checkInVoiceChannel, checkVoicePermissionJoinAndTalk]);
|
||||
|
||||
const existingQueue = useQueue(interaction.guild!.id);
|
||||
|
||||
if (existingQueue) {
|
||||
return await this.handleExisitingQueue(interaction, existingQueue, translator);
|
||||
}
|
||||
|
||||
const queue = this.createQueue(interaction);
|
||||
if (!queue) {
|
||||
return await this.handleCouldNotConnect(interaction, translator);
|
||||
}
|
||||
|
||||
await this.connectToVoiceChannel(logger, queue, interaction);
|
||||
if (!queue.dispatcher) {
|
||||
return await this.handleCouldNotConnect(interaction, translator);
|
||||
}
|
||||
|
||||
logger.debug('Responding with success embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(
|
||||
translator('commands.join.joinedChannel', {
|
||||
icon: this.embedOptions.icons.success,
|
||||
channel: `<#${queue.dispatcher.channel.id}>`,
|
||||
playCommand: formatSlashCommand('play', translator)
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.success)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private createQueue(interaction: ChatInputCommandInteraction): GuildQueue | undefined {
|
||||
try {
|
||||
const player = useMainPlayer();
|
||||
const createdQueue = player?.queues.create(interaction.guild!.id, {
|
||||
...this.playerOptions,
|
||||
maxSize: this.playerOptions.maxQueueSize,
|
||||
volume: this.playerOptions.defaultVolume,
|
||||
metadata: {
|
||||
channel: interaction.channel,
|
||||
client: interaction.client
|
||||
}
|
||||
});
|
||||
return createdQueue;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private async connectToVoiceChannel(
|
||||
logger: Logger,
|
||||
queue: GuildQueue,
|
||||
interaction: ChatInputCommandInteraction
|
||||
): Promise<void> {
|
||||
try {
|
||||
logger.debug('Connecting to channel.');
|
||||
const channel = (interaction.member! as GuildMember).voice.channel!;
|
||||
await queue.connect(channel);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private async handleCouldNotConnect(
|
||||
interaction: ChatInputCommandInteraction,
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(
|
||||
translator('commands.join.couldNotJoin', {
|
||||
icon: this.embedOptions.icons.warning
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async handleExisitingQueue(
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
const connectedChannel = queue.dispatcher?.channel;
|
||||
const channelMention = connectedChannel?.id ? `<#${connectedChannel.id}>` : '<#0>';
|
||||
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(
|
||||
translator('commands.join.alreadyConnected', {
|
||||
icon: this.embedOptions.icons.warning,
|
||||
channel: channelMention,
|
||||
leaveCommand: formatSlashCommand('leave', translator)
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default new JoinCommand();
|
||||
@@ -0,0 +1,55 @@
|
||||
import { GuildQueue, useQueue } from 'discord-player';
|
||||
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkQueueExists } from '../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { formatSlashCommand } from '../../common/formattingUtils';
|
||||
|
||||
class LeaveCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(new SlashCommandBuilder().setName('leave'));
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
|
||||
await this.runValidators({ interaction, queue, executionId }, [
|
||||
checkInVoiceChannel,
|
||||
checkSameVoiceChannel,
|
||||
checkQueueExists
|
||||
]);
|
||||
|
||||
logger.debug('Deleting queue.');
|
||||
this.deleteQueue(queue);
|
||||
|
||||
logger.debug('Responding with success embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(
|
||||
translator('commands.leave.leavingChannel', {
|
||||
icon: this.embedOptions.icons.success,
|
||||
playCommand: formatSlashCommand('play', translator)
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.success)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private deleteQueue(queue: GuildQueue): void {
|
||||
if (!queue.deleted) {
|
||||
queue.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default new LeaveCommand();
|
||||
@@ -0,0 +1,187 @@
|
||||
import { GuildQueue, QueueRepeatMode, useQueue } from 'discord-player';
|
||||
import {
|
||||
ChatInputCommandInteraction,
|
||||
EmbedBuilder,
|
||||
Message,
|
||||
SlashCommandBuilder,
|
||||
SlashCommandIntegerOption
|
||||
} from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkQueueExists } from '../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { TFunction } from 'i18next';
|
||||
import { formatRepeatMode } from '../../common/formattingUtils';
|
||||
|
||||
class LoopCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(
|
||||
new SlashCommandBuilder()
|
||||
.setName('loop')
|
||||
.addIntegerOption(() =>
|
||||
new SlashCommandIntegerOption()
|
||||
.setName('mode')
|
||||
.setRequired(false)
|
||||
.addChoices(
|
||||
{ value: QueueRepeatMode.TRACK, name: ' ' },
|
||||
{ value: QueueRepeatMode.QUEUE, name: ' ' },
|
||||
{ value: QueueRepeatMode.AUTOPLAY, name: ' ' },
|
||||
{ value: QueueRepeatMode.OFF, name: ' ' }
|
||||
)
|
||||
)
|
||||
);
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
|
||||
await this.runValidators({ interaction, queue, executionId }, [
|
||||
checkInVoiceChannel,
|
||||
checkSameVoiceChannel,
|
||||
checkQueueExists
|
||||
]);
|
||||
|
||||
const userInputRepeatMode: QueueRepeatMode = interaction.options.getInteger('mode')!;
|
||||
const currentRepeatMode: QueueRepeatMode = queue.repeatMode;
|
||||
|
||||
if (!userInputRepeatMode && userInputRepeatMode !== 0) {
|
||||
return await this.handleNoInputMode(logger, interaction, currentRepeatMode, translator);
|
||||
}
|
||||
|
||||
if (userInputRepeatMode === currentRepeatMode) {
|
||||
return await this.handleSameMode(logger, interaction, userInputRepeatMode, translator);
|
||||
}
|
||||
|
||||
return await this.handleChangeMode(
|
||||
logger,
|
||||
interaction,
|
||||
queue,
|
||||
currentRepeatMode,
|
||||
userInputRepeatMode,
|
||||
translator
|
||||
);
|
||||
}
|
||||
|
||||
private async handleNoInputMode(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
currentRepeatMode: QueueRepeatMode,
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
logger.debug('No repeat mode was provided, responding with current repeat mode.');
|
||||
|
||||
const repeatModeEmbedIcon =
|
||||
currentRepeatMode === 3 ? this.embedOptions.icons.autoplay : this.embedOptions.icons.loop;
|
||||
const repeatModeEmbedName = formatRepeatMode(currentRepeatMode, translator);
|
||||
|
||||
logger.debug('Responding with info embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.loop.loopModeInformation', {
|
||||
icon: repeatModeEmbedIcon,
|
||||
mode: repeatModeEmbedName
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async handleSameMode(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
currentRepeatMode: QueueRepeatMode,
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
const repeatModeEmbedName = formatRepeatMode(currentRepeatMode, translator);
|
||||
logger.debug(`Loop mode is already set to '${repeatModeEmbedName}'.`);
|
||||
logger.debug('Responding with warning embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.loop.alreadySet', {
|
||||
icon: this.embedOptions.icons.warning,
|
||||
mode: repeatModeEmbedName
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async handleChangeMode(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
fromRepeatMode: QueueRepeatMode,
|
||||
toRepeatMode: QueueRepeatMode,
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
const newRepeatModeEmbedName = formatRepeatMode(toRepeatMode, translator);
|
||||
const getChangedRepeatModeEmbedReply = this.getChangedRepeatModeEmbedReply(
|
||||
fromRepeatMode,
|
||||
toRepeatMode,
|
||||
translator
|
||||
);
|
||||
|
||||
queue.setRepeatMode(toRepeatMode);
|
||||
logger.debug(`Loop mode changed to '${newRepeatModeEmbedName}'.`);
|
||||
|
||||
logger.debug('Responding with success embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(getChangedRepeatModeEmbedReply)
|
||||
.setColor(this.embedOptions.colors.success)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private getChangedRepeatModeEmbedReply(
|
||||
fromRepeatMode: QueueRepeatMode,
|
||||
toRepeatMode: QueueRepeatMode,
|
||||
translator: TFunction
|
||||
): string {
|
||||
const fromRepeatModeEmbedName = formatRepeatMode(fromRepeatMode, translator);
|
||||
const toRepeatModeEmbedName = formatRepeatMode(toRepeatMode, translator);
|
||||
|
||||
let repeatModeIcon = this.embedOptions.icons.looping;
|
||||
let newRepeatModeMessage: string = translator('commands.loop.willNowPlay', {
|
||||
mode: toRepeatModeEmbedName
|
||||
});
|
||||
|
||||
if (toRepeatMode === QueueRepeatMode.OFF) {
|
||||
repeatModeIcon = this.embedOptions.icons.success;
|
||||
newRepeatModeMessage = translator('commands.loop.willNoLongerPlay', {
|
||||
mode: fromRepeatModeEmbedName
|
||||
});
|
||||
} else if (toRepeatMode === QueueRepeatMode.AUTOPLAY) {
|
||||
repeatModeIcon = this.embedOptions.icons.autoplaying;
|
||||
newRepeatModeMessage = translator('commands.loop.willAutoplay');
|
||||
}
|
||||
|
||||
return (
|
||||
translator('commands.loop.modeChanged', {
|
||||
icon: repeatModeIcon,
|
||||
fromName: fromRepeatModeEmbedName,
|
||||
toName: toRepeatModeEmbedName
|
||||
}) +
|
||||
'\n' +
|
||||
'\n' +
|
||||
newRepeatModeMessage
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default new LoopCommand();
|
||||
@@ -0,0 +1,242 @@
|
||||
import { LyricsData, lyricsExtractor } from '@discord-player/extractor';
|
||||
import { GuildQueue, Player, QueryType, SearchResult, Track, useMainPlayer, useQueue } from 'discord-player';
|
||||
import { ChatInputCommandInteraction, EmbedBuilder, Message, SlashCommandBuilder } from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { TFunction } from 'i18next';
|
||||
|
||||
class LyricsCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(
|
||||
new SlashCommandBuilder()
|
||||
.setName('lyrics')
|
||||
.addStringOption((option) =>
|
||||
option.setName('query').setRequired(false).setMinLength(2).setMaxLength(500).setAutocomplete(true)
|
||||
)
|
||||
);
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
const query: string = interaction.options.getString('query')!;
|
||||
|
||||
if (!query) {
|
||||
await this.runValidators({ interaction, queue, executionId }, [
|
||||
checkInVoiceChannel,
|
||||
checkSameVoiceChannel,
|
||||
checkQueueExists,
|
||||
checkQueueCurrentTrack
|
||||
]);
|
||||
}
|
||||
|
||||
const geniusSearchQuery: string = this.getGeniusSearchQuery(logger, query, queue);
|
||||
const [playerSearchResult, geniusLyricsResult] = await Promise.all([
|
||||
this.getPlayerSearchResult(logger, query),
|
||||
this.getGeniusLyricsResult(logger, geniusSearchQuery)
|
||||
]);
|
||||
const finalLyricsData: LyricsData | null = this.validateGeniusLyricsResult(
|
||||
logger,
|
||||
geniusLyricsResult,
|
||||
playerSearchResult,
|
||||
queue
|
||||
);
|
||||
|
||||
if (!finalLyricsData) {
|
||||
logger.debug('No matching lyrics found.');
|
||||
return await this.sendNoLyricsFoundEmbed(logger, interaction, geniusSearchQuery, translator);
|
||||
}
|
||||
|
||||
if (finalLyricsData.lyrics.length > 3800) {
|
||||
return await this.sendMultipleLyricsMessages(logger, interaction, finalLyricsData, translator);
|
||||
}
|
||||
|
||||
return await this.sendLyricsEmbed(logger, interaction, finalLyricsData, translator);
|
||||
}
|
||||
|
||||
private getGeniusSearchQuery(logger: Logger, query: string, queue: GuildQueue): string {
|
||||
const geniusSearchQuery =
|
||||
query ?? queue.currentTrack!.title.slice(0, 50) + ' ' + queue.currentTrack!.author.split(', ')[0];
|
||||
logger.debug(`Using query for genius search: '${geniusSearchQuery}'`);
|
||||
return geniusSearchQuery;
|
||||
}
|
||||
|
||||
private async getPlayerSearchResult(logger: Logger, query: string): Promise<Track | null> {
|
||||
if (!query) {
|
||||
return null;
|
||||
}
|
||||
logger.debug(`Query input provided, using query '${query}' for player.search().`);
|
||||
const player: Player = useMainPlayer()!;
|
||||
const searchResults: SearchResult | null = await player
|
||||
.search(query, {
|
||||
searchEngine: QueryType.SPOTIFY_SEARCH
|
||||
})
|
||||
.catch(() => null);
|
||||
|
||||
if (!searchResults || searchResults.tracks.length === 0) {
|
||||
logger.debug('No search results using player.search() found.');
|
||||
return null;
|
||||
}
|
||||
|
||||
return searchResults.tracks[0];
|
||||
}
|
||||
|
||||
private async getGeniusLyricsResult(logger: Logger, geniusSearchQuery: string): Promise<LyricsData | null> {
|
||||
const genius = lyricsExtractor();
|
||||
let geniusLyricsResult: LyricsData | null = await genius.search(geniusSearchQuery).catch(() => null);
|
||||
|
||||
if (!geniusLyricsResult && geniusSearchQuery.length > 20) {
|
||||
logger.debug('No lyrics found, trying again with shorter query.');
|
||||
geniusLyricsResult = await this.retryGeniusLyricsSearchSorterQuery(logger, geniusSearchQuery);
|
||||
}
|
||||
|
||||
return geniusLyricsResult;
|
||||
}
|
||||
|
||||
private async retryGeniusLyricsSearchSorterQuery(
|
||||
logger: Logger,
|
||||
geniusSearchQuery: string
|
||||
): Promise<LyricsData | null> {
|
||||
if (geniusSearchQuery.length < 10) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const retryQuery: string = geniusSearchQuery.slice(0, geniusSearchQuery.length - 10);
|
||||
const retryLyricsResult: LyricsData | null = await this.getGeniusLyricsResult(logger, retryQuery);
|
||||
|
||||
// recursively try again with shorter query
|
||||
if (!retryLyricsResult) {
|
||||
return this.retryGeniusLyricsSearchSorterQuery(logger, retryQuery);
|
||||
}
|
||||
|
||||
return retryLyricsResult;
|
||||
}
|
||||
|
||||
private validateGeniusLyricsResult(
|
||||
logger: Logger,
|
||||
geniusLyricsResult: LyricsData | null,
|
||||
playerSearchResult: Track | null,
|
||||
queue: GuildQueue
|
||||
): LyricsData | null {
|
||||
if (geniusLyricsResult && !this.doesArtistNameMatch(playerSearchResult, geniusLyricsResult, queue)) {
|
||||
logger.debug('Found Genius lyrics but artist name did not match from player.search() result.');
|
||||
geniusLyricsResult = null;
|
||||
}
|
||||
|
||||
if (!geniusLyricsResult || geniusLyricsResult.lyrics.length === 0) {
|
||||
logger.debug('No Genius lyrics found.');
|
||||
geniusLyricsResult = null;
|
||||
}
|
||||
|
||||
return geniusLyricsResult;
|
||||
}
|
||||
|
||||
private doesArtistNameMatch(
|
||||
playerSearchResult: Track | null,
|
||||
geniusLyricsResult: LyricsData,
|
||||
queue: GuildQueue
|
||||
): boolean {
|
||||
const playerAuthorLower = playerSearchResult?.author.toLowerCase() ?? queue.currentTrack!.author.toLowerCase();
|
||||
const geniusArtistNameLower = geniusLyricsResult.artist.name.toLowerCase();
|
||||
|
||||
return (
|
||||
playerAuthorLower.includes(geniusArtistNameLower) ||
|
||||
geniusArtistNameLower.includes(playerAuthorLower) ||
|
||||
geniusArtistNameLower.includes(playerAuthorLower.split(', ')[0])
|
||||
);
|
||||
}
|
||||
|
||||
private async sendNoLyricsFoundEmbed(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
geniusSearchQuery: string,
|
||||
translator: TFunction
|
||||
) {
|
||||
logger.debug('Responding with warning embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.lyrics.noLyricsFound', {
|
||||
icon: this.embedOptions.icons.warning,
|
||||
query: geniusSearchQuery
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async sendMultipleLyricsMessages(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
geniusLyricsResult: LyricsData,
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
logger.debug('Lyrics text too long, splitting into multiple messages.');
|
||||
const messageCount: number = Math.ceil(geniusLyricsResult.lyrics.length / 3800);
|
||||
const embedList: EmbedBuilder[] = [];
|
||||
embedList.push(
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.lyrics.lyricsEmbed', {
|
||||
icon: this.embedOptions.icons.queue,
|
||||
trackTitle: geniusLyricsResult.title,
|
||||
trackUrl: geniusLyricsResult.url,
|
||||
artistName: geniusLyricsResult.artist.name,
|
||||
artistUrl: geniusLyricsResult.artist.url
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
);
|
||||
for (let i: number = 0; i < messageCount; i++) {
|
||||
logger.debug(`Adding message ${i + 1} of ${messageCount} to embed list.`);
|
||||
const message: string = geniusLyricsResult.lyrics.slice(i * 3800, (i + 1) * 3800);
|
||||
embedList.push(
|
||||
new EmbedBuilder().setDescription(`\`\`\`fix\n${message}\`\`\``).setColor(this.embedOptions.colors.info)
|
||||
);
|
||||
}
|
||||
|
||||
logger.debug('Responding with multiple info embeds.');
|
||||
return await interaction.editReply({
|
||||
embeds: embedList
|
||||
});
|
||||
}
|
||||
|
||||
private async sendLyricsEmbed(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
geniusLyricsResult: LyricsData,
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
logger.debug('Responding with info embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.lyrics.lyricsEmbed', {
|
||||
icon: this.embedOptions.icons.queue,
|
||||
trackTitle: geniusLyricsResult.title,
|
||||
trackUrl: geniusLyricsResult.url,
|
||||
artistName: geniusLyricsResult.artist.name,
|
||||
artistUrl: geniusLyricsResult.artist.url
|
||||
}) +
|
||||
'\n' +
|
||||
'\n' +
|
||||
`\`\`\`fix\n${geniusLyricsResult.lyrics}\`\`\``
|
||||
)
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default new LyricsCommand();
|
||||
@@ -0,0 +1,127 @@
|
||||
import { GuildQueue, Track, useQueue } from 'discord-player';
|
||||
import { ChatInputCommandInteraction, EmbedBuilder, SlashCommandBuilder } from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { Logger } from 'pino';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { TFunction } from 'i18next';
|
||||
import { formatSlashCommand } from '../../common/formattingUtils';
|
||||
|
||||
class MoveCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(
|
||||
new SlashCommandBuilder()
|
||||
.setName('move')
|
||||
.addIntegerOption((option) => option.setName('from').setMinValue(1).setRequired(true))
|
||||
.addIntegerOption((option) => option.setName('to').setMinValue(1).setRequired(true))
|
||||
);
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
|
||||
await this.runValidators({ interaction, queue, executionId }, [
|
||||
checkInVoiceChannel,
|
||||
checkSameVoiceChannel,
|
||||
checkQueueExists,
|
||||
checkQueueCurrentTrack
|
||||
]);
|
||||
|
||||
const fromPositionInput: number = interaction.options.getInteger('from')!;
|
||||
const toPositionInput: number = interaction.options.getInteger('to')!;
|
||||
return await this.handleMoveTrackToPosition(
|
||||
logger,
|
||||
interaction,
|
||||
queue,
|
||||
fromPositionInput,
|
||||
toPositionInput,
|
||||
translator
|
||||
);
|
||||
}
|
||||
|
||||
private async handleMoveTrackToPosition(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
fromPosition: number,
|
||||
toPosition: number,
|
||||
translator: TFunction
|
||||
) {
|
||||
if (fromPosition > queue.tracks.data.length || toPosition > queue.tracks.data.length) {
|
||||
logger.debug('One of the specified track positions was higher than total tracks.');
|
||||
return await this.handleTrackPositionHigherThanQueueLength(
|
||||
fromPosition,
|
||||
toPosition,
|
||||
queue,
|
||||
logger,
|
||||
interaction,
|
||||
translator
|
||||
);
|
||||
} else {
|
||||
const trackToMove: Track = queue.tracks.data[fromPosition - 1];
|
||||
queue.node.move(trackToMove, toPosition - 1);
|
||||
logger.debug(`Moved track from position ${fromPosition} to position ${toPosition} in queue`);
|
||||
return await this.respondWithSuccessEmbed(trackToMove, interaction, fromPosition, toPosition, translator);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleTrackPositionHigherThanQueueLength(
|
||||
fromPosition: number,
|
||||
toPosition: number,
|
||||
queue: GuildQueue,
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
translator: TFunction
|
||||
) {
|
||||
logger.debug('One of the specified track positions was higher than total tracks.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.move.trackPositionHigherThanQueueLength', {
|
||||
icon: this.embedOptions.icons.warning,
|
||||
fromPosition,
|
||||
toPosition,
|
||||
count: queue.tracks.data.length,
|
||||
queueCommand: formatSlashCommand('queue', translator)
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async respondWithSuccessEmbed(
|
||||
movedTrack: Track,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
fromPosition: number,
|
||||
toPosition: number,
|
||||
translator: TFunction
|
||||
) {
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(
|
||||
translator('commands.move.trackMoved', {
|
||||
icon: this.embedOptions.icons.moved,
|
||||
track: this.getDisplayTrackDurationAndUrl(movedTrack, translator),
|
||||
fromPosition,
|
||||
toPosition
|
||||
})
|
||||
)
|
||||
.setThumbnail(this.getTrackThumbnailUrl(movedTrack))
|
||||
.setColor(this.embedOptions.colors.success)
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default new MoveCommand();
|
||||
@@ -0,0 +1,195 @@
|
||||
import { GuildQueue, Track, useQueue } from 'discord-player';
|
||||
import {
|
||||
APIActionRowComponent,
|
||||
APIButtonComponent,
|
||||
APIMessageActionRowComponent,
|
||||
ButtonBuilder,
|
||||
ButtonStyle,
|
||||
ComponentType,
|
||||
EmbedBuilder,
|
||||
EmbedField,
|
||||
SlashCommandBuilder
|
||||
} from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType, TrackMetadata } from '../../types/interactionTypes';
|
||||
import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { TFunction } from 'i18next';
|
||||
import { formatRepeatModeDetailed } from '../../common/formattingUtils';
|
||||
|
||||
class NowPlayingCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(new SlashCommandBuilder().setName('nowplaying'));
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
|
||||
await this.runValidators({ interaction, queue, executionId }, [
|
||||
checkInVoiceChannel,
|
||||
checkSameVoiceChannel,
|
||||
checkQueueExists,
|
||||
checkQueueCurrentTrack
|
||||
]);
|
||||
|
||||
const tracksInQueueCount: number = queue.tracks.data.length;
|
||||
const currentTrack: Track = queue.currentTrack!;
|
||||
const displayTrackUrl: string = this.getFormattedTrackUrl(currentTrack, translator);
|
||||
const displayTrackRequestedBy: string = this.getDisplayTrackRequestedBy(currentTrack, translator);
|
||||
const displayTrackPlayingStatus: string = this.getDisplayTrackPlayingStatus(queue, translator);
|
||||
const displayQueueRepeatMode: string = formatRepeatModeDetailed(
|
||||
queue.repeatMode,
|
||||
this.embedOptions,
|
||||
translator
|
||||
);
|
||||
const displayEmbedProgressBar: string = this.getDisplayQueueProgressBar(queue, translator);
|
||||
|
||||
const components: APIMessageActionRowComponent[] = [];
|
||||
|
||||
const previousButton: APIButtonComponent = new ButtonBuilder()
|
||||
.setDisabled(queue.history.tracks.data.length > 0 ? false : true)
|
||||
.setCustomId(`action-previous-button_${currentTrack.id}`)
|
||||
.setStyle(ButtonStyle.Secondary)
|
||||
.setEmoji(this.embedOptions.icons.previousTrack)
|
||||
.toJSON();
|
||||
components.push(previousButton);
|
||||
|
||||
const playPauseButton: APIButtonComponent = new ButtonBuilder()
|
||||
.setCustomId(`action-pauseresume-button_${currentTrack.id}`)
|
||||
.setStyle(ButtonStyle.Secondary)
|
||||
.setEmoji(this.embedOptions.icons.pauseResumeTrack)
|
||||
.toJSON();
|
||||
components.push(playPauseButton);
|
||||
|
||||
const skipButton: APIButtonComponent = new ButtonBuilder()
|
||||
.setCustomId(`action-skip-button_${currentTrack.id}`)
|
||||
.setStyle(ButtonStyle.Secondary)
|
||||
.setEmoji(this.embedOptions.icons.nextTrack)
|
||||
.toJSON();
|
||||
components.push(skipButton);
|
||||
|
||||
if (this.embedOptions.components.showButtonLabels) {
|
||||
previousButton.label = translator('musicPlayerCommon.controls.previous');
|
||||
playPauseButton.label = queue.node.isPaused()
|
||||
? translator('musicPlayerCommon.controls.resume')
|
||||
: translator('musicPlayerCommon.controls.pause');
|
||||
skipButton.label = translator('musicPlayerCommon.controls.skip');
|
||||
}
|
||||
|
||||
const embedActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
|
||||
type: ComponentType.ActionRow,
|
||||
components
|
||||
};
|
||||
|
||||
logger.debug('Sending info embed with action row components.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedQueueAuthor(interaction, queue, translator))
|
||||
.setDescription(
|
||||
`${displayTrackPlayingStatus}\n` +
|
||||
`${displayTrackUrl}\n` +
|
||||
`${translator('musicPlayerCommon.requestedBy', {
|
||||
user: displayTrackRequestedBy
|
||||
})}\n` +
|
||||
`${displayEmbedProgressBar}\n` +
|
||||
`${displayQueueRepeatMode}\n\n`
|
||||
)
|
||||
.addFields(this.getEmbedFields(currentTrack, translator))
|
||||
.setFooter({
|
||||
text: tracksInQueueCount
|
||||
? translator('commands.nowplaying.otherTracksInQueue', { count: tracksInQueueCount })
|
||||
: ' '
|
||||
})
|
||||
.setThumbnail(this.getTrackThumbnailUrl(queue.currentTrack!))
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
],
|
||||
components: [embedActionRow]
|
||||
});
|
||||
}
|
||||
|
||||
private getDisplayPlays(currentTrack: Track | undefined, translator: TFunction): string {
|
||||
const trackMetadata = currentTrack?.metadata as TrackMetadata;
|
||||
|
||||
return translator('commands.nowplaying.playCount', {
|
||||
count: currentTrack?.views || trackMetadata?.bridge?.views || 0
|
||||
});
|
||||
}
|
||||
|
||||
private getDisplayTrackAuthor(currentTrack: Track | undefined, translator: TFunction): string {
|
||||
let author = currentTrack?.author;
|
||||
if (!author || author === 'cdn.discordapp.com') {
|
||||
author = translator('musicPlayerCommon.unavailableAuthor');
|
||||
}
|
||||
return author;
|
||||
}
|
||||
|
||||
private getTrackSourceString(currentTrack: Track, translator: TFunction): string {
|
||||
const sourceStringsFormatted: Map<string, string> = new Map([
|
||||
['youtube', 'YouTube'],
|
||||
['soundcloud', 'SoundCloud'],
|
||||
['spotify', 'Spotify'],
|
||||
['apple_music', 'Apple Music'],
|
||||
['arbitrary', translator('commands.pause.directSource')]
|
||||
]);
|
||||
|
||||
return (
|
||||
sourceStringsFormatted.get(currentTrack.raw.source!) ?? translator('musicPlayerCommon.unavailableSource')
|
||||
);
|
||||
}
|
||||
|
||||
private getTrackSourceIcon(currentTrack: Track): string {
|
||||
const sourceIcons: Map<string, string> = new Map([
|
||||
['youtube', this.embedOptions.icons.sourceYouTube],
|
||||
['soundcloud', this.embedOptions.icons.sourceSoundCloud],
|
||||
['spotify', this.embedOptions.icons.sourceSpotify],
|
||||
['apple_music', this.embedOptions.icons.sourceAppleMusic],
|
||||
['arbitrary', this.embedOptions.icons.sourceArbitrary]
|
||||
]);
|
||||
|
||||
return sourceIcons.get(currentTrack.raw.source!) ?? '';
|
||||
}
|
||||
|
||||
private getDisplayTrackSource(currentTrack: Track, translator: TFunction) {
|
||||
const trackSource: string = this.getTrackSourceString(currentTrack, translator);
|
||||
const trackSourceIcon: string = this.getTrackSourceIcon(currentTrack) ?? '';
|
||||
|
||||
return `**${trackSourceIcon} [${trackSource}](${currentTrack.raw.url ?? currentTrack.url})**`;
|
||||
}
|
||||
|
||||
private getDisplayTrackPlayingStatus = (queue: GuildQueue, translator: TFunction): string => {
|
||||
return queue.node.isPaused()
|
||||
? translator('musicPlayerCommon.nowPausedTitle', { icon: this.embedOptions.icons.paused })
|
||||
: translator('musicPlayerCommon.nowPlayingTitle', { icon: this.embedOptions.icons.audioPlaying });
|
||||
};
|
||||
|
||||
private getEmbedFields = (currentTrack: Track, translator: TFunction): EmbedField[] => {
|
||||
const fields: EmbedField[] = [
|
||||
{
|
||||
name: translator('commands.nowplaying.embedFields.author'),
|
||||
value: this.getDisplayTrackAuthor(currentTrack, translator),
|
||||
inline: true
|
||||
},
|
||||
{
|
||||
name: translator('commands.nowplaying.embedFields.plays'),
|
||||
value: this.getDisplayPlays(currentTrack, translator),
|
||||
inline: true
|
||||
},
|
||||
{
|
||||
name: translator('commands.nowplaying.embedFields.source'),
|
||||
value: this.getDisplayTrackSource(currentTrack, translator),
|
||||
inline: true
|
||||
}
|
||||
];
|
||||
|
||||
return fields;
|
||||
};
|
||||
}
|
||||
|
||||
export default new NowPlayingCommand();
|
||||
@@ -0,0 +1,63 @@
|
||||
import { GuildQueue, Track, useQueue } from 'discord-player';
|
||||
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
|
||||
class PauseCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(new SlashCommandBuilder().setName('pause'));
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
|
||||
await this.runValidators({ interaction, queue, executionId }, [
|
||||
checkInVoiceChannel,
|
||||
checkSameVoiceChannel,
|
||||
checkQueueExists,
|
||||
checkQueueCurrentTrack
|
||||
]);
|
||||
|
||||
const currentTrack: Track = queue.currentTrack!;
|
||||
|
||||
this.togglePauseState(logger, queue);
|
||||
|
||||
logger.debug('Responding with success embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(
|
||||
translator(
|
||||
queue.node.isPaused()
|
||||
? 'commands.pause.pauseConfirmation'
|
||||
: 'commands.pause.resumeConfirmation',
|
||||
{
|
||||
icon: this.embedOptions.icons.success
|
||||
}
|
||||
) +
|
||||
'\n' +
|
||||
this.getDisplayTrackDurationAndUrl(currentTrack, translator)
|
||||
)
|
||||
.setThumbnail(currentTrack.thumbnail)
|
||||
.setColor(this.embedOptions.colors.success)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private togglePauseState(logger: Logger, queue: GuildQueue): void {
|
||||
queue.node.setPaused(!queue.node.isPaused());
|
||||
logger.debug(`Set paused state to ${queue.node.isPaused()}.`);
|
||||
}
|
||||
}
|
||||
|
||||
export default new PauseCommand();
|
||||
@@ -0,0 +1,371 @@
|
||||
import { GuildQueue, Player, SearchResult, Track, useMainPlayer, useQueue } from 'discord-player';
|
||||
import {
|
||||
ChatInputCommandInteraction,
|
||||
EmbedBuilder,
|
||||
EmbedFooterData,
|
||||
GuildMember,
|
||||
Message,
|
||||
SlashCommandBuilder
|
||||
} from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import { BaseSlashCommandInteraction, CustomError } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkVoicePermissionJoinAndTalk } from '../../utils/validation/permissionValidator';
|
||||
import { transformQuery } from '../../utils/validation/searchQueryValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { TFunction } from 'i18next';
|
||||
import { formatSlashCommand } from '../../common/formattingUtils';
|
||||
|
||||
class PlayCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(
|
||||
new SlashCommandBuilder()
|
||||
.setName('play')
|
||||
.addStringOption((option) =>
|
||||
option.setName('query').setRequired(true).setMinLength(2).setMaxLength(500).setAutocomplete(true)
|
||||
)
|
||||
);
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
await this.runValidators({ interaction, executionId }, [checkInVoiceChannel]);
|
||||
|
||||
let queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
if (queue) {
|
||||
await this.runValidators({ interaction, queue, executionId }, [checkSameVoiceChannel]);
|
||||
} else {
|
||||
await this.runValidators({ interaction, executionId }, [checkVoicePermissionJoinAndTalk]);
|
||||
}
|
||||
|
||||
const player = useMainPlayer()!;
|
||||
const searchQuery = interaction.options.getString('query')!;
|
||||
const transformedQuery = transformQuery({ query: searchQuery, executionId });
|
||||
|
||||
const searchResult = await this.searchTrack(player, transformedQuery, interaction, logger);
|
||||
if (!searchResult || searchResult.tracks.length === 0) {
|
||||
return await this.handleNoResultsFound(transformedQuery, interaction, logger, translator);
|
||||
}
|
||||
|
||||
queue = useQueue(interaction.guild!.id)!;
|
||||
const queueSize = queue?.size ?? 0;
|
||||
|
||||
if ((searchResult.playlist! && searchResult.tracks.length) > this.playerOptions.maxQueueSize - queueSize) {
|
||||
return await this.handlePlaylistTooLarge(searchQuery, interaction, logger, translator);
|
||||
}
|
||||
|
||||
const track: Track | void = await this.addResultsToPlayer(
|
||||
player,
|
||||
searchResult,
|
||||
interaction,
|
||||
logger,
|
||||
executionId,
|
||||
searchQuery
|
||||
);
|
||||
|
||||
if (!track) {
|
||||
logger.error('Failed to add track to player.');
|
||||
throw new Error('Failed to add track to player.');
|
||||
}
|
||||
|
||||
return await this.handleResultAddedToQueue(track, searchResult, interaction, logger, translator);
|
||||
}
|
||||
|
||||
private async searchTrack(
|
||||
player: Player,
|
||||
transformedQuery: string,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
logger: Logger
|
||||
): Promise<SearchResult | undefined> {
|
||||
logger.debug(`Searching for track with query: '${transformedQuery}'.`);
|
||||
let searchResult: SearchResult | undefined;
|
||||
try {
|
||||
searchResult = await player.search(transformedQuery, {
|
||||
requestedBy: interaction.user
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error, `Failed to search for track with player.search() with query: ${transformedQuery}.`);
|
||||
}
|
||||
return searchResult;
|
||||
}
|
||||
|
||||
private async addResultsToPlayer(
|
||||
player: Player,
|
||||
searchResult: SearchResult,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
logger: Logger,
|
||||
executionId: string,
|
||||
query: string
|
||||
): Promise<Track | void> {
|
||||
let track;
|
||||
try {
|
||||
logger.debug(`Attempting to add track with player.play(). Query: '${query}'.`);
|
||||
|
||||
({ track } = await player.play((interaction.member as GuildMember).voice.channel!, searchResult, {
|
||||
requestedBy: interaction.user,
|
||||
nodeOptions: {
|
||||
...this.playerOptions,
|
||||
maxSize: this.playerOptions.maxQueueSize,
|
||||
volume: this.playerOptions.defaultVolume,
|
||||
metadata: {
|
||||
channel: interaction.channel,
|
||||
client: interaction.client,
|
||||
requestedBy: interaction.user
|
||||
}
|
||||
}
|
||||
}));
|
||||
} catch (error) {
|
||||
if (error instanceof CustomError) {
|
||||
if (error.message.includes('Sign in to confirm your age')) {
|
||||
this.handleAgeConfirmationError(interaction, logger, executionId);
|
||||
}
|
||||
|
||||
if (error.message.includes('The following content may contain')) {
|
||||
this.handleSensitiveTopicError(interaction, logger, executionId);
|
||||
}
|
||||
|
||||
if (
|
||||
error.message === "Cannot read properties of null (reading 'createStream')" ||
|
||||
error.message.includes('Failed to fetch resources for ytdl streaming') ||
|
||||
error.message.includes('Could not extract stream for this track')
|
||||
) {
|
||||
this.handleStreamError(interaction, logger, executionId, error, query);
|
||||
}
|
||||
|
||||
if (error.message === 'Cancelled') {
|
||||
this.handleCancelledError(interaction, logger, executionId, query);
|
||||
}
|
||||
|
||||
logger.error(error, 'Failed to play track with player.play(), unhandled error.');
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return Promise.resolve();
|
||||
}
|
||||
return track;
|
||||
}
|
||||
|
||||
private async handleResultAddedToQueue(
|
||||
track: Track,
|
||||
searchResult: SearchResult,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
logger: Logger,
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
logger.debug('Result found and added with player.play(), added to queue.');
|
||||
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
const trackUrl = this.getDisplayTrackDurationAndUrl(track, translator);
|
||||
|
||||
let embedFooter: EmbedFooterData | undefined = this.getDisplayFooterTrackPosition(
|
||||
queue.tracks.data.length ?? 0,
|
||||
translator
|
||||
);
|
||||
let message =
|
||||
translator('commands.play.addedToQueueTitle', {
|
||||
icon: this.embedOptions.icons.success
|
||||
}) +
|
||||
'\n' +
|
||||
trackUrl;
|
||||
if (searchResult.playlist) {
|
||||
message =
|
||||
translator('commands.play.playlistAddedTitle', {
|
||||
icon: this.embedOptions.icons.success
|
||||
}) +
|
||||
'\n' +
|
||||
trackUrl +
|
||||
'\n' +
|
||||
'\n' +
|
||||
translator('commands.play.playlistAddedTrackCount', {
|
||||
count: searchResult.tracks.length,
|
||||
queueCommand: formatSlashCommand('queue', translator)
|
||||
});
|
||||
if (queue.tracks.data.length != searchResult.tracks.length) {
|
||||
const posistionFirstTrackInPlaylist = queue.tracks.data.length - searchResult.tracks.length + 1;
|
||||
embedFooter = this.getDisplayFooterTrackPosition(posistionFirstTrackInPlaylist, translator);
|
||||
}
|
||||
} else if (queue.currentTrack === track && queue.tracks.data.length === 0) {
|
||||
if (!this.embedOptions.behavior.enablePlayerStartMessages) {
|
||||
message =
|
||||
translator('musicPlayerCommon.nowPlayingTitle', {
|
||||
icon: this.embedOptions.icons.audioStartedPlaying
|
||||
}) +
|
||||
'\n' +
|
||||
trackUrl;
|
||||
embedFooter = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(message)
|
||||
.setThumbnail(this.getTrackThumbnailUrl(track))
|
||||
.setColor(this.embedOptions.colors.success);
|
||||
|
||||
if (embedFooter) {
|
||||
embed.setFooter(embedFooter);
|
||||
}
|
||||
|
||||
logger.debug('Responding with success embed.');
|
||||
|
||||
return await interaction.editReply({
|
||||
embeds: [embed]
|
||||
});
|
||||
}
|
||||
|
||||
private getDisplayFooterTrackPosition(position: number, translator: TFunction): EmbedFooterData {
|
||||
const fullFooterData = {
|
||||
text: translator('commands.play.footerAddedPosition', {
|
||||
position: position
|
||||
})
|
||||
};
|
||||
|
||||
return fullFooterData;
|
||||
}
|
||||
|
||||
private async handleNoResultsFound(
|
||||
transformedQuery: string,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
logger: Logger,
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
logger.debug(`No results found for query: '${transformedQuery}'`);
|
||||
|
||||
logger.debug('Responding with warning embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.play.trackNotFound', {
|
||||
icon: this.embedOptions.icons.warning,
|
||||
query: transformedQuery
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async handlePlaylistTooLarge(
|
||||
query: string,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
logger: Logger,
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
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()
|
||||
.setDescription(
|
||||
translator('commands.play.playlistTooLarge', {
|
||||
icon: this.embedOptions.icons.warning,
|
||||
count: this.playerOptions.maxQueueSize
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async handleAgeConfirmationError(
|
||||
interaction: ChatInputCommandInteraction,
|
||||
logger: Logger,
|
||||
executionId: string
|
||||
): Promise<Message> {
|
||||
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()
|
||||
.setDescription(
|
||||
`**${this.embedOptions.icons.warning} Cannot retrieve audio for track**\n` +
|
||||
'This audio source is age restricted and requires login to access. Because of this I cannot retrieve the audio for the track.\n\n' +
|
||||
`_If you think this message is incorrect, please submit a bug report in the **[support server](${this.botOptions.serverInviteUrl})**._`
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
.setFooter({ text: `Execution ID: ${executionId}` })
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async handleSensitiveTopicError(
|
||||
interaction: ChatInputCommandInteraction,
|
||||
logger: Logger,
|
||||
executionId: string
|
||||
): Promise<Message> {
|
||||
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()
|
||||
.setDescription(
|
||||
`**${this.embedOptions.icons.warning} Cannot retrieve audio for track**\n` +
|
||||
'This audio source cannot be played as the video source has a warning for graphic or sensistive topics. It requires a manual confirmation to to play the video, and because of this I am unable to extract the audio for this source.\n\n' +
|
||||
`_If you think this message is incorrect, please submit a bug report in the **[support server](${this.botOptions.serverInviteUrl})**._`
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
.setFooter({ text: `Execution ID: ${executionId}` })
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async handleStreamError(
|
||||
interaction: ChatInputCommandInteraction,
|
||||
logger: Logger,
|
||||
executionId: string,
|
||||
error: Error,
|
||||
query: string
|
||||
): Promise<Message> {
|
||||
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()
|
||||
.setDescription(
|
||||
`**${this.embedOptions.icons.error} Uh-oh... Failed to add track!**\n` +
|
||||
'After finding a result, I was unable to retrieve audio for the track.\n\n' +
|
||||
'You can try to perform the command again.\n\n' +
|
||||
`_If you think this message is incorrect, please submit a bug report in the **[support server](${this.botOptions.serverInviteUrl})**._`
|
||||
)
|
||||
.setColor(this.embedOptions.colors.error)
|
||||
.setFooter({ text: `Execution ID: ${executionId}` })
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async handleCancelledError(
|
||||
interaction: ChatInputCommandInteraction,
|
||||
logger: Logger,
|
||||
executionId: string,
|
||||
query: string
|
||||
): Promise<Message> {
|
||||
logger.debug(`Operation cancelled. Query: ${query}.`);
|
||||
|
||||
logger.debug('Responding with error embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
`**${this.embedOptions.icons.error} Uh-oh... Failed to add track!**` +
|
||||
'\nSomething unexpected happened and the operation was cancelled.\n\n' +
|
||||
'You can try to perform the command again.\n\n' +
|
||||
`_If you think this message is incorrect, please submit a bug report in the **[support server](${this.botOptions.serverInviteUrl})**._`
|
||||
)
|
||||
.setColor(this.embedOptions.colors.error)
|
||||
.setFooter({ text: `Execution ID: ${executionId}` })
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default new PlayCommand();
|
||||
@@ -0,0 +1,268 @@
|
||||
import { GuildQueue, Track, useQueue } from 'discord-player';
|
||||
import {
|
||||
APIActionRowComponent,
|
||||
APIButtonComponent,
|
||||
APIMessageActionRowComponent,
|
||||
ButtonBuilder,
|
||||
ButtonStyle,
|
||||
ChatInputCommandInteraction,
|
||||
ComponentType,
|
||||
EmbedBuilder,
|
||||
EmbedFooterData,
|
||||
SlashCommandBuilder
|
||||
} from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkQueueExists } from '../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { formatDuration, formatRepeatModeDetailed, formatSlashCommand } from '../../common/formattingUtils';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { TFunction } from 'i18next';
|
||||
|
||||
class QueueCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(
|
||||
new SlashCommandBuilder()
|
||||
.setName('queue')
|
||||
.addIntegerOption((option) => option.setName('page').setMinValue(1))
|
||||
);
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
|
||||
await this.runValidators({ interaction, queue, executionId }, [
|
||||
checkInVoiceChannel,
|
||||
checkSameVoiceChannel,
|
||||
checkQueueExists
|
||||
]);
|
||||
|
||||
const pageIndex: number = this.getPageIndex(interaction);
|
||||
const totalPages: number = this.getTotalPages(queue);
|
||||
|
||||
if (pageIndex > totalPages - 1) {
|
||||
return await this.handleInvalidPage(logger, interaction, pageIndex, totalPages, translator);
|
||||
}
|
||||
|
||||
const queueTracksListString: string = this.getQueueTracksListString(queue, pageIndex, translator);
|
||||
|
||||
const currentTrack: Track = queue.currentTrack!;
|
||||
if (currentTrack) {
|
||||
return await this.handleCurrentTrack(
|
||||
logger,
|
||||
interaction,
|
||||
queue,
|
||||
currentTrack,
|
||||
queueTracksListString,
|
||||
translator
|
||||
);
|
||||
}
|
||||
|
||||
return await this.handleNoCurrentTrack(logger, interaction, queue, queueTracksListString, translator);
|
||||
}
|
||||
|
||||
private async handleCurrentTrack(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
currentTrack: Track,
|
||||
queueTracksListString: string,
|
||||
translator: TFunction
|
||||
) {
|
||||
logger.debug('Queue exists with current track, gathering information.');
|
||||
|
||||
const components: APIMessageActionRowComponent[] = [];
|
||||
|
||||
const previousButton: APIButtonComponent = new ButtonBuilder()
|
||||
.setDisabled(queue.history.tracks.data.length > 0 ? false : true)
|
||||
.setCustomId(`action-previous-button_${currentTrack.id}`)
|
||||
.setStyle(ButtonStyle.Secondary)
|
||||
.setEmoji(this.embedOptions.icons.previousTrack)
|
||||
.toJSON();
|
||||
components.push(previousButton);
|
||||
|
||||
const playPauseButton: APIButtonComponent = new ButtonBuilder()
|
||||
.setCustomId(`action-pauseresume-button_${currentTrack.id}`)
|
||||
.setStyle(ButtonStyle.Secondary)
|
||||
.setEmoji(this.embedOptions.icons.pauseResumeTrack)
|
||||
.toJSON();
|
||||
components.push(playPauseButton);
|
||||
|
||||
const skipButton: APIButtonComponent = new ButtonBuilder()
|
||||
.setCustomId(`action-skip-button_${currentTrack.id}`)
|
||||
.setStyle(ButtonStyle.Secondary)
|
||||
.setEmoji(this.embedOptions.icons.nextTrack)
|
||||
.toJSON();
|
||||
components.push(skipButton);
|
||||
|
||||
if (this.embedOptions.components.showButtonLabels) {
|
||||
previousButton.label = translator('musicPlayerCommon.controls.previous');
|
||||
playPauseButton.label = queue.node.isPaused()
|
||||
? translator('musicPlayerCommon.controls.resume')
|
||||
: translator('musicPlayerCommon.controls.pause');
|
||||
skipButton.label = translator('musicPlayerCommon.controls.skip');
|
||||
}
|
||||
|
||||
const embedActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
|
||||
type: ComponentType.ActionRow,
|
||||
components
|
||||
};
|
||||
|
||||
logger.debug('Responding with info embed.');
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedQueueAuthor(interaction, queue, translator))
|
||||
.setDescription(
|
||||
this.getDisplayTrackPlayingStatus(queue, translator) +
|
||||
'\n' +
|
||||
this.getFormattedTrackUrl(currentTrack, translator) +
|
||||
'\n' +
|
||||
translator('musicPlayerCommon.requestedBy', {
|
||||
user: this.getDisplayTrackRequestedBy(currentTrack, translator)
|
||||
}) +
|
||||
'\n' +
|
||||
`${this.getDisplayQueueProgressBar(queue, translator)}\n` +
|
||||
`${formatRepeatModeDetailed(queue.repeatMode, this.embedOptions, translator)}\n` +
|
||||
`${translator('commands.queue.tracksInQueueTitle', {
|
||||
icon: this.embedOptions.icons.queue
|
||||
})}\n` +
|
||||
queueTracksListString
|
||||
)
|
||||
.setThumbnail(this.getTrackThumbnailUrl(currentTrack))
|
||||
.setFooter(this.getDisplayFullFooterInfo(interaction, queue, translator))
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
],
|
||||
components: [embedActionRow]
|
||||
});
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
private getDisplayTrackPlayingStatus = (queue: GuildQueue, translator: TFunction): string => {
|
||||
return queue.node.isPaused()
|
||||
? translator('musicPlayerCommon.nowPausedTitle', { icon: this.embedOptions.icons.paused })
|
||||
: translator('musicPlayerCommon.nowPlayingTitle', { icon: this.embedOptions.icons.audioPlaying });
|
||||
};
|
||||
|
||||
private async handleNoCurrentTrack(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
queueTracksListString: string,
|
||||
translator: TFunction
|
||||
) {
|
||||
logger.debug('Queue exists but there is no current track.');
|
||||
|
||||
logger.debug('Responding with info embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedQueueAuthor(interaction, queue, translator))
|
||||
.setDescription(
|
||||
`${formatRepeatModeDetailed(queue.repeatMode, this.embedOptions, translator)}` +
|
||||
`${translator('commands.queue.tracksInQueueTitle', {
|
||||
icon: this.embedOptions.icons.queue
|
||||
})}\n` +
|
||||
queueTracksListString
|
||||
)
|
||||
.setFooter(this.getDisplayFullFooterInfo(interaction, queue, translator))
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async handleInvalidPage(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
pageIndex: number,
|
||||
totalPages: number,
|
||||
translator: TFunction
|
||||
) {
|
||||
logger.debug('Specified page was higher than total pages.');
|
||||
|
||||
logger.debug('Responding with warning embed.');
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.queue.invalidPageNumber', {
|
||||
icon: this.embedOptions.icons.warning,
|
||||
page: pageIndex + 1,
|
||||
count: totalPages
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
private getPageIndex(interaction: ChatInputCommandInteraction): number {
|
||||
return (interaction.options.getInteger('page') || 1) - 1;
|
||||
}
|
||||
|
||||
private getTotalPages(queue: GuildQueue): number {
|
||||
return Math.ceil(queue.tracks.data.length / 10) || 1;
|
||||
}
|
||||
|
||||
private getQueueTracksListString(queue: GuildQueue, pageIndex: number, translator: TFunction): string {
|
||||
if (!queue || queue.tracks.data.length === 0) {
|
||||
return translator('commands.queue.emptyQueue', {
|
||||
playCommand: formatSlashCommand('play', translator)
|
||||
});
|
||||
}
|
||||
|
||||
return queue.tracks.data
|
||||
.slice(pageIndex * 10, pageIndex * 10 + 10)
|
||||
.map((track, index) => {
|
||||
return `**${pageIndex * 10 + index + 1}.** ${this.getDisplayTrackDurationAndUrl(track, translator)}`;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
private getDisplayQueueTotalDuration(queue: GuildQueue, translator: TFunction): string {
|
||||
if (queue.tracks.data.length > 1000) {
|
||||
return translator('commands.queue.estimatedReallyLongTime', {
|
||||
playCommand: formatSlashCommand('play', translator)
|
||||
});
|
||||
}
|
||||
|
||||
let queueDurationMs: number = queue.estimatedDuration;
|
||||
if (queue.currentTrack) {
|
||||
queueDurationMs += queue.currentTrack.durationMS;
|
||||
}
|
||||
|
||||
if (queueDurationMs < 0) {
|
||||
return translator('commands.queue.estimatedReallyLongTime', {
|
||||
playCommand: formatSlashCommand('play', translator)
|
||||
});
|
||||
}
|
||||
|
||||
return translator('commands.queue.estimatedDuration', {
|
||||
duration: formatDuration(queueDurationMs)
|
||||
});
|
||||
}
|
||||
|
||||
private getDisplayFullFooterInfo(
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
translator: TFunction
|
||||
): EmbedFooterData {
|
||||
const pagination = this.getFooterDisplayPageInfo(interaction, queue, translator);
|
||||
const totalDuration = this.getDisplayQueueTotalDuration(queue, translator);
|
||||
|
||||
const fullFooterData = {
|
||||
text: `${pagination.text} - ${totalDuration}`
|
||||
};
|
||||
|
||||
return fullFooterData;
|
||||
}
|
||||
}
|
||||
|
||||
export default new QueueCommand();
|
||||
@@ -0,0 +1,121 @@
|
||||
import {
|
||||
ApplicationCommandOption,
|
||||
ApplicationCommandOptionData,
|
||||
ChatInputCommandInteraction,
|
||||
EmbedBuilder,
|
||||
SlashCommandBuilder
|
||||
} from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { ExtendedClient } from '../../types/clientTypes';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkValidGuildId } from '../../utils/validation/systemCommandValidator';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { TFunction } from 'i18next';
|
||||
|
||||
class ReloadCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(new SlashCommandBuilder().setName('reload'));
|
||||
const isSystemCommand: boolean = true;
|
||||
super(data, isSystemCommand);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction, client } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
await this.runValidators({ interaction, executionId }, [checkValidGuildId]);
|
||||
|
||||
try {
|
||||
await this.reloadInteractionsAcrossShards(logger, executionId, client!);
|
||||
} catch (error) {
|
||||
return await this.handleReloadError(logger, interaction, executionId, error, translator);
|
||||
}
|
||||
|
||||
return await this.respondWithSuccessEmbed(logger, interaction, client!, translator);
|
||||
}
|
||||
|
||||
private async reloadInteractionsAcrossShards(logger: Logger, executionId: string, client: ExtendedClient) {
|
||||
logger.debug('Reloading interaction module across all shards.');
|
||||
await client!.shard!.broadcastEval(
|
||||
async (shardClient: ExtendedClient, { executionId }) => {
|
||||
shardClient.registerClientInteractions!({ client: shardClient, executionId });
|
||||
},
|
||||
{ context: { executionId: executionId } }
|
||||
);
|
||||
logger.debug('Successfully reloaded interaction module across all shards.');
|
||||
}
|
||||
|
||||
private async handleReloadError(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
executionId: string,
|
||||
error: Error | unknown,
|
||||
translator: TFunction
|
||||
) {
|
||||
logger.error(error, 'Failed to reload interaction module across shards.');
|
||||
|
||||
logger.debug('Responding with error embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.reload.unableToReload', {
|
||||
icon: this.embedOptions.icons.error
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.error)
|
||||
.setFooter({ text: `Execution ID: ${executionId}` })
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async respondWithSuccessEmbed(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
client: ExtendedClient,
|
||||
translator: TFunction
|
||||
) {
|
||||
const commands = this.getCommands(client);
|
||||
const embedDescription = this.buildEmbedDescription(commands, translator);
|
||||
|
||||
logger.debug('Responding with success embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [new EmbedBuilder().setDescription(embedDescription).setColor(this.embedOptions.colors.success)]
|
||||
});
|
||||
}
|
||||
|
||||
private getCommands(client: ExtendedClient): string[] | undefined {
|
||||
return client!.slashCommandInteractions?.map((command: BaseSlashCommandInteraction) => {
|
||||
const params = this.getCommandParams(command);
|
||||
return `- **\`/${command.data.name}\`** ${params}- ${command.data.description}`;
|
||||
});
|
||||
}
|
||||
|
||||
private getCommandParams(command: BaseSlashCommandInteraction): string {
|
||||
let params: string = '';
|
||||
|
||||
if (command.data.options && command.data.options.length > 1) {
|
||||
const options = command.data.options as unknown as ApplicationCommandOptionData[];
|
||||
|
||||
options.map((option: ApplicationCommandOption) => {
|
||||
params += `**\`${option.name}\`**` + ' ';
|
||||
});
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
private buildEmbedDescription(commands: string[] | undefined, translator: TFunction): string {
|
||||
return (
|
||||
translator('commands.reload.reloadedCommands', {
|
||||
icon: this.embedOptions.icons.bot
|
||||
}) +
|
||||
'\n' +
|
||||
commands?.join('\n')
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default new ReloadCommand();
|
||||
@@ -0,0 +1,301 @@
|
||||
import { GuildQueue, Track, useQueue } from 'discord-player';
|
||||
import { ChatInputCommandInteraction, EmbedBuilder, SlashCommandBuilder } from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkQueueExists } from '../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { Logger } from 'pino';
|
||||
import { TFunction } from 'i18next';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { formatSlashCommand } from '../../common/formattingUtils';
|
||||
|
||||
class RemoveCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(
|
||||
new SlashCommandBuilder()
|
||||
.setName('remove')
|
||||
.addSubcommand((subcommand) =>
|
||||
subcommand
|
||||
.setName('track')
|
||||
.addIntegerOption((option) => option.setName('position').setMinValue(1).setRequired(true))
|
||||
)
|
||||
.addSubcommand((subcommand) =>
|
||||
subcommand
|
||||
.setName('range')
|
||||
.addIntegerOption((option) => option.setName('start').setMinValue(1).setRequired(true))
|
||||
.addIntegerOption((option) => option.setName('end').setMinValue(1).setRequired(true))
|
||||
)
|
||||
.addSubcommand((subcommand) => subcommand.setName('queue'))
|
||||
.addSubcommand((subcommand) =>
|
||||
subcommand.setName('user').addUserOption((option) => option.setName('target').setRequired(true))
|
||||
)
|
||||
.addSubcommand((subcommand) => subcommand.setName('duplicates'))
|
||||
);
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
|
||||
await this.runValidators({ interaction, queue, executionId }, [
|
||||
checkInVoiceChannel,
|
||||
checkSameVoiceChannel,
|
||||
checkQueueExists
|
||||
]);
|
||||
|
||||
const subcommand = interaction.options.getSubcommand();
|
||||
|
||||
switch (subcommand) {
|
||||
case 'track':
|
||||
return await this.handleRemovedTrack(logger, interaction, queue, translator);
|
||||
case 'range':
|
||||
return await this.handleRemoveRange(logger, interaction, queue, translator);
|
||||
case 'queue':
|
||||
return await this.handleRemoveQueue(logger, interaction, queue, translator);
|
||||
case 'user':
|
||||
return await this.handleRemoveUserTracks(logger, interaction, queue, translator);
|
||||
case 'duplicates':
|
||||
return await this.handleRemoveDuplicates(logger, interaction, queue, translator);
|
||||
default:
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
private async handleRemoveUserTracks(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
translator: TFunction
|
||||
) {
|
||||
const targetUser = interaction.options.getUser('target')!;
|
||||
const removedTracks: Track[] = [];
|
||||
queue.tracks.data.forEach((track) => {
|
||||
if (track.requestedBy?.id === targetUser.id) {
|
||||
const removedTrack = queue.node.remove(track);
|
||||
if (removedTrack) {
|
||||
removedTracks.push(removedTrack);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (removedTracks.length === 0) {
|
||||
return await this.handleNoTracksRemoved(logger, interaction, translator);
|
||||
}
|
||||
|
||||
logger.debug(`Removed ${removedTracks.length} tracks from queue added by a user.`);
|
||||
|
||||
return await this.handleResponseRemovedTracks(logger, interaction, removedTracks.length, translator);
|
||||
}
|
||||
|
||||
private async handleRemoveDuplicates(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
translator: TFunction
|
||||
) {
|
||||
const removedTracks: Track[] = [];
|
||||
const uniqueTrackUrls = new Set<string>();
|
||||
queue.tracks.data.forEach((track) => {
|
||||
if (uniqueTrackUrls.has(track.url)) {
|
||||
const removedTrack = queue.node.remove(track);
|
||||
if (removedTrack) {
|
||||
removedTracks.push(removedTrack);
|
||||
}
|
||||
} else {
|
||||
uniqueTrackUrls.add(track.url);
|
||||
}
|
||||
});
|
||||
|
||||
if (removedTracks.length === 0) {
|
||||
return await this.handleNoTracksRemoved(logger, interaction, translator);
|
||||
}
|
||||
|
||||
logger.debug(`Removed ${removedTracks.length} duplicate tracks from queue.`);
|
||||
|
||||
return await this.handleResponseRemovedTracks(logger, interaction, removedTracks.length, translator);
|
||||
}
|
||||
|
||||
private async handleRemoveRange(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
translator: TFunction
|
||||
) {
|
||||
const start: number = interaction.options.getInteger('start')!;
|
||||
const end: number = interaction.options.getInteger('end')!;
|
||||
|
||||
if (start > queue.tracks.data.length || end > queue.tracks.data.length) {
|
||||
return await this.handleTrackPositionHigherThanQueueLength(logger, interaction, start, queue, translator);
|
||||
} else if (start > end) {
|
||||
logger.debug('Start position is higher than end position.');
|
||||
|
||||
logger.debug('Responding with warning embed.');
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.remove.startPositionHigherThanEndPosition', {
|
||||
icon: this.embedOptions.icons.warning,
|
||||
start,
|
||||
end,
|
||||
queueCommand: formatSlashCommand('queue', translator)
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
const removedTracks: Track[] = [];
|
||||
for (let i = start; i <= end; i++) {
|
||||
const track = queue.node.remove(start - 1);
|
||||
if (track) {
|
||||
removedTracks.push(track);
|
||||
}
|
||||
}
|
||||
|
||||
if (removedTracks.length === 0) {
|
||||
return await this.handleNoTracksRemoved(logger, interaction, translator);
|
||||
}
|
||||
|
||||
logger.debug(`Removed ${removedTracks.length} tracks from queue.`);
|
||||
|
||||
return await this.handleResponseRemovedTracks(logger, interaction, removedTracks.length, translator);
|
||||
}
|
||||
|
||||
private async handleRemoveQueue(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
translator: TFunction
|
||||
) {
|
||||
const queueLength = queue.tracks.data.length;
|
||||
queue.clear();
|
||||
|
||||
if (queueLength === 0) {
|
||||
return await this.handleNoTracksRemoved(logger, interaction, translator);
|
||||
}
|
||||
|
||||
logger.debug('Cleared the queue and removed all tracks.');
|
||||
|
||||
return await this.handleResponseRemovedTracks(logger, interaction, queueLength, translator);
|
||||
}
|
||||
|
||||
private async handleRemovedTrack(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
translator: TFunction
|
||||
) {
|
||||
const trackPositionInput: number = interaction.options.getInteger('position')!;
|
||||
|
||||
if (trackPositionInput > queue.tracks.data.length) {
|
||||
return await this.handleTrackPositionHigherThanQueueLength(
|
||||
logger,
|
||||
interaction,
|
||||
trackPositionInput,
|
||||
queue,
|
||||
translator
|
||||
);
|
||||
}
|
||||
|
||||
const removedTrack: Track = queue.node.remove(trackPositionInput - 1)!;
|
||||
logger.debug(`Removed track '${removedTrack.url}' from queue.`);
|
||||
|
||||
logger.debug('Responding with success embed.');
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(
|
||||
translator('commands.remove.removedTrack', {
|
||||
icon: this.embedOptions.icons.success
|
||||
}) +
|
||||
'\n' +
|
||||
this.getDisplayTrackDurationAndUrl(removedTrack, translator)
|
||||
)
|
||||
.setThumbnail(this.getTrackThumbnailUrl(removedTrack))
|
||||
.setColor(this.embedOptions.colors.success)
|
||||
]
|
||||
});
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
private async handleNoTracksRemoved(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
translator: TFunction
|
||||
) {
|
||||
logger.debug('Responding with warning embed.');
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(
|
||||
translator('commands.remove.noTracksRemoved', {
|
||||
icon: this.embedOptions.icons.warning
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
private async handleResponseRemovedTracks(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
removedAmount: number,
|
||||
translator: TFunction
|
||||
) {
|
||||
logger.debug('Responding with success embed.');
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(
|
||||
translator('commands.remove.removedTracks', {
|
||||
icon: this.embedOptions.icons.success,
|
||||
count: removedAmount
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.success)
|
||||
]
|
||||
});
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
private async handleTrackPositionHigherThanQueueLength(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
trackPositionInput: number,
|
||||
queue: GuildQueue,
|
||||
translator: TFunction
|
||||
) {
|
||||
logger.debug('Specified track position is higher than total tracks.');
|
||||
|
||||
logger.debug('Responding with warning embed.');
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.skip.trackPositionHigherThanQueueLength', {
|
||||
icon: this.embedOptions.icons.warning,
|
||||
position: trackPositionInput,
|
||||
count: queue.tracks.data.length,
|
||||
queueCommand: formatSlashCommand('queue', translator)
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
export default new RemoveCommand();
|
||||
@@ -0,0 +1,187 @@
|
||||
import { GuildQueue, useQueue } from 'discord-player';
|
||||
import { ChatInputCommandInteraction, EmbedBuilder, Message, SlashCommandBuilder } from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { Logger } from 'pino';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { TFunction } from 'i18next';
|
||||
import { formatSlashCommand } from '../../common/formattingUtils';
|
||||
|
||||
class SeekCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(
|
||||
new SlashCommandBuilder()
|
||||
.setName('seek')
|
||||
.addStringOption((option) => option.setName('duration').setRequired(true))
|
||||
);
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
|
||||
await this.runValidators({ interaction, queue, executionId }, [
|
||||
checkInVoiceChannel,
|
||||
checkSameVoiceChannel,
|
||||
checkQueueExists,
|
||||
checkQueueCurrentTrack
|
||||
]);
|
||||
|
||||
const durationInputSplit: string[] = interaction.options.getString('duration')!.split(':');
|
||||
const formattedDurationString: string = this.parseDurationArray(durationInputSplit);
|
||||
|
||||
if (!this.validateDurationFormat(formattedDurationString)) {
|
||||
return await this.handleInvalidDurationFormat(logger, interaction, formattedDurationString, translator);
|
||||
}
|
||||
|
||||
const currentTrackMaxDurationInMs: number = queue.currentTrack!.durationMS;
|
||||
const inputDurationInMilliseconds: number = this.getDurationInputInMilliseconds(durationInputSplit);
|
||||
|
||||
if (inputDurationInMilliseconds > currentTrackMaxDurationInMs - 1000) {
|
||||
return await this.handleDurationLongerThanTrack(
|
||||
logger,
|
||||
interaction,
|
||||
formattedDurationString,
|
||||
queue,
|
||||
translator
|
||||
);
|
||||
}
|
||||
|
||||
return await this.seekToDurationInCurrentTrack(
|
||||
logger,
|
||||
interaction,
|
||||
queue,
|
||||
inputDurationInMilliseconds,
|
||||
formattedDurationString,
|
||||
translator
|
||||
);
|
||||
}
|
||||
|
||||
private async handleInvalidDurationFormat(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
formattedDurationString: string,
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
logger.debug('Invalid duration format input.');
|
||||
|
||||
logger.debug('Responding with warning embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.seek.correctFormatInstruction', {
|
||||
icon: this.embedOptions.icons.warning,
|
||||
wrongDuration: formattedDurationString,
|
||||
seekCommand: formatSlashCommand('seek', translator)
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async seekToDurationInCurrentTrack(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
durationInMilliseconds: number,
|
||||
formattedDurationString: string,
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
queue.node.seek(durationInMilliseconds);
|
||||
logger.debug(`Seeked to '${formattedDurationString}' in current track.`);
|
||||
|
||||
logger.debug('Responding with success embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(await this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(
|
||||
translator('commands.seek.seekingToTimestamp', {
|
||||
icon: this.embedOptions.icons.success,
|
||||
duration: formattedDurationString
|
||||
})
|
||||
)
|
||||
.setThumbnail(this.getTrackThumbnailUrl(queue.currentTrack!))
|
||||
.setColor(this.embedOptions.colors.success)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async handleDurationLongerThanTrack(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
formattedDurationString: string,
|
||||
queue: GuildQueue,
|
||||
translator: TFunction
|
||||
): Promise<Message> {
|
||||
logger.debug('Duration specified is longer than the track duration.');
|
||||
|
||||
logger.debug('Responding with warning embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.seek.durationLongerThanTrackDuration', {
|
||||
icon: this.embedOptions.icons.warning,
|
||||
wrongDuration: formattedDurationString,
|
||||
trackDuration: queue.currentTrack!.duration
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private parseDurationArray(durationInputSplit: string[]): string {
|
||||
switch (durationInputSplit.length) {
|
||||
case 1:
|
||||
durationInputSplit.unshift('00', '00');
|
||||
break;
|
||||
case 2:
|
||||
durationInputSplit.unshift('00');
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
durationInputSplit = durationInputSplit.map((value) => {
|
||||
return value.padStart(2, '0');
|
||||
});
|
||||
|
||||
return durationInputSplit.join(':');
|
||||
}
|
||||
|
||||
private validateDurationFormat(formattedDurationString: string): boolean {
|
||||
const formattedDurationSplit: string[] = formattedDurationString.split(':');
|
||||
if (formattedDurationSplit.length === 0 || formattedDurationSplit.length > 3) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!formattedDurationSplit.every((value) => value.length === 2)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const regex: RegExp = new RegExp('([0-1][0-9]|2[0-3]):?[0-5][0-9]:?[0-5][0-9]');
|
||||
const isValidDuration: boolean = regex.test(formattedDurationString);
|
||||
return isValidDuration;
|
||||
}
|
||||
|
||||
private getDurationInputInMilliseconds(durationInputSplit: string[]): number {
|
||||
const durationInMilliseconds =
|
||||
Number(durationInputSplit[0]) * 3600000 +
|
||||
Number(durationInputSplit[1]) * 60000 +
|
||||
Number(durationInputSplit[2]) * 1000;
|
||||
|
||||
return durationInMilliseconds;
|
||||
}
|
||||
}
|
||||
|
||||
export default new SeekCommand();
|
||||
@@ -0,0 +1,226 @@
|
||||
import {
|
||||
ChatInputCommandInteraction,
|
||||
EmbedBuilder,
|
||||
EmbedField,
|
||||
EmbedFooterData,
|
||||
SlashCommandBuilder
|
||||
} from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { ExtendedClient } from '../../types/clientTypes';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType, ShardInfo } from '../../types/interactionTypes';
|
||||
import { checkValidGuildId } from '../../utils/validation/systemCommandValidator';
|
||||
import { Logger } from 'pino';
|
||||
import { localizeCommand } from '../../common/localeUtil';
|
||||
|
||||
class ShardsCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(
|
||||
new SlashCommandBuilder()
|
||||
.setName('shards')
|
||||
.addStringOption((option) =>
|
||||
option
|
||||
.setName('sort')
|
||||
.setRequired(false)
|
||||
.addChoices(
|
||||
{ value: 'none', name: ' ' },
|
||||
{ value: 'memory', name: ' ' },
|
||||
{ value: 'connections', name: ' ' },
|
||||
{ value: 'tracks', name: ' ' },
|
||||
{ value: 'listeners', name: ' ' },
|
||||
{ value: 'guilds', name: ' ' },
|
||||
{ value: 'members', name: ' ' }
|
||||
)
|
||||
)
|
||||
.addIntegerOption((option) => option.setName('page').setMinValue(1))
|
||||
);
|
||||
const isSystemCommand: boolean = true;
|
||||
super(data, isSystemCommand);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction, client } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
|
||||
await this.runValidators({ interaction, executionId }, [checkValidGuildId]);
|
||||
|
||||
const shardInfoList: ShardInfo[] = await this.fetchShardInfo(
|
||||
client!,
|
||||
logger,
|
||||
interaction.options.getString('sort')
|
||||
);
|
||||
|
||||
const currentShardId: number = client!.shard!.ids[0];
|
||||
const shardCount: number = shardInfoList.length;
|
||||
const pageIndex: number = this.getPageIndex(interaction);
|
||||
const totalPages: number = this.getTotalPages(shardCount);
|
||||
|
||||
if (pageIndex > totalPages - 1) {
|
||||
return await this.handleInvalidPage(logger, interaction, pageIndex, totalPages);
|
||||
}
|
||||
|
||||
const currentPageShards: ShardInfo[] = shardInfoList.slice(pageIndex * 10, pageIndex * 10 + 10);
|
||||
const embedFields: EmbedField[] = this.buildEmbedFields(currentPageShards);
|
||||
|
||||
logger.debug('Responding with info embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
`**${this.embedOptions.icons.server} Shard overview - ${shardCount} total shards**\n`
|
||||
)
|
||||
.addFields(...embedFields)
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
.setFooter(this.getFooterPageInfo(currentShardId, pageIndex, totalPages))
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async fetchShardInfo(
|
||||
client: ExtendedClient,
|
||||
logger: Logger,
|
||||
sortOption: string | null
|
||||
): Promise<ShardInfo[]> {
|
||||
let shardInfoList: ShardInfo[] = [];
|
||||
|
||||
logger.debug('Fetching player statistics and client values from each shard.');
|
||||
try {
|
||||
await client!
|
||||
.shard!.broadcastEval((shardClient: ExtendedClient) => {
|
||||
const playerStats = player.generateStatistics();
|
||||
const nodeProcessMemUsageInMb: number = parseFloat(
|
||||
(process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2)
|
||||
);
|
||||
|
||||
const shardInfo: 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.filter(Boolean) as ShardInfo[];
|
||||
shardInfoList = this.sortShardInfoList(shardInfoList, sortOption);
|
||||
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.');
|
||||
throw error;
|
||||
}
|
||||
|
||||
return shardInfoList;
|
||||
}
|
||||
|
||||
private buildEmbedFields(shards: ShardInfo[]): EmbedField[] {
|
||||
const evenShardIndexes: ShardInfo[] = shards.filter((shard, index) => index % 2 === 0);
|
||||
const oddShardIndexes: ShardInfo[] = shards.filter((shard, index) => index % 2 !== 0);
|
||||
|
||||
const evenShardIndexesString: string =
|
||||
evenShardIndexes.map(this.shardInfoToString).join('\n') + 'ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ';
|
||||
const oddShardIndexesString: string = oddShardIndexes.map(this.shardInfoToString).join('\n');
|
||||
|
||||
const embedFields: EmbedField[] = [];
|
||||
|
||||
if (shards.length === 1) {
|
||||
embedFields.push({
|
||||
name: ' ',
|
||||
value: shards.map(this.shardInfoToString).join('\n'),
|
||||
inline: false
|
||||
});
|
||||
} else {
|
||||
embedFields.push(
|
||||
{
|
||||
name: ' ',
|
||||
value: evenShardIndexesString,
|
||||
inline: true
|
||||
},
|
||||
{
|
||||
name: ' ',
|
||||
value: oddShardIndexesString,
|
||||
inline: true
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return embedFields;
|
||||
}
|
||||
|
||||
private sortShardInfoList(shardInfoList: ShardInfo[], sortOption: string | null): ShardInfo[] {
|
||||
switch (sortOption) {
|
||||
case 'memory':
|
||||
return shardInfoList.sort((a, b) => b.memUsage - a.memUsage);
|
||||
case 'connections':
|
||||
return shardInfoList.sort(
|
||||
(a, b) => b.playerStatistics.activeVoiceConnections - a.playerStatistics.activeVoiceConnections
|
||||
);
|
||||
case 'tracks':
|
||||
return shardInfoList.sort((a, b) => b.playerStatistics.totalTracks - a.playerStatistics.totalTracks);
|
||||
case 'listeners':
|
||||
return shardInfoList.sort(
|
||||
(a, b) => b.playerStatistics.totalListeners - a.playerStatistics.totalListeners
|
||||
);
|
||||
case 'guilds':
|
||||
return shardInfoList.sort((a, b) => b.guildCount - a.guildCount);
|
||||
case 'members':
|
||||
return shardInfoList.sort((a, b) => b.guildMemberCount - a.guildMemberCount);
|
||||
default:
|
||||
return shardInfoList.sort((a, b) => a.shardId - b.shardId);
|
||||
}
|
||||
}
|
||||
|
||||
private shardInfoToString(shard: ShardInfo): string {
|
||||
let string: string = '';
|
||||
string += `**Shard ${shard.shardId}** - Guilds: ${shard.guildCount.toLocaleString(
|
||||
'en-US'
|
||||
)} (${shard.guildMemberCount.toLocaleString('en-US')})\n`;
|
||||
string += `**Node.js memory:** ${shard.memUsage.toLocaleString('en-US')} MB\n`;
|
||||
string += `**┣** Connections: ${shard.playerStatistics.activeVoiceConnections.toLocaleString('en-US')}\n`;
|
||||
string += `**┣** Tracks: ${shard.playerStatistics.totalTracks.toLocaleString('en-US')}\n`;
|
||||
string += `**┗** Listeners: ${shard.playerStatistics.totalListeners.toLocaleString('en-US')}\n`;
|
||||
return string;
|
||||
}
|
||||
|
||||
private getPageIndex(interaction: ChatInputCommandInteraction): number {
|
||||
return (interaction.options.getInteger('page') || 1) - 1;
|
||||
}
|
||||
|
||||
private getTotalPages(shardCount: number): number {
|
||||
return Math.ceil(shardCount / 10) || 1;
|
||||
}
|
||||
|
||||
private getFooterPageInfo(currentShardId: number, pageIndex: number, totalPages: number): EmbedFooterData {
|
||||
return { text: `Shard id: ${currentShardId}, page ${pageIndex + 1} of ${totalPages}` };
|
||||
}
|
||||
|
||||
private async handleInvalidPage(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
pageIndex: number,
|
||||
totalPages: number
|
||||
) {
|
||||
logger.debug('Specified page was higher than total pages.');
|
||||
|
||||
logger.debug('Responding with warning embed.');
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
`**${this.embedOptions.icons.warning} Oops!**\n` +
|
||||
`Page **\`${pageIndex + 1}\`** is not a valid page number.\n\n` +
|
||||
`There are only a total of **\`${totalPages}\`** pages available.`
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
export default new ShardsCommand();
|
||||
@@ -0,0 +1,51 @@
|
||||
import { GuildQueue, useQueue } from 'discord-player';
|
||||
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkQueueEmpty, checkQueueExists } from '../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { formatSlashCommand } from '../../common/formattingUtils';
|
||||
|
||||
class ShuffleCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(new SlashCommandBuilder().setName('shuffle'));
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
|
||||
await this.runValidators({ interaction, queue, executionId }, [
|
||||
checkInVoiceChannel,
|
||||
checkSameVoiceChannel,
|
||||
checkQueueExists,
|
||||
checkQueueEmpty
|
||||
]);
|
||||
|
||||
queue.tracks.shuffle();
|
||||
logger.debug('Shuffled queue tracks.');
|
||||
|
||||
logger.debug('Responding with success embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(
|
||||
translator('commands.shuffle.shuffledTracks', {
|
||||
icon: this.embedOptions.icons.shuffled,
|
||||
count: queue.tracks.data.length,
|
||||
queueCommand: formatSlashCommand('queue', translator)
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.success)
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default new ShuffleCommand();
|
||||
@@ -0,0 +1,153 @@
|
||||
import { GuildQueue, Track, useQueue } from 'discord-player';
|
||||
import { ChatInputCommandInteraction, EmbedBuilder, SlashCommandBuilder } from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { Logger } from 'pino';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { TFunction } from 'i18next';
|
||||
import { formatRepeatModeDetailed, formatSlashCommand } from '../../common/formattingUtils';
|
||||
|
||||
class SkipCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(
|
||||
new SlashCommandBuilder()
|
||||
.setName('skip')
|
||||
.addIntegerOption((option) => option.setName('position').setMinValue(1))
|
||||
);
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
|
||||
await this.runValidators({ interaction, queue, executionId }, [
|
||||
checkInVoiceChannel,
|
||||
checkSameVoiceChannel,
|
||||
checkQueueExists,
|
||||
checkQueueCurrentTrack
|
||||
]);
|
||||
|
||||
const trackPositionInput: number = interaction.options.getInteger('position')!;
|
||||
|
||||
if (trackPositionInput) {
|
||||
return await this.handleSkipToTrackPosition(logger, interaction, queue, trackPositionInput, translator);
|
||||
} else {
|
||||
return await this.handleSkipToNextTrack(logger, interaction, queue, translator);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleSkipToTrackPosition(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
trackPosition: number,
|
||||
translator: TFunction
|
||||
) {
|
||||
if (trackPosition > queue.tracks.data.length) {
|
||||
return await this.handleTrackPositionHigherThanQueueLength(
|
||||
trackPosition,
|
||||
queue,
|
||||
logger,
|
||||
interaction,
|
||||
translator
|
||||
);
|
||||
} else {
|
||||
const skippedTrack: Track = queue.currentTrack!;
|
||||
queue.node.skipTo(trackPosition - 1);
|
||||
logger.debug('Skipped to specified track position.');
|
||||
return await this.respondWithSuccessEmbed(skippedTrack, interaction, queue, translator);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleTrackPositionHigherThanQueueLength(
|
||||
trackPosition: number,
|
||||
queue: GuildQueue,
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
translator: TFunction
|
||||
) {
|
||||
logger.debug('Specified track position was higher than total tracks.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.skip.trackPositionHigherThanQueueLength', {
|
||||
icon: this.embedOptions.icons.warning,
|
||||
position: trackPosition,
|
||||
queueCommand: formatSlashCommand('queue', translator),
|
||||
count: queue.tracks.data.length
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async handleSkipToNextTrack(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
translator: TFunction
|
||||
) {
|
||||
if (queue.tracks.data.length === 0 && !queue.currentTrack) {
|
||||
return await this.handleNoTracksInQueueAndNoCurrentTrack(logger, interaction, translator);
|
||||
}
|
||||
|
||||
const skippedTrack: Track = queue.currentTrack!;
|
||||
queue.node.skip();
|
||||
logger.debug('Skipped current track.');
|
||||
return await this.respondWithSuccessEmbed(skippedTrack, interaction, queue, translator);
|
||||
}
|
||||
|
||||
private async handleNoTracksInQueueAndNoCurrentTrack(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
translator: TFunction
|
||||
) {
|
||||
logger.debug('No tracks in queue and no current track.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.skip.emptyQueue', {
|
||||
icon: this.embedOptions.icons.warning,
|
||||
playCommand: formatSlashCommand('play', translator)
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async respondWithSuccessEmbed(
|
||||
skippedTrack: Track,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
translator: TFunction
|
||||
) {
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(
|
||||
translator('commands.skip.skippedTrack', {
|
||||
icon: this.embedOptions.icons.skipped
|
||||
}) +
|
||||
'\n' +
|
||||
`${this.getDisplayTrackDurationAndUrl(skippedTrack, translator)}\n` +
|
||||
`${formatRepeatModeDetailed(queue.repeatMode, this.embedOptions, translator, 'success')}`
|
||||
)
|
||||
.setThumbnail(this.getTrackThumbnailUrl(skippedTrack))
|
||||
.setColor(this.embedOptions.colors.success)
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default new SkipCommand();
|
||||
@@ -0,0 +1,88 @@
|
||||
// @ts-ignore
|
||||
import { version } from '../../../package.json';
|
||||
import {
|
||||
APIActionRowComponent,
|
||||
APIButtonComponent,
|
||||
APIMessageActionRowComponent,
|
||||
ButtonBuilder,
|
||||
ButtonStyle,
|
||||
ComponentType,
|
||||
EmbedBuilder,
|
||||
SlashCommandBuilder
|
||||
} from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { getBotStatistics, getDiscordStatus, getPlayerStatistics, getSystemStatus } from '../../common/statusUtils';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
|
||||
class StatusCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(new SlashCommandBuilder().setName('status'));
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction, client } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const [botStatisticsEmbedString, playerStatisticsEmbedString, systemStatusEmbedString] = await Promise.all([
|
||||
getBotStatistics(client!, version, translator),
|
||||
getPlayerStatistics(client!, translator),
|
||||
getSystemStatus(executionId, false, translator)
|
||||
]);
|
||||
const discordStatusEmbedString = getDiscordStatus(client!, translator);
|
||||
|
||||
const components: APIMessageActionRowComponent[] = [];
|
||||
if (this.botOptions.openSourceUrl && this.botOptions.openSourceUrl !== '') {
|
||||
const openSourceButton: APIButtonComponent = new ButtonBuilder()
|
||||
.setURL(this.botOptions.openSourceUrl)
|
||||
.setStyle(ButtonStyle.Link)
|
||||
.setEmoji(this.embedOptions.icons.openSource)
|
||||
.setLabel(translator('commands.status.openSourceButtonLabel'))
|
||||
.toJSON();
|
||||
components.push(openSourceButton);
|
||||
}
|
||||
|
||||
const embedActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
|
||||
type: ComponentType.ActionRow,
|
||||
components
|
||||
};
|
||||
|
||||
logger.debug('Responding with info embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('statistics.botStatus.title', { icon: this.embedOptions.icons.bot }) +
|
||||
'\n' +
|
||||
botStatisticsEmbedString
|
||||
)
|
||||
.addFields(
|
||||
{
|
||||
name: translator('statistics.queueStatus.title', {
|
||||
icon: this.embedOptions.icons.queue
|
||||
}),
|
||||
value: playerStatisticsEmbedString
|
||||
},
|
||||
{
|
||||
name: translator('statistics.systemStatus.title', {
|
||||
icon: this.embedOptions.icons.server
|
||||
}),
|
||||
value: systemStatusEmbedString
|
||||
},
|
||||
{
|
||||
name: translator('statistics.discordStatus.title', {
|
||||
icon: this.embedOptions.icons.discord
|
||||
}),
|
||||
value: discordStatusEmbedString
|
||||
}
|
||||
)
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
],
|
||||
components: components.length > 0 ? [embedActionRow] : []
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default new StatusCommand();
|
||||
@@ -0,0 +1,52 @@
|
||||
import { GuildQueue, QueueRepeatMode, useQueue } from 'discord-player';
|
||||
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkQueueExists } from '../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { formatSlashCommand } from '../../common/formattingUtils';
|
||||
|
||||
class StopCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(new SlashCommandBuilder().setName('stop'));
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
|
||||
await this.runValidators({ interaction, queue, executionId }, [
|
||||
checkInVoiceChannel,
|
||||
checkSameVoiceChannel,
|
||||
checkQueueExists
|
||||
]);
|
||||
|
||||
if (!queue.deleted) {
|
||||
queue.setRepeatMode(QueueRepeatMode.OFF);
|
||||
queue.node.stop();
|
||||
logger.debug('Cleared and stopped the queue.');
|
||||
}
|
||||
|
||||
logger.debug('Responding with success embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(
|
||||
translator('commands.stop.stoppedPlaying', {
|
||||
icon: this.embedOptions.icons.success,
|
||||
playCommand: formatSlashCommand('play', translator)
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.success)
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default new StopCommand();
|
||||
@@ -0,0 +1,86 @@
|
||||
// @ts-ignore
|
||||
import { dependencies, version } from '../../../package.json';
|
||||
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { getBotStatistics, getDiscordStatus, getPlayerStatistics, getSystemStatus } from '../../common/statusUtils';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkValidGuildId } from '../../utils/validation/systemCommandValidator';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
|
||||
class SystemStatusCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(new SlashCommandBuilder().setName('systemstatus'));
|
||||
const isSystemCommand: boolean = true;
|
||||
super(data, isSystemCommand);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction, client } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
await this.runValidators({ interaction, executionId }, [checkValidGuildId]);
|
||||
|
||||
const [botStatisticsEmbedString, playerStatisticsEmbedString, systemStatusEmbedString] = await Promise.all([
|
||||
getBotStatistics(client!, version, translator),
|
||||
getPlayerStatistics(client!, translator),
|
||||
getSystemStatus(executionId, false, translator)
|
||||
]);
|
||||
const discordStatusEmbedString = getDiscordStatus(client!, translator);
|
||||
const dependenciesEmbedString = this.getDependencies();
|
||||
|
||||
logger.debug('Responding with info embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('statistics.botStatus.title', { icon: this.embedOptions.icons.bot }) +
|
||||
'\n' +
|
||||
botStatisticsEmbedString
|
||||
)
|
||||
.addFields(
|
||||
{
|
||||
name: translator('statistics.queueStatus.title', {
|
||||
icon: this.embedOptions.icons.queue
|
||||
}),
|
||||
value: playerStatisticsEmbedString
|
||||
},
|
||||
{
|
||||
name: translator('statistics.systemStatus.title', {
|
||||
icon: this.embedOptions.icons.server
|
||||
}),
|
||||
value: systemStatusEmbedString
|
||||
},
|
||||
{
|
||||
name: translator('statistics.discordStatus.title', {
|
||||
icon: this.embedOptions.icons.discord
|
||||
}),
|
||||
value: discordStatusEmbedString
|
||||
},
|
||||
{
|
||||
name: translator('statistics.dependencies.title', {
|
||||
icon: this.embedOptions.icons.bot
|
||||
}),
|
||||
value: dependenciesEmbedString
|
||||
}
|
||||
)
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private getDependencies(): string {
|
||||
return (
|
||||
`**${dependencies['discord.js']}** discord.js\n` +
|
||||
`**┗ ${dependencies['@discordjs/rest']}** @discordjs/rest\n` +
|
||||
`**${dependencies['discord-player']}** discord-player\n` +
|
||||
`**┗ ${dependencies['@discord-player/opus']}** @discord-player/opus\n` +
|
||||
`**┗ ${dependencies['@discord-player/extractor']}** @discord-player/extractor\n` +
|
||||
`**${dependencies['discord-voip']}** discord-voip\n` +
|
||||
`**${dependencies['mediaplex']}** mediaplex\n` +
|
||||
`**${dependencies['youtube-ext']}** youtube-ext`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default new SystemStatusCommand();
|
||||
@@ -0,0 +1,138 @@
|
||||
import { GuildQueue, useQueue } from 'discord-player';
|
||||
import { ChatInputCommandInteraction, EmbedBuilder, SlashCommandBuilder } from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from '../../classes/interactions';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../types/interactionTypes';
|
||||
import { checkQueueExists } from '../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
|
||||
import { Logger } from 'pino';
|
||||
import { localizeCommand, useServerTranslator } from '../../common/localeUtil';
|
||||
import { TFunction } from 'i18next';
|
||||
|
||||
class VolumeCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = localizeCommand(
|
||||
new SlashCommandBuilder()
|
||||
.setName('volume')
|
||||
.addIntegerOption((option) => option.setName('percentage').setMinValue(0).setMaxValue(100))
|
||||
);
|
||||
super(data);
|
||||
}
|
||||
|
||||
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
|
||||
const { executionId, interaction } = params;
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
const translator = useServerTranslator(interaction);
|
||||
|
||||
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
|
||||
|
||||
await this.runValidators({ interaction, queue, executionId }, [
|
||||
checkInVoiceChannel,
|
||||
checkSameVoiceChannel,
|
||||
checkQueueExists
|
||||
]);
|
||||
|
||||
const volume: number = interaction.options.getInteger('percentage')!;
|
||||
|
||||
if (!volume && volume !== 0) {
|
||||
return await this.handleShowCurrentVolume(queue, logger, interaction, translator);
|
||||
} else if (volume > 100 || volume < 0) {
|
||||
return await this.handleInvalidVolumeInput(volume, logger, interaction, translator);
|
||||
} else {
|
||||
return await this.handleValidVolumeInput(volume, queue, logger, interaction, translator);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleShowCurrentVolume(
|
||||
queue: GuildQueue,
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
translator: TFunction
|
||||
) {
|
||||
const currentVolume: number = queue.node.volume;
|
||||
logger.debug('No volume input was provided, showing current volume.');
|
||||
|
||||
const currentVolumeIcon =
|
||||
currentVolume === 0 ? this.embedOptions.icons.volumeIsMuted : this.embedOptions.icons.volume;
|
||||
|
||||
logger.debug('Responding with info embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
translator('commands.volume.volumeInformation', {
|
||||
icon: currentVolumeIcon,
|
||||
volume: currentVolume
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async handleInvalidVolumeInput(
|
||||
volume: number,
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
translator: TFunction
|
||||
) {
|
||||
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()
|
||||
.setDescription(
|
||||
translator('commands.volume.invalidVolumeRange', {
|
||||
icon: this.embedOptions.icons.warning,
|
||||
wrongVolume: volume
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
private async handleValidVolumeInput(
|
||||
volume: number,
|
||||
queue: GuildQueue,
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
translator: TFunction
|
||||
) {
|
||||
queue.node.setVolume(volume);
|
||||
logger.debug(`Set volume to ${volume}%.`);
|
||||
|
||||
if (volume === 0) {
|
||||
logger.debug('Responding with success embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(
|
||||
translator('commands.volume.volumeMuted', {
|
||||
icon: this.embedOptions.icons.volumeMuted
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.success)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
logger.debug('Responding with success embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(this.getEmbedUserAuthor(interaction))
|
||||
.setDescription(
|
||||
translator('commands.volume.volumeChanged', {
|
||||
icon: this.embedOptions.icons.volumeChanged,
|
||||
volume
|
||||
})
|
||||
)
|
||||
.setColor(this.embedOptions.colors.success)
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default new VolumeCommand();
|
||||
Reference in new issue
Block a user