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 | |
| 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')
36 files changed, 982 insertions, 1103 deletions
@@ -1,147 +1,167 @@ -import {Client, Message, Collection} from 'discord.js'; +import {Client, Collection, User} from 'discord.js'; import {inject, injectable} from 'inversify'; import ora from 'ora'; import {TYPES} from './types.js'; -import {prisma} from './utils/db.js'; import container from './inversify.config.js'; import Command from './commands/index.js'; import debug from './utils/debug.js'; -import NaturalLanguage from './services/natural-language-commands.js'; import handleGuildCreate from './events/guild-create.js'; import handleVoiceStateUpdate from './events/voice-state-update.js'; +import handleGuildUpdate from './events/guild-update.js'; import errorMsg from './utils/error-msg.js'; import {isUserInVoice} from './utils/channels.js'; import Config from './services/config.js'; import {generateDependencyReport} from '@discordjs/voice'; +import {REST} from '@discordjs/rest'; +import {Routes} from 'discord-api-types/v9'; +import updatePermissionsForGuild from './utils/update-permissions-for-guild.js'; @injectable() export default class { private readonly client: Client; - private readonly naturalLanguage: NaturalLanguage; private readonly token: string; - private readonly commands!: Collection<string, Command>; + private readonly shouldRegisterCommandsOnBot: boolean; + private readonly commandsByName!: Collection<string, Command>; + private readonly commandsByButtonId!: Collection<string, Command>; constructor( @inject(TYPES.Client) client: Client, - @inject(TYPES.Services.NaturalLanguage) naturalLanguage: NaturalLanguage, @inject(TYPES.Config) config: Config, ) { this.client = client; - this.naturalLanguage = naturalLanguage; this.token = config.DISCORD_TOKEN; - this.commands = new Collection(); + this.shouldRegisterCommandsOnBot = config.REGISTER_COMMANDS_ON_BOT; + this.commandsByName = new Collection(); + this.commandsByButtonId = new Collection(); } - public async listen(): Promise<string> { + public async register(): Promise<void> { // Load in commands - container.getAll<Command>(TYPES.Command).forEach(command => { - const commandNames = [command.name, ...command.aliases]; - - commandNames.forEach(commandName => - this.commands.set(commandName, command), - ); - }); - - this.client.on('messageCreate', async (msg: Message) => { - // Get guild settings - if (!msg.guild) { - return; - } - - const settings = await prisma.setting.findUnique({ - where: { - guildId: msg.guild.id, - }, - }); - - if (!settings) { - // Got into a bad state, send owner welcome message - this.client.emit('guildCreate', msg.guild); - return; - } - - const {prefix, channel} = settings; - - if ( - !msg.content.startsWith(prefix) - && !msg.author.bot - && msg.channel.id === channel - && (await this.naturalLanguage.execute(msg)) - ) { - // Natural language command handled message - return; + for (const command of container.getAll<Command>(TYPES.Command)) { + // Make sure we can serialize to JSON without errors + try { + command.slashCommand.toJSON(); + } catch (error) { + console.error(error); + throw new Error(`Could not serialize /${command.slashCommand.name ?? ''} to JSON`); } - if ( - !msg.content.startsWith(prefix) - || msg.author.bot - || msg.channel.id !== channel - ) { - return; + if (command.slashCommand.name) { + this.commandsByName.set(command.slashCommand.name, command); } - let args = msg.content.slice(prefix.length).split(/ +/); - const command = args.shift()!.toLowerCase(); - - const shortcut = await prisma.shortcut.findFirst({ - where: { - guildId: msg.guild.id, - shortcut: command, - }, - }); - - let handler: Command; - - if (this.commands.has(command)) { - handler = this.commands.get(command)!; - } else if (shortcut) { - const possibleHandler = this.commands.get( - shortcut.command.split(' ')[0], - ); - - if (possibleHandler) { - handler = possibleHandler; - args = shortcut.command.split(/ +/).slice(1); - } else { - return; + if (command.handledButtonIds) { + for (const buttonId of command.handledButtonIds) { + this.commandsByButtonId.set(buttonId, command); } - } else { - return; } + } + // Register event handlers + this.client.on('interactionCreate', async interaction => { try { - if (handler.requiresVC && !isUserInVoice(msg.guild, msg.author)) { - await msg.channel.send(errorMsg('gotta be in a voice channel')); - return; + if (interaction.isCommand()) { + const command = this.commandsByName.get(interaction.commandName); + + if (!command) { + return; + } + + if (!interaction.guild) { + await interaction.reply(errorMsg('you can\'t use this bot in a DM')); + return; + } + + const requiresVC = command.requiresVC instanceof Function ? command.requiresVC(interaction) : command.requiresVC; + + if (requiresVC && interaction.member && !isUserInVoice(interaction.guild, interaction.member.user as User)) { + await interaction.reply({content: errorMsg('gotta be in a voice channel'), ephemeral: true}); + return; + } + + if (command.execute) { + await command.execute(interaction); + } + } else if (interaction.isButton()) { + const command = this.commandsByButtonId.get(interaction.customId); + + if (!command) { + return; + } + + if (command.handleButtonInteraction) { + await command.handleButtonInteraction(interaction); + } + } else if (interaction.isAutocomplete()) { + const command = this.commandsByName.get(interaction.commandName); + + if (!command) { + return; + } + + if (command.handleAutocompleteInteraction) { + await command.handleAutocompleteInteraction(interaction); + } } - - await handler.execute(msg, args); } catch (error: unknown) { debug(error); - await msg.channel.send( - errorMsg((error as Error).message.toLowerCase()), - ); + + // This can fail if the message was deleted, and we don't want to crash the whole bot + try { + if ((interaction.isApplicationCommand() || interaction.isButton()) && (interaction.replied || interaction.deferred)) { + await interaction.editReply(errorMsg(error as Error)); + } else if (interaction.isApplicationCommand() || interaction.isButton()) { + await interaction.reply({content: errorMsg(error as Error), ephemeral: true}); + } + } catch {} } }); const spinner = ora('📡 connecting to Discord...').start(); - this.client.on('ready', () => { + this.client.once('ready', async () => { debug(generateDependencyReport()); - spinner.succeed( - `Ready! Invite the bot with https://discordapp.com/oauth2/authorize?client_id=${this.client.user?.id ?? '' - }&scope=bot&permissions=36752448`, - ); + // Update commands + const rest = new REST({version: '9'}).setToken(this.token); + + if (this.shouldRegisterCommandsOnBot) { + spinner.text = '📡 updating commands on bot...'; + + await rest.put( + Routes.applicationCommands(this.client.user!.id), + {body: this.commandsByName.map(command => command.slashCommand.toJSON())}, + ); + } else { + spinner.text = '📡 updating commands in all guilds...'; + + await Promise.all([ + ...this.client.guilds.cache.map(async guild => { + await rest.put( + Routes.applicationGuildCommands(this.client.user!.id, guild.id), + {body: this.commandsByName.map(command => command.slashCommand.toJSON())}, + ); + }), + // Remove commands registered on bot (if they exist) + rest.put(Routes.applicationCommands(this.client.user!.id), {body: []}), + ], + ); + } + + // Update permissions + spinner.text = '📡 updating permissions...'; + await Promise.all(this.client.guilds.cache.map(async guild => updatePermissionsForGuild(guild))); + + spinner.succeed(`Ready! Invite the bot with https://discordapp.com/oauth2/authorize?client_id=${this.client.user?.id ?? ''}&scope=bot%20applications.commands&permissions=36700160`); }); this.client.on('error', console.error); this.client.on('debug', debug); - // Register event handlers this.client.on('guildCreate', handleGuildCreate); this.client.on('voiceStateUpdate', handleVoiceStateUpdate); + this.client.on('guildUpdate', handleGuildUpdate); - return this.client.login(this.token); + await this.client.login(this.token); } } 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)], - }); } } diff --git a/src/events/guild-create.ts b/src/events/guild-create.ts index 9a26b2a..630d6cb 100644 --- a/src/events/guild-create.ts +++ b/src/events/guild-create.ts @@ -1,10 +1,11 @@ -import {Guild, TextChannel, Message, MessageReaction, User} from 'discord.js'; -import emoji from 'node-emoji'; -import pEvent from 'p-event'; -import {chunk} from '../utils/arrays.js'; +import {Guild, Client} from 'discord.js'; +import container from '../inversify.config.js'; +import Command from '../commands'; +import {TYPES} from '../types.js'; +import Config from '../services/config.js'; import {prisma} from '../utils/db.js'; - -const DEFAULT_PREFIX = '!'; +import {REST} from '@discordjs/rest'; +import {Routes} from 'discord-api-types/v9'; export default async (guild: Guild): Promise<void> => { await prisma.setting.upsert({ @@ -13,88 +14,26 @@ export default async (guild: Guild): Promise<void> => { }, create: { guildId: guild.id, - prefix: DEFAULT_PREFIX, - }, - update: { - prefix: DEFAULT_PREFIX, }, + update: {}, }); - const owner = await guild.client.users.fetch(guild.ownerId); + const config = container.get<Config>(TYPES.Config); - let firstStep = '👋 Hi!\n'; - firstStep += 'I just need to ask a few questions before you start listening to music.\n\n'; - firstStep += 'First, what channel should I listen to for music commands?\n\n'; + // Setup slash commands + if (!config.REGISTER_COMMANDS_ON_BOT) { + const token = container.get<Config>(TYPES.Config).DISCORD_TOKEN; + const client = container.get<Client>(TYPES.Client); - const firstStepMsg = await owner.send(firstStep); + const rest = new REST({version: '9'}).setToken(token); - // Show emoji selector - interface EmojiChannel { - name: string; - id: string; - emoji: string; + await rest.put( + Routes.applicationGuildCommands(client.user!.id, guild.id), + {body: container.getAll<Command>(TYPES.Command).map(command => command.slashCommand.toJSON())}, + ); } - const emojiChannels: EmojiChannel[] = []; - - for (const [channelId, channel] of guild.channels.cache) { - if (channel.type === 'GUILD_TEXT') { - emojiChannels.push({ - name: channel.name, - id: channelId, - emoji: emoji.random().emoji, - }); - } - } - - const sentMessageIds: string[] = []; - - chunk(emojiChannels, 10).map(async chunk => { - let str = ''; - for (const channel of chunk) { - str += `${channel.emoji}: #${channel.name}\n`; - } - - const msg = await owner.send(str); - - sentMessageIds.push(msg.id); - - await Promise.all(chunk.map(async channel => msg.react(channel.emoji))); - }); - - // Wait for response from user - const [choice] = await pEvent(guild.client, 'messageReactionAdd', { - multiArgs: true, - filter: ([reaction, user]: [MessageReaction, User]) => sentMessageIds.includes(reaction.message.id) && user.id === owner.id, - }); - - const chosenChannel = emojiChannels.find(e => e.emoji === (choice as unknown as MessageReaction).emoji.name)!; - - // Second setup step (get prefix) - let secondStep = `👍 Cool, I'll listen to **#${chosenChannel.name}** \n\n`; - secondStep += 'Last question: what character should I use for a prefix? Type a single character and hit enter.'; - - await owner.send(secondStep); - - const prefixResponses = await firstStepMsg.channel.awaitMessages({filter: (r: Message) => r.content.length === 1, max: 1}); - - const prefixCharacter = prefixResponses.first()!.content; - - // Save settings - await prisma.setting.update({ - where: { - guildId: guild.id, - }, - data: { - channel: chosenChannel.id, - prefix: prefixCharacter, - }, - }); - - // Send welcome - const boundChannel = guild.client.channels.cache.get(chosenChannel.id) as TextChannel; - - await boundChannel.send(`hey <@${owner.id}> try \`${prefixCharacter}play https://www.youtube.com/watch?v=dQw4w9WgXcQ\``); + const owner = await guild.fetchOwner(); - await firstStepMsg.channel.send(`Sounds good. Check out **#${chosenChannel.name}** to get started.`); + await owner.send('👋 Hi! Someone (probably you) just invited me to a server you own. I can\'t be used by your server members until you complete setup by running /config set-role in your server.'); }; diff --git a/src/events/guild-update.ts b/src/events/guild-update.ts new file mode 100644 index 0000000..837bbbe --- /dev/null +++ b/src/events/guild-update.ts @@ -0,0 +1,10 @@ +import {Guild} from 'discord.js'; +import updatePermissionsForGuild from '../utils/update-permissions-for-guild.js'; + +const handleGuildUpdate = async (oldGuild: Guild, newGuild: Guild) => { + if (oldGuild.ownerId !== newGuild.ownerId) { + await updatePermissionsForGuild(newGuild); + } +}; + +export default handleGuildUpdate; diff --git a/src/index.ts b/src/index.ts index e6df09d..08a7152 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,7 +18,7 @@ const startBot = async () => { await container.get<FileCacheProvider>(TYPES.FileCache).cleanup(); - await bot.listen(); + await bot.register(); }; export {startBot}; diff --git a/src/inversify.config.ts b/src/inversify.config.ts index 6ec1ba2..d29d3de 100644 --- a/src/inversify.config.ts +++ b/src/inversify.config.ts @@ -8,23 +8,22 @@ import ConfigProvider from './services/config.js'; // Managers import PlayerManager from './managers/player.js'; -// Helpers +// Services +import AddQueryToQueue from './services/add-query-to-queue.js'; import GetSongs from './services/get-songs.js'; -import NaturalLanguage from './services/natural-language-commands.js'; // Comands import Command from './commands'; import Clear from './commands/clear.js'; import Config from './commands/config.js'; import Disconnect from './commands/disconnect.js'; +import Favorites from './commands/favorites.js'; import ForwardSeek from './commands/fseek.js'; -import Help from './commands/help.js'; import Pause from './commands/pause.js'; import Play from './commands/play.js'; import QueueCommand from './commands/queue.js'; import Remove from './commands/remove.js'; import Seek from './commands/seek.js'; -import Shortcuts from './commands/shortcuts.js'; import Shuffle from './commands/shuffle.js'; import Skip from './commands/skip.js'; import Unskip from './commands/unskip.js'; @@ -49,23 +48,22 @@ container.bind<Client>(TYPES.Client).toConstantValue(new Client({intents})); // Managers container.bind<PlayerManager>(TYPES.Managers.Player).to(PlayerManager).inSingletonScope(); -// Helpers +// Services container.bind<GetSongs>(TYPES.Services.GetSongs).to(GetSongs).inSingletonScope(); -container.bind<NaturalLanguage>(TYPES.Services.NaturalLanguage).to(NaturalLanguage).inSingletonScope(); +container.bind<AddQueryToQueue>(TYPES.Services.AddQueryToQueue).to(AddQueryToQueue).inSingletonScope(); // Commands [ Clear, Config, Disconnect, + Favorites, ForwardSeek, - Help, Pause, Play, QueueCommand, Remove, Seek, - Shortcuts, Shuffle, Skip, Unskip, diff --git a/src/managers/player.ts b/src/managers/player.ts index 5d816b8..420cf48 100644 --- a/src/managers/player.ts +++ b/src/managers/player.ts @@ -1,5 +1,4 @@ import {inject, injectable} from 'inversify'; -import {Client} from 'discord.js'; import {TYPES} from '../types.js'; import Player from '../services/player.js'; import FileCacheProvider from '../services/file-cache.js'; @@ -7,12 +6,10 @@ import FileCacheProvider from '../services/file-cache.js'; @injectable() export default class { private readonly guildPlayers: Map<string, Player>; - private readonly discordClient: Client; private readonly fileCache: FileCacheProvider; - constructor(@inject(TYPES.FileCache) fileCache: FileCacheProvider, @inject(TYPES.Client) client: Client) { + constructor(@inject(TYPES.FileCache) fileCache: FileCacheProvider) { this.guildPlayers = new Map(); - this.discordClient = client; this.fileCache = fileCache; } @@ -20,7 +17,7 @@ export default class { let player = this.guildPlayers.get(guildId); if (!player) { - player = new Player(this.discordClient, this.fileCache); + player = new Player(this.fileCache, guildId); this.guildPlayers.set(guildId, player); } diff --git a/src/scripts/run-with-database-url.ts b/src/scripts/run-with-database-url.ts index b7ae3a7..e4ab39a 100644 --- a/src/scripts/run-with-database-url.ts +++ b/src/scripts/run-with-database-url.ts @@ -2,12 +2,14 @@ import {DATA_DIR} from '../services/config.js'; import createDatabaseUrl from '../utils/create-database-url.js'; import {execa} from 'execa'; -process.env.DATABASE_URL = createDatabaseUrl(DATA_DIR); - (async () => { await execa(process.argv[2], process.argv.slice(3), { preferLocal: true, stderr: process.stderr, stdout: process.stdout, + stdin: process.stdin, + env: { + DATABASE_URL: createDatabaseUrl(DATA_DIR), + }, }); })(); diff --git a/src/services/add-query-to-queue.ts b/src/services/add-query-to-queue.ts new file mode 100644 index 0000000..bb512c6 --- /dev/null +++ b/src/services/add-query-to-queue.ts @@ -0,0 +1,155 @@ +import {CommandInteraction, GuildMember} from 'discord.js'; +import {inject, injectable} from 'inversify'; +import {Except} from 'type-fest'; +import shuffle from 'array-shuffle'; +import {TYPES} from '../types.js'; +import GetSongs from '../services/get-songs.js'; +import {QueuedSong} from './player.js'; +import PlayerManager from '../managers/player.js'; +import {prisma} from '../utils/db.js'; +import {buildPlayingMessageEmbed} from '../utils/build-embed.js'; +import {getMemberVoiceChannel, getMostPopularVoiceChannel} from '../utils/channels.js'; + +@injectable() +export default class AddQueryToQueue { + constructor(@inject(TYPES.Services.GetSongs) private readonly getSongs: GetSongs, @inject(TYPES.Managers.Player) private readonly playerManager: PlayerManager) {} + + public async addToQueue({ + query, + addToFrontOfQueue, + shuffleAdditions, + interaction, + }: { + query: string; + addToFrontOfQueue: boolean; + shuffleAdditions: boolean; + interaction: CommandInteraction; + }): Promise<void> { + const guildId = interaction.guild!.id; + const player = this.playerManager.get(guildId); + const wasPlayingSong = player.getCurrent() !== null; + + const [targetVoiceChannel] = getMemberVoiceChannel(interaction.member as GuildMember) ?? getMostPopularVoiceChannel(interaction.guild!); + + const settings = await prisma.setting.findUnique({where: {guildId}}); + + if (!settings) { + throw new Error('Could not find settings for guild'); + } + + const {playlistLimit} = settings; + + await interaction.deferReply(); + + let newSongs: Array<Except<QueuedSong, 'addedInChannelId' | 'requestedBy'>> = []; + let extraMsg = ''; + + // Test if it's a complete URL + try { + const url = new URL(query); + + 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 { + const song = await this.getSongs.youtubeVideo(url.href); + + if (song) { + newSongs.push(song); + } else { + throw new Error('that doesn\'t exist'); + } + } + } else if (url.protocol === 'spotify:' || url.host === 'open.spotify.com') { + const [convertedSongs, nSongsNotFound, totalSongs] = await this.getSongs.spotifySource(query, 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 song = await this.getSongs.youtubeVideoSearch(query); + + if (song) { + newSongs.push(song); + } else { + throw new Error('that doesn\'t exist'); + } + } + + if (newSongs.length === 0) { + throw new Error('no songs found'); + } + + if (shuffleAdditions) { + newSongs = shuffle(newSongs); + } + + newSongs.forEach(song => { + player.add({...song, addedInChannelId: interaction.channel!.id, requestedBy: interaction.member!.user.id}, {immediate: addToFrontOfQueue ?? false}); + }); + + const firstSong = newSongs[0]; + + let statusMsg = ''; + + if (player.voiceConnection === null) { + await player.connect(targetVoiceChannel); + + // Resume / start playback + await player.play(); + + if (wasPlayingSong) { + statusMsg = 'resuming playback'; + } + + await interaction.editReply({ + embeds: [buildPlayingMessageEmbed(player)], + }); + } + + // Build response message + if (statusMsg !== '') { + if (extraMsg === '') { + extraMsg = statusMsg; + } else { + extraMsg = `${statusMsg}, ${extraMsg}`; + } + } + + if (extraMsg !== '') { + extraMsg = ` (${extraMsg})`; + } + + if (newSongs.length === 1) { + await interaction.editReply(`u betcha, **${firstSong.title}** added to the${addToFrontOfQueue ? ' front of the' : ''} queue${extraMsg}`); + } else { + await interaction.editReply(`u betcha, **${firstSong.title}** and ${newSongs.length - 1} other songs were added to the queue${extraMsg}`); + } + } +} diff --git a/src/services/config.ts b/src/services/config.ts index 0720c2c..cd56915 100644 --- a/src/services/config.ts +++ b/src/services/config.ts @@ -13,6 +13,7 @@ const CONFIG_MAP = { YOUTUBE_API_KEY: process.env.YOUTUBE_API_KEY, SPOTIFY_CLIENT_ID: process.env.SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET: process.env.SPOTIFY_CLIENT_SECRET, + REGISTER_COMMANDS_ON_BOT: process.env.REGISTER_COMMANDS_ON_BOT === 'true', DATA_DIR, CACHE_DIR: path.join(DATA_DIR, 'cache'), CACHE_LIMIT_IN_BYTES: xbytes.parseSize(process.env.CACHE_LIMIT ?? '2GB'), @@ -24,6 +25,7 @@ export default class Config { readonly YOUTUBE_API_KEY!: string; readonly SPOTIFY_CLIENT_ID!: string; readonly SPOTIFY_CLIENT_SECRET!: string; + readonly REGISTER_COMMANDS_ON_BOT!: boolean; readonly DATA_DIR!: string; readonly CACHE_DIR!: string; readonly CACHE_LIMIT_IN_BYTES!: number; @@ -39,6 +41,8 @@ export default class Config { this[key as ConditionalKeys<typeof CONFIG_MAP, number>] = value; } else if (typeof value === 'string') { this[key as ConditionalKeys<typeof CONFIG_MAP, string>] = value.trim(); + } else if (typeof value === 'boolean') { + this[key as ConditionalKeys<typeof CONFIG_MAP, boolean>] = value; } else { throw new Error(`Unsupported type for ${key}`); } diff --git a/src/services/get-songs.ts b/src/services/get-songs.ts index e132d7b..33c3173 100644 --- a/src/services/get-songs.ts +++ b/src/services/get-songs.ts @@ -15,12 +15,10 @@ import {cleanUrl} from '../utils/url.js'; import ThirdParty from './third-party.js'; import Config from './config.js'; import KeyValueCacheProvider from './key-value-cache.js'; +import {ONE_HOUR_IN_SECONDS, ONE_MINUTE_IN_SECONDS} from '../utils/constants.js'; type SongMetadata = Except<QueuedSong, 'addedInChannelId' | 'requestedBy'>; -const ONE_HOUR_IN_SECONDS = 60 * 60; -const ONE_MINUTE_IN_SECONDS = 1 * 60; - @injectable() export default class { private readonly youtube: YouTube; diff --git a/src/services/natural-language-commands.ts b/src/services/natural-language-commands.ts deleted file mode 100644 index 4ce8ea3..0000000 --- a/src/services/natural-language-commands.ts +++ /dev/null @@ -1,131 +0,0 @@ -import {inject, injectable} from 'inversify'; -import {Message, Guild, GuildMember} from 'discord.js'; -import {TYPES} from '../types.js'; -import PlayerManager from '../managers/player.js'; -import {QueuedSong} from '../services/player.js'; -import {getMostPopularVoiceChannel, getMemberVoiceChannel} from '../utils/channels.js'; - -@injectable() -export default class { - private readonly playerManager: PlayerManager; - - constructor(@inject(TYPES.Managers.Player) playerManager: PlayerManager) { - this.playerManager = playerManager; - } - - async execute(msg: Message): Promise<boolean> { - if (msg.content.startsWith('say') && msg.content.endsWith('muse')) { - const res = msg.content.slice(3, msg.content.indexOf('muse')).trim(); - - await msg.channel.send(res); - return true; - } - - if (msg.content.toLowerCase().includes('packers')) { - await Promise.all([ - msg.channel.send('GO PACKERS GO!!!'), - this.playClip(msg.guild!, msg.member!, { - title: 'GO PACKERS!', - artist: 'Unknown', - url: 'https://www.youtube.com/watch?v=qkdtID7mY3E', - length: 204, - playlist: null, - isLive: false, - addedInChannelId: msg.channel.id, - thumbnailUrl: null, - requestedBy: msg.author.id, - }, 8, 10), - ]); - - return true; - } - - if (msg.content.toLowerCase().includes('bears')) { - await Promise.all([ - msg.channel.send('F*** THE BEARS'), - this.playClip(msg.guild!, msg.member!, { - title: 'GO PACKERS!', - artist: 'Charlie Berens', - url: 'https://www.youtube.com/watch?v=UaqlE9Pyy_Q', - length: 385, - playlist: null, - isLive: false, - addedInChannelId: msg.channel.id, - thumbnailUrl: null, - requestedBy: msg.author.id, - }, 358, 5.5), - ]); - - return true; - } - - if (msg.content.toLowerCase().includes('bitconnect')) { - await Promise.all([ - msg.channel.send('🌊 🌊 🌊 🌊'), - this.playClip(msg.guild!, msg.member!, { - title: 'BITCONNEEECCT', - artist: 'Carlos Matos', - url: 'https://www.youtube.com/watch?v=lCcwn6bGUtU', - length: 227, - playlist: null, - isLive: false, - addedInChannelId: msg.channel.id, - thumbnailUrl: null, - requestedBy: msg.author.id, - }, 50, 13), - ]); - - return true; - } - - return false; - } - - private async playClip(guild: Guild, member: GuildMember, song: QueuedSong, position: number, duration: number): Promise<void> { - const player = this.playerManager.get(guild.id); - - const [channel, n] = getMemberVoiceChannel(member) ?? getMostPopularVoiceChannel(guild); - - if (!player.voiceConnection && n === 0) { - return; - } - - if (!player.voiceConnection) { - await player.connect(channel); - } - - const isPlaying = player.getCurrent() !== null; - let oldPosition = 0; - - player.add(song, {immediate: true}); - - if (isPlaying) { - oldPosition = player.getPosition(); - - player.manualForward(1); - } - - await player.seek(position); - - return new Promise((resolve, reject) => { - try { - setTimeout(async () => { - if (player.getCurrent()?.title === song.title) { - player.removeCurrent(); - - if (isPlaying) { - await player.back(); - await player.seek(oldPosition); - } else { - player.disconnect(); - } - } - - resolve(); - }, duration * 1000); - } catch (error: unknown) { - reject(error); - } - }); - } -} diff --git a/src/services/player.ts b/src/services/player.ts index f46240a..ce611e8 100644 --- a/src/services/player.ts +++ b/src/services/player.ts @@ -1,13 +1,13 @@ -import {VoiceChannel, Snowflake, Client, TextChannel} from 'discord.js'; +import {VoiceChannel, Snowflake} from 'discord.js'; import {Readable} from 'stream'; import hasha from 'hasha'; import ytdl from 'ytdl-core'; import {WriteStream} from 'fs-capacitor'; import ffmpeg from 'fluent-ffmpeg'; import shuffle from 'array-shuffle'; -import errorMsg from '../utils/error-msg.js'; import {AudioPlayer, AudioPlayerStatus, createAudioPlayer, createAudioResource, joinVoiceChannel, StreamType, VoiceConnection, VoiceConnectionStatus} from '@discordjs/voice'; import FileCacheProvider from './file-cache.js'; +import debug from '../utils/debug.js'; export interface QueuedPlaylist { title: string; @@ -31,9 +31,15 @@ export enum STATUS { PAUSED, } +export interface PlayerEvents { + statusChange: (oldStatus: STATUS, newStatus: STATUS) => void; +} + export default class { - public status = STATUS.PAUSED; public voiceConnection: VoiceConnection | null = null; + public status = STATUS.PAUSED; + public guildId: string; + private queue: QueuedSong[] = []; private queuePosition = 0; private audioPlayer: AudioPlayer | null = null; @@ -43,12 +49,11 @@ export default class { private positionInSeconds = 0; - private readonly discordClient: Client; private readonly fileCache: FileCacheProvider; - constructor(client: Client, fileCache: FileCacheProvider) { - this.discordClient = client; + constructor(fileCache: FileCacheProvider, guildId: string) { this.fileCache = fileCache; + this.guildId = guildId; } async connect(channel: VoiceChannel): Promise<void> { @@ -150,9 +155,11 @@ export default class { }, }); this.voiceConnection.subscribe(this.audioPlayer); - this.audioPlayer.play(createAudioResource(stream, { + const resource = createAudioResource(stream, { inputType: StreamType.WebmOpus, - })); + }); + + this.audioPlayer.play(resource); this.attachListeners(); @@ -167,14 +174,13 @@ export default class { this.lastSongURL = currentSong.url; } } catch (error: unknown) { - const currentSong = this.getCurrent(); await this.forward(1); if ((error as {statusCode: number}).statusCode === 410 && currentSong) { const channelId = currentSong.addedInChannelId; if (channelId) { - await (this.discordClient.channels.cache.get(channelId) as TextChannel).send(errorMsg(`${currentSong.title} is unavailable`)); + debug(`${currentSong.title} is unavailable`); return; } } @@ -213,8 +219,12 @@ export default class { } } + canGoForward(skip: number) { + return (this.queuePosition + skip - 1) < this.queue.length; + } + manualForward(skip: number): void { - if ((this.queuePosition + skip - 1) < this.queue.length) { + if (this.canGoForward(skip)) { this.queuePosition += skip; this.positionInSeconds = 0; this.stopTrackingPosition(); @@ -223,8 +233,12 @@ export default class { } } + canGoBack() { + return this.queuePosition - 1 >= 0; + } + async back(): Promise<void> { - if (this.queuePosition - 1 >= 0) { + if (this.canGoBack()) { this.queuePosition--; this.positionInSeconds = 0; this.stopTrackingPosition(); @@ -397,6 +411,9 @@ export default class { .on('error', error => { console.error(error); reject(error); + }) + .on('start', command => { + debug(`Spawned ffmpeg with ${command as string}`); }); youtubeStream.pipe(capacitor); diff --git a/src/types.ts b/src/types.ts index e6edd14..47108b9 100644 --- a/src/types.ts +++ b/src/types.ts @@ -8,9 +8,10 @@ export const TYPES = { ThirdParty: Symbol('ThirdParty'), Managers: { Player: Symbol('PlayerManager'), + UpdatingQueueEmbed: Symbol('UpdatingQueueEmbed'), }, Services: { + AddQueryToQueue: Symbol('AddQueryToQueue'), GetSongs: Symbol('GetSongs'), - NaturalLanguage: Symbol('NaturalLanguage'), }, }; diff --git a/src/utils/constants.ts b/src/utils/constants.ts new file mode 100644 index 0000000..70d9e2c --- /dev/null +++ b/src/utils/constants.ts @@ -0,0 +1,2 @@ +export const ONE_HOUR_IN_SECONDS = 60 * 60; +export const ONE_MINUTE_IN_SECONDS = 1 * 60; diff --git a/src/utils/error-msg.ts b/src/utils/error-msg.ts index 832de3c..0f4e0b2 100644 --- a/src/utils/error-msg.ts +++ b/src/utils/error-msg.ts @@ -5,7 +5,7 @@ export default (error?: string | Error): string => { if (typeof error === 'string') { str = `🚫 ${error}`; } else if (error instanceof Error) { - str = `🚫 ope: ${error.name}`; + str = `🚫 ope: ${error.message}`; } } diff --git a/src/utils/get-youtube-and-spotify-suggestions-for.ts b/src/utils/get-youtube-and-spotify-suggestions-for.ts new file mode 100644 index 0000000..10f9394 --- /dev/null +++ b/src/utils/get-youtube-and-spotify-suggestions-for.ts @@ -0,0 +1,70 @@ +import {ApplicationCommandOptionChoice} from 'discord.js'; +import SpotifyWebApi from 'spotify-web-api-node'; +import getYouTubeSuggestionsFor from './get-youtube-suggestions-for.js'; + +const filterDuplicates = <T extends {name: string}>(items: T[]) => { + const results: T[] = []; + + for (const item of items) { + if (!results.some(result => result.name === item.name)) { + results.push(item); + } + } + + return results; +}; + +const getYouTubeAndSpotifySuggestionsFor = async (query: string, spotify: SpotifyWebApi, limit = 10): Promise<ApplicationCommandOptionChoice[]> => { + const [youtubeSuggestions, spotifyResults] = await Promise.all([ + getYouTubeSuggestionsFor(query), + spotify.search(query, ['track', 'album'], {limit: 5}), + ]); + + const totalYouTubeResults = youtubeSuggestions.length; + + const spotifyAlbums = filterDuplicates(spotifyResults.body.albums?.items ?? []); + const spotifyTracks = filterDuplicates(spotifyResults.body.tracks?.items ?? []); + + const totalSpotifyResults = spotifyAlbums.length + spotifyTracks.length; + + // Number of results for each source should be roughly the same. + // If we don't have enough Spotify suggestions, prioritize YouTube results. + const maxSpotifySuggestions = Math.floor(limit / 2); + const numOfSpotifySuggestions = Math.min(maxSpotifySuggestions, totalSpotifyResults); + + const maxYouTubeSuggestions = limit - numOfSpotifySuggestions; + const numOfYouTubeSuggestions = Math.min(maxYouTubeSuggestions, totalYouTubeResults); + + const suggestions: ApplicationCommandOptionChoice[] = []; + + suggestions.push( + ...youtubeSuggestions + .slice(0, numOfYouTubeSuggestions) + .map(suggestion => ({ + name: `YouTube: ${suggestion}`, + value: suggestion, + }), + )); + + const maxSpotifyAlbums = Math.floor(numOfSpotifySuggestions / 2); + const numOfSpotifyAlbums = Math.min(maxSpotifyAlbums, spotifyResults.body.albums?.items.length ?? 0); + const maxSpotifyTracks = numOfSpotifySuggestions - numOfSpotifyAlbums; + + suggestions.push( + ...spotifyAlbums.slice(0, maxSpotifyAlbums).map(album => ({ + name: `Spotify: 💿 ${album.name}${album.artists.length > 0 ? ` - ${album.artists[0].name}` : ''}`, + value: `spotify:album:${album.id}`, + })), + ); + + suggestions.push( + ...spotifyTracks.slice(0, maxSpotifyTracks).map(track => ({ + name: `Spotify: 🎵 ${track.name}${track.artists.length > 0 ? ` - ${track.artists[0].name}` : ''}`, + value: `spotify:track:${track.id}`, + })), + ); + + return suggestions; +}; + +export default getYouTubeAndSpotifySuggestionsFor; diff --git a/src/utils/get-youtube-suggestions-for.ts b/src/utils/get-youtube-suggestions-for.ts new file mode 100644 index 0000000..11977e4 --- /dev/null +++ b/src/utils/get-youtube-suggestions-for.ts @@ -0,0 +1,15 @@ +import got from 'got'; + +const getYouTubeSuggestionsFor = async (query: string): Promise<string[]> => { + const [_, suggestions] = await got('https://suggestqueries.google.com/complete/search?client=firefox&ds=yt&q=', { + searchParams: { + client: 'firefox', + ds: 'yt', + q: query, + }, + }).json<[string, string[]]>(); + + return suggestions; +}; + +export default getYouTubeSuggestionsFor; diff --git a/src/utils/loading-message.ts b/src/utils/loading-message.ts deleted file mode 100644 index 53a2aed..0000000 --- a/src/utils/loading-message.ts +++ /dev/null @@ -1,81 +0,0 @@ -import {TextChannel, Message, MessageReaction} from 'discord.js'; -import delay from 'delay'; - -const INITAL_DELAY = 500; -const PERIOD = 500; - -export default class { - public isStopped = true; - private readonly channel: TextChannel; - private readonly text: string; - private msg!: Message; - - constructor(channel: TextChannel, text = 'cows! count \'em') { - this.channel = channel; - this.text = text; - } - - async start(): Promise<void> { - this.msg = await this.channel.send(this.text); - - const icons = ['🐮', '🐴', '🐄']; - - const reactions: MessageReaction[] = []; - - let i = 0; - let isRemoving = false; - - this.isStopped = false; - - (async () => { - await delay(INITAL_DELAY); - - while (!this.isStopped) { - if (reactions.length === icons.length) { - isRemoving = true; - } - - // eslint-disable-next-line no-await-in-loop - await delay(PERIOD); - - if (isRemoving) { - const reactionToRemove = reactions.shift(); - - if (reactionToRemove) { - // eslint-disable-next-line no-await-in-loop - await reactionToRemove.users.remove(this.msg.client.user!.id); - } else { - isRemoving = false; - } - } else { - if (!this.isStopped) { - // eslint-disable-next-line no-await-in-loop - reactions.push(await this.msg.react(icons[i % icons.length])); - } - - i++; - } - } - })(); - } - - async stop(str = 'u betcha'): Promise<Message> { - const wasAlreadyStopped = this.isStopped; - - this.isStopped = true; - - const editPromise = str ? this.msg.edit(str) : null; - const reactPromise = str && !wasAlreadyStopped ? (async () => { - await this.msg.fetch(); - await Promise.all(this.msg.reactions.cache.map(async react => { - if (react.me) { - await react.users.remove(this.msg.client.user!.id); - } - })); - })() : null; - - await Promise.all([editPromise, reactPromise]); - - return this.msg; - } -} diff --git a/src/utils/log-banner.ts b/src/utils/log-banner.ts index 0ad6466..9cde988 100644 --- a/src/utils/log-banner.ts +++ b/src/utils/log-banner.ts @@ -9,6 +9,7 @@ const logBanner = () => { paypalUser: 'codetheweb', githubSponsor: 'codetheweb', madeByPrefix: 'Made with 🎶 by ', + buildDate: process.env.BUILD_DATE ? new Date(process.env.BUILD_DATE) : undefined, }).join('\n')); console.log('\n'); }; diff --git a/src/utils/update-permissions-for-guild.ts b/src/utils/update-permissions-for-guild.ts new file mode 100644 index 0000000..ca7c427 --- /dev/null +++ b/src/utils/update-permissions-for-guild.ts @@ -0,0 +1,44 @@ +import {ApplicationCommandPermissionData, Guild} from 'discord.js'; +import {prisma} from './db.js'; + +const COMMANDS_TO_LIMIT_TO_GUILD_OWNER = ['config']; + +const updatePermissionsForGuild = async (guild: Guild) => { + const settings = await prisma.setting.findUnique({ + where: { + guildId: guild.id, + }, + }); + + if (!settings) { + throw new Error('could not find settings for guild'); + } + + const permissions: ApplicationCommandPermissionData[] = [ + { + id: guild.ownerId, + type: 'USER', + permission: true, + }, + { + id: guild.roles.everyone.id, + type: 'ROLE', + permission: false, + }, + ]; + const commands = await guild.commands.fetch(); + + await guild.commands.permissions.set({fullPermissions: commands.map(command => ({ + id: command.id, + permissions: COMMANDS_TO_LIMIT_TO_GUILD_OWNER.includes(command.name) ? permissions : [ + ...permissions, + ...(settings.roleId ? [{ + id: settings.roleId, + type: 'ROLE' as const, + permission: true, + }] : []), + ], + }))}); +}; + +export default updatePermissionsForGuild; |
