mirror of
https://github.com/darksaid98/cadence-discord-bot.git
synced 2026-12-02 22:16:13 +00:00
fix: refactored queue command, added more common methods
This commit is contained in:
1 parent
bf30d565d7
commit
1ebb7c3b89
6 files changed
+175
-149
No files matched your search
@@ -1,10 +1,11 @@
|
||||
import config from 'config';
|
||||
import { GuildQueue, Track } from 'discord-player';
|
||||
import { GuildQueue, PlayerTimestamp, Track } from 'discord-player';
|
||||
import {
|
||||
ApplicationCommandOptionChoiceData,
|
||||
AutocompleteInteraction,
|
||||
ChatInputCommandInteraction,
|
||||
EmbedAuthorOptions,
|
||||
EmbedFooterData,
|
||||
GuildMember,
|
||||
Interaction,
|
||||
Message,
|
||||
@@ -113,6 +114,44 @@ abstract class BaseInteraction {
|
||||
return thumbnailUrl;
|
||||
}
|
||||
|
||||
protected getFooterDisplayPageInfo(interaction: ChatInputCommandInteraction, queue: GuildQueue): EmbedFooterData {
|
||||
if (!queue.tracks.data.length) {
|
||||
return { text: 'Page 1 of 1 (0 tracks)' };
|
||||
}
|
||||
|
||||
const pageIndex: number = (interaction.options.getNumber('page') || 1) - 1;
|
||||
const totalPages: number = Math.ceil(queue.tracks.data.length / 10) || 1;
|
||||
return {
|
||||
text: `Page ${pageIndex + 1} of ${totalPages} (${queue.tracks.data.length} tracks)`
|
||||
};
|
||||
}
|
||||
|
||||
protected getDisplayTrackRequestedBy = (track: Track): string => {
|
||||
return track.requestedBy ? `<@${track.requestedBy.id}>` : 'Unavailable';
|
||||
};
|
||||
|
||||
protected getDisplayQueueProgressBar(queue: GuildQueue): string {
|
||||
const timestamp: PlayerTimestamp = queue.node.getTimestamp()!;
|
||||
let progressBar: string = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({
|
||||
queue: false,
|
||||
length: this.playerOptions.progressBar.length ?? 12,
|
||||
timecodes: this.playerOptions.progressBar.timecodes ?? false,
|
||||
indicator: this.playerOptions.progressBar.indicator ?? '🔘',
|
||||
leftChar: this.playerOptions.progressBar.leftChar ?? '▬',
|
||||
rightChar: this.playerOptions.progressBar.rightChar ?? '▬'
|
||||
})} **\`${timestamp.total.label}\`**`;
|
||||
|
||||
if (Number(queue.currentTrack?.raw.duration) === 0 || queue.currentTrack?.duration === '0:00') {
|
||||
progressBar = '_No duration available._';
|
||||
}
|
||||
|
||||
if (queue.currentTrack?.raw.live) {
|
||||
progressBar = `${this.embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`;
|
||||
}
|
||||
|
||||
return progressBar;
|
||||
}
|
||||
|
||||
abstract execute(
|
||||
params: BaseInteractionParams
|
||||
): Promise<Message<boolean> | ApplicationCommandOptionChoiceData | void>;
|
||||
|
||||
@@ -61,7 +61,7 @@ class FiltersCommand extends BaseSlashCommandInteraction {
|
||||
switch (filterProvider.toLowerCase()) {
|
||||
case 'ffmpeg':
|
||||
logger.debug('Handling ffmpeg filters.');
|
||||
return await this.handleFfmpegFilters(queue, logger, interaction);
|
||||
return await this.handleFfmpegFilters(logger, interaction, queue);
|
||||
case 'biquad':
|
||||
logger.debug('Handling biquad filters.');
|
||||
return await this.tempNotImplementedResponse(logger, interaction);
|
||||
@@ -70,14 +70,14 @@ class FiltersCommand extends BaseSlashCommandInteraction {
|
||||
return await this.tempNotImplementedResponse(logger, interaction);
|
||||
case 'disable':
|
||||
logger.debug('Disabling filters.');
|
||||
return await this.tempDisableFilters(queue, logger, interaction);
|
||||
return await this.tempDisableFilters(logger, interaction, queue);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleFfmpegFilters(
|
||||
queue: GuildQueue<unknown>,
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue<unknown>
|
||||
) {
|
||||
const filterOptions: StringSelectMenuOptionBuilder[] = [];
|
||||
|
||||
@@ -134,7 +134,7 @@ class FiltersCommand extends BaseSlashCommandInteraction {
|
||||
});
|
||||
}
|
||||
|
||||
private async tempDisableFilters(queue: GuildQueue, logger: Logger, interaction: ChatInputCommandInteraction) {
|
||||
private async tempDisableFilters(logger: Logger, interaction: ChatInputCommandInteraction, queue: GuildQueue) {
|
||||
if (queue.filters.ffmpeg.filters.length > 0) {
|
||||
queue.filters.ffmpeg.setFilters(false);
|
||||
logger.debug('Reset queue filters.');
|
||||
|
||||
@@ -61,7 +61,7 @@ class LyricsCommand extends BaseSlashCommandInteraction {
|
||||
return await this.sendMultipleLyricsMessages(logger, interaction, finalLyricsData);
|
||||
}
|
||||
|
||||
return await this.sendLyricsEmbed(finalLyricsData, interaction, logger);
|
||||
return await this.sendLyricsEmbed(logger, interaction, finalLyricsData);
|
||||
}
|
||||
|
||||
private getGeniusSearchQuery(logger: Logger, query: string, queue: GuildQueue): string {
|
||||
@@ -203,9 +203,9 @@ class LyricsCommand extends BaseSlashCommandInteraction {
|
||||
}
|
||||
|
||||
private async sendLyricsEmbed(
|
||||
geniusLyricsResult: LyricsData,
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
logger: Logger
|
||||
geniusLyricsResult: LyricsData
|
||||
) {
|
||||
logger.debug('Responding with info embed.');
|
||||
return await interaction.editReply({
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import config from 'config';
|
||||
import { GuildQueue, PlayerTimestamp, Track, useQueue } from 'discord-player';
|
||||
import { GuildQueue, Track, useQueue } from 'discord-player';
|
||||
import {
|
||||
APIActionRowComponent,
|
||||
APIButtonComponent,
|
||||
@@ -12,13 +11,10 @@ import {
|
||||
SlashCommandBuilder
|
||||
} from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from '../../../classes/interactions';
|
||||
import { PlayerOptions } from '../../../types/configTypes';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType, TrackMetadata } from '../../../types/interactionTypes';
|
||||
import { checkQueueCurrentTrack, checkQueueExists } from '../../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
|
||||
|
||||
const playerOptions: PlayerOptions = config.get('playerOptions');
|
||||
|
||||
class NowPlayingCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = new SlashCommandBuilder()
|
||||
@@ -46,7 +42,7 @@ class NowPlayingCommand extends BaseSlashCommandInteraction {
|
||||
const displayTrackRequestedBy: string = this.getDisplayTrackRequestedBy(currentTrack);
|
||||
const displayTrackPlayingStatus: string = this.getDisplayTrackPlayingStatus(queue);
|
||||
const displayQueueRepeatMode: string = this.getDisplayQueueRepeatMode(queue);
|
||||
const displayEmbedProgressBar: string = await this.getDisplayQueueProgressBar(queue);
|
||||
const displayEmbedProgressBar: string = this.getDisplayQueueProgressBar(queue);
|
||||
|
||||
const customId: string = `nowplaying-skip-button_${currentTrack.id}`;
|
||||
logger.debug(`Generated custom id for skip button: ${customId}`);
|
||||
@@ -107,28 +103,6 @@ class NowPlayingCommand extends BaseSlashCommandInteraction {
|
||||
return author;
|
||||
}
|
||||
|
||||
private async getDisplayQueueProgressBar(queue: GuildQueue): Promise<string> {
|
||||
const timestamp: PlayerTimestamp = queue.node.getTimestamp()!;
|
||||
let progressBar: string = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({
|
||||
queue: false,
|
||||
length: playerOptions.progressBar.length ?? 12,
|
||||
timecodes: playerOptions.progressBar.timecodes ?? false,
|
||||
indicator: playerOptions.progressBar.indicator ?? '🔘',
|
||||
leftChar: playerOptions.progressBar.leftChar ?? '▬',
|
||||
rightChar: playerOptions.progressBar.rightChar ?? '▬'
|
||||
})} **\`${timestamp.total.label}\`**`;
|
||||
|
||||
if (Number(queue.currentTrack?.raw.duration) === 0 || queue.currentTrack?.duration === '0:00') {
|
||||
progressBar = '_No duration available._';
|
||||
}
|
||||
|
||||
if (queue.currentTrack?.raw.live) {
|
||||
progressBar = `${this.embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`;
|
||||
}
|
||||
|
||||
return progressBar;
|
||||
}
|
||||
|
||||
private getTrackSourceString(currentTrack: Track): string {
|
||||
const sourceStringsFormatted: Map<string, string> = new Map([
|
||||
['youtube', 'YouTube'],
|
||||
@@ -188,10 +162,6 @@ class NowPlayingCommand extends BaseSlashCommandInteraction {
|
||||
: `**${this.embedOptions.icons.audioPlaying} Now Playing**`;
|
||||
};
|
||||
|
||||
private getDisplayTrackRequestedBy = (currentTrack: Track): string => {
|
||||
return currentTrack.requestedBy ? `<@${currentTrack.requestedBy.id}>` : 'Unavailable';
|
||||
};
|
||||
|
||||
private getEmbedFields = (currentTrack: Track): EmbedField[] => {
|
||||
const fields: EmbedField[] = [
|
||||
{
|
||||
|
||||
@@ -27,7 +27,7 @@ class PauseCommand extends BaseSlashCommandInteraction {
|
||||
|
||||
const currentTrack: Track = queue.currentTrack!;
|
||||
|
||||
this.togglePauseState(queue, logger);
|
||||
this.togglePauseState(logger, queue);
|
||||
|
||||
logger.debug('Responding with success embed.');
|
||||
return await interaction.editReply({
|
||||
@@ -45,7 +45,7 @@ class PauseCommand extends BaseSlashCommandInteraction {
|
||||
});
|
||||
}
|
||||
|
||||
private togglePauseState(queue: GuildQueue, logger: Logger): void {
|
||||
private togglePauseState(logger: Logger, queue: GuildQueue): void {
|
||||
queue.node.setPaused(!queue.node.isPaused());
|
||||
logger.debug(`Set paused state to ${queue.node.isPaused()}.`);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import config from 'config';
|
||||
import { GuildQueue, PlayerTimestamp, Track, useQueue } from 'discord-player';
|
||||
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
|
||||
import { GuildQueue, Track, useQueue } from 'discord-player';
|
||||
import { ChatInputCommandInteraction, EmbedBuilder, SlashCommandBuilder } from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import { BaseSlashCommandInteraction } from '../../../classes/interactions';
|
||||
import { PlayerOptions } from '../../../types/configTypes';
|
||||
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../../types/interactionTypes';
|
||||
import { checkQueueExists } from '../../../utils/validation/queueValidator';
|
||||
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
|
||||
|
||||
const playerOptions: PlayerOptions = config.get('playerOptions');
|
||||
|
||||
class QueueCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = new SlashCommandBuilder()
|
||||
@@ -32,120 +29,140 @@ class QueueCommand extends BaseSlashCommandInteraction {
|
||||
checkQueueExists
|
||||
]);
|
||||
|
||||
const pageIndex: number = (interaction.options.getNumber('page') || 1) - 1;
|
||||
let queueString: string = '';
|
||||
|
||||
const queueLength: number = queue.tracks.data.length;
|
||||
const totalPages: number = Math.ceil(queueLength / 10) || 1;
|
||||
const pageIndex: number = this.getPageIndex(interaction);
|
||||
const totalPages: number = this.getTotalPages(queue);
|
||||
|
||||
if (pageIndex > totalPages - 1) {
|
||||
logger.debug('Specified page was higher than total pages.');
|
||||
|
||||
logger.debug('Responding with warning embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(
|
||||
`**${this.embedOptions.icons.warning} Oops!**\nPage **\`${
|
||||
pageIndex + 1
|
||||
}\`** is not a valid page number.\n\nThere are only a total of **\`${totalPages}\`** pages in the queue.`
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
return await this.handleInvalidPage(logger, interaction, pageIndex, totalPages);
|
||||
}
|
||||
|
||||
if (queue.tracks.data.length === 0) {
|
||||
logger.debug('Queue exists but with no tracks, displaying empty queue.');
|
||||
queueString = 'The queue is empty, add some tracks with **`/play`**!';
|
||||
} else {
|
||||
queueString = queue.tracks.data
|
||||
.slice(pageIndex * 10, pageIndex * 10 + 10)
|
||||
.map((track, index) => {
|
||||
return `**${pageIndex * 10 + index + 1}.** ${this.getDisplayTrackDurationAndUrl(track)}`;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
const queueTracksListString: string = this.getQueueTracksListString(queue, pageIndex);
|
||||
|
||||
const currentTrack: Track = queue.currentTrack!;
|
||||
if (currentTrack) {
|
||||
return await this.handleCurrentTrack(logger, interaction, queue, currentTrack, queueTracksListString);
|
||||
}
|
||||
|
||||
const loopModesFormatted = new Map([
|
||||
return await this.handleNoCurrentTrack(logger, interaction, queue, queueTracksListString);
|
||||
}
|
||||
|
||||
private async handleCurrentTrack(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
currentTrack: Track,
|
||||
queueTracksListString: string
|
||||
) {
|
||||
logger.debug('Queue exists with current track, gathering information.');
|
||||
|
||||
logger.debug('Responding with info embed.');
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(await this.getEmbedQueueAuthor(interaction, queue))
|
||||
.setDescription(
|
||||
`**${this.embedOptions.icons.audioPlaying} Now playing**\n` +
|
||||
`${this.getFormattedTrackUrl(currentTrack)}\n` +
|
||||
`${this.getDisplayTrackRequestedBy(currentTrack)}\n` +
|
||||
`${this.getDisplayQueueProgressBar(queue)}\n\n` +
|
||||
`${this.getDisplayRepeatMode(queue.repeatMode)}` +
|
||||
`**${this.embedOptions.icons.queue} Tracks in queue**\n` +
|
||||
queueTracksListString
|
||||
)
|
||||
.setThumbnail(this.getTrackThumbnailUrl(currentTrack))
|
||||
.setFooter(this.getFooterDisplayPageInfo(interaction, queue))
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
]
|
||||
});
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
private async handleNoCurrentTrack(
|
||||
logger: Logger,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
queue: GuildQueue,
|
||||
queueTracksListString: string
|
||||
) {
|
||||
logger.debug('Queue exists but there is no current track.');
|
||||
|
||||
logger.debug('Responding with info embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(await this.getEmbedQueueAuthor(interaction, queue))
|
||||
.setDescription(
|
||||
`${this.getDisplayRepeatMode(queue.repeatMode)}` +
|
||||
`**${this.embedOptions.icons.queue} Tracks in queue**\n` +
|
||||
queueTracksListString
|
||||
)
|
||||
.setFooter(this.getFooterDisplayPageInfo(interaction, queue))
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
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 in the queue.`
|
||||
)
|
||||
.setColor(this.embedOptions.colors.warning)
|
||||
]
|
||||
});
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
private getDisplayRepeatMode(repeatMode: number): string {
|
||||
const repeatModesFormatted = new Map([
|
||||
[0, 'disabled'],
|
||||
[1, 'track'],
|
||||
[2, 'queue'],
|
||||
[3, 'autoplay']
|
||||
]);
|
||||
|
||||
const loopModeUserString: string = loopModesFormatted.get(queue.repeatMode)!;
|
||||
|
||||
const getRepeatModeMessage = (repeatMode: number): string => {
|
||||
const icon = repeatMode === 3 ? this.embedOptions.icons.autoplay : this.embedOptions.icons.loop;
|
||||
return `**${icon} Looping**\nLoop mode is set to **\`${loopModeUserString}\`**. You can change it with **\`/loop\`**.\n\n`;
|
||||
};
|
||||
|
||||
const repeatModeString: string = queue.repeatMode === 0 ? '' : getRepeatModeMessage(queue.repeatMode);
|
||||
|
||||
if (!currentTrack) {
|
||||
logger.debug('Queue exists but there is no current track.');
|
||||
|
||||
logger.debug('Responding with info embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(await this.getEmbedQueueAuthor(interaction, queue))
|
||||
.setDescription(
|
||||
`${repeatModeString}` +
|
||||
`**${this.embedOptions.icons.queue} Tracks in queue**\n${queueString}`
|
||||
)
|
||||
.setFooter({
|
||||
text: `Page ${pageIndex + 1} of ${totalPages} (${queueLength} tracks)`
|
||||
})
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
]
|
||||
});
|
||||
} else {
|
||||
logger.debug('Queue exists with current track, gathering information.');
|
||||
const timestamp: PlayerTimestamp = queue.node.getTimestamp()!;
|
||||
let bar: string = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({
|
||||
queue: false,
|
||||
length: playerOptions.progressBar.length ?? 12,
|
||||
timecodes: playerOptions.progressBar.timecodes ?? false,
|
||||
indicator: playerOptions.progressBar.indicator ?? '🔘',
|
||||
leftChar: playerOptions.progressBar.leftChar ?? '▬',
|
||||
rightChar: playerOptions.progressBar.rightChar ?? '▬'
|
||||
})} **\`${timestamp.total.label}\`**`;
|
||||
|
||||
if (Number(currentTrack.raw.duration) === 0 || currentTrack.duration === '0:00') {
|
||||
bar = '_No duration available._';
|
||||
}
|
||||
|
||||
if (currentTrack.raw.live) {
|
||||
bar = `${this.embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`;
|
||||
}
|
||||
|
||||
logger.debug('Responding with info embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setAuthor(await this.getEmbedQueueAuthor(interaction, queue))
|
||||
.setDescription(
|
||||
`**${this.embedOptions.icons.audioPlaying} Now playing**\n` +
|
||||
(currentTrack
|
||||
? `**[${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**`
|
||||
: 'None') +
|
||||
`\nRequested by: <@${currentTrack.requestedBy?.id}>` +
|
||||
`\n ${bar}\n\n` +
|
||||
`${repeatModeString}` +
|
||||
`**${this.embedOptions.icons.queue} Tracks in queue**\n${queueString}`
|
||||
)
|
||||
.setThumbnail(this.getTrackThumbnailUrl(currentTrack))
|
||||
.setFooter({
|
||||
text: `Page ${pageIndex + 1} of ${totalPages} (${queueLength} tracks)`
|
||||
})
|
||||
.setColor(this.embedOptions.colors.info)
|
||||
]
|
||||
});
|
||||
if (repeatMode === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const loopModeUserString: string = repeatModesFormatted.get(repeatMode)!;
|
||||
const icon = repeatMode === 3 ? this.embedOptions.icons.autoplay : this.embedOptions.icons.loop;
|
||||
return (
|
||||
`**${icon} Looping**\n` +
|
||||
`Loop mode is set to **\`${loopModeUserString}\`**. You can change it with **\`/loop\`**.\n\n`
|
||||
);
|
||||
}
|
||||
|
||||
private getPageIndex(interaction: ChatInputCommandInteraction): number {
|
||||
return (interaction.options.getNumber('page') || 1) - 1;
|
||||
}
|
||||
|
||||
private getTotalPages(queue: GuildQueue): number {
|
||||
return Math.ceil(queue.tracks.data.length / 10) || 1;
|
||||
}
|
||||
|
||||
private getQueueTracksListString(queue: GuildQueue, pageIndex: number): string {
|
||||
if (!queue || queue.tracks.data.length === 0) {
|
||||
return 'The queue is empty, add some tracks with **`/play`**!';
|
||||
}
|
||||
|
||||
return queue.tracks.data
|
||||
.slice(pageIndex * 10, pageIndex * 10 + 10)
|
||||
.map((track, index) => {
|
||||
return `**${pageIndex * 10 + index + 1}.** ${this.getDisplayTrackDurationAndUrl(track)}`;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user