diff options
| author | Max Isom <[email protected]> | 2022-02-05 16:16:17 -0600 |
|---|---|---|
| committer | GitHub <[email protected]> | 2022-02-05 16:16:17 -0600 |
| commit | 56a469a999774c8b8683adeb59b243fdf85b14c9 (patch) | |
| tree | 2e11f067d6e4caae9301986a0b432825cc65839e /src/commands | |
| parent | e883275d831f3d9bf3a57bd91e0deeeaf4951242 (diff) | |
| download | muse-56a469a999774c8b8683adeb59b243fdf85b14c9.tar.xz muse-56a469a999774c8b8683adeb59b243fdf85b14c9.zip | |
Migrate to slash commands (#431)
Co-authored-by: Federico fuji97 Rapetti <[email protected]>
Diffstat (limited to 'src/commands')
| -rw-r--r-- | src/commands/clear.ts | 17 | ||||
| -rw-r--r-- | src/commands/config.ts | 154 | ||||
| -rw-r--r-- | src/commands/disconnect.ts | 21 | ||||
| -rw-r--r-- | src/commands/favorites.ts | 195 | ||||
| -rw-r--r-- | src/commands/fseek.ts | 52 | ||||
| -rw-r--r-- | src/commands/help.ts | 70 | ||||
| -rw-r--r-- | src/commands/index.ts | 14 | ||||
| -rw-r--r-- | src/commands/pause.ts | 21 | ||||
| -rw-r--r-- | src/commands/play.ts | 260 | ||||
| -rw-r--r-- | src/commands/queue.ts | 24 | ||||
| -rw-r--r-- | src/commands/remove.ts | 79 | ||||
| -rw-r--r-- | src/commands/seek.ts | 52 | ||||
| -rw-r--r-- | src/commands/shortcuts.ts | 128 | ||||
| -rw-r--r-- | src/commands/shuffle.ts | 21 | ||||
| -rw-r--r-- | src/commands/skip.ts | 52 | ||||
| -rw-r--r-- | src/commands/unskip.ts | 28 |
16 files changed, 503 insertions, 685 deletions
diff --git a/src/commands/clear.ts b/src/commands/clear.ts index 9906dab..2b258cb 100644 --- a/src/commands/clear.ts +++ b/src/commands/clear.ts @@ -1,16 +1,15 @@ import {inject, injectable} from 'inversify'; -import {Message} from 'discord.js'; +import {CommandInteraction} from 'discord.js'; +import {SlashCommandBuilder} from '@discordjs/builders'; import {TYPES} from '../types.js'; import PlayerManager from '../managers/player.js'; import Command from '.'; @injectable() export default class implements Command { - public name = 'clear'; - public aliases = ['c']; - public examples = [ - ['clear', 'clears all songs in queue except currently playing'], - ]; + public readonly slashCommand = new SlashCommandBuilder() + .setName('clear') + .setDescription('clears all songs in queue except currently playing song'); public requiresVC = true; @@ -20,9 +19,9 @@ export default class implements Command { this.playerManager = playerManager; } - public async execute(msg: Message, _: string []): Promise<void> { - this.playerManager.get(msg.guild!.id).clear(); + public async execute(interaction: CommandInteraction) { + this.playerManager.get(interaction.guild!.id).clear(); - await msg.channel.send('clearer than a field after a fresh harvest'); + await interaction.reply('clearer than a field after a fresh harvest'); } } diff --git a/src/commands/config.ts b/src/commands/config.ts index 20dafed..65aa36b 100644 --- a/src/commands/config.ts +++ b/src/commands/config.ts @@ -1,121 +1,103 @@ -import {TextChannel, Message, GuildChannel, ThreadChannel} from 'discord.js'; +import {SlashCommandBuilder} from '@discordjs/builders'; +import {CommandInteraction, MessageEmbed} from 'discord.js'; import {injectable} from 'inversify'; -import errorMsg from '../utils/error-msg.js'; -import Command from '.'; import {prisma} from '../utils/db.js'; +import updatePermissionsForGuild from '../utils/update-permissions-for-guild.js'; +import Command from './index.js'; @injectable() export default class implements Command { - public name = 'config'; - public aliases = []; - public examples = [ - ['config prefix !', 'set the prefix to !'], - ['config channel music-commands', 'bind the bot to the music-commands channel'], - ['config playlist-limit 30', 'set the playlist song limit to 30'], - ]; - - public async execute(msg: Message, args: string []): Promise<void> { - if (args.length === 0) { - // Show current settings - const settings = await prisma.setting.findUnique({ - where: { - guildId: msg.guild!.id, - }, - }); - - if (settings?.channel) { - let response = `prefix: \`${settings.prefix}\`\n`; - // eslint-disable-next-line @typescript-eslint/no-base-to-string - response += `channel: ${msg.guild!.channels.cache.get(settings.channel)!.toString()}\n`; - response += `playlist-limit: ${settings.playlistLimit}`; - - await msg.channel.send(response); - } - - return; - } + public readonly slashCommand = new SlashCommandBuilder() + .setName('config') + .setDescription('configure bot settings') + .addSubcommand(subcommand => subcommand + .setName('set-playlist-limit') + .setDescription('set the maximum number of tracks that can be added from a playlist') + .addIntegerOption(option => option + .setName('limit') + .setDescription('maximum number of tracks') + .setRequired(true))) + .addSubcommand(subcommand => subcommand + .setName('set-role') + .setDescription('set the role that is allowed to use the bot') + .addRoleOption(option => option + .setName('role') + .setDescription('allowed role') + .setRequired(true))) + .addSubcommand(subcommand => subcommand + .setName('get') + .setDescription('show all settings')); + + async execute(interaction: CommandInteraction) { + switch (interaction.options.getSubcommand()) { + case 'set-playlist-limit': { + const limit = interaction.options.getInteger('limit')!; + + if (limit < 1) { + throw new Error('invalid limit'); + } - const setting = args[0]; + await prisma.setting.update({ + where: { + guildId: interaction.guild!.id, + }, + data: { + playlistLimit: limit, + }, + }); - if (args.length !== 2) { - await msg.channel.send(errorMsg('incorrect number of arguments')); - return; - } + await interaction.reply('👍 limit updated'); - if (msg.author.id !== msg.guild!.ownerId) { - await msg.channel.send(errorMsg('not authorized')); - return; - } + break; + } - switch (setting) { - case 'prefix': { - const newPrefix = args[1]; + case 'set-role': { + const role = interaction.options.getRole('role')!; await prisma.setting.update({ where: { - guildId: msg.guild!.id, + guildId: interaction.guild!.id, }, data: { - prefix: newPrefix, + roleId: role.id, }, }); - await msg.channel.send(`👍 prefix updated to \`${newPrefix}\``); + await updatePermissionsForGuild(interaction.guild!); + + await interaction.reply('👍 role updated'); + break; } - case 'channel': { - let channel: GuildChannel | ThreadChannel | undefined; + case 'get': { + const embed = new MessageEmbed().setTitle('Config'); - if (args[1].includes('<#') && args[1].includes('>')) { - channel = msg.guild!.channels.cache.find(c => c.id === args[1].slice(2, args[1].indexOf('>'))); - } else { - channel = msg.guild!.channels.cache.find(c => c.name === args[1]); - } + const config = await prisma.setting.findUnique({where: {guildId: interaction.guild!.id}}); - if (channel && channel.type === 'GUILD_TEXT') { - await prisma.setting.update({ - where: { - guildId: msg.guild!.id, - }, - data: { - channel: channel.id, - }, - }); - - await Promise.all([ - (channel as TextChannel).send('hey apparently I\'m bound to this channel now'), - msg.react('👍'), - ]); - } else { - await msg.channel.send(errorMsg('either that channel doesn\'t exist or you want me to become sentient and listen to a voice channel')); + if (!config) { + throw new Error('no config found'); } - break; - } + const settingsToShow = { + 'Playlist Limit': config.playlistLimit, + Role: config.roleId ? `<@&${config.roleId}>` : 'not set', + }; - case 'playlist-limit': { - const playlistLimit = parseInt(args[1], 10); - if (playlistLimit <= 0) { - await msg.channel.send(errorMsg('please enter a valid number')); - return; + let description = ''; + for (const [key, value] of Object.entries(settingsToShow)) { + description += `**${key}**: ${value}\n`; } - await prisma.setting.update({ - where: { - guildId: msg.guild!.id, - }, - data: { - playlistLimit, - }, - }); + embed.setDescription(description); + + await interaction.reply({embeds: [embed]}); - await msg.channel.send(`👍 playlist-limit updated to ${playlistLimit}`); break; } default: - await msg.channel.send(errorMsg('I\'ve never met this setting in my life')); + throw new Error('unknown subcommand'); } } } diff --git a/src/commands/disconnect.ts b/src/commands/disconnect.ts index 89b0b85..4df76db 100644 --- a/src/commands/disconnect.ts +++ b/src/commands/disconnect.ts @@ -1,17 +1,15 @@ -import {Message} from 'discord.js'; +import {CommandInteraction} from 'discord.js'; +import {SlashCommandBuilder} from '@discordjs/builders'; import {TYPES} from '../types.js'; import {inject, injectable} from 'inversify'; import PlayerManager from '../managers/player.js'; -import errorMsg from '../utils/error-msg.js'; import Command from '.'; @injectable() export default class implements Command { - public name = 'disconnect'; - public aliases = ['dc']; - public examples = [ - ['disconnect', 'pauses and disconnects player'], - ]; + public readonly slashCommand = new SlashCommandBuilder() + .setName('disconnect') + .setDescription('pauses and disconnects player'); public requiresVC = true; @@ -21,16 +19,15 @@ export default class implements Command { this.playerManager = playerManager; } - public async execute(msg: Message, _: string []): Promise<void> { - const player = this.playerManager.get(msg.guild!.id); + public async execute(interaction: CommandInteraction) { + const player = this.playerManager.get(interaction.guild!.id); if (!player.voiceConnection) { - await msg.channel.send(errorMsg('not connected')); - return; + throw new Error('not connected'); } player.disconnect(); - await msg.channel.send('u betcha'); + await interaction.reply('u betcha'); } } diff --git a/src/commands/favorites.ts b/src/commands/favorites.ts new file mode 100644 index 0000000..98f1ba9 --- /dev/null +++ b/src/commands/favorites.ts @@ -0,0 +1,195 @@ +import {SlashCommandBuilder} from '@discordjs/builders'; +import {AutocompleteInteraction, CommandInteraction, MessageEmbed} from 'discord.js'; +import {inject, injectable} from 'inversify'; +import Command from '.'; +import AddQueryToQueue from '../services/add-query-to-queue.js'; +import {TYPES} from '../types.js'; +import {prisma} from '../utils/db.js'; + +@injectable() +export default class implements Command { + public readonly slashCommand = new SlashCommandBuilder() + .setName('favorites') + .setDescription('adds a song to your favorites') + .addSubcommand(subcommand => subcommand + .setName('use') + .setDescription('use a favorite') + .addStringOption(option => option + .setName('name') + .setDescription('name of favorite') + .setRequired(true) + .setAutocomplete(true)) + .addBooleanOption(option => option + .setName('immediate') + .setDescription('add track to the front of the queue')) + .addBooleanOption(option => option + .setName('shuffle') + .setDescription('shuffle the input if you\'re adding multiple tracks'))) + .addSubcommand(subcommand => subcommand + .setName('list') + .setDescription('list all favorites')) + .addSubcommand(subcommand => subcommand + .setName('create') + .setDescription('create a new favorite') + .addStringOption(option => option + .setName('name') + .setDescription('you\'ll type this when using this favorite') + .setRequired(true)) + .addStringOption(option => option + .setName('query') + .setDescription('any input you\'d normally give to the play command') + .setRequired(true), + )) + .addSubcommand(subcommand => subcommand + .setName('remove') + .setDescription('remove a favorite') + .addStringOption(option => option + .setName('name') + .setDescription('name of favorite') + .setAutocomplete(true) + .setRequired(true), + ), + ); + + constructor(@inject(TYPES.Services.AddQueryToQueue) private readonly addQueryToQueue: AddQueryToQueue) {} + + requiresVC = (interaction: CommandInteraction) => interaction.options.getSubcommand() === 'use'; + + async execute(interaction: CommandInteraction) { + switch (interaction.options.getSubcommand()) { + case 'use': + await this.use(interaction); + break; + case 'list': + await this.list(interaction); + break; + case 'create': + await this.create(interaction); + break; + case 'remove': + await this.remove(interaction); + break; + default: + throw new Error('unknown subcommand'); + } + } + + async handleAutocompleteInteraction(interaction: AutocompleteInteraction) { + const subcommand = interaction.options.getSubcommand(); + const query = interaction.options.getString('name')!.trim(); + + const favorites = await prisma.favoriteQuery.findMany({ + where: { + guildId: interaction.guild!.id, + }, + }); + + let results = query === '' ? favorites : favorites.filter(f => f.name.startsWith(query)); + + if (subcommand === 'remove') { + // Only show favorites that user is allowed to remove + results = interaction.member?.user.id === interaction.guild?.ownerId ? results : results.filter(r => r.authorId === interaction.member!.user.id); + } + + await interaction.respond(results.map(r => ({ + name: r.name, + value: r.name, + }))); + } + + private async use(interaction: CommandInteraction) { + const name = interaction.options.getString('name')!.trim(); + + const favorite = await prisma.favoriteQuery.findFirst({ + where: { + name, + guildId: interaction.guild!.id, + }, + }); + + if (!favorite) { + throw new Error('no favorite with that name exists'); + } + + await this.addQueryToQueue.addToQueue({ + interaction, + query: favorite.query, + shuffleAdditions: interaction.options.getBoolean('shuffle') ?? false, + addToFrontOfQueue: interaction.options.getBoolean('immediate') ?? false, + }); + } + + private async list(interaction: CommandInteraction) { + const favorites = await prisma.favoriteQuery.findMany({ + where: { + guildId: interaction.guild!.id, + }, + }); + + if (favorites.length === 0) { + await interaction.reply('there aren\'t any favorites yet'); + return; + } + + const embed = new MessageEmbed().setTitle('Favorites'); + + let description = ''; + for (const favorite of favorites) { + description += `**${favorite.name}**: ${favorite.query} (<@${favorite.authorId}>)\n`; + } + + embed.setDescription(description); + + await interaction.reply({ + embeds: [embed], + }); + } + + private async create(interaction: CommandInteraction) { + const name = interaction.options.getString('name')!.trim(); + const query = interaction.options.getString('query')!.trim(); + + const existingFavorite = await prisma.favoriteQuery.findFirst({where: { + guildId: interaction.guild!.id, + name, + }}); + + if (existingFavorite) { + throw new Error('a favorite with that name already exists'); + } + + await prisma.favoriteQuery.create({ + data: { + authorId: interaction.member!.user.id, + guildId: interaction.guild!.id, + name, + query, + }, + }); + + await interaction.reply('👍 favorite created'); + } + + private async remove(interaction: CommandInteraction) { + const name = interaction.options.getString('name')!.trim(); + + const favorite = await prisma.favoriteQuery.findFirst({where: { + name, + guildId: interaction.guild!.id, + }}); + + if (!favorite) { + throw new Error('no favorite with that name exists'); + } + + const isUserGuildOwner = interaction.member!.user.id === interaction.guild!.ownerId; + + if (favorite.authorId !== interaction.member!.user.id && !isUserGuildOwner) { + throw new Error('you can only remove your own favorites'); + } + + await prisma.favoriteQuery.delete({where: {id: favorite.id}}); + + await interaction.reply('👍 favorite removed'); + } +} diff --git a/src/commands/fseek.ts b/src/commands/fseek.ts index 16d1430..985a7c4 100644 --- a/src/commands/fseek.ts +++ b/src/commands/fseek.ts @@ -1,18 +1,20 @@ -import {Message, TextChannel} from 'discord.js'; +import {CommandInteraction} from 'discord.js'; +import {SlashCommandBuilder} from '@discordjs/builders'; import {TYPES} from '../types.js'; import {inject, injectable} from 'inversify'; import PlayerManager from '../managers/player.js'; -import LoadingMessage from '../utils/loading-message.js'; -import errorMsg from '../utils/error-msg.js'; import Command from '.'; +import {prettyTime} from '../utils/time.js'; @injectable() export default class implements Command { - public name = 'fseek'; - public aliases = []; - public examples = [ - ['fseek 10', 'skips forward in current song by 10 seconds'], - ]; + public readonly slashCommand = new SlashCommandBuilder() + .setName('fseek') + .setDescription('seek forward in the current song') + .addNumberOption(option => option + .setName('seconds') + .setDescription('the number of seconds to skip forward') + .setRequired(true)); public requiresVC = true; @@ -22,38 +24,34 @@ export default class implements Command { this.playerManager = playerManager; } - public async execute(msg: Message, args: string []): Promise<void> { - const player = this.playerManager.get(msg.guild!.id); + public async execute(interaction: CommandInteraction): Promise<void> { + const player = this.playerManager.get(interaction.guild!.id); const currentSong = player.getCurrent(); if (!currentSong) { - await msg.channel.send(errorMsg('nothing is playing')); - return; + throw new Error('nothing is playing'); } if (currentSong.isLive) { - await msg.channel.send(errorMsg('can\'t seek in a livestream')); - return; + throw new Error('can\'t seek in a livestream'); } - const seekTime = parseInt(args[0], 10); + const seekTime = interaction.options.getNumber('seconds'); - if (seekTime + player.getPosition() > currentSong.length) { - await msg.channel.send(errorMsg('can\'t seek past the end of the song')); - return; + if (!seekTime) { + throw new Error('missing number of seconds to seek'); } - const loading = new LoadingMessage(msg.channel as TextChannel); - - await loading.start(); + if (seekTime + player.getPosition() > currentSong.length) { + throw new Error('can\'t seek past the end of the song'); + } - try { - await player.forwardSeek(seekTime); + await Promise.all([ + player.forwardSeek(seekTime), + interaction.deferReply(), + ]); - await loading.stop(); - } catch (error: unknown) { - await loading.stop(errorMsg(error as Error)); - } + await interaction.editReply(`👍 seeked to ${prettyTime(player.getPosition())}`); } } diff --git a/src/commands/help.ts b/src/commands/help.ts deleted file mode 100644 index ebac00b..0000000 --- a/src/commands/help.ts +++ /dev/null @@ -1,70 +0,0 @@ -import {Message, Util} from 'discord.js'; -import {injectable} from 'inversify'; -import Command from '.'; -import {TYPES} from '../types.js'; -import container from '../inversify.config.js'; -import {prisma} from '../utils/db.js'; - -@injectable() -export default class implements Command { - public name = 'help'; - public aliases = ['h']; - public examples = [ - ['help', 'you don\'t need a description'], - ]; - - private commands: Command[] = []; - - public async execute(msg: Message, _: string []): Promise<void> { - if (this.commands.length === 0) { - // Lazy load to avoid circular dependencies - this.commands = container.getAll<Command>(TYPES.Command); - } - - const settings = await prisma.setting.findUnique({ - where: { - guildId: msg.guild!.id, - }, - }); - - if (!settings) { - return; - } - - const {prefix} = settings; - - const res = Util.splitMessage(this.commands.sort((a, b) => a.name.localeCompare(b.name)).reduce((content, command) => { - const aliases = command.aliases.reduce((str, alias, i) => { - str += alias; - - if (i !== command.aliases.length - 1) { - str += ', '; - } - - return str; - }, ''); - - if (aliases === '') { - content += `**${command.name}**:\n`; - } else { - content += `**${command.name}** (${aliases}):\n`; - } - - command.examples.forEach(example => { - content += `- \`${prefix}${example[0]}\`: ${example[1]}\n`; - }); - - content += '\n'; - - return content; - }, '')); - - for (const r of res) { - // eslint-disable-next-line no-await-in-loop - await msg.author.send(r); - } - - await msg.react('🇩'); - await msg.react('🇲'); - } -} diff --git a/src/commands/index.ts b/src/commands/index.ts index a945072..02349d2 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -1,9 +1,11 @@ -import {Message} from 'discord.js'; +import {SlashCommandBuilder, SlashCommandSubcommandsOnlyBuilder} from '@discordjs/builders'; +import {AutocompleteInteraction, ButtonInteraction, CommandInteraction} from 'discord.js'; export default interface Command { - name: string; - aliases: string[]; - examples: string[][]; - requiresVC?: boolean; - execute: (msg: Message, args: string[]) => Promise<void>; + readonly slashCommand: Partial<SlashCommandBuilder | SlashCommandSubcommandsOnlyBuilder> & Pick<SlashCommandBuilder, 'toJSON'>; + readonly handledButtonIds?: readonly string[]; + readonly requiresVC?: boolean | ((interaction: CommandInteraction) => boolean); + execute: (interaction: CommandInteraction) => Promise<void>; + handleButtonInteraction?: (interaction: ButtonInteraction) => Promise<void>; + handleAutocompleteInteraction?: (interaction: AutocompleteInteraction) => Promise<void>; } diff --git a/src/commands/pause.ts b/src/commands/pause.ts index 1dee95d..fc98bdf 100644 --- a/src/commands/pause.ts +++ b/src/commands/pause.ts @@ -1,18 +1,16 @@ -import {Message} from 'discord.js'; +import {CommandInteraction} from 'discord.js'; +import {SlashCommandBuilder} from '@discordjs/builders'; import {TYPES} from '../types.js'; import {inject, injectable} from 'inversify'; import PlayerManager from '../managers/player.js'; import {STATUS} from '../services/player.js'; -import errorMsg from '../utils/error-msg.js'; import Command from '.'; @injectable() export default class implements Command { - public name = 'pause'; - public aliases = []; - public examples = [ - ['pause', 'pauses currently playing song'], - ]; + public readonly slashCommand = new SlashCommandBuilder() + .setName('pause') + .setDescription('pauses the current song'); public requiresVC = true; @@ -22,15 +20,14 @@ export default class implements Command { this.playerManager = playerManager; } - public async execute(msg: Message, _: string []): Promise<void> { - const player = this.playerManager.get(msg.guild!.id); + public async execute(interaction: CommandInteraction) { + const player = this.playerManager.get(interaction.guild!.id); if (player.status !== STATUS.PLAYING) { - await msg.channel.send(errorMsg('not currently playing')); - return; + throw new Error('not currently playing'); } player.pause(); - await msg.channel.send('the stop-and-go light is now red'); + await interaction.reply('the stop-and-go light is now red'); } } diff --git a/src/commands/play.ts b/src/commands/play.ts index 16d16dd..2d2fc6d 100644 --- a/src/commands/play.ts +++ b/src/commands/play.ts @@ -1,211 +1,113 @@ -import {TextChannel, Message} from 'discord.js'; +import {AutocompleteInteraction, CommandInteraction, GuildMember} from 'discord.js'; import {URL} from 'url'; -import {Except} from 'type-fest'; -import shuffle from 'array-shuffle'; -import {TYPES} from '../types.js'; +import {SlashCommandBuilder} from '@discordjs/builders'; import {inject, injectable} from 'inversify'; -import {QueuedSong, STATUS} from '../services/player.js'; -import PlayerManager from '../managers/player.js'; -import {getMostPopularVoiceChannel, getMemberVoiceChannel} from '../utils/channels.js'; -import LoadingMessage from '../utils/loading-message.js'; -import errorMsg from '../utils/error-msg.js'; +import Spotify from 'spotify-web-api-node'; import Command from '.'; -import GetSongs from '../services/get-songs.js'; -import {prisma} from '../utils/db.js'; +import {TYPES} from '../types.js'; +import ThirdParty from '../services/third-party.js'; +import getYouTubeAndSpotifySuggestionsFor from '../utils/get-youtube-and-spotify-suggestions-for.js'; +import KeyValueCacheProvider from '../services/key-value-cache.js'; +import {ONE_HOUR_IN_SECONDS} from '../utils/constants.js'; +import AddQueryToQueue from '../services/add-query-to-queue.js'; +import PlayerManager from '../managers/player.js'; +import {STATUS} from '../services/player.js'; import {buildPlayingMessageEmbed} from '../utils/build-embed.js'; +import {getMemberVoiceChannel, getMostPopularVoiceChannel} from '../utils/channels.js'; @injectable() export default class implements Command { - public name = 'play'; - public aliases = ['p']; - public examples = [ - ['play', 'resume paused playback'], - ['play https://www.youtube.com/watch?v=dQw4w9WgXcQ', 'plays a YouTube video'], - ['play cool music', 'plays the first search result for "cool music" from YouTube'], - ['play https://www.youtube.com/watch?list=PLi9drqWffJ9FWBo7ZVOiaVy0UQQEm4IbP', 'adds the playlist to the queue'], - ['play https://open.spotify.com/track/3ebXMykcMXOcLeJ9xZ17XH?si=tioqSuyMRBWxhThhAW51Ig', 'plays a song from Spotify'], - ['play https://open.spotify.com/album/5dv1oLETxdsYOkS2Sic00z?si=bDa7PaloRx6bMIfKdnvYQw', 'adds all songs from album to the queue'], - ['play https://open.spotify.com/playlist/37i9dQZF1DX94qaYRnkufr?si=r2fOVL_QQjGxFM5MWb84Xw', 'adds all songs from playlist to the queue'], - ['play cool music immediate', 'adds the first search result for "cool music" to the front of the queue'], - ['play cool music i', 'adds the first search result for "cool music" to the front of the queue'], - ['play https://www.youtube.com/watch?list=PLi9drqWffJ9FWBo7ZVOiaVy0UQQEm4IbP shuffle', 'adds the shuffled playlist to the queue'], - ['play https://www.youtube.com/watch?list=PLi9drqWffJ9FWBo7ZVOiaVy0UQQEm4IbP s', 'adds the shuffled playlist to the queue'], - ]; + public readonly slashCommand = new SlashCommandBuilder() + .setName('play') + // TODO: make sure verb tense is consistent between all command descriptions + .setDescription('play a song or resume playback') + .addStringOption(option => option + .setName('query') + .setDescription('YouTube URL, Spotify URL, or search query') + .setAutocomplete(true)) + .addBooleanOption(option => option + .setName('immediate') + .setDescription('add track to the front of the queue')) + .addBooleanOption(option => option + .setName('shuffle') + .setDescription('shuffle the input if you\'re adding multiple tracks')); public requiresVC = true; + private readonly spotify: Spotify; + private readonly cache: KeyValueCacheProvider; + private readonly addQueryToQueue: AddQueryToQueue; private readonly playerManager: PlayerManager; - private readonly getSongs: GetSongs; - constructor(@inject(TYPES.Managers.Player) playerManager: PlayerManager, @inject(TYPES.Services.GetSongs) getSongs: GetSongs) { + constructor(@inject(TYPES.ThirdParty) thirdParty: ThirdParty, @inject(TYPES.KeyValueCache) cache: KeyValueCacheProvider, @inject(TYPES.Services.AddQueryToQueue) addQueryToQueue: AddQueryToQueue, @inject(TYPES.Managers.Player) playerManager: PlayerManager) { + this.spotify = thirdParty.spotify; + this.cache = cache; + this.addQueryToQueue = addQueryToQueue; this.playerManager = playerManager; - this.getSongs = getSongs; } // eslint-disable-next-line complexity - public async execute(msg: Message, args: string[]): Promise<void> { - const [targetVoiceChannel] = getMemberVoiceChannel(msg.member!) ?? getMostPopularVoiceChannel(msg.guild!); - const setting = await prisma.setting.findUnique({ - where: { - guildId: msg.guild!.id, - }}); - if (!setting) { - throw new Error(`Couldn't find settings for guild ${msg.guild!.id}`); - } - - const {playlistLimit} = setting; + public async execute(interaction: CommandInteraction): Promise<void> { + const query = interaction.options.getString('query'); - const res = new LoadingMessage(msg.channel as TextChannel); - await res.start(); - - try { - const player = this.playerManager.get(msg.guild!.id); + const player = this.playerManager.get(interaction.guild!.id); + const [targetVoiceChannel] = getMemberVoiceChannel(interaction.member as GuildMember) ?? getMostPopularVoiceChannel(interaction.guild!); - const wasPlayingSong = player.getCurrent() !== null; - - if (args.length === 0) { - if (player.status === STATUS.PLAYING) { - await res.stop(errorMsg('already playing, give me a song name')); - return; - } - - // Must be resuming play - if (!wasPlayingSong) { - await res.stop(errorMsg('nothing to play')); - return; - } - - await player.connect(targetVoiceChannel); - await player.play(); - - await Promise.all([ - res.stop('the stop-and-go light is now green'), - msg.channel.send({embeds: [buildPlayingMessageEmbed(player)]}), - ]); - - return; + if (!query) { + if (player.status === STATUS.PLAYING) { + throw new Error('already playing, give me a song name'); } - const addToFrontOfQueue = args[args.length - 1] === 'i' || args[args.length - 1] === 'immediate'; - const shuffleAdditions = args[args.length - 1] === 's' || args[args.length - 1] === 'shuffle'; - - let newSongs: Array<Except<QueuedSong, 'addedInChannelId' | 'requestedBy'>> = []; - let extraMsg = ''; - - // Test if it's a complete URL - try { - const url = new URL(args[0]); - - const YOUTUBE_HOSTS = [ - 'www.youtube.com', - 'youtu.be', - 'youtube.com', - 'music.youtube.com', - 'www.music.youtube.com', - ]; - - if (YOUTUBE_HOSTS.includes(url.host)) { - // YouTube source - if (url.searchParams.get('list')) { - // YouTube playlist - newSongs.push(...await this.getSongs.youtubePlaylist(url.searchParams.get('list')!)); - } else { - // Single video - const song = await this.getSongs.youtubeVideo(url.href); - - if (song) { - newSongs.push(song); - } else { - await res.stop(errorMsg('that doesn\'t exist')); - return; - } - } - } else if (url.protocol === 'spotify:' || url.host === 'open.spotify.com') { - const [convertedSongs, nSongsNotFound, totalSongs] = await this.getSongs.spotifySource(args[0], playlistLimit); - - if (totalSongs > playlistLimit) { - extraMsg = `a random sample of ${playlistLimit} songs was taken`; - } - - if (totalSongs > playlistLimit && nSongsNotFound !== 0) { - extraMsg += ' and '; - } - - if (nSongsNotFound !== 0) { - if (nSongsNotFound === 1) { - extraMsg += '1 song was not found'; - } else { - extraMsg += `${nSongsNotFound.toString()} songs were not found`; - } - } - - newSongs.push(...convertedSongs); - } - } catch (_: unknown) { - // Not a URL, must search YouTube - const query = addToFrontOfQueue ? args.slice(0, args.length - 1).join(' ') : args.join(' '); - - const song = await this.getSongs.youtubeVideoSearch(query); - - if (song) { - newSongs.push(song); - } else { - await res.stop(errorMsg('that doesn\'t exist')); - return; - } + // Must be resuming play + if (!player.getCurrent()) { + throw new Error('nothing to play'); } - if (newSongs.length === 0) { - await res.stop(errorMsg('no songs found')); - return; - } + await player.connect(targetVoiceChannel); + await player.play(); - if (shuffleAdditions) { - newSongs = shuffle(newSongs); - } - - newSongs.forEach(song => { - player.add({...song, addedInChannelId: msg.channel.id, requestedBy: msg.author.id}, {immediate: addToFrontOfQueue}); + await interaction.reply({ + content: 'the stop-and-go light is now green', + embeds: [buildPlayingMessageEmbed(player)], }); - const firstSong = newSongs[0]; - - let statusMsg = ''; - - if (player.voiceConnection === null) { - await player.connect(targetVoiceChannel); - - // Resume / start playback - await player.play(); + return; + } - if (wasPlayingSong) { - statusMsg = 'resuming playback'; - } + await this.addQueryToQueue.addToQueue({ + interaction, + query: query.trim(), + addToFrontOfQueue: interaction.options.getBoolean('immediate') ?? false, + shuffleAdditions: interaction.options.getBoolean('shuffle') ?? false, + }); + } - await msg.channel.send({embeds: [buildPlayingMessageEmbed(player)]}); - } + public async handleAutocompleteInteraction(interaction: AutocompleteInteraction): Promise<void> { + const query = interaction.options.getString('query')?.trim(); - // Build response message - if (statusMsg !== '') { - if (extraMsg === '') { - extraMsg = statusMsg; - } else { - extraMsg = `${statusMsg}, ${extraMsg}`; - } - } + if (!query || query.length === 0) { + await interaction.respond([]); + return; + } - if (extraMsg !== '') { - extraMsg = ` (${extraMsg})`; - } + try { + // Don't return suggestions for URLs + // eslint-disable-next-line no-new + new URL(query); + await interaction.respond([]); + return; + } catch {} + + const suggestions = await this.cache.wrap( + getYouTubeAndSpotifySuggestionsFor, + query, + this.spotify, + 10, + { + expiresIn: ONE_HOUR_IN_SECONDS, + key: `autocomplete:${query}`, + }); - if (newSongs.length === 1) { - await res.stop(`u betcha, **${firstSong.title}** added to the${addToFrontOfQueue ? ' front of the' : ''} queue${extraMsg}`); - } else { - await res.stop(`u betcha, **${firstSong.title}** and ${newSongs.length - 1} other songs were added to the queue${extraMsg}`); - } - } catch (error) { - await res.stop(); - throw error; - } + await interaction.respond(suggestions); } } diff --git a/src/commands/queue.ts b/src/commands/queue.ts index 79285b1..4d75d42 100644 --- a/src/commands/queue.ts +++ b/src/commands/queue.ts @@ -1,4 +1,5 @@ -import {Message} from 'discord.js'; +import {CommandInteraction} from 'discord.js'; +import {SlashCommandBuilder} from '@discordjs/builders'; import {inject, injectable} from 'inversify'; import {TYPES} from '../types.js'; import PlayerManager from '../managers/player.js'; @@ -7,12 +8,13 @@ import {buildQueueEmbed} from '../utils/build-embed.js'; @injectable() export default class implements Command { - public name = 'queue'; - public aliases = ['q']; - public examples = [ - ['queue', 'shows current queue'], - ['queue 2', 'shows second page of queue'], - ]; + public readonly slashCommand = new SlashCommandBuilder() + .setName('queue') + .setDescription('show the current queue') + .addIntegerOption(option => option + .setName('page') + .setDescription('page of queue to show [default: 1]') + .setRequired(false)); private readonly playerManager: PlayerManager; @@ -20,11 +22,11 @@ export default class implements Command { this.playerManager = playerManager; } - public async execute(msg: Message, args: string []): Promise<void> { - const player = this.playerManager.get(msg.guild!.id); + public async execute(interaction: CommandInteraction) { + const player = this.playerManager.get(interaction.guild!.id); - const embed = buildQueueEmbed(player, args[0] ? parseInt(args[0], 10) : 1); + const embed = buildQueueEmbed(player, interaction.options.getInteger('page') ?? 1); - await msg.channel.send({embeds: [embed]}); + await interaction.reply({embeds: [embed]}); } } diff --git a/src/commands/remove.ts b/src/commands/remove.ts index 9c40a71..55c416f 100644 --- a/src/commands/remove.ts +++ b/src/commands/remove.ts @@ -1,18 +1,24 @@ -import {Message} from 'discord.js'; +import {CommandInteraction} from 'discord.js'; import {inject, injectable} from 'inversify'; import {TYPES} from '../types.js'; import PlayerManager from '../managers/player.js'; import Command from '.'; -import errorMsg from '../utils/error-msg.js'; +import {SlashCommandBuilder} from '@discordjs/builders'; @injectable() export default class implements Command { - public name = 'remove'; - public aliases = ['rm']; - public examples = [ - ['remove 1', 'removes the next song in the queue'], - ['rm 5-7', 'remove every song in range 5 - 7 (inclusive) from the queue'], - ]; + public readonly slashCommand = new SlashCommandBuilder() + .setName('remove') + .setDescription('remove songs from the queue') + .addIntegerOption(option => + option.setName('position') + .setDescription('position of the song to remove [default: 1]') + .setRequired(false), + ) + .addIntegerOption(option => + option.setName('range') + .setDescription('number of songs to remove [default: 1]') + .setRequired(false)); private readonly playerManager: PlayerManager; @@ -20,57 +26,22 @@ export default class implements Command { this.playerManager = playerManager; } - public async execute(msg: Message, args: string []): Promise<void> { - const player = this.playerManager.get(msg.guild!.id); + public async execute(interaction: CommandInteraction): Promise<void> { + const player = this.playerManager.get(interaction.guild!.id); - if (args.length === 0) { - await msg.channel.send(errorMsg('missing song position or range')); - return; - } - - const reg = /^(\d+)-(\d+)$|^(\d+)$/g; // Expression has 3 groups: x-y or z. x-y is range, z is a single digit. - const match = reg.exec(args[0]); + const position = interaction.options.getInteger('position') ?? 1; + const range = interaction.options.getInteger('range') ?? 1; - if (match === null) { - await msg.channel.send(errorMsg('incorrect format')); - return; + if (position < 1) { + throw new Error('position must be at least 1'); } - if (match[3] === undefined) { // 3rd group (z) doesn't exist -> a range - const range = [parseInt(match[1], 10), parseInt(match[2], 10)]; - - if (range[0] < 1) { - await msg.channel.send(errorMsg('position must be greater than 0')); - return; - } - - if (range[1] > player.queueSize()) { - await msg.channel.send(errorMsg('position is outside of the queue\'s range')); - return; - } - - if (range[0] < range[1]) { - player.removeFromQueue(range[0], range[1] - range[0] + 1); - } else { - await msg.channel.send(errorMsg('range is backwards')); - return; - } - } else { // 3rd group exists -> just one song - const index = parseInt(match[3], 10); - - if (index < 1) { - await msg.channel.send(errorMsg('position must be greater than 0')); - return; - } - - if (index > player.queueSize()) { - await msg.channel.send(errorMsg('position is outside of the queue\'s range')); - return; - } - - player.removeFromQueue(index, 1); + if (range < 1) { + throw new Error('range must be at least 1'); } - await msg.channel.send(':wastebasket: removed'); + player.removeFromQueue(position, range); + + await interaction.reply(':wastebasket: removed'); } } diff --git a/src/commands/seek.ts b/src/commands/seek.ts index 5578aca..07f6590 100644 --- a/src/commands/seek.ts +++ b/src/commands/seek.ts @@ -1,21 +1,21 @@ -import {Message, TextChannel} from 'discord.js'; +import {CommandInteraction} from 'discord.js'; import {TYPES} from '../types.js'; import {inject, injectable} from 'inversify'; import PlayerManager from '../managers/player.js'; -import LoadingMessage from '../utils/loading-message.js'; -import errorMsg from '../utils/error-msg.js'; import Command from '.'; -import {parseTime} from '../utils/time.js'; +import {parseTime, prettyTime} from '../utils/time.js'; +import {SlashCommandBuilder} from '@discordjs/builders'; @injectable() export default class implements Command { - public name = 'seek'; - public aliases = []; - public examples = [ - ['seek 10', 'seeks to 10 seconds from beginning of song'], - ['seek 1:30', 'seeks to 1 minute and 30 seconds from beginning of song'], - ['seek 1:00:00', 'seeks to 1 hour from beginning of song'], - ]; + public readonly slashCommand = new SlashCommandBuilder() + .setName('seek') + .setDescription('seek to a position from beginning of song') + .addStringOption(option => + option.setName('time') + .setDescription('time to seek') + .setRequired(true), + ); public requiresVC = true; @@ -25,22 +25,20 @@ export default class implements Command { this.playerManager = playerManager; } - public async execute(msg: Message, args: string []): Promise<void> { - const player = this.playerManager.get(msg.guild!.id); + public async execute(interaction: CommandInteraction): Promise<void> { + const player = this.playerManager.get(interaction.guild!.id); const currentSong = player.getCurrent(); if (!currentSong) { - await msg.channel.send(errorMsg('nothing is playing')); - return; + throw new Error('nothing is playing'); } if (currentSong.isLive) { - await msg.channel.send(errorMsg('can\'t seek in a livestream')); - return; + throw new Error('can\'t seek in a livestream'); } - const time = args[0]; + const time = interaction.options.getString('time')!; let seekTime = 0; @@ -51,20 +49,14 @@ export default class implements Command { } if (seekTime > currentSong.length) { - await msg.channel.send(errorMsg('can\'t seek past the end of the song')); - return; + throw new Error('can\'t seek past the end of the song'); } - const loading = new LoadingMessage(msg.channel as TextChannel); + await Promise.all([ + player.seek(seekTime), + interaction.deferReply(), + ]); - await loading.start(); - - try { - await player.seek(seekTime); - - await loading.stop(); - } catch (error: unknown) { - await loading.stop(errorMsg(error as Error)); - } + await interaction.editReply(`👍 seeked to ${prettyTime(player.getPosition())}`); } } diff --git a/src/commands/shortcuts.ts b/src/commands/shortcuts.ts deleted file mode 100644 index e40d10a..0000000 --- a/src/commands/shortcuts.ts +++ /dev/null @@ -1,128 +0,0 @@ -import {Message} from 'discord.js'; -import {injectable} from 'inversify'; -import errorMsg from '../utils/error-msg.js'; -import Command from '.'; -import {prisma} from '../utils/db.js'; - -@injectable() -export default class implements Command { - public name = 'shortcuts'; - public aliases = []; - public examples = [ - ['shortcuts', 'show all shortcuts'], - ['shortcuts set s skip', 'aliases `s` to `skip`'], - ['shortcuts set party play https://www.youtube.com/watch?v=zK6oOJ1wz8k', 'aliases `party` to a specific play command'], - ['shortcuts delete party', 'removes the `party` shortcut'], - ]; - - public async execute(msg: Message, args: string []): Promise<void> { - if (args.length === 0) { - // Get shortcuts for guild - const shortcuts = await prisma.shortcut.findMany({ - where: { - guildId: msg.guild!.id, - }, - }); - - if (shortcuts.length === 0) { - await msg.channel.send('no shortcuts exist'); - return; - } - - // Get prefix for guild - const settings = await prisma.setting.findUnique({ - where: { - guildId: msg.guild!.id, - }, - }); - - if (!settings) { - return; - } - - const {prefix} = settings; - - const res = shortcuts.reduce((accum, shortcut) => { - accum += `${prefix}${shortcut.shortcut}: ${shortcut.command}\n`; - - return accum; - }, ''); - - await msg.channel.send(res); - } else { - const action = args[0]; - - const shortcutName = args[1]; - - switch (action) { - case 'set': { - const shortcut = await prisma.shortcut.findFirst({ - where: { - guildId: msg.guild!.id, - shortcut: shortcutName, - }, - }); - - const command = args.slice(2).join(' '); - - const newShortcut = {shortcut: shortcutName, command, guildId: msg.guild!.id, authorId: msg.author.id}; - - if (shortcut) { - if (shortcut.authorId !== msg.author.id && msg.author.id !== msg.guild!.ownerId) { - await msg.channel.send(errorMsg('you do\'nt have permission to do that')); - return; - } - - await prisma.shortcut.update({ - where: { - id: shortcut.id, - }, - data: newShortcut, - }); - await msg.channel.send('shortcut updated'); - } else { - await prisma.shortcut.create({data: newShortcut}); - await msg.channel.send('shortcut created'); - } - - break; - } - - case 'delete': { - // Check if shortcut exists - const shortcut = await prisma.shortcut.findFirst({ - where: { - guildId: msg.guild!.id, - shortcut: shortcutName, - }, - }); - - if (!shortcut) { - await msg.channel.send(errorMsg('shortcut doesn\'t exist')); - return; - } - - // Check permissions - if (shortcut.authorId !== msg.author.id && msg.author.id !== msg.guild!.ownerId) { - await msg.channel.send(errorMsg('you don\'t have permission to do that')); - return; - } - - await prisma.shortcut.delete({ - where: { - id: shortcut.id, - }, - }); - - await msg.channel.send('shortcut deleted'); - - break; - } - - default: { - await msg.channel.send(errorMsg('unknown command')); - } - } - } - } -} diff --git a/src/commands/shuffle.ts b/src/commands/shuffle.ts index d50f0b3..e27f1e2 100644 --- a/src/commands/shuffle.ts +++ b/src/commands/shuffle.ts @@ -1,17 +1,15 @@ -import {Message} from 'discord.js'; +import {CommandInteraction} from 'discord.js'; import {TYPES} from '../types.js'; import {inject, injectable} from 'inversify'; import PlayerManager from '../managers/player.js'; -import errorMsg from '../utils/error-msg.js'; import Command from '.'; +import {SlashCommandBuilder} from '@discordjs/builders'; @injectable() export default class implements Command { - public name = 'shuffle'; - public aliases = []; - public examples = [ - ['shuffle', 'shuffles the current queue'], - ]; + public readonly slashCommand = new SlashCommandBuilder() + .setName('shuffle') + .setDescription('shuffles the current queue'); public requiresVC = true; @@ -21,16 +19,15 @@ export default class implements Command { this.playerManager = playerManager; } - public async execute(msg: Message, _: string []): Promise<void> { - const player = this.playerManager.get(msg.guild!.id); + public async execute(interaction: CommandInteraction): Promise<void> { + const player = this.playerManager.get(interaction.guild!.id); if (player.isQueueEmpty()) { - await msg.channel.send(errorMsg('not enough songs to shuffle')); - return; + throw new Error('not enough songs to shuffle'); } player.shuffle(); - await msg.channel.send('shuffled'); + await interaction.reply('shuffled'); } } diff --git a/src/commands/skip.ts b/src/commands/skip.ts index ad9d4dc..4c51e77 100644 --- a/src/commands/skip.ts +++ b/src/commands/skip.ts @@ -1,20 +1,20 @@ -import {Message, TextChannel} from 'discord.js'; +import {CommandInteraction} from 'discord.js'; import {TYPES} from '../types.js'; import {inject, injectable} from 'inversify'; import PlayerManager from '../managers/player.js'; import Command from '.'; -import LoadingMessage from '../utils/loading-message.js'; -import errorMsg from '../utils/error-msg.js'; +import {SlashCommandBuilder} from '@discordjs/builders'; import {buildPlayingMessageEmbed} from '../utils/build-embed.js'; @injectable() export default class implements Command { - public name = 'skip'; - public aliases = ['s']; - public examples = [ - ['skip', 'skips the current song'], - ['skip 2', 'skips the next 2 songs'], - ]; + public readonly slashCommand = new SlashCommandBuilder() + .setName('skip') + .setDescription('skips the next songs') + .addIntegerOption(option => option + .setName('number') + .setDescription('number of songs to skip [default: 1]') + .setRequired(false)); public requiresVC = true; @@ -24,37 +24,23 @@ export default class implements Command { this.playerManager = playerManager; } - public async execute(msg: Message, args: string []): Promise<void> { - let numToSkip = 1; + public async execute(interaction: CommandInteraction): Promise<void> { + const numToSkip = interaction.options.getInteger('skip') ?? 1; - if (args.length === 1) { - if (!Number.isNaN(parseInt(args[0], 10))) { - numToSkip = parseInt(args[0], 10); - } + if (numToSkip < 1) { + throw new Error('invalid number of songs to skip'); } - const player = this.playerManager.get(msg.guild!.id); - - const loader = new LoadingMessage(msg.channel as TextChannel); + const player = this.playerManager.get(interaction.guild!.id); try { - await loader.start(); await player.forward(numToSkip); + await interaction.reply({ + content: 'keep \'er movin\'', + embeds: player.getCurrent() ? [buildPlayingMessageEmbed(player)] : [], + }); } catch (_: unknown) { - await loader.stop(errorMsg('no song to skip to')); - return; + throw new Error('no song to skip to'); } - - const promises = [ - loader.stop('keep \'er movin\''), - ]; - - if (player.getCurrent()) { - promises.push(msg.channel.send({ - embeds: [buildPlayingMessageEmbed(player)], - })); - } - - await Promise.all(promises); } } diff --git a/src/commands/unskip.ts b/src/commands/unskip.ts index adc44e7..17d6489 100644 --- a/src/commands/unskip.ts +++ b/src/commands/unskip.ts @@ -1,18 +1,16 @@ -import {Message} from 'discord.js'; +import {CommandInteraction} from 'discord.js'; import {TYPES} from '../types.js'; import {inject, injectable} from 'inversify'; import PlayerManager from '../managers/player.js'; -import errorMsg from '../utils/error-msg.js'; import Command from '.'; +import {SlashCommandBuilder} from '@discordjs/builders'; import {buildPlayingMessageEmbed} from '../utils/build-embed.js'; @injectable() export default class implements Command { - public name = 'unskip'; - public aliases = ['back']; - public examples = [ - ['unskip', 'goes back in the queue by one song'], - ]; + public readonly slashCommand = new SlashCommandBuilder() + .setName('unskip') + .setDescription('goes back in the queue by one song'); public requiresVC = true; @@ -22,19 +20,17 @@ export default class implements Command { this.playerManager = playerManager; } - public async execute(msg: Message, _: string []): Promise<void> { - const player = this.playerManager.get(msg.guild!.id); + public async execute(interaction: CommandInteraction): Promise<void> { + const player = this.playerManager.get(interaction.guild!.id); try { await player.back(); + await interaction.reply({ + content: 'back \'er up\'', + embeds: player.getCurrent() ? [buildPlayingMessageEmbed(player)] : [], + }); } catch (_: unknown) { - await msg.channel.send(errorMsg('no song to go back to')); - return; + throw new Error('no song to go back to'); } - - await msg.channel.send({ - content: 'back \'er up\'', - embeds: [buildPlayingMessageEmbed(player)], - }); } } |
