feat!: Change interaction structure and handling of component responses

This commit is contained in:
Marius Begby committed 2023-08-27 23:20:32 +02:00
1 parent 905df36ef8
commit 9b02b21283
24 files changed
+232 -239

No files matched your search

+71
View File
@@ -0,0 +1,71 @@
import config from 'config';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../../services/logger';
import { CommandParams } from '../../../types/commandTypes';
import { BotOptions, EmbedOptions } from '../../../types/configTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('help')
.setDescription('Show a list of commands and their usage.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'help.js',
module: 'slashCommand',
name: '/help',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (!client || !client.commands) {
logger.error('Client is undefined or does not have commands property.');
return;
}
const commandList = client.commands
.filter((command) => {
// don't include system commands
if (command.isSystemCommand) {
return false;
}
return true;
})
.map((command) => {
const params = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : '';
const beta = command.isBeta ? `${embedOptions.icons.beta} ` : '';
const newCommand = command.isNew ? `${embedOptions.icons.new} ` : '';
return `- **\`/${command.data.name}\`** ${params}- ${beta}${newCommand}${command.data.description}`;
});
const commandListString = commandList.join('\n');
const supportServerString = botOptions.serverInviteUrl
? `${embedOptions.icons.support} **Support server**\nJoin the support server for help or to suggest improvements: \n**${botOptions.serverInviteUrl}**\n\n`
: '';
const addBotString = botOptions.botInviteUrl
? `${embedOptions.icons.bot} **Enjoying ${botOptions.name}?**\nAdd me to another server: \n**[Click me!](${botOptions.botInviteUrl})**`
: '';
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`${embedOptions.icons.rule} **List of commands**\n` +
`${commandListString}\n\n` +
supportServerString +
addBotString
)
.setColor(embedOptions.colors.info)
]
});
}
};
+135
View File
@@ -0,0 +1,135 @@
import config from 'config';
import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js';
import osu from 'node-os-utils';
// @ts-ignore
import { version } from '../../../../package.json';
import loggerModule from '../../../services/logger';
import { CommandParams } from '../../../types/commandTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('status')
.setDescription('Show the bot and system status.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'status.js',
module: 'slashCommand',
name: '/status',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
const uptimeString = await getUptimeFormatted({ executionId });
const usedMemoryInMB = Math.ceil((await osu.mem.info()).usedMemMb).toLocaleString('en-US');
const cpuUsage = await osu.cpu.usage();
const releaseVersion = version;
let guildCount: number = 0;
let memberCount: number = 0;
let activeVoiceConnections: number = 0;
let totalTracks: number = 0;
let totalListeners: number = 0;
if (!client || !client.shard) {
logger.error('Client is undefined or does not have shard property.');
return;
}
await client.shard
.broadcastEval(() => {
/* eslint-disable no-undef */
return player.generateStatistics();
})
.then((results) => {
const queueCountList: number[] = [];
const trackCountList: number[] = [];
const listenerCountList: number[] = [];
results.map((result) => {
queueCountList.push(result.queues.length);
if (result.queues.length > 0) {
result.queues.map((queue) => {
trackCountList.push(queue.status.playing ? queue.tracksCount + 1 : queue.tracksCount);
listenerCountList.push(queue.listeners);
});
}
});
activeVoiceConnections = queueCountList.reduce((acc, queueAmount) => acc + queueAmount, 0);
totalTracks = trackCountList.reduce((acc, trackAmount) => acc + trackAmount, 0);
totalListeners = listenerCountList.reduce((acc, listenerAmount) => acc + listenerAmount, 0);
logger.debug('Successfully fetched player statistics from shards.');
})
.catch((error) => {
logger.error(error, 'Failed to fetch player statistics from shards.');
});
await client.shard
.fetchClientValues('guilds.cache')
.then((results) => {
const guildCaches = results as Guild[][];
guildCaches.map((guildCache: Guild[]) => {
if (guildCache) {
guildCount += guildCache.length;
memberCount += guildCache.reduce((acc: number, guild: Guild) => acc + guild.memberCount, 0);
}
});
logger.debug('Successfully fetched client values from shards.');
})
.catch((error) => {
logger.error(error, 'Failed to fetch client values from shards.');
});
const botStatusString =
`**${guildCount.toLocaleString('en-US')}** Joined servers\n` +
`**${memberCount.toLocaleString('en-US')}** Total members\n` +
`**v${releaseVersion}** Release version`;
const queueStatusString =
`**${activeVoiceConnections.toLocaleString('en-US')}** Voice connections\n` +
`**${totalTracks.toLocaleString('en-US')}** Tracks in queues\n` +
`**${totalListeners.toLocaleString('en-US')}** Users listening`;
const systemStatusString =
`**${uptimeString}** Uptime\n` + `**${cpuUsage}%** CPU usage\n` + `**${usedMemoryInMB} MB** Memory usage`;
const discordStatusString = `**${client.ws.ping} ms** Discord API latency`;
logger.debug('Transformed status into into embed description.');
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(`**${embedOptions.icons.bot} Bot status**\n` + botStatusString)
.addFields(
{
name: `**${embedOptions.icons.queue} Queue status**`,
value: queueStatusString,
inline: false
},
{
name: `**${embedOptions.icons.server} System status**`,
value: systemStatusString,
inline: false
},
{
name: `**${embedOptions.icons.discord} Discord status**`,
value: discordStatusString,
inline: false
}
)
.setColor(embedOptions.colors.info)
]
});
}
};
+239
View File
@@ -0,0 +1,239 @@
import config from 'config';
import { NodeResolvable, QueueFilters, useQueue } from 'discord-player';
import {
APIActionRowComponent,
APIMessageActionRowComponent,
ButtonBuilder,
ButtonStyle,
ComponentType,
EmbedBuilder,
GuildMember,
Interaction,
SlashCommandBuilder,
StringSelectMenuBuilder,
StringSelectMenuOptionBuilder
} from 'discord.js';
import loggerModule from '../../../services/logger';
import { CommandParams, CustomError } from '../../../types/commandTypes';
import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('filters')
.setDescription('Toggle various audio filters during playback.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'filters.js',
module: 'slashCommand',
name: '/filters',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
}
const filterOptions: StringSelectMenuOptionBuilder[] = [];
ffmpegFilterOptions.availableFilters.forEach((filter: FFmpegFilterOption) => {
let isEnabled = 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)
);
});
const filterSelect = new StringSelectMenuBuilder()
.setCustomId('filters')
.setPlaceholder('Select multiple options.')
.setMinValues(0)
.setMaxValues(filterOptions.length)
.addOptions(filterOptions)
.toJSON();
const filterActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
type: ComponentType.ActionRow,
components: [filterSelect]
};
const disableButton = new ButtonBuilder()
.setCustomId('disable-filters')
.setLabel('Disable all filters')
.setStyle(ButtonStyle.Secondary)
.setEmoji(embedOptions.icons.disable)
.toJSON();
const disableFiltersActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
type: ComponentType.ActionRow,
components: [disableButton]
};
logger.debug('Sending info embed with action row components.');
const response = await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription('**Toggle filters**\nEnable or disable audio filters for playback from the menu.')
.setColor(embedOptions.colors.info)
],
components: [filterActionRow, disableFiltersActionRow]
});
const collectorFilter = (i: Interaction) => i.user.id === interaction.user.id;
try {
const confirmation = await response.awaitMessageComponent({
filter: collectorFilter,
time: 300_000
});
confirmation.deferUpdate();
logger.debug('Received component interaction response.');
queue.filters.ffmpeg.setInputArgs([
'-threads',
ffmpegFilterOptions.threadAmount,
'-reconnect',
'1',
'-reconnect_streamed',
'1',
'-reconnect_delay_max',
'10',
'-vn'
]);
// Reset filters before enabling provided filters
if (queue.filters.ffmpeg.filters.length > 0) {
queue.filters.ffmpeg.setFilters(false);
logger.debug('Reset queue filters.');
}
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
if ('values' in confirmation) {
// if bassboost is enabled and not normalizer, also enable normalizer to avoid distrorion
if (
(confirmation.values.includes('bassboost_low') || confirmation.values.includes('bassboost')) &&
!confirmation.values.includes('normalizer')
) {
confirmation.values.push('normalizer');
}
// Enable provided filters
queue.filters.ffmpeg.toggle(confirmation.values as (keyof QueueFilters)[]);
logger.debug(`Enabled filters ${confirmation.values.join(', ')}.`);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${
embedOptions.icons.success
} Filters toggled**\nNow using these filters:\n${confirmation.values
.map((enabledFilter: string) => {
const filter = ffmpegFilterOptions.availableFilters.find(
(filter) => enabledFilter == filter.value
);
if (!filter) {
return enabledFilter;
}
return `- **${filter.emoji} ${filter.label}**`;
})
.join('\n')}`
)
.setColor(embedOptions.colors.success)
],
components: []
});
} else if (confirmation.customId === 'disable-filters') {
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.success} Disabled filters**\nAll audio filters have been disabled.`
)
.setColor(embedOptions.colors.success)
],
components: []
});
} else {
logger.warn('Unhandled component interaction response.');
}
} catch (error) {
if (error instanceof CustomError) {
if (error.code === 'InteractionCollectorError') {
logger.debug('Interaction response timed out.');
return;
}
if (error.message === 'Collector received no interactions before ending with reason: time') {
logger.debug('Interaction response timed out.');
return;
}
logger.error(error, 'Unhandled error while awaiting or handling component interaction.');
return;
} else {
if (
error instanceof Error &&
error.message === 'Collector received no interactions before ending with reason: time'
) {
logger.debug('Interaction response timed out.');
return;
}
throw error;
}
}
}
};
+82
View File
@@ -0,0 +1,82 @@
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../../services/logger';
import { CommandParams } from '../../../types/commandTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('leave')
.setDescription('Clear the track queue and remove the bot from voice channel.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'leave.js',
module: 'slashCommand',
name: '/leave',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (!queue) {
logger.debug('There is already no queue.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\n_Hmm.._ It seems I am not in a voice channel!`
)
.setColor(embedOptions.colors.warning)
]
});
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (!queue.deleted) {
queue.delete();
logger.debug('Deleted the queue.');
}
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.success} Leaving channel**\nCleared the track queue and left voice channel.\n\nTo play more music, use the **\`/play\`** command!`
)
.setColor(embedOptions.colors.success)
]
});
}
};
+186
View File
@@ -0,0 +1,186 @@
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../../services/logger';
import { CommandParams } from '../../../types/commandTypes';
import { BotOptions, EmbedOptions } from '../../../types/configTypes';
import { queueDoesNotExist } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('loop')
.setDescription('Toggle looping a track, the whole queue or autoplay.')
.setDMPermission(false)
.setNSFW(false)
.addStringOption((option) =>
option
.setName('mode')
.setDescription('Mode to set for looping.')
.setRequired(false)
.addChoices(
{ name: 'Track', value: '1' },
{ name: 'Queue', value: '2' },
{ name: 'Autoplay', value: '3' },
{ name: 'Disabled', value: '0' }
)
),
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'loop.js',
module: 'slashCommand',
name: '/loop',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
const loopModesFormatted = new Map([
[0, 'disabled'],
[1, 'track'],
[2, 'queue'],
[3, 'autoplay']
]);
const mode = parseInt(interaction.options.getString('mode')!);
const modeUserString = loopModesFormatted.get(mode);
const currentMode = queue.repeatMode;
const currentModeUserString = loopModesFormatted.get(currentMode);
if (!mode && mode !== 0) {
logger.debug('No mode input was provided, responding with current loop mode.');
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${
currentMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop
} Current loop mode**\nThe looping mode is currently set to **\`${currentModeUserString}\`**.`
)
.setColor(embedOptions.colors.info)
]
});
}
if (mode === currentMode) {
logger.debug(`Loop mode is already set to ${modeUserString}.`);
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nLoop mode is already **\`${modeUserString}\`**.`
)
.setColor(embedOptions.colors.warning)
]
});
}
queue.setRepeatMode(mode);
// switch(queue.repeatMode) instead of multiple if statements
if (queue.repeatMode !== mode) {
logger.warn(
'Failed to change loop mode. After setting queue repeat mode, the value was not the same as input.'
);
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.error} Uh-oh... Failed to change loop mode!**\nI tried to change the loop mode to **\`${modeUserString}\`**, but something went wrong.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect or the issue persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
if (queue.repeatMode === 0) {
logger.debug('Disabled loop mode.');
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.success} Loop mode disabled**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nThe ${currentModeUserString} will no longer play on repeat!`
)
.setColor(embedOptions.colors.success)
]
});
}
if (queue.repeatMode === 3) {
logger.debug('Enabled autoplay mode.');
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.autoplaying} Loop mode changed**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nWhen the queue is empty, similar tracks will start playing!`
)
.setColor(embedOptions.colors.success)
]
});
}
logger.debug('Enabled loop mode.');
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.looping} Loop mode changed**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nThe ${modeUserString} will now play on repeat!`
)
.setColor(embedOptions.colors.success)
]
});
}
};
+269
View File
@@ -0,0 +1,269 @@
import config from 'config';
import { NodeResolvable, QueryType, useMainPlayer, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import { lyricsExtractor } from '@discord-player/extractor';
import loggerModule from '../../../services/logger';
import { CommandAutocompleteParams, CommandParams } from '../../../types/commandTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const recentQueries = new Map();
const loggerTemplate = loggerModule.child({
source: 'lyrics.js',
module: 'slashCommand',
name: '/lyrics'
});
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('lyrics')
.setDescription('Get lyrics from Genius for current or specified track.')
.setDMPermission(false)
.setNSFW(false)
.addStringOption((option) =>
option
.setName('query')
.setDescription('Search query or URL.')
.setRequired(false)
.setMinLength(2)
.setMaxLength(500)
.setAutocomplete(true)
),
autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => {
const logger = loggerTemplate.child({
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
const query = interaction.options.getString('query', true);
const { lastQuery, result, timestamp } = recentQueries.get(interaction.user.id) || {};
if (lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - timestamp < 500) {
logger.debug(`Responding with results from lastQuery for query '${query}'`);
return interaction.respond(result);
}
if (query.length < 3) {
logger.debug(`Responding with empty results due to < 3 length for query '${query}'`);
return interaction.respond([]);
}
const genius = lyricsExtractor();
const lyricsResult = await genius.search(query).catch(() => null);
let response = [];
if (!lyricsResult) {
logger.debug(`No Genius lyrics found for query '${query}', using player.search() as fallback.`);
const player = useMainPlayer()!;
const searchResults = await player.search(query);
response = searchResults.tracks.slice(0, 1).map((track) => ({
name:
`${track.title} [Artist: ${track.author}]`.length > 100
? `${track.title}`.slice(0, 100)
: `${track.title} [Artist: ${track.author}]`,
value: track.title.slice(0, 100)
}));
} else {
logger.debug(`Found Genius lyrics for query '${query}'.`);
response = [
{
name: `${lyricsResult.title} [Artist: ${lyricsResult.artist.name}]`.slice(0, 100),
value: lyricsResult.title.slice(0, 100)
}
];
}
if (!response || response.length === 0) {
logger.debug(`Responding with empty results for query '${query}'`);
return interaction.respond([]);
}
recentQueries.set(interaction.user.id, {
lastQuery: query,
result: response,
timestamp: Date.now()
});
logger.debug(`Responding to autocomplete with results for query: '${query}'.`);
return interaction.respond(response);
},
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerTemplate.child({
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
const query = interaction.options.getString('query');
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
let geniusSearchQuery = '';
if (!query) {
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
}
geniusSearchQuery = queue.currentTrack!.title.slice(0, 50);
logger.debug(
`No input query provided, using current track. Using query for genius: '${geniusSearchQuery}'`
);
}
let searchResult;
if (query) {
logger.debug(`Query input provided, using query '${query}' for player.search().`);
const player = useMainPlayer()!;
const searchResults = await player.search(query, {
searchEngine: QueryType.SPOTIFY_SEARCH
});
if (searchResults.tracks.length === 0) {
logger.debug('No search results using player.search() found.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} No search results found**\nThere was no search results found for query **${query}**.`
)
.setColor(embedOptions.colors.warning)
]
});
}
searchResult = searchResults.tracks[0];
geniusSearchQuery = searchResults.tracks[0].title;
logger.debug(`Using query for genius: '${geniusSearchQuery}'`);
}
// get lyrics
const genius = lyricsExtractor();
let lyricsResult = await genius.search(geniusSearchQuery).catch(() => null);
// try again with shorter query (some titles just have added info in the end)
if (!lyricsResult && geniusSearchQuery.length > 20) {
logger.debug(
`No Genius lyrics found for query '${geniusSearchQuery}', trying again with shorter query (20 chars).`
);
lyricsResult = await genius.search(geniusSearchQuery.slice(0, 20)).catch(() => null);
}
if (!lyricsResult && geniusSearchQuery.length > 10) {
logger.debug(
`No Genius lyrics found for query '${geniusSearchQuery}', trying again with shorter query (10 chars).`
);
lyricsResult = await genius.search(geniusSearchQuery.slice(0, 10)).catch(() => null);
}
// Check if authors in track from searchResult includes the artist name from genius
if (searchResult && lyricsResult) {
const searchResultAuthorIncludesArtist = searchResult.author
.toLowerCase()
.includes(lyricsResult.artist.name.toLowerCase());
const lyricsResultArtistIncludesAuthor = lyricsResult.artist.name
.toLowerCase()
.includes(searchResult.author.toLowerCase());
const searchResultAuthorSplitIncludesArtist = lyricsResult.artist.name
.toLowerCase()
.includes(searchResult.author.split(', ')[0].toLowerCase());
if (
!searchResultAuthorIncludesArtist &&
!lyricsResultArtistIncludesAuthor &&
!searchResultAuthorSplitIncludesArtist
) {
lyricsResult = null;
logger.debug('Found Genius lyrics but artist name did not match from player.search() result.');
}
}
if (!lyricsResult || !lyricsResult.lyrics) {
logger.debug('No matching lyrics found.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} No lyrics found**\nThere was no Genius lyrics found for track **${geniusSearchQuery}**.`
)
.setColor(embedOptions.colors.warning)
]
});
}
logger.debug(`Successfully found matching Genius lyrics for query '${geniusSearchQuery}'.`);
// If message length is too long, split into multiple messages
if (lyricsResult.lyrics.length > 3800) {
logger.debug('Lyrics text too long, splitting into multiple messages.');
const messageCount = Math.ceil(lyricsResult.lyrics.length / 3800);
for (let i = 0; i < messageCount; i++) {
logger.debug(`Lyrics, sending message ${i + 1} of ${messageCount}.`);
const message = lyricsResult.lyrics.slice(i * 3800, (i + 1) * 3800);
if (i === 0) {
logger.debug('Responding with info embed for first message with lyrics.');
await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.queue} Showing lyrics**\n` +
`**Track: [${lyricsResult.title}](${lyricsResult.url})**\n` +
`**Artist: [${lyricsResult.artist.name}](${lyricsResult.artist.url})**` +
`\n\n\`\`\`fix\n${message}\`\`\``
)
.setColor(embedOptions.colors.info)
]
});
continue;
} else {
logger.debug('Sending consecutive message with lyrics.');
await interaction.channel!.send({
embeds: [
new EmbedBuilder()
.setDescription(`\`\`\`fix\n${message}\`\`\``)
.setColor(embedOptions.colors.info)
]
});
}
}
return;
}
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.queue} Showing lyrics**\n` +
`**Track: [${lyricsResult.title}](${lyricsResult.url})**\n` +
`**Artist: [${lyricsResult.artist.name}](${lyricsResult.artist.url})**` +
`\n\n\`\`\`fix\n${lyricsResult.lyrics}\`\`\``
)
.setColor(embedOptions.colors.info)
]
});
}
};
@@ -0,0 +1,191 @@
import config from 'config';
import { NodeResolvable, Track, useQueue } from 'discord-player';
import {
APIActionRowComponent,
APIMessageActionRowComponent,
ButtonBuilder,
ButtonStyle,
ComponentType,
EmbedBuilder,
SlashCommandBuilder
} from 'discord.js';
import loggerModule from '../../../services/logger';
import { CommandParams, TrackMetadata } from '../../../types/commandTypes';
import { EmbedOptions, PlayerOptions } from '../../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const playerOptions: PlayerOptions = config.get('playerOptions');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('nowplaying')
.setDescription('Show information about the track currently playing.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'nowplaying.js',
module: 'slashCommand',
name: '/nowplaying',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
}
const sourceStringsFormatted = new Map([
['youtube', 'YouTube'],
['soundcloud', 'SoundCloud'],
['spotify', 'Spotify'],
['apple_music', 'Apple Music'],
['arbitrary', 'Direct source']
]);
const sourceIcons = new Map([
['youtube', embedOptions.icons.sourceYouTube],
['soundcloud', embedOptions.icons.sourceSoundCloud],
['spotify', embedOptions.icons.sourceSpotify],
['apple_music', embedOptions.icons.sourceAppleMusic],
['arbitrary', embedOptions.icons.sourceArbitrary]
]);
const currentTrack: Track = queue.currentTrack!;
let author = currentTrack.author ? currentTrack.author : 'Unavailable';
if (author === 'cdn.discordapp.com') {
author = 'Unavailable';
}
const plays = currentTrack.views !== 0 ? currentTrack.views : 0;
let displayPlays: string = plays.toLocaleString('en-US');
const metadata = currentTrack.metadata as TrackMetadata;
if (plays === 0 && metadata.bridge && metadata.bridge.views !== 0 && metadata.bridge.views !== undefined) {
displayPlays = metadata.bridge.views.toLocaleString('en-US');
} else if (plays === 0) {
displayPlays = 'Unavailable';
}
const source = sourceStringsFormatted.get(currentTrack.raw.source!) ?? 'Unavailable';
const queueLength = queue.tracks.data.length;
const timestamp = queue.node.getTimestamp()!;
let bar = `**\`${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 = `${embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`;
}
const customId = `nowplaying-skip-button_${currentTrack.id}`;
logger.debug(`Generated custom id for skip button: ${customId}`);
const nowPlayingButton = new ButtonBuilder()
.setCustomId(customId)
.setLabel('Skip track')
.setStyle(ButtonStyle.Secondary)
.setEmoji(embedOptions.icons.nextTrack)
.toJSON();
const nowPlayingActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
type: ComponentType.ActionRow,
components: [nowPlayingButton]
};
const loopModesFormatted = new Map([
[0, 'disabled'],
[1, 'track'],
[2, 'queue'],
[3, 'autoplay']
]);
const loopModeUserString = loopModesFormatted.get(queue.repeatMode);
logger.debug('Successfully retrieved information about the current track.');
logger.debug('Sending info embed with action row components.');
await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: `Channel: ${queue.channel!.name} (${queue.channel!.bitrate / 1000}kbps)`,
iconURL: interaction.guild!.iconURL() || ''
})
.setDescription(
(queue.node.isPaused()
? '**Currently Paused**\n'
: `**${embedOptions.icons.audioPlaying} Now Playing**\n`) +
`**[${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**` +
`\nRequested by: <@${currentTrack.requestedBy?.id}>` +
`\n ${bar}\n\n` +
`${
queue.repeatMode === 0
? ''
: `**${
queue.repeatMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop
} Looping**\nLoop mode is set to ${loopModeUserString}. You can change it with **\`/loop\`**.`
}`
)
.addFields(
{
name: '**Author**',
value: author,
inline: true
},
{
name: '**Plays**',
value: displayPlays,
inline: true
},
{
name: '**Track source**',
value: `**${sourceIcons.get(currentTrack.raw.source!)} [${source}](${
currentTrack.raw.url ?? currentTrack.url
})**`,
inline: true
}
)
.setFooter({
text: queueLength ? `${queueLength} other tracks in the queue...` : ' '
})
.setThumbnail(queue.currentTrack!.thumbnail)
.setColor(embedOptions.colors.info)
],
components: [nowPlayingActionRow as APIActionRowComponent<APIMessageActionRowComponent>]
});
logger.debug('Finished sending response.');
}
};
+89
View File
@@ -0,0 +1,89 @@
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../../services/logger';
import { CommandParams } from '../../../types/commandTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('pause')
.setDescription('Pause or resume the current track.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'pause.js',
module: 'slashCommand',
name: '/pause',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
}
const currentTrack = queue.currentTrack!;
let durationFormat =
Number(currentTrack.raw.duration) === 0 || currentTrack.duration === '0:00'
? ''
: `\`${currentTrack.duration}\``;
if (currentTrack.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
// change paused state to opposite of current state
queue.node.setPaused(!queue.node.isPaused());
logger.debug(`Set paused state to ${queue.node.isPaused()}.`);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.pauseResumed} ${
queue.node.isPaused() ? 'Paused Track' : 'Resumed track'
}**\n**${durationFormat} [${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**`
)
.setThumbnail(currentTrack.thumbnail)
.setColor(embedOptions.colors.success)
]
});
}
};
+413
View File
@@ -0,0 +1,413 @@
import config from 'config';
import { useMainPlayer, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../../services/logger';
import { CommandAutocompleteParams, CommandParams } from '../../../types/commandTypes';
import { BotOptions, EmbedOptions, PlayerOptions } from '../../../types/configTypes';
import { cannotJoinVoiceOrTalk } from '../../../utils/validation/permissionValidator';
import { transformQuery } from '../../../utils/validation/searchQueryValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
const playerOptions: PlayerOptions = config.get('playerOptions');
const recentQueries = new Map();
const loggerTemplate = loggerModule.child({
source: 'play.js',
module: 'slashCommand',
name: '/play'
});
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('play')
.setDescription('Add a track or playlist to the queue by searching or url.')
.setDMPermission(false)
.setNSFW(false)
.addStringOption((option) =>
option
.setName('query')
.setDescription('Search query or URL.')
.setRequired(true)
.setMinLength(2)
.setMaxLength(500)
.setAutocomplete(true)
),
autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => {
const logger = loggerTemplate.child({
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
const player = useMainPlayer()!;
const query = interaction.options.getString('query', true);
const { lastQuery, results, timestamp } = recentQueries.get(interaction.user.id) || {};
if (lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - timestamp < 500) {
logger.debug(`Responding with results from lastQuery for query '${query}'`);
return interaction.respond(results);
}
if (query.length < 3) {
logger.debug(`Responding with empty results due to < 3 length for query '${query}'`);
return interaction.respond([]);
}
const searchResults = await player.search(query);
let response = [];
response = searchResults.tracks.slice(0, 5).map((track) => {
if (track.url.length > 100) {
track.url = track.title.slice(0, 100);
}
return {
name:
`${track.title} [Author: ${track.author}]`.length > 100
? `${track.title}`.slice(0, 100)
: `${track.title} [Author: ${track.author}]`,
value: track.url
};
});
recentQueries.set(interaction.user.id, {
lastQuery: query,
results: response,
timestamp: Date.now()
});
if (!response || response.length === 0) {
logger.debug(`Responding with empty results for query '${query}'`);
return interaction.respond([]);
}
logger.debug(`Responding to autocomplete with results for query: '${query}'.`);
return interaction.respond(response);
},
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerTemplate.child({
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
if (await cannotJoinVoiceOrTalk({ interaction, executionId })) {
return;
}
let queue = useQueue(interaction.guild!.id);
if (queue && (await notInSameVoiceChannel({ interaction, queue, executionId }))) {
return;
}
const player = useMainPlayer()!;
const query = interaction.options.getString('query')!;
const transformedQuery = await transformQuery({ query, executionId });
let searchResult;
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}.`);
}
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(
`**${embedOptions.icons.warning} No track found**\nNo results found for **\`${transformedQuery}\`**.\n\nIf you specified a URL, please make sure it is valid and public.`
)
.setColor(embedOptions.colors.warning)
]
});
}
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(
`**${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(embedOptions.colors.warning)
]
});
}
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,
metadata: {
channel: interaction.channel,
client: interaction.client,
requestedBy: interaction.user,
track: searchResult.tracks[0]
}
}
}));
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('Sign in to confirm your age')) {
logger.debug('Found track but failed to retrieve audio due to age confirmation warning.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${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](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.warning)
]
});
}
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(
`**${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](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.warning)
]
});
}
if (
error.message.includes("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')
) {
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(
`**${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](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
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(
`**${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](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
if (error.message === "Cannot read properties of null (reading 'createStream')") {
// Can happen if /play then /leave before track starts playing
logger.warn(
error,
'Found track but failed to play back audio. Voice connection might be unavailable.'
);
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nSomething unexpected happened and it was not possible to start playing the track. This could happen if the voice connection is lost or queue is destroyed while adding 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](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
logger.error(error, 'Failed to play track with player.play(), unhandled error.');
} else {
throw error;
}
}
logger.debug(`Successfully added track with player.play(). Query: '${query}'.`);
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(
`**${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](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
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 = embedOptions.info.fallbackThumbnailUrl;
}
let durationFormat =
Number(track.raw.duration) === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``;
if (track.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
if (searchResult.playlist && searchResult.tracks.length > 1) {
logger.debug(`Playlist found and added with player.play(). Query: '${query}'`);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.success} Added playlist to queue**\n**${durationFormat} [${
track.title
}](${track.raw.url ?? track.url})**\n\nAnd **${
searchResult.tracks.length - 1
}** more tracks... **\`/queue\`** to view all.`
)
.setThumbnail(track.thumbnail)
.setColor(embedOptions.colors.success)
]
});
}
if (queue.currentTrack === track && queue.tracks.data.length === 0) {
logger.debug(`Track found and added with player.play(), started playing. Query: '${query}'.`);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.audioStartedPlaying} Started playing**\n**${durationFormat} [${
track.title
}](${track.raw.url ?? track.url})**`
)
.setThumbnail(track.thumbnail)
.setColor(embedOptions.colors.success)
]
});
}
logger.debug(`Track found and added with player.play(), added to queue. Query: '${query}'.`);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`${embedOptions.icons.success} **Added to queue**\n**${durationFormat} [${track.title}](${
track.raw.url ?? track.url
})**`
)
.setThumbnail(track.thumbnail)
.setColor(embedOptions.colors.success)
]
});
}
};
+209
View File
@@ -0,0 +1,209 @@
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../../services/logger';
import { CommandParams } from '../../../types/commandTypes';
import { EmbedOptions, PlayerOptions } from '../../../types/configTypes';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const playerOptions: PlayerOptions = config.get('playerOptions');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('queue')
.setDescription('Show the list of tracks added to the queue.')
.setDMPermission(false)
.setNSFW(false)
.addNumberOption((option) => option.setName('page').setDescription('Page number of the queue').setMinValue(1)),
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'queue.js',
module: 'slashCommand',
name: '/queue',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
const pageIndex = (interaction.options.getNumber('page') || 1) - 1;
let queueString = '';
if (!queue) {
if (pageIndex >= 1) {
logger.debug(`There is no queue and user tried to access page ${pageIndex + 1}.`);
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nPage **\`${
pageIndex + 1
}\`** is not a valid page number.\n\nThe queue is currently empty, first add some tracks with **\`/play\`**!`
)
.setColor(embedOptions.colors.warning)
]
});
}
logger.debug('There is no queue, displaying empty queue.');
queueString = 'The queue is empty, add some tracks with **`/play`**!';
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.guild!.name,
iconURL: interaction.guild!.iconURL() || ''
})
.setDescription(`**${embedOptions.icons.queue} Tracks in queue**\n${queueString}`)
.setColor(embedOptions.colors.info)
.setFooter({
text: 'Page 1 of 1 (0 tracks)'
})
]
});
}
const queueLength = queue.tracks.data.length;
const totalPages = Math.ceil(queueLength / 10) || 1;
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(
`**${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(embedOptions.colors.warning)
]
});
}
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) => {
let durationFormat =
Number(track.raw.duration) === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``;
if (track.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
return `**${pageIndex * 10 + index + 1}.** **${durationFormat} [${track.title}](${
track.raw.url ?? track.url
})**`;
})
.join('\n');
}
const currentTrack = queue.currentTrack;
const loopModesFormatted = new Map([
[0, 'disabled'],
[1, 'track'],
[2, 'queue'],
[3, 'autoplay']
]);
const loopModeUserString = loopModesFormatted.get(queue.repeatMode);
const repeatModeString = `${
queue.repeatMode === 0
? ''
: `**${
queue.repeatMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop
} Looping**\nLoop mode is set to ${loopModeUserString}. You can change it with **\`/loop\`**.\n\n`
}`;
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({
name: `Channel: ${queue.channel!.name} (${queue.channel!.bitrate / 1000}kbps)`,
iconURL: interaction.guild!.iconURL() || ''
})
.setDescription(
`${repeatModeString}` + `**${embedOptions.icons.queue} Tracks in queue**\n${queueString}`
)
.setFooter({
text: `Page ${pageIndex + 1} of ${totalPages} (${queueLength} tracks)`
})
.setColor(embedOptions.colors.info)
]
});
} else {
logger.debug('Queue exists with current track, gathering information.');
const timestamp = queue.node.getTimestamp()!;
let bar = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({
queue: false,
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 = `${embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`;
}
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: `Channel: ${queue.channel!.name} (${queue.channel!.bitrate / 1000}kbps)`,
iconURL: interaction.guild!.iconURL() || ''
})
.setDescription(
`**${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}` +
`**${embedOptions.icons.queue} Tracks in queue**\n${queueString}`
)
.setThumbnail(queue.currentTrack.thumbnail)
.setFooter({
text: `Page ${pageIndex + 1} of ${totalPages} (${queueLength} tracks)`
})
.setColor(embedOptions.colors.info)
]
});
}
}
};
+106
View File
@@ -0,0 +1,106 @@
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../../services/logger';
import { CommandParams } from '../../../types/commandTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { queueDoesNotExist } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('remove')
.setDescription('Remove a specific track from the queue.')
.setDMPermission(false)
.setNSFW(false)
.addNumberOption((option) =>
option
.setName('tracknumber')
.setDescription('Track number to remove from queue.')
.setMinValue(1)
.setRequired(true)
),
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'remove.js',
module: 'slashCommand',
name: '/remove',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
const removeTrackNumber = interaction.options.getNumber('tracknumber')!;
if (removeTrackNumber > queue.tracks.data.length) {
logger.debug('Specified track number is higher than total tracks.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nTrack **\`${removeTrackNumber}\`** is not a valid track number. There are a total of **\`${queue.tracks.data.length}\`** tracks in the queue.\n\nView tracks added to the queue with **\`/queue\`**.`
)
.setColor(embedOptions.colors.warning)
]
});
}
// Remove specified track number from queue
const removedTrack = queue.node.remove(removeTrackNumber - 1)!;
logger.debug(`Removed track '${removedTrack.url}' from queue.`);
let durationFormat =
Number(removedTrack.raw.duration) === 0 || removedTrack.duration === '0:00'
? ''
: `\`${removedTrack.duration}\``;
if (removedTrack.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.success} Removed track**\n**${durationFormat} [${removedTrack.title}](${
removedTrack.raw.url ?? removedTrack.url
})**`
)
.setThumbnail(removedTrack.thumbnail)
.setColor(embedOptions.colors.success)
]
});
}
};
+188
View File
@@ -0,0 +1,188 @@
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../../services/logger';
import { CommandParams } from '../../../types/commandTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('seek')
.setDescription('Seek to a specified duration in the current track.')
.setDMPermission(false)
.setNSFW(false)
.addStringOption((option) =>
option
.setName('duration')
.setDescription('Duration in format 00:00:00 (HH:mm:ss) to seek to.')
.setRequired(true)
),
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'seek.js',
module: 'slashCommand',
name: '/seek',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
}
const durationInput = interaction.options.getString('duration');
let durationArray = durationInput!.split(':');
switch (durationArray.length) {
case 1:
durationArray.unshift('00', '00');
break;
case 2:
durationArray.unshift('00');
break;
default:
break;
}
durationArray = durationArray.map((value) => {
return value.padStart(2, '0');
});
const durationString = durationArray.join(':');
if (durationArray.length === 0 || durationArray.length > 3) {
logger.debug('Invalid duration format input.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` +
'- **`/seek`** **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' +
'- **`/seek`** **`3:27`** - Seek to 3 minutes and 27 seconds.\n' +
'- **`/seek`** **`42`** - Seek to 42 seconds.'
)
.setColor(embedOptions.colors.warning)
]
});
}
const validElements = durationArray.every((value) => {
return value.length === 2;
});
if (!validElements) {
logger.debug('Invalid duration after parsing duration input.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` +
'- **`/seek`** **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' +
'- **`/seek`** **`3:27`** - Seek to 3 minutes and 27 seconds.\n' +
'- **`/seek`** **`42`** - Seek to 42 seconds.'
)
.setColor(embedOptions.colors.warning)
]
});
}
// Now array should only be 3 elements long, all with 2 characters, e.g. ['00', '00', '00'].
// Regex can now validate if this is a valid duration format. E.g. check if the first element is 0-23, second element is 0-59 and third element is 0-59.
const regex = new RegExp('([0-1][0-9]|2[0-3]):?[0-5][0-9]:?[0-5][0-9]');
const isValidDuration = regex.test(durationString);
if (!isValidDuration) {
logger.debug('Invalid duration after regex checks.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` +
'- **`/seek`** **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' +
'- **`/seek`** **`3:27`** - Seek to 3 minutes and 27 seconds.\n' +
'- **`/seek`** **`42`** - Seek to 42 seconds.'
)
.setColor(embedOptions.colors.warning)
]
});
}
const currentTrackMaxDurationInMs = queue.currentTrack!.durationMS;
const durationInMilliseconds: number =
Number(durationArray[0]) * 3600000 + Number(durationArray[1]) * 60000 + Number(durationArray[2]) * 1000;
if (durationInMilliseconds > currentTrackMaxDurationInMs - 1000) {
logger.debug('Duration specified is longer than the track duration.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${
embedOptions.icons.warning
} Oops!**\nYou entered **\`${durationString}\`**, which is a duration that is longer than the duration for the current track.\n\nPlease try a duration that is less than the duration of the track (**\`${
queue.currentTrack!.duration
}\`**).`
)
.setColor(embedOptions.colors.warning)
]
});
}
queue.node.seek(durationInMilliseconds);
logger.debug(`Seeked to '${durationString}' in current track.`);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.success} Seeking to duration**\nSeeking to **\`${durationString}\`** in current track.`
)
.setThumbnail(queue.currentTrack!.thumbnail)
.setColor(embedOptions.colors.success)
]
});
}
};
@@ -0,0 +1,74 @@
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../../services/logger';
import { CommandParams } from '../../../types/commandTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { queueDoesNotExist, queueIsEmpty } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('shuffle')
.setDescription('Shuffle tracks in the queue randomly.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'shuffle.js',
module: 'slashCommand',
name: '/shuffle',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (await queueIsEmpty({ interaction, queue, executionId })) {
return;
}
queue.tracks.shuffle();
logger.debug('Shuffled queue tracks.');
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.shuffled} Shuffled queue tracks**\nThe **${queue.tracks.data.length}** tracks in the queue has been shuffled.\n\nView the new queue order with **\`/queue\`**.`
)
.setColor(embedOptions.colors.success)
]
});
}
};
+183
View File
@@ -0,0 +1,183 @@
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../../services/logger';
import { CommandParams } from '../../../types/commandTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('skip')
.setDescription('Skip current or specified track.')
.setDMPermission(false)
.setNSFW(false)
.addNumberOption((option) =>
option.setName('tracknumber').setDescription('Track number to skip to in the queue.').setMinValue(1)
),
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'skip.js',
module: 'slashCommand',
name: '/skip',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
}
const skipToTrack = interaction.options.getNumber('tracknumber');
if (skipToTrack) {
if (skipToTrack > queue.tracks.data.length) {
logger.debug('Specified track number was higher than total tracks.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nThere are only **\`${queue.tracks.data.length}\`** tracks in the queue. You cannot skip to track **\`${skipToTrack}\`**.\n\nView tracks added to the queue with **\`/queue\`**.`
)
.setColor(embedOptions.colors.warning)
]
});
} else {
const skippedTrack = queue.currentTrack!;
logger.debug('Responding with warning embed.');
let durationFormat =
Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00'
? ''
: `\`${skippedTrack.duration}\``;
if (skippedTrack.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
queue.node.skipTo(skipToTrack - 1);
logger.debug('Skipped to specified track number.');
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${
skippedTrack.title
}](${skippedTrack.raw.url ?? skippedTrack.url})**`
)
.setThumbnail(skippedTrack.thumbnail)
.setColor(embedOptions.colors.success)
]
});
}
} else {
if (queue.tracks.data.length === 0 && !queue.currentTrack) {
logger.debug('No tracks in queue and no current track.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!`
)
.setColor(embedOptions.colors.warning)
]
});
}
const skippedTrack = queue.currentTrack!;
let durationFormat =
Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00'
? ''
: `\`${skippedTrack.duration}\``;
if (skippedTrack.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
queue.node.skip();
logger.debug('Skipped current track.');
const loopModesFormatted = new Map([
[0, 'disabled'],
[1, 'track'],
[2, 'queue'],
[3, 'autoplay']
]);
const loopModeUserString = loopModesFormatted.get(queue.repeatMode);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${
skippedTrack.title
}](${skippedTrack.raw.url ?? skippedTrack.url})**` +
`${
queue.repeatMode === 0
? ''
: `\n\n**${
queue.repeatMode === 3
? embedOptions.icons.autoplaying
: embedOptions.icons.looping
} Looping**\nLoop mode is set to ${loopModeUserString}. You can change it with **\`/loop\`**.`
}`
)
.setThumbnail(skippedTrack.thumbnail)
.setColor(embedOptions.colors.success)
]
});
}
}
};
+84
View File
@@ -0,0 +1,84 @@
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../../services/logger';
import { CommandParams } from '../../../types/commandTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('stop')
.setDescription('Stop playing audio and clear the track queue.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'stop.js',
module: 'slashCommand',
name: '/stop',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (!queue) {
logger.debug('There is no queue.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\n_Hmm.._ It seems I am not in a voice channel!`
)
.setColor(embedOptions.colors.warning)
]
});
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (!queue.deleted) {
queue.setRepeatMode(0);
queue.clear();
queue.node.stop();
logger.debug('Cleared and stopped the queue.');
}
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.success} Stopped playing**\nStopped playing audio and cleared the track queue.\n\nTo play more music, use the **\`/play\`** command!`
)
.setColor(embedOptions.colors.success)
]
});
}
};
+128
View File
@@ -0,0 +1,128 @@
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../../services/logger';
import { CommandParams } from '../../../types/commandTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { queueDoesNotExist } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('volume')
.setDescription('Show or set the playback volume for tracks.')
.setDMPermission(false)
.setNSFW(false)
.addNumberOption((option) =>
option
.setName('percentage')
.setDescription('Set volume percentage from 1% to 100%.')
.setMinValue(0)
.setMaxValue(100)
),
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'volume.js',
module: 'slashCommand',
name: '/volume',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
const volume = interaction.options.getNumber('percentage');
if (!volume && volume !== 0) {
const currentVolume = queue.node.volume;
logger.debug('No volume input was provided, showing current volume.');
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${
currentVolume === 0 ? embedOptions.icons.volumeIsMuted : embedOptions.icons.volume
} Playback volume**\nThe playback volume is currently set to **\`${currentVolume}%\`**.`
)
.setColor(embedOptions.colors.info)
]
});
} else if (volume > 100 || volume < 0) {
logger.debug('Volume specified was higher than 100% or lower than 0%.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nYou cannot set the volume to **\`${volume}%\`**, please pick a value betwen **\`1%\`** and **\`100%\`**.`
)
.setColor(embedOptions.colors.warning)
]
});
} else {
queue.node.setVolume(volume);
logger.debug(`Set volume to ${volume}%.`);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
if (volume === 0) {
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.volumeMuted} Audio muted**\nPlayback audio has been muted, because volume was set to **\`${volume}%\`**.`
)
.setColor(embedOptions.colors.success)
]
});
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.volumeChanged} Volume changed**\nPlayback volume has been changed to **\`${volume}%\`**.`
)
.setColor(embedOptions.colors.success)
]
});
}
}
};
@@ -0,0 +1,88 @@
import config from 'config';
import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../../services/logger';
import { CommandParams } from '../../../types/commandTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isSystemCommand: true,
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('guilds')
.setDescription('Show list of guilds where bot is added.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'guilds.js',
module: 'slashCommand',
name: '/guilds',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notValidGuildId({ interaction, executionId })) {
return;
}
let shardGuilds: Guild[] = [];
let totalGuildCount = 0;
if (!client || !client.shard) {
logger.error('Client is undefined or does not have shard property.');
return;
}
logger.debug('Fetching guilds from all shards.');
await client.shard
.broadcastEval((c) => {
return c.guilds.cache.map((guild) => {
return guild;
});
})
.then((guilds) => {
shardGuilds = guilds.flat(1) as Guild[];
});
totalGuildCount = shardGuilds.length;
logger.debug(`Successfully fetched ${totalGuildCount} guilds.`);
const guildListFormatted = shardGuilds
.map((guild) => {
return {
name: guild.name,
memberCount: guild.memberCount
};
})
.sort((a, b) => b.memberCount - a.memberCount)
.slice(0, 25)
.map((guild, index) => `${index + 1}. \`${guild.name} (#${guild.memberCount})\``)
.join('\n');
const totalMemberCount = shardGuilds.reduce((a, b) => a + b.memberCount, 0);
let embedDescription =
`**${embedOptions.icons.bot} ${
totalGuildCount < 25 ? `Top ${totalGuildCount} guilds` : 'Top 25 guilds'
} by member count (${totalGuildCount} total)**\n${guildListFormatted}` +
`\n\n**Total members:** **\`${totalMemberCount}\`**`;
logger.debug('Transformed guild into into embed description.');
if (embedDescription.length >= 4000) {
logger.debug('Embed description is too long, truncating.');
embedDescription = `${embedDescription.slice(0, 3996)}...`;
}
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [new EmbedBuilder().setDescription(embedDescription).setColor(embedOptions.colors.info)]
});
}
};
@@ -0,0 +1,84 @@
import config from 'config';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../../services/logger';
import { ExtendedClient } from '../../../types/clientTypes';
import { CommandParams } from '../../../types/commandTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isSystemCommand: true,
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('reload')
.setDescription('Reload the bot commands.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'reload.js',
module: 'slashCommand',
name: '/reload',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notValidGuildId({ interaction, executionId })) {
return;
}
if (!client || !client.shard) {
logger.error('Client is undefined or does not have shard property.');
return;
}
try {
logger.debug('Reloading commands across all shards.');
await client.shard
.broadcastEval(
async (shardClient: ExtendedClient, { executionId }) => {
if (!shardClient.registerClientCommands) {
return;
}
shardClient.registerClientCommands({ client: shardClient, executionId });
},
{ context: { executionId: executionId } }
)
.then(() => {
logger.debug('Successfully reloaded commands across all shards.');
});
} catch (error) {
logger.error(error, 'Failed to reload commands across shards.');
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.error} Oops!**\n_Hmm.._ It seems I am unable to reload commands across shards.`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
const commands = client.commands?.map((command) => {
const params = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : '';
return `- **\`/${command.data.name}\`** ${params}- ${command.data.description}`;
});
const embedDescription = `**${embedOptions.icons.bot} Reloaded commands**\n` + commands?.join('\n');
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [new EmbedBuilder().setDescription(embedDescription).setColor(embedOptions.colors.success)]
});
}
};
+200
View File
@@ -0,0 +1,200 @@
import config from 'config';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../../services/logger';
import { ExtendedClient } from '../../../types/clientTypes';
import { CommandParams, ShardInfo } from '../../../types/commandTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isSystemCommand: true,
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('shards')
.setDescription('Show information about the running shards.')
.setDMPermission(false)
.setNSFW(false)
.addStringOption((option) =>
option
.setName('sort')
.setDescription('If specified, what to sort the shards by.')
.setRequired(false)
.addChoices(
{ name: 'None (Shard ID)', value: 'none' },
{ name: 'Memory usage', value: 'memory' },
{ name: 'Voice Connections', value: 'connections' },
{ name: 'Tracks', value: 'tracks' },
{ name: 'Listeners', value: 'listeners' },
{ name: 'Guilds', value: 'guilds' },
{ name: 'Members', value: 'members' }
)
)
.addNumberOption((option) => option.setName('page').setDescription('Page number to show').setMinValue(1)),
execute: async ({ interaction, client, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'shards.js',
module: 'slashCommand',
name: '/shards',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notValidGuildId({ interaction, executionId })) {
return;
}
let shardInfoList: ShardInfo[] = [];
if (!client || !client.shard) {
logger.error('Client is undefined or does not have shard property.');
return;
}
logger.debug('Fetching player statistics and client values from each shard.');
try {
await client.shard
.broadcastEval((shardClient: ExtendedClient) => {
if (!shardClient.shard) {
return;
}
/* eslint-disable no-undef */
const playerStats = player.generateStatistics();
const nodeProcessMemUsageInMb = parseFloat(
(process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2)
);
const 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[];
switch (interaction.options.getString('sort')) {
case 'memory':
shardInfoList = shardInfoList.sort((a, b) => b.memUsage - a.memUsage);
break;
case 'connections':
shardInfoList = shardInfoList.sort(
(a, b) =>
b.playerStatistics.activeVoiceConnections -
a.playerStatistics.activeVoiceConnections
);
break;
case 'tracks':
shardInfoList = shardInfoList.sort(
(a, b) => b.playerStatistics.totalTracks - a.playerStatistics.totalTracks
);
break;
case 'listeners':
shardInfoList = shardInfoList.sort(
(a, b) => b.playerStatistics.totalListeners - a.playerStatistics.totalListeners
);
break;
case 'guilds':
shardInfoList = shardInfoList.sort((a, b) => b.guildCount - a.guildCount);
break;
case 'members':
shardInfoList = shardInfoList.sort((a, b) => b.guildMemberCount - a.guildMemberCount);
break;
default:
shardInfoList = shardInfoList.sort((a, b) => a.shardId - b.shardId);
break;
}
logger.debug('Successfully fetched player statistics and client values from shards.');
});
} catch (error) {
logger.error(error, 'Failed to fetch player statistics and client values from shards.');
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.error} Oops!**\n_Hmm.._ It seems I am unable to fetch player statistics and client values from shards.`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
const shardCount = shardInfoList.length;
const totalPages = Math.ceil(shardCount / 10) || 1;
const pageIndex = (interaction.options.getNumber('page') || 1) - 1;
const currentPageShards = shardInfoList.slice(pageIndex * 10, pageIndex * 10 + 10);
const evenShardIndexes = currentPageShards.filter((shard, index) => index % 2 === 0);
const oddShardIndexes = currentPageShards.filter((shard, index) => index % 2 !== 0);
function shardInfoToString(shard: ShardInfo) {
let 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;
}
const evenShardIndexesString = evenShardIndexes.map(shardInfoToString).join('\n') + 'ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ';
const oddShardIndexesString = oddShardIndexes.map(shardInfoToString).join('\n');
const embedFields = [];
if (currentPageShards.length === 1) {
embedFields.push({
name: ' ',
value: currentPageShards.map(shardInfoToString).join('\n'),
inline: false
});
} else {
embedFields.push(
{
name: ' ',
value: evenShardIndexesString,
inline: true
},
{
name: ' ',
value: oddShardIndexesString,
inline: true
}
);
}
logger.debug('Successfully gathered and transformed shard information into embed fields.');
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(`**${embedOptions.icons.server} Shard overview - ${shardCount} total shards**\n`)
.addFields(...embedFields)
.setColor(embedOptions.colors.info)
.setFooter({ text: `Shard id: ${client.shard.ids[0]}, page ${pageIndex + 1} of ${totalPages}` })
]
});
}
};
@@ -0,0 +1,173 @@
import config from 'config';
import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js';
import osu from 'node-os-utils';
// @ts-ignore
import { dependencies, version } from '../../../../package.json';
import loggerModule from '../../../services/logger';
import { CommandParams } from '../../../types/commandTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted';
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isSystemCommand: true,
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('systemstatus')
.setDescription('Show the bot and system status.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'systemstatus.js',
module: 'slashCommand',
name: '/systemstatus',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notValidGuildId({ interaction, executionId })) {
return;
}
// from normal /status command
const uptimeString = await getUptimeFormatted({ executionId });
const usedMemoryInMB = Math.ceil((await osu.mem.info()).usedMemMb).toLocaleString('en-US');
const cpuUsage = await osu.cpu.usage();
const releaseVersion = version;
let guildCount = 0;
let memberCount = 0;
let activeVoiceConnections = 0;
let totalTracks = 0;
let totalListeners = 0;
// specific to /systemstatus command
const totalMemoryInMb = Math.ceil((await osu.mem.info()).totalMemMb).toLocaleString('en-US');
const cpuCores = await osu.cpu.count();
const platform = await osu.os.platform();
const discordJsVersion = dependencies['discord.js'];
const opusVersion = dependencies['@discord-player/opus'];
const restVersion = dependencies['@discordjs/rest'];
const voiceVersion = dependencies['discord-voip'];
const discordPlayerVersion = dependencies['discord-player'];
const extractorVersion = dependencies['@discord-player/extractor'];
const mediaplexVersion = dependencies['mediaplex'];
const distubeYtdlVersion = dependencies['@distube/ytdl-core'];
logger.debug('Fetching player statistics from all shards.');
if (!client || !client.shard) {
logger.error('Client is undefined or does not have shard property.');
return;
}
await client.shard
.broadcastEval(() => {
/* eslint-disable no-undef */
return player.generateStatistics();
})
.then((results) => {
const queueCountList: number[] = [];
const trackCountList: number[] = [];
const listenerCountList: number[] = [];
results.map((result) => {
queueCountList.push(result.queues.length);
if (result.queues.length > 0) {
result.queues.map((queue) => {
trackCountList.push(queue.status.playing ? queue.tracksCount + 1 : queue.tracksCount);
listenerCountList.push(queue.listeners);
});
}
});
activeVoiceConnections = queueCountList.reduce((acc, queueAmount) => acc + queueAmount, 0);
totalTracks = trackCountList.reduce((acc, trackAmount) => acc + trackAmount, 0);
totalListeners = listenerCountList.reduce((acc, listenerAmount) => acc + listenerAmount, 0);
logger.debug('Successfully fetched player statistics from shards.');
});
logger.debug('Fetching client values from all shards.');
await client.shard
.fetchClientValues('guilds.cache')
.then((results) => {
const guildCaches = results as Guild[][];
guildCaches.map((guildCache: Guild[]) => {
if (guildCache) {
guildCount += guildCache.length;
memberCount += guildCache.reduce((acc: number, guild: Guild) => acc + guild.memberCount, 0);
}
});
logger.debug('Successfully fetched client values from shards.');
})
.catch((error) => {
logger.error(error, 'Failed to fetch client values from shards.');
});
const botStatusString =
`**${guildCount.toLocaleString('en-US')}** Joined servers\n` +
`**${memberCount.toLocaleString('en-US')}** Total members\n` +
`**v${releaseVersion}** Release version`;
const queueStatusString =
`**${activeVoiceConnections.toLocaleString('en-US')}** Voice connections\n` +
`**${totalTracks.toLocaleString('en-US')}** Tracks in queues\n` +
`**${totalListeners.toLocaleString('en-US')}** Users listening`;
const systemStatusString =
`**${platform}** Platform\n` +
`**${uptimeString}** Uptime\n` +
`**${cpuUsage}% @ ${cpuCores} cores** CPU usage\n` +
`**${usedMemoryInMB} / ${totalMemoryInMb} MB** Memory usage`;
const dependenciesString =
`**${discordJsVersion}** discord.js\n` +
`**┗ ${restVersion}** @discordjs/rest\n` +
`**${discordPlayerVersion}** discord-player\n` +
`**┗ ${opusVersion}** @discord-player/opus\n` +
`**┗ ${extractorVersion}** @discord-player/extractor\n` +
`**${voiceVersion}** discord-voip\n` +
`**${mediaplexVersion}** mediaplex\n` +
`**${distubeYtdlVersion}** @distube/ytdl-core`;
const discordStatusString = `**${client.ws.ping} ms** Discord API latency`;
logger.debug('Transformed system status into embed description.');
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(`**${embedOptions.icons.bot} Bot status**\n` + botStatusString)
.addFields(
{
name: `**${embedOptions.icons.queue} Queue status**`,
value: queueStatusString,
inline: false
},
{
name: `**${embedOptions.icons.server} System status**`,
value: systemStatusString,
inline: false
},
{
name: `**${embedOptions.icons.discord} Discord status**`,
value: discordStatusString,
inline: false
},
{
name: `**${embedOptions.icons.bot} Dependencies**`,
value: dependenciesString,
inline: false
}
)
.setColor(embedOptions.colors.info)
]
});
}
};
@@ -0,0 +1,111 @@
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember } from 'discord.js';
import loggerModule from '../../services/logger';
import { EmbedOptions } from '../../types/configTypes';
import { ComponentInteractionParams } from '../../types/interactionTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
export const execute = async ({ interaction, trackId, executionId }: ComponentInteractionParams) => {
const logger = loggerModule.child({
source: 'nowplaying-skip.js',
module: 'componentInteraction',
name: 'nowplaying-skip',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
logger.debug(`Received skip confirmation for track id ${trackId}.`);
if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) {
logger.debug('Tried skipping track but there was no queue.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!`
)
.setColor(embedOptions.colors.warning)
],
components: []
});
}
if (queue.currentTrack!.id !== trackId) {
logger.debug('Tried skipping track but it is not the current track and therefore already skipped/removed.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nThis track has already been skipped or is no longer playing.`
)
.setColor(embedOptions.colors.warning)
],
components: []
});
}
const skippedTrack = queue.currentTrack!;
let durationFormat =
Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00'
? ''
: `\`${skippedTrack.duration}\``;
if (skippedTrack.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
queue.node.skip();
logger.debug('Skipped the track.');
const loopModesFormatted = new Map([
[0, 'disabled'],
[1, 'track'],
[2, 'queue'],
[3, 'autoplay']
]);
const repeatModeUserString = loopModesFormatted.get(queue.repeatMode);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${
skippedTrack.raw.url ?? skippedTrack.url
})**` +
`${
queue.repeatMode === 0
? ''
: `\n\n**${
queue.repeatMode === 3
? embedOptions.icons.autoplaying
: embedOptions.icons.looping
} Looping**\nLoop mode is set to ${repeatModeUserString}. You can change it with **\`/loop\`**.`
}`
)
.setThumbnail(skippedTrack.thumbnail)
.setColor(embedOptions.colors.success)
],
components: []
});
};