fix: refactored play command and added common method for getting thumbnail url

This commit is contained in:
Marius Begby committed 2023-09-12 20:54:49 +02:00
1 parent 85e27afc5c
commit bf30d565d7
7 files changed
+248 -196

No files matched your search

+29 -1
View File
@@ -14,7 +14,7 @@ import {
} from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../services/logger';
import { BotOptions, EmbedOptions } from '../types/configTypes';
import { BotOptions, EmbedOptions, PlayerOptions } from '../types/configTypes';
import {
BaseAutocompleteParams,
BaseAutocompleteReturnType,
@@ -29,10 +29,12 @@ import { Validator, ValidatorParams } from '../types/utilTypes';
abstract class BaseInteraction {
embedOptions: EmbedOptions;
botOptions: BotOptions;
playerOptions: PlayerOptions;
constructor() {
this.embedOptions = config.get('embedOptions');
this.botOptions = config.get('botOptions');
this.playerOptions = config.get('playerOptions');
}
protected getLoggerBase(
@@ -85,6 +87,32 @@ abstract class BaseInteraction {
return `${formattedDuration} ${formattedUrl}`;
}
protected getTrackThumbnailUrl(track: Track): string {
let thumbnailUrl = '';
if (track.source === 'youtube') {
if (track.raw.thumbnail) {
// @ts-ignore -- discord-player bug with thumbnail for youtube?
thumbnailUrl = track.raw.thumbnail.url;
} else if (track.thumbnail && !track.thumbnail.endsWith('maxresdefault.jpg')) {
// @ts-ignore -- discord-player bug with thumbnail for youtube?
thumbnailUrl = track.thumbnail.url;
} else {
thumbnailUrl = this.embedOptions.info.fallbackThumbnailUrl;
}
} else {
if (track.raw.thumbnail) {
thumbnailUrl = track.raw.thumbnail;
} else if (track.thumbnail) {
thumbnailUrl = track.thumbnail;
} else {
thumbnailUrl = this.embedOptions.info.fallbackThumbnailUrl;
}
}
return thumbnailUrl;
}
abstract execute(
params: BaseInteractionParams
): Promise<Message<boolean> | ApplicationCommandOptionChoiceData | void>;
@@ -79,7 +79,7 @@ class NowPlayingCommand extends BaseSlashCommandInteraction {
.setFooter({
text: tracksInQueueCount ? `${tracksInQueueCount} other tracks in the queue...` : ' '
})
.setThumbnail(queue.currentTrack!.thumbnail)
.setThumbnail(this.getTrackThumbnailUrl(queue.currentTrack!))
.setColor(this.embedOptions.colors.info)
],
components: [embedActionRow as APIActionRowComponent<APIMessageActionRowComponent>]
+213 -189
View File
@@ -1,14 +1,11 @@
import config from 'config';
import { GuildQueue, useMainPlayer, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import { GuildQueue, Player, SearchResult, Track, useMainPlayer, useQueue } from 'discord-player';
import { ChatInputCommandInteraction, EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import { Logger } from 'pino';
import { BaseSlashCommandInteraction, CustomError } from '../../../classes/interactions';
import { PlayerOptions } from '../../../types/configTypes';
import { BaseSlashCommandParams, BaseSlashCommandReturnType } from '../../../types/interactionTypes';
import { checkVoicePermissionJoinAndTalk } from '../../../utils/validation/permissionValidator';
import { transformQuery } from '../../../utils/validation/searchQueryValidator';
import { checkSameVoiceChannel, checkInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const playerOptions: PlayerOptions = config.get('playerOptions');
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
class PlayCommand extends BaseSlashCommandInteraction {
constructor() {
@@ -41,12 +38,46 @@ class PlayCommand extends BaseSlashCommandInteraction {
}
const player = useMainPlayer()!;
const query = interaction.options.getString('query')!;
const searchQuery = interaction.options.getString('query')!;
const transformedQuery = await transformQuery({ query: searchQuery, executionId });
const transformedQuery = await transformQuery({ query, executionId });
const searchResult = await this.searchTrack(player, transformedQuery, interaction, logger);
if (!searchResult || searchResult.tracks.length === 0) {
return await this.handleNoResultsFound(transformedQuery, interaction, logger);
}
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);
}
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);
}
private async searchTrack(
player: Player,
transformedQuery: string,
interaction: ChatInputCommandInteraction,
logger: Logger
) {
logger.debug(`Searching for track with query: '${transformedQuery}'.`);
let searchResult;
try {
searchResult = await player.search(transformedQuery, {
requestedBy: interaction.user
@@ -54,99 +85,42 @@ class PlayCommand extends BaseSlashCommandInteraction {
} catch (error) {
logger.error(error, `Failed to search for track with player.search() with query: ${transformedQuery}.`);
}
return searchResult;
}
if (!searchResult || searchResult.tracks.length === 0) {
logger.debug(`No results found for query: '${query}'`);
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${this.embedOptions.icons.warning} No track found**\nNo results found for **\`${transformedQuery}\`**.\n\nIf you specified a URL, please make sure it is valid and public.`
)
.setColor(this.embedOptions.colors.warning)
]
});
}
queue = useQueue(interaction.guild!.id)!;
const queueSize = queue?.size ?? 0;
if ((searchResult.playlist! && searchResult.tracks.length) > playerOptions.maxQueueSize - queueSize) {
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(
`**${this.embedOptions.icons.warning} Playlist too large**\nThis playlist is too large to be added to the queue.\n\nThe maximum amount of tracks that can be added to the queue is **${playerOptions.maxQueueSize}**.`
)
.setColor(this.embedOptions.colors.warning)
]
});
}
private async addResultsToPlayer(
player: Player,
searchResult: SearchResult,
interaction: ChatInputCommandInteraction,
logger: Logger,
executionId: string,
query: string
) {
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: {
leaveOnEmpty: playerOptions.leaveOnEmpty ?? true,
leaveOnEmptyCooldown: playerOptions.leaveOnEmptyCooldown ?? 300_000,
leaveOnEnd: playerOptions.leaveOnEnd ?? true,
leaveOnEndCooldown: playerOptions.leaveOnEndCooldown ?? 300_000,
leaveOnStop: playerOptions.leaveOnStop ?? true,
leaveOnStopCooldown: playerOptions.leaveOnStopCooldown ?? 300_000,
maxSize: playerOptions.maxQueueSize ?? 1000,
maxHistorySize: playerOptions.maxHistorySize ?? 100,
volume: playerOptions.defaultVolume ?? 50,
bufferingTimeout: playerOptions.bufferingTimeout ?? 3000,
connectionTimeout: playerOptions.connectionTimeout ?? 30000,
...this.playerOptions,
maxSize: this.playerOptions.maxQueueSize,
volume: this.playerOptions.defaultVolume,
metadata: {
channel: interaction.channel,
client: interaction.client,
requestedBy: interaction.user,
track: searchResult.tracks[0]
requestedBy: interaction.user
}
}
}));
} catch (error) {
if (error instanceof CustomError) {
if (error.message.includes('Sign in to confirm your age')) {
logger.debug('Found track but failed to retrieve audio due to age confirmation warning.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${this.embedOptions.icons.warning} Cannot retrieve audio for track**\nThis 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)
]
});
return this.handleAgeConfirmationError(interaction, logger, executionId);
}
if (error.message.includes('The following content may contain')) {
logger.debug(
'Found track but failed to retrieve audio due to graphic/mature/sensitive topic warning.'
);
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${this.embedOptions.icons.warning} Cannot retrieve audio for track**\nThis 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)
]
});
return this.handleSensitiveTopicError(interaction, logger, executionId);
}
if (
@@ -154,37 +128,11 @@ class PlayCommand extends BaseSlashCommandInteraction {
error.message.includes('Failed to fetch resources for ytdl streaming') ||
error.message.includes('Could not extract stream for this track')
) {
logger.debug(error, `Found track but failed to retrieve audio. Query: ${query}.`);
// note: reading 'createStream' error can happen if queue is destroyed before track starts playing, e.g. /leave quickly after /play
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${this.embedOptions.icons.error} Uh-oh... Failed to add track!**\nAfter finding a result, I was unable to retrieve audio for the track.\n\nYou 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}` })
]
});
return this.handleStreamError(interaction, logger, executionId, error, query);
}
if (error.message === 'Cancelled') {
logger.debug(error, `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\nYou 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}` })
]
});
return this.handleCancelledError(interaction, logger, executionId, query);
}
logger.error(error, 'Failed to play track with player.play(), unhandled error.');
@@ -192,97 +140,173 @@ class PlayCommand extends BaseSlashCommandInteraction {
throw error;
}
}
return track;
}
logger.debug(`Successfully added track with player.play(). Query: '${query}'.`);
private async handleResultAddedToQueue(
track: Track,
searchResult: SearchResult,
interaction: ChatInputCommandInteraction,
logger: Logger
) {
logger.debug('Result found and added with player.play(), added to queue.');
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
const trackUrl = this.getDisplayTrackDurationAndUrl(track);
queue = useQueue(interaction.guild!.id)!;
if (!queue || !track) {
logger.warn(`After player.play(), queue is undefined. 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!**\nThere was an issue adding this track to the queue.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${this.botOptions.serverInviteUrl})**._`
)
.setColor(this.embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
let message = `${this.embedOptions.icons.success} **Added to queue**\n${trackUrl}`;
if (searchResult.playlist) {
const otherTracksString = `And **${searchResult.tracks.length}** more tracks... **\`/queue\`** to view all.`;
message = `${this.embedOptions.icons.success} **Added playlist to queue**\n${trackUrl}\n\n${otherTracksString}`;
} else if (queue.currentTrack === track && queue.tracks.data.length === 0) {
message = `**${this.embedOptions.icons.audioStartedPlaying} Now playing**\n${trackUrl}`;
}
if (
track.source.length === 0 ||
track.source === 'arbitrary' ||
track.thumbnail === null ||
track.thumbnail === undefined ||
track.thumbnail === ''
) {
logger.debug(
`Track found but source is arbitrary or missing thumbnail. Using fallback thumbnail url. Query: '${query}'.`
);
track.thumbnail = this.embedOptions.info.fallbackThumbnailUrl;
}
if (searchResult.playlist && searchResult.tracks.length > 1) {
logger.debug(`Playlist found and added with player.play(). Query: '${query}'`);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor(await this.getEmbedUserAuthor(interaction))
.setDescription(
`**${
this.embedOptions.icons.success
} Added playlist to queue**\n${this.getDisplayTrackDurationAndUrl(track)}\n\nAnd **${
searchResult.tracks.length - 1
}** more tracks... **\`/queue\`** to view all.`
)
.setThumbnail(track.thumbnail)
.setColor(this.embedOptions.colors.success)
]
});
}
if (queue && queue.currentTrack === track && queue.tracks.data.length === 0) {
logger.debug(`Track found and added with player.play(), started playing. Query: '${query}'.`);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor(await this.getEmbedUserAuthor(interaction))
.setDescription(
`**${
this.embedOptions.icons.audioStartedPlaying
} Started playing**\n${this.getDisplayTrackDurationAndUrl(track)}`
)
.setThumbnail(track.thumbnail)
.setColor(this.embedOptions.colors.success)
]
});
}
logger.debug(`Track found and added with player.play(), added to queue. Query: '${query}'.`);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor(await this.getEmbedUserAuthor(interaction))
.setDescription(
`${this.embedOptions.icons.success} **Added to queue**\n${this.getDisplayTrackDurationAndUrl(
track
)}`
)
.setThumbnail(track.thumbnail)
.setDescription(message)
.setThumbnail(this.getTrackThumbnailUrl(track))
.setColor(this.embedOptions.colors.success)
]
});
}
private async handleNoResultsFound(
transformedQuery: string,
interaction: ChatInputCommandInteraction,
logger: Logger
) {
logger.debug(`No results found for query: '${transformedQuery}'`);
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${this.embedOptions.icons.warning} No track found**\n` +
`No results found for **\`${transformedQuery}\`**.\n\n` +
'If you specified a URL, please make sure it is valid and public.'
)
.setColor(this.embedOptions.colors.warning)
]
});
}
private async handlePlaylistTooLarge(query: string, interaction: ChatInputCommandInteraction, logger: Logger) {
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(
`**${this.embedOptions.icons.warning} Playlist too large**\n` +
'This playlist is too large to be added to the queue.\n\n' +
`The maximum amount of tracks that can be added to the queue is **${this.playerOptions.maxQueueSize}**.`
)
.setColor(this.embedOptions.colors.warning)
]
});
}
private async handleAgeConfirmationError(
interaction: ChatInputCommandInteraction,
logger: Logger,
executionId: string
) {
logger.debug('Found track but failed to retrieve audio due to age confirmation warning.');
logger.debug('Responding with warning embed.');
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}` })
]
});
return Promise.resolve();
}
private async handleSensitiveTopicError(
interaction: ChatInputCommandInteraction,
logger: Logger,
executionId: string
) {
logger.debug('Found track but failed to retrieve audio due to graphic/mature/sensitive topic warning.');
logger.debug('Responding with warning embed.');
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}` })
]
});
return Promise.resolve();
}
private async handleStreamError(
interaction: ChatInputCommandInteraction,
logger: Logger,
executionId: string,
error: Error,
query: string
) {
logger.debug(error, `Found track but failed to retrieve audio. Query: ${query}.`);
logger.debug('Responding with error embed.');
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}` })
]
});
return Promise.resolve();
}
private async handleCancelledError(
interaction: ChatInputCommandInteraction,
logger: Logger,
executionId: string,
query: string
) {
logger.debug(`Operation cancelled. Query: ${query}.`);
logger.debug('Responding with error embed.');
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}` })
]
});
return Promise.resolve();
}
}
export default new PlayCommand();
+1 -1
View File
@@ -138,7 +138,7 @@ class QueueCommand extends BaseSlashCommandInteraction {
`${repeatModeString}` +
`**${this.embedOptions.icons.queue} Tracks in queue**\n${queueString}`
)
.setThumbnail(currentTrack.thumbnail)
.setThumbnail(this.getTrackThumbnailUrl(currentTrack))
.setFooter({
text: `Page ${pageIndex + 1} of ${totalPages} (${queueLength} tracks)`
})
+1 -1
View File
@@ -63,7 +63,7 @@ class RemoveCommand extends BaseSlashCommandInteraction {
removedTrack
)}`
)
.setThumbnail(removedTrack.thumbnail)
.setThumbnail(this.getTrackThumbnailUrl(removedTrack))
.setColor(this.embedOptions.colors.success)
]
});
+1 -1
View File
@@ -147,7 +147,7 @@ class SeekCommand extends BaseSlashCommandInteraction {
.setDescription(
`**${this.embedOptions.icons.success} Seeking to duration**\nSeeking to **\`${durationString}\`** in current track.`
)
.setThumbnail(queue.currentTrack!.thumbnail)
.setThumbnail(this.getTrackThumbnailUrl(queue.currentTrack!))
.setColor(this.embedOptions.colors.success)
]
});
+2 -2
View File
@@ -62,7 +62,7 @@ class SkipCommand extends BaseSlashCommandInteraction {
this.embedOptions.icons.skipped
} Skipped track**\n${this.getDisplayTrackDurationAndUrl(skippedTrack)}`
)
.setThumbnail(skippedTrack.thumbnail)
.setThumbnail(this.getTrackThumbnailUrl(skippedTrack))
.setColor(this.embedOptions.colors.success)
]
});
@@ -114,7 +114,7 @@ class SkipCommand extends BaseSlashCommandInteraction {
skippedTrack
)}` + `\n\n${repeatModeString}`
)
.setThumbnail(skippedTrack.thumbnail)
.setThumbnail(this.getTrackThumbnailUrl(skippedTrack))
.setColor(this.embedOptions.colors.success)
]
});