From dcb1351791e23165b23a8b549aabbb38294f55a5 Mon Sep 17 00:00:00 2001 From: Max Isom Date: Sun, 12 Dec 2021 20:22:21 -0500 Subject: Migrate play command to slash command --- src/bot.ts | 90 +++++++++++++++++++------------------------------ src/commands/help.ts | 66 ------------------------------------ src/commands/index.ts | 13 ++++--- src/commands/play.ts | 72 ++++++++++++++++++--------------------- src/inversify.config.ts | 2 -- src/services/player.ts | 2 +- 6 files changed, 76 insertions(+), 169 deletions(-) delete mode 100644 src/commands/help.ts (limited to 'src') diff --git a/src/bot.ts b/src/bot.ts index b49c1f6..09e9833 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -1,113 +1,91 @@ -import {Client, Message, Collection} from 'discord.js'; +import {Client, Collection, User} from 'discord.js'; import {inject, injectable} from 'inversify'; import {TYPES} from './types.js'; -import {Settings, Shortcut} from './models/index.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 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'; @injectable() export default class { private readonly client: Client; - private readonly naturalLanguage: NaturalLanguage; private readonly token: string; private readonly commands!: Collection; - constructor(@inject(TYPES.Client) client: Client, @inject(TYPES.Services.NaturalLanguage) naturalLanguage: NaturalLanguage, @inject(TYPES.Config) config: Config) { + constructor(@inject(TYPES.Client) client: Client, @inject(TYPES.Config) config: Config) { this.client = client; - this.naturalLanguage = naturalLanguage; this.token = config.DISCORD_TOKEN; this.commands = new Collection(); } - public async listen(): Promise { + public async listen(): Promise { // Load in commands container.getAll(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; + // TODO: remove ! + if (command.slashCommand?.name) { + this.commands.set(command.slashCommand.name, command); } + }); - const settings = await Settings.findByPk(msg.guild.id); - - if (!settings) { - // Got into a bad state, send owner welcome message - this.client.emit('guildCreate', msg.guild); + // Register event handlers + this.client.on('interactionCreate', async interaction => { + if (!interaction.isCommand()) { 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; - } + const command = this.commands.get(interaction.commandName); - if (!msg.content.startsWith(prefix) || msg.author.bot || msg.channel.id !== channel) { + if (!command) { return; } - let args = msg.content.slice(prefix.length).split(/ +/); - const command = args.shift()!.toLowerCase(); - - // Get possible shortcut - const shortcut = await Shortcut.findOne({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; - } - } else { + if (!interaction.guild) { + await interaction.reply(errorMsg('you can\'t use this bot in a DM')); return; } try { - if (handler.requiresVC && !isUserInVoice(msg.guild, msg.author)) { - await msg.channel.send(errorMsg('gotta be in a voice channel')); + if (command.requiresVC && !isUserInVoice(interaction.guild, interaction.member.user as User)) { + await interaction.reply({content: errorMsg('gotta be in a voice channel'), ephemeral: true}); return; } - await handler.execute(msg, args); + if (command.executeFromInteraction) { + await command.executeFromInteraction(interaction); + } } catch (error: unknown) { debug(error); - await msg.channel.send(errorMsg((error as Error).message.toLowerCase())); + await interaction.reply({content: errorMsg(error as Error), ephemeral: true}); } }); - this.client.on('ready', async () => { + this.client.once('ready', async () => { debug(generateDependencyReport()); - console.log(`Ready! Invite the bot with https://discordapp.com/oauth2/authorize?client_id=${this.client.user?.id ?? ''}&scope=bot&permissions=36752448`); + console.log(`Ready! Invite the bot with https://discordapp.com/oauth2/authorize?client_id=${this.client.user?.id ?? ''}&scope=bot&permissions=2184236096`); }); this.client.on('error', console.error); this.client.on('debug', debug); - // Register event handlers this.client.on('guildCreate', handleGuildCreate); this.client.on('voiceStateUpdate', handleVoiceStateUpdate); - return this.client.login(this.token); + // Update commands + await this.client.login(this.token); + + const rest = new REST({version: '9'}).setToken(this.token); + + await rest.put( + Routes.applicationGuildCommands(this.client.user!.id, this.client.guilds.cache.first()!.id), + // TODO: remove + {body: this.commands.map(command => command.slashCommand ? command.slashCommand.toJSON() : null)}, + ); } } diff --git a/src/commands/help.ts b/src/commands/help.ts deleted file mode 100644 index 7058efd..0000000 --- a/src/commands/help.ts +++ /dev/null @@ -1,66 +0,0 @@ -import {Message, Util} from 'discord.js'; -import {injectable} from 'inversify'; -import Command from '.'; -import {TYPES} from '../types.js'; -import {Settings} from '../models/index.js'; -import container from '../inversify.config.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 { - if (this.commands.length === 0) { - // Lazy load to avoid circular dependencies - this.commands = container.getAll(TYPES.Command); - } - - const settings = await Settings.findOne({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..981c1fb 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -1,9 +1,12 @@ -import {Message} from 'discord.js'; +import {SlashCommandBuilder} from '@discordjs/builders'; +import {CommandInteraction} from 'discord.js'; export default interface Command { - name: string; - aliases: string[]; - examples: string[][]; + // TODO: remove + name?: string; + aliases?: string[]; + examples?: string[][]; + slashCommand?: Partial & Pick; requiresVC?: boolean; - execute: (msg: Message, args: string[]) => Promise; + executeFromInteraction?: (interaction: CommandInteraction) => Promise; } diff --git a/src/commands/play.ts b/src/commands/play.ts index 856edec..9a79819 100644 --- a/src/commands/play.ts +++ b/src/commands/play.ts @@ -1,31 +1,27 @@ -import {TextChannel, Message} from 'discord.js'; +import {CommandInteraction, GuildMember} from 'discord.js'; import {URL} from 'url'; import {Except} from 'type-fest'; -import {TYPES} from '../types.js'; +import {SlashCommandBuilder} from '@discordjs/builders'; import {inject, injectable} from 'inversify'; +import Command from '.'; +import {TYPES} from '../types.js'; 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 Command from '.'; import GetSongs from '../services/get-songs.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'], - ]; + public readonly slashCommand = new SlashCommandBuilder() + .setName('play') + .setDescription('Play a song') + .addStringOption(option => option + .setName('query') + .setDescription('YouTube URL, Spotify URL, or search query')) + .addBooleanOption(option => option + .setName('immediate') + .setDescription('adds track to the front of the queue')); public requiresVC = true; @@ -38,43 +34,43 @@ export default class implements Command { } // eslint-disable-next-line complexity - public async execute(msg: Message, args: string[]): Promise { - const [targetVoiceChannel] = getMemberVoiceChannel(msg.member!) ?? getMostPopularVoiceChannel(msg.guild!); - - const res = new LoadingMessage(msg.channel as TextChannel); - await res.start(); - - const player = this.playerManager.get(msg.guild!.id); + public async executeFromInteraction(interaction: CommandInteraction): Promise { + const [targetVoiceChannel] = getMemberVoiceChannel(interaction.member as GuildMember) ?? getMostPopularVoiceChannel(interaction.guild!); + const player = this.playerManager.get(interaction.guild!.id); const wasPlayingSong = player.getCurrent() !== null; - if (args.length === 0) { + const query = interaction.options.getString('query'); + + if (!query) { if (player.status === STATUS.PLAYING) { - await res.stop(errorMsg('already playing, give me a song name')); + await interaction.reply({content: errorMsg('already playing, give me a song name'), ephemeral: true}); return; } // Must be resuming play if (!wasPlayingSong) { - await res.stop(errorMsg('nothing to play')); + await interaction.reply({content: errorMsg('nothing to play'), ephemeral: true}); return; } await player.connect(targetVoiceChannel); await player.play(); - await res.stop('the stop-and-go light is now green'); + await interaction.reply('the stop-and-go light is now green'); return; } - const addToFrontOfQueue = args[args.length - 1] === 'i' || args[args.length - 1] === 'immediate'; + const addToFrontOfQueue = interaction.options.getBoolean('immediate'); const newSongs: Array> = []; let extraMsg = ''; + await interaction.deferReply(); + // Test if it's a complete URL try { - const url = new URL(args[0]); + const url = new URL(query); const YOUTUBE_HOSTS = [ 'www.youtube.com', @@ -96,12 +92,12 @@ export default class implements Command { if (song) { newSongs.push(song); } else { - await res.stop(errorMsg('that doesn\'t exist')); + await interaction.editReply(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]); + const [convertedSongs, nSongsNotFound, totalSongs] = await this.getSongs.spotifySource(query); if (totalSongs > 50) { extraMsg = 'a random sample of 50 songs was taken'; @@ -123,25 +119,23 @@ export default class implements Command { } } 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')); + await interaction.editReply(errorMsg('that doesn\'t exist')); return; } } if (newSongs.length === 0) { - await res.stop(errorMsg('no songs found')); + await interaction.editReply(errorMsg('no songs found')); return; } newSongs.forEach(song => { - player.add({...song, addedInChannelId: msg.channel.id}, {immediate: addToFrontOfQueue}); + player.add({...song, addedInChannelId: interaction.channel?.id}, {immediate: addToFrontOfQueue ?? false}); }); const firstSong = newSongs[0]; @@ -173,9 +167,9 @@ export default class implements Command { } if (newSongs.length === 1) { - await res.stop(`u betcha, **${firstSong.title}** added to the${addToFrontOfQueue ? ' front of the' : ''} queue${extraMsg}`); + await interaction.editReply(`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}`); + await interaction.editReply(`u betcha, **${firstSong.title}** and ${newSongs.length - 1} other songs were added to the queue${extraMsg}`); } } } diff --git a/src/inversify.config.ts b/src/inversify.config.ts index 6ec1ba2..77ed99b 100644 --- a/src/inversify.config.ts +++ b/src/inversify.config.ts @@ -18,7 +18,6 @@ import Clear from './commands/clear.js'; import Config from './commands/config.js'; import Disconnect from './commands/disconnect.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'; @@ -59,7 +58,6 @@ container.bind(TYPES.Services.NaturalLanguage).to(NaturalLangua Config, Disconnect, ForwardSeek, - Help, Pause, Play, QueueCommand, diff --git a/src/services/player.ts b/src/services/player.ts index 4a226c5..5caace2 100644 --- a/src/services/player.ts +++ b/src/services/player.ts @@ -21,7 +21,7 @@ export interface QueuedSong { length: number; playlist: QueuedPlaylist | null; isLive: boolean; - addedInChannelId: Snowflake; + addedInChannelId?: Snowflake; } export enum STATUS { -- cgit v1.2.3 From d2ab10a13ab22d21f3e52106f355fc8272e11651 Mon Sep 17 00:00:00 2001 From: Max Isom Date: Sun, 12 Dec 2021 20:31:55 -0500 Subject: Edit interaction reply if necessary for error messages --- src/bot.ts | 7 ++++++- src/commands/play.ts | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/bot.ts b/src/bot.ts index 09e9833..01616ff 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -62,7 +62,12 @@ export default class { } } catch (error: unknown) { debug(error); - await interaction.reply({content: errorMsg(error as Error), ephemeral: true}); + + if (interaction.replied || interaction.deferred) { + await interaction.editReply(errorMsg('something went wrong')); + } else { + await interaction.reply({content: errorMsg(error as Error), ephemeral: true}); + } } }); diff --git a/src/commands/play.ts b/src/commands/play.ts index 9a79819..8e1616b 100644 --- a/src/commands/play.ts +++ b/src/commands/play.ts @@ -15,7 +15,7 @@ import GetSongs from '../services/get-songs.js'; export default class implements Command { public readonly slashCommand = new SlashCommandBuilder() .setName('play') - .setDescription('Play a song') + .setDescription('Play a song or resume playback') .addStringOption(option => option .setName('query') .setDescription('YouTube URL, Spotify URL, or search query')) -- cgit v1.2.3 From c5e4c4b5cf1c08d304eb6e41aac1615e7007ee6e Mon Sep 17 00:00:00 2001 From: Max Isom Date: Mon, 13 Dec 2021 20:45:01 -0500 Subject: Migrate clear command --- src/commands/clear.ts | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/commands/clear.ts b/src/commands/clear.ts index 9906dab..5c1a1eb 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 { - this.playerManager.get(msg.guild!.id).clear(); + public async executeFromInteraction(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'); } } -- cgit v1.2.3 From c33526b8b7825cbf01a9ca1c84ab3fd30a94ef0f Mon Sep 17 00:00:00 2001 From: Max Isom Date: Mon, 13 Dec 2021 20:51:08 -0500 Subject: Migrate disconnect command --- src/commands/config.ts | 81 ---------------------------------------------- src/commands/disconnect.ts | 23 +++++++------ src/commands/index.ts | 2 +- src/inversify.config.ts | 2 -- 4 files changed, 14 insertions(+), 94 deletions(-) delete mode 100644 src/commands/config.ts (limited to 'src') diff --git a/src/commands/config.ts b/src/commands/config.ts deleted file mode 100644 index 8f3e0aa..0000000 --- a/src/commands/config.ts +++ /dev/null @@ -1,81 +0,0 @@ -import {TextChannel, Message, GuildChannel, ThreadChannel} from 'discord.js'; -import {injectable} from 'inversify'; -import {Settings} from '../models/index.js'; -import errorMsg from '../utils/error-msg.js'; -import Command from '.'; - -@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'], - ]; - - public async execute(msg: Message, args: string []): Promise { - if (args.length === 0) { - // Show current settings - const settings = await Settings.findByPk(msg.guild!.id); - - if (settings) { - 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()}`; - - await msg.channel.send(response); - } - - return; - } - - const setting = args[0]; - - if (args.length !== 2) { - await msg.channel.send(errorMsg('incorrect number of arguments')); - return; - } - - if (msg.author.id !== msg.guild!.ownerId) { - await msg.channel.send(errorMsg('not authorized')); - return; - } - - switch (setting) { - case 'prefix': { - const newPrefix = args[1]; - - await Settings.update({prefix: newPrefix}, {where: {guildId: msg.guild!.id}}); - - await msg.channel.send(`👍 prefix updated to \`${newPrefix}\``); - break; - } - - case 'channel': { - let channel: GuildChannel | ThreadChannel | undefined; - - 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]); - } - - if (channel && channel.type === 'GUILD_TEXT') { - await Settings.update({channel: channel.id}, {where: {guildId: msg.guild!.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')); - } - - break; - } - - default: - await msg.channel.send(errorMsg('I\'ve never met this setting in my life')); - } - } -} diff --git a/src/commands/disconnect.ts b/src/commands/disconnect.ts index 89b0b85..d196985 100644 --- a/src/commands/disconnect.ts +++ b/src/commands/disconnect.ts @@ -1,4 +1,5 @@ -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'; @@ -7,11 +8,9 @@ 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 +20,20 @@ export default class implements Command { this.playerManager = playerManager; } - public async execute(msg: Message, _: string []): Promise { - const player = this.playerManager.get(msg.guild!.id); + public async executeFromInteraction(interaction: CommandInteraction) { + const player = this.playerManager.get(interaction.guild!.id); if (!player.voiceConnection) { - await msg.channel.send(errorMsg('not connected')); + await interaction.reply({ + content: errorMsg('not connected'), + ephemeral: true, + }); + return; } player.disconnect(); - await msg.channel.send('u betcha'); + await interaction.reply('u betcha'); } } diff --git a/src/commands/index.ts b/src/commands/index.ts index 981c1fb..91b76c5 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -6,7 +6,7 @@ export default interface Command { name?: string; aliases?: string[]; examples?: string[][]; - slashCommand?: Partial & Pick; + readonly slashCommand?: Partial & Pick; requiresVC?: boolean; executeFromInteraction?: (interaction: CommandInteraction) => Promise; } diff --git a/src/inversify.config.ts b/src/inversify.config.ts index 77ed99b..6272dd3 100644 --- a/src/inversify.config.ts +++ b/src/inversify.config.ts @@ -15,7 +15,6 @@ 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 ForwardSeek from './commands/fseek.js'; import Pause from './commands/pause.js'; @@ -55,7 +54,6 @@ container.bind(TYPES.Services.NaturalLanguage).to(NaturalLangua // Commands [ Clear, - Config, Disconnect, ForwardSeek, Pause, -- cgit v1.2.3 From cbc9aafe780805d6aa3fb456fdb1620dc66679d3 Mon Sep 17 00:00:00 2001 From: Max Isom Date: Mon, 13 Dec 2021 21:04:17 -0500 Subject: Migrate fseek command --- src/commands/fseek.ts | 63 +++++++++++++++++++++++++++++++++------------------ 1 file changed, 41 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/commands/fseek.ts b/src/commands/fseek.ts index 16d1430..5a46a17 100644 --- a/src/commands/fseek.ts +++ b/src/commands/fseek.ts @@ -1,18 +1,21 @@ -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 +25,54 @@ export default class implements Command { this.playerManager = playerManager; } - public async execute(msg: Message, args: string []): Promise { - const player = this.playerManager.get(msg.guild!.id); + public async executeFromInteraction(interaction: CommandInteraction): Promise { + const player = this.playerManager.get(interaction.guild!.id); const currentSong = player.getCurrent(); if (!currentSong) { - await msg.channel.send(errorMsg('nothing is playing')); + await interaction.reply({ + content: errorMsg('nothing is playing'), + ephemeral: true, + }); + return; } if (currentSong.isLive) { - await msg.channel.send(errorMsg('can\'t seek in a livestream')); + await interaction.reply({ + content: errorMsg('can\'t seek in a livestream'), + ephemeral: true, + }); + return; } - const seekTime = parseInt(args[0], 10); + const seekTime = interaction.options.getNumber('seconds'); + + if (!seekTime) { + await interaction.reply({ + content: errorMsg('missing number of seconds to seek'), + ephemeral: true, + }); - if (seekTime + player.getPosition() > currentSong.length) { - await msg.channel.send(errorMsg('can\'t seek past the end of the song')); return; } - const loading = new LoadingMessage(msg.channel as TextChannel); + if (seekTime + player.getPosition() > currentSong.length) { + await interaction.reply({ + content: errorMsg('can\'t seek past the end of the song'), + ephemeral: true, + }); - await loading.start(); + return; + } - 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())}`); } } -- cgit v1.2.3 From e965c023582b7f0699c37015ce79049db2be55f4 Mon Sep 17 00:00:00 2001 From: Max Isom Date: Wed, 15 Dec 2021 13:46:03 -0500 Subject: Migrate pause command --- src/commands/pause.ts | 22 ++++++++++++---------- src/commands/play.ts | 2 +- 2 files changed, 13 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/commands/pause.ts b/src/commands/pause.ts index 1dee95d..c3e8c24 100644 --- a/src/commands/pause.ts +++ b/src/commands/pause.ts @@ -1,4 +1,5 @@ -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'; @@ -8,11 +9,9 @@ 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 +21,18 @@ export default class implements Command { this.playerManager = playerManager; } - public async execute(msg: Message, _: string []): Promise { - const player = this.playerManager.get(msg.guild!.id); + public async executeFromInteraction(interaction: CommandInteraction) { + const player = this.playerManager.get(interaction.guild!.id); if (player.status !== STATUS.PLAYING) { - await msg.channel.send(errorMsg('not currently playing')); + await interaction.reply({ + content: errorMsg('not currently playing'), + ephemeral: true, + }); return; } 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 8e1616b..6e76e37 100644 --- a/src/commands/play.ts +++ b/src/commands/play.ts @@ -15,7 +15,7 @@ import GetSongs from '../services/get-songs.js'; export default class implements Command { public readonly slashCommand = new SlashCommandBuilder() .setName('play') - .setDescription('Play a song or resume playback') + .setDescription('play a song or resume playback') .addStringOption(option => option .setName('query') .setDescription('YouTube URL, Spotify URL, or search query')) -- cgit v1.2.3 From 0b20cb3982942196303dea3cbbb98644dde441a3 Mon Sep 17 00:00:00 2001 From: Max Isom Date: Wed, 15 Dec 2021 22:01:54 -0500 Subject: Start migrating queue command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Also: make it persistent & updating, add buttons ✨ --- src/bot.ts | 42 +++++++- src/commands/index.ts | 8 +- src/commands/play.ts | 1 + src/commands/queue.ts | 106 ++++++++++--------- src/inversify.config.ts | 2 + src/managers/updating-queue-embed.ts | 33 ++++++ src/services/player.ts | 35 ++++++- src/services/updating-queue-embed.ts | 196 +++++++++++++++++++++++++++++++++++ src/types.ts | 1 + 9 files changed, 358 insertions(+), 66 deletions(-) create mode 100644 src/managers/updating-queue-embed.ts create mode 100644 src/services/updating-queue-embed.ts (limited to 'src') diff --git a/src/bot.ts b/src/bot.ts index f0fb442..6152d2f 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -18,12 +18,14 @@ import {Routes} from 'discord-api-types/v9'; export default class { private readonly client: Client; private readonly token: string; - private readonly commands!: Collection; + private readonly commandsByName!: Collection; + private readonly commandsByButtonId!: Collection; constructor(@inject(TYPES.Client) client: Client, @inject(TYPES.Config) config: Config) { this.client = client; this.token = config.DISCORD_TOKEN; - this.commands = new Collection(); + this.commandsByName = new Collection(); + this.commandsByButtonId = new Collection(); } public async listen(): Promise { @@ -31,7 +33,11 @@ export default class { container.getAll(TYPES.Command).forEach(command => { // TODO: remove ! if (command.slashCommand?.name) { - this.commands.set(command.slashCommand.name, command); + this.commandsByName.set(command.slashCommand.name, command); + } + + if (command.handledButtonIds) { + command.handledButtonIds.forEach(id => this.commandsByButtonId.set(id, command)); } }); @@ -41,7 +47,7 @@ export default class { return; } - const command = this.commands.get(interaction.commandName); + const command = this.commandsByName.get(interaction.commandName); if (!command) { return; @@ -72,6 +78,32 @@ export default class { } }); + this.client.on('interactionCreate', async interaction => { + if (!interaction.isButton()) { + return; + } + + const command = this.commandsByButtonId.get(interaction.customId); + + if (!command) { + return; + } + + try { + if (command.handleButtonInteraction) { + await command.handleButtonInteraction(interaction); + } + } catch (error: unknown) { + debug(error); + + if (interaction.replied || interaction.deferred) { + await interaction.editReply(errorMsg('something went wrong')); + } else { + await interaction.reply({content: errorMsg(error as Error), ephemeral: true}); + } + } + }); + const spinner = ora('📡 connecting to Discord...').start(); this.client.once('ready', () => { @@ -94,7 +126,7 @@ export default class { await rest.put( Routes.applicationGuildCommands(this.client.user!.id, this.client.guilds.cache.first()!.id), // TODO: remove - {body: this.commands.map(command => command.slashCommand ? command.slashCommand.toJSON() : null)}, + {body: this.commandsByName.map(command => command.slashCommand ? command.slashCommand.toJSON() : null)}, ); } } diff --git a/src/commands/index.ts b/src/commands/index.ts index 91b76c5..1cd927b 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -1,12 +1,14 @@ import {SlashCommandBuilder} from '@discordjs/builders'; -import {CommandInteraction} from 'discord.js'; +import {ButtonInteraction, CommandInteraction} from 'discord.js'; -export default interface Command { +export default class Command { // TODO: remove name?: string; aliases?: string[]; examples?: string[][]; readonly slashCommand?: Partial & Pick; - requiresVC?: boolean; + readonly handledButtonIds?: readonly string[]; + readonly requiresVC?: boolean; executeFromInteraction?: (interaction: CommandInteraction) => Promise; + handleButtonInteraction?: (interaction: ButtonInteraction) => Promise; } diff --git a/src/commands/play.ts b/src/commands/play.ts index 6e76e37..7dc5e41 100644 --- a/src/commands/play.ts +++ b/src/commands/play.ts @@ -15,6 +15,7 @@ import GetSongs from '../services/get-songs.js'; export default class implements Command { 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') diff --git a/src/commands/queue.ts b/src/commands/queue.ts index 1c0735c..479bc33 100644 --- a/src/commands/queue.ts +++ b/src/commands/queue.ts @@ -1,82 +1,80 @@ -import {Message, MessageEmbed} from 'discord.js'; -import getYouTubeID from 'get-youtube-id'; +import {ButtonInteraction, 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'; -import {STATUS} from '../services/player.js'; +import UpdatingQueueEmbedManager from '../managers/updating-queue-embed.js'; +import {BUTTON_IDS} from '../services/updating-queue-embed.js'; import Command from '.'; -import getProgressBar from '../utils/get-progress-bar.js'; -import errorMsg from '../utils/error-msg.js'; -import {prettyTime} from '../utils/time.js'; - -const PAGE_SIZE = 10; @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'); + + public readonly handledButtonIds = Object.values(BUTTON_IDS); private readonly playerManager: PlayerManager; + private readonly updatingQueueEmbedManager: UpdatingQueueEmbedManager; - constructor(@inject(TYPES.Managers.Player) playerManager: PlayerManager) { + constructor(@inject(TYPES.Managers.Player) playerManager: PlayerManager, @inject(TYPES.Managers.UpdatingQueueEmbed) updatingQueueEmbedManager: UpdatingQueueEmbedManager) { this.playerManager = playerManager; + this.updatingQueueEmbedManager = updatingQueueEmbedManager; } - public async execute(msg: Message, args: string []): Promise { - const player = this.playerManager.get(msg.guild!.id); - - const currentlyPlaying = player.getCurrent(); - - if (currentlyPlaying) { - const queueSize = player.queueSize(); - const queuePage = args[0] ? parseInt(args[0], 10) : 1; - - const maxQueuePage = Math.ceil((queueSize + 1) / PAGE_SIZE); + public async executeFromInteraction(interaction: CommandInteraction) { + const embed = this.updatingQueueEmbedManager.get(interaction.guild!.id); - if (queuePage > maxQueuePage) { - await msg.channel.send(errorMsg('the queue isn\'t that big')); - return; - } + await embed.createFromInteraction(interaction); + } - const embed = new MessageEmbed(); + public async handleButtonInteraction(interaction: ButtonInteraction) { + const player = this.playerManager.get(interaction.guild!.id); + const embed = this.updatingQueueEmbedManager.get(interaction.guild!.id); - embed.setTitle(currentlyPlaying.title); - embed.setURL(`https://www.youtube.com/watch?v=${currentlyPlaying.url.length === 11 ? currentlyPlaying.url : getYouTubeID(currentlyPlaying.url) ?? ''}`); + const buttonId = interaction.customId as keyof typeof this.handledButtonIds; - let description = player.status === STATUS.PLAYING ? 'âšī¸' : 'â–ļī¸'; - description += ' '; - description += getProgressBar(20, player.getPosition() / currentlyPlaying.length); - description += ' '; - description += `\`[${prettyTime(player.getPosition())}/${currentlyPlaying.isLive ? 'live' : prettyTime(currentlyPlaying.length)}]\``; - description += ' 🔉'; - description += player.isQueueEmpty() ? '' : '\n\n**Next up:**'; + // Not entirely sure why this is necessary. + // We don't wait for the Promise to resolve here to avoid blocking the + // main logic. However, we need to wait for the Promise to be resolved before + // throwing as otherwise a race condition pops up when bot.ts tries updating + // the interaction. + const deferedUpdatePromise = interaction.deferUpdate(); - embed.setDescription(description); + try { + switch (buttonId) { + case BUTTON_IDS.TRACK_BACK: + await player.back(); + break; - let footer = `Source: ${currentlyPlaying.artist}`; + case BUTTON_IDS.TRACK_FORWARD: + await player.forward(1); + break; - if (currentlyPlaying.playlist) { - footer += ` (${currentlyPlaying.playlist.title})`; - } + case BUTTON_IDS.PAUSE: + player.pause(); + break; - embed.setFooter(footer); + case BUTTON_IDS.PLAY: + await player.play(); + break; - const queuePageBegin = (queuePage - 1) * PAGE_SIZE; - const queuePageEnd = queuePageBegin + PAGE_SIZE; + case BUTTON_IDS.PAGE_BACK: + await embed.pageBack(); + break; - player.getQueue().slice(queuePageBegin, queuePageEnd).forEach((song, i) => { - embed.addField(`${(i + 1 + queuePageBegin).toString()}/${queueSize.toString()}`, song.title, false); - }); + case BUTTON_IDS.PAGE_FORWARD: + await embed.pageForward(); + break; - embed.addField('Page', `${queuePage} out of ${maxQueuePage}`, false); + default: + throw new Error('unknown customId'); + } + } catch (error: unknown) { + await deferedUpdatePromise; - await msg.channel.send({embeds: [embed]}); - } else { - await msg.channel.send('queue empty'); + throw error; } } } diff --git a/src/inversify.config.ts b/src/inversify.config.ts index 6272dd3..623e631 100644 --- a/src/inversify.config.ts +++ b/src/inversify.config.ts @@ -7,6 +7,7 @@ import ConfigProvider from './services/config.js'; // Managers import PlayerManager from './managers/player.js'; +import UpdatingQueueEmbed from './managers/updating-queue-embed.js'; // Helpers import GetSongs from './services/get-songs.js'; @@ -46,6 +47,7 @@ container.bind(TYPES.Client).toConstantValue(new Client({intents})); // Managers container.bind(TYPES.Managers.Player).to(PlayerManager).inSingletonScope(); +container.bind(TYPES.Managers.UpdatingQueueEmbed).to(UpdatingQueueEmbed).inSingletonScope(); // Helpers container.bind(TYPES.Services.GetSongs).to(GetSongs).inSingletonScope(); diff --git a/src/managers/updating-queue-embed.ts b/src/managers/updating-queue-embed.ts new file mode 100644 index 0000000..37732de --- /dev/null +++ b/src/managers/updating-queue-embed.ts @@ -0,0 +1,33 @@ +import {inject, injectable} from 'inversify'; +import {TYPES} from '../types.js'; +import PlayerManager from '../managers/player.js'; +import UpdatingQueueEmbed from '../services/updating-queue-embed.js'; + +@injectable() +export default class { + private readonly embedsByGuild: Map; + private readonly playerManager: PlayerManager; + + constructor(@inject(TYPES.Managers.Player) playerManager: PlayerManager) { + this.embedsByGuild = new Map(); + this.playerManager = playerManager; + } + + get(guildId: string): UpdatingQueueEmbed { + let embed = this.embedsByGuild.get(guildId); + + if (!embed) { + const player = this.playerManager.get(guildId); + + if (!player) { + throw new Error('Player does not exist for guild.'); + } + + embed = new UpdatingQueueEmbed(player); + + this.embedsByGuild.set(guildId, embed); + } + + return embed; + } +} diff --git a/src/services/player.ts b/src/services/player.ts index 5caace2..26e1e36 100644 --- a/src/services/player.ts +++ b/src/services/player.ts @@ -1,5 +1,7 @@ import {VoiceChannel, Snowflake, Client, TextChannel} from 'discord.js'; import {Readable} from 'stream'; +import EventEmitter from 'events'; +import TypedEmitter from 'typed-emitter'; import hasha from 'hasha'; import ytdl from 'ytdl-core'; import {WriteStream} from 'fs-capacitor'; @@ -29,8 +31,11 @@ export enum STATUS { PAUSED, } -export default class { - public status = STATUS.PAUSED; +export interface PlayerEvents { + statusChange: (oldStatus: STATUS, newStatus: STATUS) => void; +} + +export default class extends (EventEmitter as new () => TypedEmitter) { public voiceConnection: VoiceConnection | null = null; private queue: QueuedSong[] = []; private queuePosition = 0; @@ -40,11 +45,14 @@ export default class { private lastSongURL = ''; private positionInSeconds = 0; + private internalStatus = STATUS.PAUSED; private readonly discordClient: Client; private readonly fileCache: FileCacheProvider; constructor(client: Client, fileCache: FileCacheProvider) { + // eslint-disable-next-line constructor-super + super(); this.discordClient = client; this.fileCache = fileCache; } @@ -203,8 +211,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(); @@ -213,8 +225,12 @@ export default class { } } + canGoBack() { + return this.queuePosition - 1 >= 0; + } + async back(): Promise { - if (this.queuePosition - 1 >= 0) { + if (this.canGoBack()) { this.queuePosition--; this.positionInSeconds = 0; this.stopTrackingPosition(); @@ -290,6 +306,17 @@ export default class { return this.queueSize() === 0; } + get status() { + return this.internalStatus; + } + + set status(newStatus: STATUS) { + const previousStatus = this.internalStatus; + this.internalStatus = newStatus; + + this.emit('statusChange', previousStatus, newStatus); + } + private getHashForCache(url: string): string { return hasha(url); } diff --git a/src/services/updating-queue-embed.ts b/src/services/updating-queue-embed.ts new file mode 100644 index 0000000..31d58ff --- /dev/null +++ b/src/services/updating-queue-embed.ts @@ -0,0 +1,196 @@ +import {CommandInteraction, MessageActionRow, MessageButton, MessageEmbed} from 'discord.js'; +import getYouTubeID from 'get-youtube-id'; +import getProgressBar from '../utils/get-progress-bar.js'; +import {prettyTime} from '../utils/time.js'; +import Player, {STATUS} from './player.js'; + +const PAGE_SIZE = 10; + +const REFRESH_INTERVAL_MS = 5 * 1000; + +export enum BUTTON_IDS { + PAGE_BACK = 'page-back', + PAGE_FORWARD = 'page-forward', + TRACK_BACK = 'track-back', + TRACK_FORWARD = 'track-forward', + PAUSE = 'pause', + PLAY = 'play', +} + +export default class { + private readonly player: Player; + private interaction?: CommandInteraction; + + // 1-indexed + private currentPage = 1; + + private refreshTimeout?: NodeJS.Timeout; + + constructor(player: Player) { + this.player = player; + + this.addEventHandlers(); + } + + /** + * Creates & replies with a new embed from the given interaction. + * Starts updating the embed at a regular interval. + * Can be called multiple times within the lifecycle of this class. + * Calling this method will make it forgot the previous interaction & reply. + * @param interaction + */ + async createFromInteraction(interaction: CommandInteraction) { + this.interaction = interaction; + this.currentPage = 1; + + await interaction.reply({ + embeds: [this.buildEmbed()], + components: this.buildButtons(this.player), + }); + + if (!this.refreshTimeout) { + this.refreshTimeout = setInterval(async () => this.update(), REFRESH_INTERVAL_MS); + } + } + + async update(shouldResetPage = false) { + if (shouldResetPage) { + this.currentPage = 1; + } + + await this.interaction?.editReply({ + embeds: [this.buildEmbed()], + components: this.buildButtons(this.player), + }); + } + + async pageBack() { + if (this.currentPage > 1) { + this.currentPage--; + } + + await this.update(); + } + + async pageForward() { + if (this.currentPage < this.getMaxPage()) { + this.currentPage++; + } + + await this.update(); + } + + private buildButtons(player: Player): MessageActionRow[] { + const queuePageControls = new MessageActionRow() + .addComponents( + new MessageButton() + .setCustomId(BUTTON_IDS.PAGE_BACK) + .setStyle('SECONDARY') + .setDisabled(this.currentPage === 1) + .setEmoji('âŦ…ī¸'), + + new MessageButton() + .setCustomId(BUTTON_IDS.PAGE_FORWARD) + .setStyle('SECONDARY') + .setDisabled(this.currentPage >= this.getMaxPage()) + .setEmoji('âžĄī¸'), + ); + + const components = []; + + components.push( + new MessageButton() + .setCustomId(BUTTON_IDS.TRACK_BACK) + .setStyle('PRIMARY') + .setDisabled(!player.canGoBack()) + .setEmoji('⏎')); + + if (player.status === STATUS.PLAYING) { + components.push( + new MessageButton() + .setCustomId(BUTTON_IDS.PAUSE) + .setStyle('PRIMARY') + .setDisabled(!player.getCurrent()) + .setEmoji('â¸ī¸')); + } else { + components.push( + new MessageButton() + .setCustomId(BUTTON_IDS.PLAY) + .setStyle('PRIMARY') + .setDisabled(!player.getCurrent()) + .setEmoji('â–ļī¸')); + } + + components.push( + new MessageButton() + .setCustomId(BUTTON_IDS.TRACK_FORWARD) + .setStyle('PRIMARY') + .setDisabled(!player.canGoForward(1)) + .setEmoji('⏭'), + ); + + const playerControls = new MessageActionRow().addComponents(components); + + return [queuePageControls, playerControls]; + } + + /** + * Generates an embed for the current page of the queue. + * @returns MessageEmbed + */ + private buildEmbed() { + const currentlyPlaying = this.player.getCurrent(); + + if (!currentlyPlaying) { + throw new Error('queue is empty'); + } + + const queueSize = this.player.queueSize(); + + if (this.currentPage > this.getMaxPage()) { + throw new Error('the queue isn\'t that big'); + } + + const embed = new MessageEmbed(); + + embed.setTitle(currentlyPlaying.title); + embed.setURL(`https://www.youtube.com/watch?v=${currentlyPlaying.url.length === 11 ? currentlyPlaying.url : getYouTubeID(currentlyPlaying.url) ?? ''}`); + + let description = getProgressBar(20, this.player.getPosition() / currentlyPlaying.length); + description += ' '; + description += `\`[${prettyTime(this.player.getPosition())}/${currentlyPlaying.isLive ? 'live' : prettyTime(currentlyPlaying.length)}]\``; + description += ' 🔉'; + description += this.player.isQueueEmpty() ? '' : '\n\n**Next up:**'; + + embed.setDescription(description); + + let footer = `Source: ${currentlyPlaying.artist}`; + + if (currentlyPlaying.playlist) { + footer += ` (${currentlyPlaying.playlist.title})`; + } + + embed.setFooter(footer); + + const queuePageBegin = (this.currentPage - 1) * PAGE_SIZE; + const queuePageEnd = queuePageBegin + PAGE_SIZE; + + this.player.getQueue().slice(queuePageBegin, queuePageEnd).forEach((song, i) => { + embed.addField(`${(i + 1 + queuePageBegin).toString()}/${queueSize.toString()}`, song.title, false); + }); + + embed.addField('Page', `${this.currentPage} out of ${this.getMaxPage()}`, false); + + return embed; + } + + private getMaxPage() { + return Math.ceil((this.player.queueSize() + 1) / PAGE_SIZE); + } + + private addEventHandlers() { + this.player.on('statusChange', async () => this.update(true)); + + // TODO: also update on other player events + } +} diff --git a/src/types.ts b/src/types.ts index e6edd14..19c734d 100644 --- a/src/types.ts +++ b/src/types.ts @@ -8,6 +8,7 @@ export const TYPES = { ThirdParty: Symbol('ThirdParty'), Managers: { Player: Symbol('PlayerManager'), + UpdatingQueueEmbed: Symbol('UpdatingQueueEmbed'), }, Services: { GetSongs: Symbol('GetSongs'), -- cgit v1.2.3 From 812d01edbd929c4d6140ed54a49cd493e9ab2b06 Mon Sep 17 00:00:00 2001 From: Max Isom Date: Thu, 16 Dec 2021 15:18:50 -0500 Subject: Handle if queue reply is deleted --- src/bot.ts | 13 +++++---- src/services/updating-queue-embed.ts | 53 +++++++++++++++++++++++++++++------- 2 files changed, 51 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/bot.ts b/src/bot.ts index 6152d2f..b9c31a7 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -70,11 +70,14 @@ export default class { } catch (error: unknown) { debug(error); - if (interaction.replied || interaction.deferred) { - await interaction.editReply(errorMsg('something went wrong')); - } else { - await interaction.reply({content: errorMsg(error as Error), ephemeral: true}); - } + // This can fail if the message was deleted, and we don't want to crash the whole bot + try { + if (interaction.replied || interaction.deferred) { + await interaction.editReply(errorMsg('something went wrong')); + } else { + await interaction.reply({content: errorMsg(error as Error), ephemeral: true}); + } + } catch {} } }); diff --git a/src/services/updating-queue-embed.ts b/src/services/updating-queue-embed.ts index 31d58ff..6496fb5 100644 --- a/src/services/updating-queue-embed.ts +++ b/src/services/updating-queue-embed.ts @@ -1,4 +1,4 @@ -import {CommandInteraction, MessageActionRow, MessageButton, MessageEmbed} from 'discord.js'; +import {CommandInteraction, MessageActionRow, MessageButton, MessageEmbed, DiscordAPIError} from 'discord.js'; import getYouTubeID from 'get-youtube-id'; import getProgressBar from '../utils/get-progress-bar.js'; import {prettyTime} from '../utils/time.js'; @@ -40,13 +40,23 @@ export default class { * @param interaction */ async createFromInteraction(interaction: CommandInteraction) { + const oldInteraction = this.interaction; + + this.resetState(); + this.interaction = interaction; - this.currentPage = 1; - await interaction.reply({ - embeds: [this.buildEmbed()], - components: this.buildButtons(this.player), - }); + await Promise.all([ + interaction.reply({ + embeds: [this.buildEmbed()], + components: this.buildButtons(this.player), + }), + (async () => { + if (oldInteraction) { + await oldInteraction.deleteReply(); + } + })(), + ]); if (!this.refreshTimeout) { this.refreshTimeout = setInterval(async () => this.update(), REFRESH_INTERVAL_MS); @@ -58,10 +68,23 @@ export default class { this.currentPage = 1; } - await this.interaction?.editReply({ - embeds: [this.buildEmbed()], - components: this.buildButtons(this.player), - }); + try { + await this.interaction?.editReply({ + embeds: [this.buildEmbed()], + components: this.buildButtons(this.player), + }); + } catch (error: unknown) { + if (error instanceof DiscordAPIError) { + // Interaction / message was deleted + if (error.code === 10008) { + this.resetState(); + + return; + } + } + + throw error; + } } async pageBack() { @@ -80,6 +103,16 @@ export default class { await this.update(); } + private resetState() { + if (this.refreshTimeout) { + clearInterval(this.refreshTimeout); + this.refreshTimeout = undefined; + } + + this.currentPage = 1; + this.interaction = undefined; + } + private buildButtons(player: Player): MessageActionRow[] { const queuePageControls = new MessageActionRow() .addComponents( -- cgit v1.2.3 From 827ff350ee5df918bc4ecb2e19b64eccc94a46c7 Mon Sep 17 00:00:00 2001 From: Federico fuji97 Rapetti Date: Sun, 26 Dec 2021 04:45:50 +0100 Subject: Improve commands registration --- src/bot.ts | 25 ++++++++++++++----------- src/events/guild-create.ts | 19 ++++++++++++++++++- src/index.ts | 2 +- 3 files changed, 33 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/bot.ts b/src/bot.ts index b9c31a7..fd606cf 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -109,10 +109,22 @@ export default class { const spinner = ora('📡 connecting to Discord...').start(); - this.client.once('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=2184236096`); + spinner.text = '📡 Updating commands in all guilds...'; + + // Update commands + const rest = new REST({version: '9'}).setToken(this.token); + + this.client.guilds.cache.each(async guild => { + await rest.put( + Routes.applicationGuildCommands(this.client.user!.id, guild.id), + {body: this.commandsByName.map(command => command.slashCommand ? command.slashCommand.toJSON() : null)}, + ); + }); + + spinner.succeed(`Ready! Invite the bot with https://discordapp.com/oauth2/authorize?client_id=${this.client.user?.id ?? ''}&scope=applications.commands%20bot&permissions=2184236096`); }); this.client.on('error', console.error); @@ -121,15 +133,6 @@ export default class { this.client.on('guildCreate', handleGuildCreate); this.client.on('voiceStateUpdate', handleVoiceStateUpdate); - // Update commands await this.client.login(this.token); - - const rest = new REST({version: '9'}).setToken(this.token); - - await rest.put( - Routes.applicationGuildCommands(this.client.user!.id, this.client.guilds.cache.first()!.id), - // TODO: remove - {body: this.commandsByName.map(command => command.slashCommand ? command.slashCommand.toJSON() : null)}, - ); } } diff --git a/src/events/guild-create.ts b/src/events/guild-create.ts index 01f0910..38f6e6c 100644 --- a/src/events/guild-create.ts +++ b/src/events/guild-create.ts @@ -1,14 +1,31 @@ -import {Guild, TextChannel, Message, MessageReaction, User} from 'discord.js'; +import { + Guild, + TextChannel, + Message, + MessageReaction, + User, + ApplicationCommandData, +} from 'discord.js'; import emoji from 'node-emoji'; import pEvent from 'p-event'; import {Settings} from '../models/index.js'; import {chunk} from '../utils/arrays.js'; +import container from '../inversify.config.js'; +import Command from '../commands'; +import {TYPES} from '../types.js'; const DEFAULT_PREFIX = '!'; export default async (guild: Guild): Promise => { await Settings.upsert({guildId: guild.id, prefix: DEFAULT_PREFIX}); + // Setup slash commands + const commands: ApplicationCommandData[] = container.getAll(TYPES.Command) + .filter(command => command.slashCommand?.name) + .map(command => command.slashCommand as ApplicationCommandData); + + await guild.commands.set(commands); + const owner = await guild.client.users.fetch(guild.ownerId); let firstStep = '👋 Hi!\n'; diff --git a/src/index.ts b/src/index.ts index a6b6d35..ac96352 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,7 +7,7 @@ import Bot from './bot.js'; import {sequelize} from './utils/db.js'; import Config from './services/config.js'; import FileCacheProvider from './services/file-cache.js'; -import metadata from '../package.json'; +import metadata from '../package.json' assert {type: "json"}; const bot = container.get(TYPES.Bot); -- cgit v1.2.3 From 767cbf0e6c9f50c96a2af2792909b81739e89a02 Mon Sep 17 00:00:00 2001 From: Federico fuji97 Rapetti Date: Sun, 26 Dec 2021 18:05:56 +0100 Subject: Rollback to Node v16.13.0 --- src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/index.ts b/src/index.ts index ac96352..a6b6d35 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,7 +7,7 @@ import Bot from './bot.js'; import {sequelize} from './utils/db.js'; import Config from './services/config.js'; import FileCacheProvider from './services/file-cache.js'; -import metadata from '../package.json' assert {type: "json"}; +import metadata from '../package.json'; const bot = container.get(TYPES.Bot); -- cgit v1.2.3 From 7298ae15623c069fa297321ba51b3d66957cc542 Mon Sep 17 00:00:00 2001 From: Federico fuji97 Rapetti Date: Sun, 26 Dec 2021 18:06:24 +0100 Subject: Update remove command to slash command --- src/commands/remove.ts | 41 ++++++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/commands/remove.ts b/src/commands/remove.ts index 9c40a71..f0c1b15 100644 --- a/src/commands/remove.ts +++ b/src/commands/remove.ts @@ -1,18 +1,26 @@ -import {Message} from 'discord.js'; +import {CommandInteraction, Message} 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') + // TODO: make sure verb tense is consistent between all command descriptions + .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,6 +28,25 @@ export default class implements Command { this.playerManager = playerManager; } + public async executeFromInteraction(interaction: CommandInteraction): Promise { + const player = this.playerManager.get(interaction.guild!.id); + + const position = interaction.options.getInteger('position') ?? 1; + const range = interaction.options.getInteger('range') ?? 1; + + if (position < 1) { + await interaction.reply('position must be greater than 0'); + } + + if (range < 1) { + await interaction.reply('range must be greater than 0'); + } + + player.removeFromQueue(position, range); + + await interaction.reply(':wastebasket: removed'); + } + public async execute(msg: Message, args: string []): Promise { const player = this.playerManager.get(msg.guild!.id); -- cgit v1.2.3 From 995c0360fe2ae11e9c9c2c82f8bdd81966e2919b Mon Sep 17 00:00:00 2001 From: Federico fuji97 Rapetti Date: Sun, 26 Dec 2021 19:44:17 +0100 Subject: Change module version to ES2020 --- src/events/guild-create.ts | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) (limited to 'src') diff --git a/src/events/guild-create.ts b/src/events/guild-create.ts index 38f6e6c..722b736 100644 --- a/src/events/guild-create.ts +++ b/src/events/guild-create.ts @@ -1,10 +1,4 @@ -import { - Guild, - TextChannel, - Message, - MessageReaction, - User, - ApplicationCommandData, +import {Guild, TextChannel, Message, MessageReaction, User, ApplicationCommandData, } from 'discord.js'; import emoji from 'node-emoji'; import pEvent from 'p-event'; -- cgit v1.2.3 From 1890f264ac2cf9e51d58707772f27a7500bdfc4d Mon Sep 17 00:00:00 2001 From: Federico fuji97 Rapetti Date: Mon, 27 Dec 2021 16:43:23 +0100 Subject: Refactor skip command as slash command --- src/commands/skip.ts | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/commands/skip.ts b/src/commands/skip.ts index 4bab307..e38204c 100644 --- a/src/commands/skip.ts +++ b/src/commands/skip.ts @@ -1,10 +1,11 @@ -import {Message, TextChannel} from 'discord.js'; +import {CommandInteraction, Message, TextChannel} 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'; @injectable() export default class implements Command { @@ -15,6 +16,15 @@ export default class implements Command { ['skip 2', 'skips the next 2 songs'], ]; + public readonly slashCommand = new SlashCommandBuilder() + .setName('skip') + // TODO: make sure verb tense is consistent between all command descriptions + .setDescription('skips the next songs') + .addIntegerOption(option => option + .setName('number') + .setDescription('number of songs to skip [default: 1]') + .setRequired(false)); + public requiresVC = true; private readonly playerManager: PlayerManager; @@ -23,6 +33,23 @@ export default class implements Command { this.playerManager = playerManager; } + public async executeFromInteraction(interaction: CommandInteraction): Promise { + const numToSkip = interaction.options.getInteger('skip') ?? 1; + + if (numToSkip < 1) { + await interaction.reply({content: errorMsg('invalid number of songs to skip'), ephemeral: true}); + } + + const player = this.playerManager.get(interaction.guild!.id); + + try { + await player.forward(numToSkip); + await interaction.reply('keep \'er movin\''); + } catch (_: unknown) { + await interaction.reply({content: errorMsg('invalid number of songs to skip'), ephemeral: true}); + } + } + public async execute(msg: Message, args: string []): Promise { let numToSkip = 1; -- cgit v1.2.3 From 29c32ce65ec0c7103e4c895ec6e98207eb298ae6 Mon Sep 17 00:00:00 2001 From: Federico fuji97 Rapetti Date: Mon, 27 Dec 2021 16:53:36 +0100 Subject: Refactor unskip command as slash command --- src/commands/unskip.ts | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/commands/unskip.ts b/src/commands/unskip.ts index a453448..8945553 100644 --- a/src/commands/unskip.ts +++ b/src/commands/unskip.ts @@ -1,12 +1,17 @@ -import {Message} from 'discord.js'; +import {CommandInteraction, Message} 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 readonly slashCommand = new SlashCommandBuilder() + .setName('unskip') + .setDescription('goes back in the queue by one song'); + public name = 'unskip'; public aliases = ['back']; public examples = [ @@ -21,6 +26,21 @@ export default class implements Command { this.playerManager = playerManager; } + public async executeFromInteraction(interaction: CommandInteraction): Promise { + const player = this.playerManager.get(interaction.guild!.id); + + try { + await player.back(); + + await interaction.reply('back \'er up\''); + } catch (_: unknown) { + await interaction.reply({ + content: errorMsg('no song to go back to'), + ephemeral: true, + }); + } + } + public async execute(msg: Message, _: string []): Promise { const player = this.playerManager.get(msg.guild!.id); -- cgit v1.2.3 From e7a87c4f529b85cf03a8a8cfc009336fd85334c9 Mon Sep 17 00:00:00 2001 From: Federico fuji97 Rapetti Date: Mon, 27 Dec 2021 16:56:19 +0100 Subject: Remove old functions from commands --- src/commands/remove.ts | 67 +++++++------------------------------------------- src/commands/skip.ts | 3 +-- src/commands/unskip.ts | 20 +-------------- 3 files changed, 11 insertions(+), 79 deletions(-) (limited to 'src') diff --git a/src/commands/remove.ts b/src/commands/remove.ts index f0c1b15..76ba901 100644 --- a/src/commands/remove.ts +++ b/src/commands/remove.ts @@ -1,4 +1,4 @@ -import {CommandInteraction, 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'; @@ -10,7 +10,6 @@ import {SlashCommandBuilder} from '@discordjs/builders'; export default class implements Command { public readonly slashCommand = new SlashCommandBuilder() .setName('remove') - // TODO: make sure verb tense is consistent between all command descriptions .setDescription('remove songs from the queue') .addIntegerOption(option => option.setName('position') @@ -35,69 +34,21 @@ export default class implements Command { const range = interaction.options.getInteger('range') ?? 1; if (position < 1) { - await interaction.reply('position must be greater than 0'); + await interaction.reply({ + content: errorMsg('position must be greater than 0'), + ephemeral: true, + }); } if (range < 1) { - await interaction.reply('range must be greater than 0'); + await interaction.reply({ + content: errorMsg('range must be greater than 0'), + ephemeral: true, + }); } player.removeFromQueue(position, range); await interaction.reply(':wastebasket: removed'); } - - public async execute(msg: Message, args: string []): Promise { - const player = this.playerManager.get(msg.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]); - - if (match === null) { - await msg.channel.send(errorMsg('incorrect format')); - return; - } - - 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); - } - - await msg.channel.send(':wastebasket: removed'); - } } diff --git a/src/commands/skip.ts b/src/commands/skip.ts index e38204c..93b8bc3 100644 --- a/src/commands/skip.ts +++ b/src/commands/skip.ts @@ -18,8 +18,7 @@ export default class implements Command { public readonly slashCommand = new SlashCommandBuilder() .setName('skip') - // TODO: make sure verb tense is consistent between all command descriptions - .setDescription('skips the next songs') + .setDescription('skips the next songs') .addIntegerOption(option => option .setName('number') .setDescription('number of songs to skip [default: 1]') diff --git a/src/commands/unskip.ts b/src/commands/unskip.ts index 8945553..6842498 100644 --- a/src/commands/unskip.ts +++ b/src/commands/unskip.ts @@ -1,4 +1,4 @@ -import {CommandInteraction, 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'; @@ -12,12 +12,6 @@ export default class implements Command { .setName('unskip') .setDescription('goes back in the queue by one song'); - public name = 'unskip'; - public aliases = ['back']; - public examples = [ - ['unskip', 'goes back in the queue by one song'], - ]; - public requiresVC = true; private readonly playerManager: PlayerManager; @@ -40,16 +34,4 @@ export default class implements Command { }); } } - - public async execute(msg: Message, _: string []): Promise { - const player = this.playerManager.get(msg.guild!.id); - - try { - await player.back(); - - await msg.channel.send('back \'er up\''); - } catch (_: unknown) { - await msg.channel.send(errorMsg('no song to go back to')); - } - } } -- cgit v1.2.3 From 65e1f975b9653a8baafdf023d6e14bac2856fc19 Mon Sep 17 00:00:00 2001 From: Federico fuji97 Rapetti Date: Mon, 27 Dec 2021 18:26:37 +0100 Subject: Refactor seek command as slash command --- src/commands/seek.ts | 57 ++++++++++++++++++++++++++++------------------------ 1 file changed, 31 insertions(+), 26 deletions(-) (limited to 'src') diff --git a/src/commands/seek.ts b/src/commands/seek.ts index 5578aca..708567f 100644 --- a/src/commands/seek.ts +++ b/src/commands/seek.ts @@ -1,21 +1,22 @@ -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 +26,28 @@ export default class implements Command { this.playerManager = playerManager; } - public async execute(msg: Message, args: string []): Promise { - const player = this.playerManager.get(msg.guild!.id); + public async executeFromInteraction(interaction: CommandInteraction): Promise { + const player = this.playerManager.get(interaction.guild!.id); const currentSong = player.getCurrent(); if (!currentSong) { - await msg.channel.send(errorMsg('nothing is playing')); + await interaction.reply({ + content: errorMsg('nothing is playing'), + ephemeral: true, + }); return; } if (currentSong.isLive) { - await msg.channel.send(errorMsg('can\'t seek in a livestream')); + await interaction.reply({ + content: errorMsg('can\'t seek in a livestream'), + ephemeral: true, + }); return; } - const time = args[0]; + const time = interaction.options.getString('time')!; let seekTime = 0; @@ -51,20 +58,18 @@ export default class implements Command { } if (seekTime > currentSong.length) { - await msg.channel.send(errorMsg('can\'t seek past the end of the song')); + await interaction.reply({ + content: errorMsg('can\'t seek past the end of the song'), + ephemeral: true, + }); return; } - 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())}`); } } -- cgit v1.2.3 From 55d8a2e97b6391e000af59c1e86966edc4e4aa81 Mon Sep 17 00:00:00 2001 From: Federico fuji97 Rapetti Date: Mon, 27 Dec 2021 18:41:26 +0100 Subject: Refactor shuffle command as slash command --- src/commands/shuffle.ts | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/commands/shuffle.ts b/src/commands/shuffle.ts index d50f0b3..f560e41 100644 --- a/src/commands/shuffle.ts +++ b/src/commands/shuffle.ts @@ -1,17 +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'; @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 +20,19 @@ export default class implements Command { this.playerManager = playerManager; } - public async execute(msg: Message, _: string []): Promise { - const player = this.playerManager.get(msg.guild!.id); + public async executeFromInteraction(interaction: CommandInteraction): Promise { + const player = this.playerManager.get(interaction.guild!.id); if (player.isQueueEmpty()) { - await msg.channel.send(errorMsg('not enough songs to shuffle')); + await interaction.reply({ + content: errorMsg('not enough songs to shuffle'), + ephemeral: true, + }); return; } player.shuffle(); - await msg.channel.send('shuffled'); + await interaction.reply('shuffled'); } } -- cgit v1.2.3 From 83fa78e9fad8a217b7eaef28903d388e53854cf2 Mon Sep 17 00:00:00 2001 From: Max Isom Date: Mon, 27 Dec 2021 22:58:22 -0600 Subject: Fix invite scope --- src/bot.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/bot.ts b/src/bot.ts index b9c31a7..d59fb9f 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -112,7 +112,7 @@ export default class { this.client.once('ready', () => { debug(generateDependencyReport()); - spinner.succeed(`Ready! Invite the bot with https://discordapp.com/oauth2/authorize?client_id=${this.client.user?.id ?? ''}&scope=bot&permissions=2184236096`); + spinner.succeed(`Ready! Invite the bot with https://discordapp.com/oauth2/authorize?client_id=${this.client.user?.id ?? ''}&scope=bot%20applications.commands&permissions=2184236096`); }); this.client.on('error', console.error); -- cgit v1.2.3 From ac1fef836fed6ffe5be9830c73a06e29c70628c8 Mon Sep 17 00:00:00 2001 From: Federico fuji97 Rapetti Date: Mon, 10 Jan 2022 19:41:43 +0100 Subject: Change welcome message to use slash command --- src/events/guild-create.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/events/guild-create.ts b/src/events/guild-create.ts index 722b736..6263673 100644 --- a/src/events/guild-create.ts +++ b/src/events/guild-create.ts @@ -86,7 +86,7 @@ export default async (guild: Guild): Promise => { // 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\``); + await boundChannel.send(`hey <@${owner.id}> try \`\\play https://www.youtube.com/watch?v=dQw4w9WgXcQ\``); await firstStepMsg.channel.send(`Sounds good. Check out **#${chosenChannel.name}** to get started.`); }; -- cgit v1.2.3 From ab164353c1151666a8ed339fd753099391a1f08d Mon Sep 17 00:00:00 2001 From: Federico fuji97 Rapetti Date: Mon, 10 Jan 2022 20:13:50 +0100 Subject: Refactor bot commands update system --- src/bot.ts | 28 ++++++++++++++++++++++------ src/events/guild-create.ts | 13 +++++++++---- src/services/config.ts | 2 ++ 3 files changed, 33 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/bot.ts b/src/bot.ts index fd606cf..bcd6c20 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -18,17 +18,22 @@ import {Routes} from 'discord-api-types/v9'; export default class { private readonly client: Client; private readonly token: string; + private readonly env: string; private readonly commandsByName!: Collection; private readonly commandsByButtonId!: Collection; constructor(@inject(TYPES.Client) client: Client, @inject(TYPES.Config) config: Config) { this.client = client; this.token = config.DISCORD_TOKEN; + this.env = config.NODE_ENV; this.commandsByName = new Collection(); this.commandsByButtonId = new Collection(); } public async listen(): Promise { + // Log environment + console.log(`Starting environment: ${this.env}\n`); + // Load in commands container.getAll(TYPES.Command).forEach(command => { // TODO: remove ! @@ -117,12 +122,23 @@ export default class { // Update commands const rest = new REST({version: '9'}).setToken(this.token); - this.client.guilds.cache.each(async guild => { - await rest.put( - Routes.applicationGuildCommands(this.client.user!.id, guild.id), - {body: this.commandsByName.map(command => command.slashCommand ? command.slashCommand.toJSON() : null)}, - ); - }); + switch (this.env) { + case 'production': + // If production, set commands bot-wide + await rest.put( + Routes.applicationCommands(this.client.user!.id), + {body: this.commandsByName.map(command => command.slashCommand ? command.slashCommand.toJSON() : null)}, + ); + break; + default: + // If development, set commands guild-wide + this.client.guilds.cache.each(async guild => { + await rest.put( + Routes.applicationGuildCommands(this.client.user!.id, guild.id), + {body: this.commandsByName.map(command => command.slashCommand ? command.slashCommand.toJSON() : null)}, + ); + }); + } spinner.succeed(`Ready! Invite the bot with https://discordapp.com/oauth2/authorize?client_id=${this.client.user?.id ?? ''}&scope=applications.commands%20bot&permissions=2184236096`); }); diff --git a/src/events/guild-create.ts b/src/events/guild-create.ts index 6263673..5e0ee59 100644 --- a/src/events/guild-create.ts +++ b/src/events/guild-create.ts @@ -7,18 +7,23 @@ import {chunk} from '../utils/arrays.js'; import container from '../inversify.config.js'; import Command from '../commands'; import {TYPES} from '../types.js'; +import Config from '../services/config.js'; const DEFAULT_PREFIX = '!'; export default async (guild: Guild): Promise => { await Settings.upsert({guildId: guild.id, prefix: DEFAULT_PREFIX}); + const config = container.get(TYPES.Config); + // Setup slash commands - const commands: ApplicationCommandData[] = container.getAll(TYPES.Command) - .filter(command => command.slashCommand?.name) - .map(command => command.slashCommand as ApplicationCommandData); + if (config.NODE_ENV === 'production') { + const commands: ApplicationCommandData[] = container.getAll(TYPES.Command) + .filter(command => command.slashCommand?.name) + .map(command => command.slashCommand as ApplicationCommandData); - await guild.commands.set(commands); + await guild.commands.set(commands); + } const owner = await guild.client.users.fetch(guild.ownerId); diff --git a/src/services/config.ts b/src/services/config.ts index 96b161c..838873f 100644 --- a/src/services/config.ts +++ b/src/services/config.ts @@ -12,6 +12,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, + NODE_ENV: process.env.NODE_ENV ?? 'development', DATA_DIR, CACHE_DIR: path.join(DATA_DIR, 'cache'), CACHE_LIMIT_IN_BYTES: xbytes.parseSize(process.env.CACHE_LIMIT ?? '2GB'), @@ -23,6 +24,7 @@ export default class Config { readonly YOUTUBE_API_KEY!: string; readonly SPOTIFY_CLIENT_ID!: string; readonly SPOTIFY_CLIENT_SECRET!: string; + readonly NODE_ENV!: string; readonly DATA_DIR!: string; readonly CACHE_DIR!: string; readonly CACHE_LIMIT_IN_BYTES!: number; -- cgit v1.2.3 From ce686b42815c4f7a1e87496612a647009da7a741 Mon Sep 17 00:00:00 2001 From: Federico fuji97 Rapetti Date: Mon, 10 Jan 2022 22:02:55 +0100 Subject: Fix lint commands and lint errors --- src/bot.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/bot.ts b/src/bot.ts index b2e591b..d42a718 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -139,7 +139,7 @@ export default class { ); }); } - + spinner.succeed(`Ready! Invite the bot with https://discordapp.com/oauth2/authorize?client_id=${this.client.user?.id ?? ''}&scope=bot%20applications.commands&permissions=2184236096`); }); -- cgit v1.2.3 From 03fdf1aab7ff5278f22c7dda9fc77e49c458d76a Mon Sep 17 00:00:00 2001 From: Federico fuji97 Rapetti Date: Wed, 12 Jan 2022 00:47:54 +0100 Subject: Refactor production checks --- src/bot.ts | 33 +++++++++++++++++---------------- src/events/guild-create.ts | 2 +- src/services/config.ts | 4 ++-- 3 files changed, 20 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/bot.ts b/src/bot.ts index d42a718..74b56d8 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -18,21 +18,25 @@ import {Routes} from 'discord-api-types/v9'; export default class { private readonly client: Client; private readonly token: string; - private readonly env: string; + private readonly isProduction: boolean; private readonly commandsByName!: Collection; private readonly commandsByButtonId!: Collection; constructor(@inject(TYPES.Client) client: Client, @inject(TYPES.Config) config: Config) { this.client = client; this.token = config.DISCORD_TOKEN; - this.env = config.NODE_ENV; + this.isProduction = config.IS_PRODUCTION; this.commandsByName = new Collection(); this.commandsByButtonId = new Collection(); } public async listen(): Promise { // Log environment - console.log(`Starting environment: ${this.env}\n`); + if (this.isProduction) { + console.log('Production environment\n'); + } else { + console.log('Development environment\n'); + } // Load in commands container.getAll(TYPES.Command).forEach(command => { @@ -122,22 +126,19 @@ export default class { // Update commands const rest = new REST({version: '9'}).setToken(this.token); - switch (this.env) { - case 'production': - // If production, set commands bot-wide + if (this.isProduction) { + await rest.put( + Routes.applicationCommands(this.client.user!.id), + {body: this.commandsByName.map(command => command.slashCommand ? command.slashCommand.toJSON() : null)}, + ); + } else { + // If development, set commands guild-wide + this.client.guilds.cache.each(async guild => { await rest.put( - Routes.applicationCommands(this.client.user!.id), + Routes.applicationGuildCommands(this.client.user!.id, guild.id), {body: this.commandsByName.map(command => command.slashCommand ? command.slashCommand.toJSON() : null)}, ); - break; - default: - // If development, set commands guild-wide - this.client.guilds.cache.each(async guild => { - await rest.put( - Routes.applicationGuildCommands(this.client.user!.id, guild.id), - {body: this.commandsByName.map(command => command.slashCommand ? command.slashCommand.toJSON() : null)}, - ); - }); + }); } spinner.succeed(`Ready! Invite the bot with https://discordapp.com/oauth2/authorize?client_id=${this.client.user?.id ?? ''}&scope=bot%20applications.commands&permissions=2184236096`); diff --git a/src/events/guild-create.ts b/src/events/guild-create.ts index 5e0ee59..c305527 100644 --- a/src/events/guild-create.ts +++ b/src/events/guild-create.ts @@ -17,7 +17,7 @@ export default async (guild: Guild): Promise => { const config = container.get(TYPES.Config); // Setup slash commands - if (config.NODE_ENV === 'production') { + if (config.IS_PRODUCTION) { const commands: ApplicationCommandData[] = container.getAll(TYPES.Command) .filter(command => command.slashCommand?.name) .map(command => command.slashCommand as ApplicationCommandData); diff --git a/src/services/config.ts b/src/services/config.ts index 838873f..ae7ef4b 100644 --- a/src/services/config.ts +++ b/src/services/config.ts @@ -12,7 +12,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, - NODE_ENV: process.env.NODE_ENV ?? 'development', + IS_PRODUCTION: process.env.NODE_ENV === 'production', DATA_DIR, CACHE_DIR: path.join(DATA_DIR, 'cache'), CACHE_LIMIT_IN_BYTES: xbytes.parseSize(process.env.CACHE_LIMIT ?? '2GB'), @@ -24,7 +24,7 @@ export default class Config { readonly YOUTUBE_API_KEY!: string; readonly SPOTIFY_CLIENT_ID!: string; readonly SPOTIFY_CLIENT_SECRET!: string; - readonly NODE_ENV!: string; + readonly IS_PRODUCTION!: boolean; readonly DATA_DIR!: string; readonly CACHE_DIR!: string; readonly CACHE_LIMIT_IN_BYTES!: number; -- cgit v1.2.3 From 732a3bb87acd1e6c8e500f1615a549b311961bea Mon Sep 17 00:00:00 2001 From: "Federico \"fuji97\" Rapetti" Date: Thu, 13 Jan 2022 12:51:56 +0100 Subject: Fix typo in guild-create.ts --- src/events/guild-create.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/events/guild-create.ts b/src/events/guild-create.ts index c305527..008e22b 100644 --- a/src/events/guild-create.ts +++ b/src/events/guild-create.ts @@ -17,7 +17,7 @@ export default async (guild: Guild): Promise => { const config = container.get(TYPES.Config); // Setup slash commands - if (config.IS_PRODUCTION) { + if (!config.IS_PRODUCTION) { const commands: ApplicationCommandData[] = container.getAll(TYPES.Command) .filter(command => command.slashCommand?.name) .map(command => command.slashCommand as ApplicationCommandData); -- cgit v1.2.3 From 0f0c3eb6813391917c604629ae0523da3f35f012 Mon Sep 17 00:00:00 2001 From: "Federico \"fuji97\" Rapetti" Date: Thu, 13 Jan 2022 12:59:18 +0100 Subject: Wrap guild-wise command set code in a Promise.all() to correctly wait the API to resolve --- src/bot.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/bot.ts b/src/bot.ts index 74b56d8..cb10d1b 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -13,6 +13,7 @@ import Config from './services/config.js'; import {generateDependencyReport} from '@discordjs/voice'; import {REST} from '@discordjs/rest'; import {Routes} from 'discord-api-types/v9'; +import {Promise} from 'bluebird'; @injectable() export default class { @@ -133,12 +134,14 @@ export default class { ); } else { // If development, set commands guild-wide - this.client.guilds.cache.each(async guild => { - await rest.put( - Routes.applicationGuildCommands(this.client.user!.id, guild.id), - {body: this.commandsByName.map(command => command.slashCommand ? command.slashCommand.toJSON() : null)}, - ); - }); + 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 ? command.slashCommand.toJSON() : null)}, + ); + }), + ); } spinner.succeed(`Ready! Invite the bot with https://discordapp.com/oauth2/authorize?client_id=${this.client.user?.id ?? ''}&scope=bot%20applications.commands&permissions=2184236096`); -- cgit v1.2.3 From 86e9936578d19c2115fc03acae1794532a09d62e Mon Sep 17 00:00:00 2001 From: Max Isom Date: Tue, 18 Jan 2022 22:09:07 -0600 Subject: Update README, naming --- src/bot.ts | 21 +++++++-------------- src/events/guild-create.ts | 2 +- src/services/config.ts | 6 ++++-- 3 files changed, 12 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/bot.ts b/src/bot.ts index cb10d1b..fb92d14 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -13,32 +13,24 @@ import Config from './services/config.js'; import {generateDependencyReport} from '@discordjs/voice'; import {REST} from '@discordjs/rest'; import {Routes} from 'discord-api-types/v9'; -import {Promise} from 'bluebird'; @injectable() export default class { private readonly client: Client; private readonly token: string; - private readonly isProduction: boolean; + private readonly shouldRegisterCommandsOnBot: boolean; private readonly commandsByName!: Collection; private readonly commandsByButtonId!: Collection; constructor(@inject(TYPES.Client) client: Client, @inject(TYPES.Config) config: Config) { this.client = client; this.token = config.DISCORD_TOKEN; - this.isProduction = config.IS_PRODUCTION; + this.shouldRegisterCommandsOnBot = config.REGISTER_COMMANDS_ON_BOT; this.commandsByName = new Collection(); this.commandsByButtonId = new Collection(); } public async listen(): Promise { - // Log environment - if (this.isProduction) { - console.log('Production environment\n'); - } else { - console.log('Development environment\n'); - } - // Load in commands container.getAll(TYPES.Command).forEach(command => { // TODO: remove ! @@ -122,18 +114,19 @@ export default class { this.client.once('ready', async () => { debug(generateDependencyReport()); - spinner.text = '📡 Updating commands in all guilds...'; - // Update commands const rest = new REST({version: '9'}).setToken(this.token); - if (this.isProduction) { + 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 ? command.slashCommand.toJSON() : null)}, ); } else { - // If development, set commands guild-wide + spinner.text = '📡 updating commands in all guilds...'; + await Promise.all( this.client.guilds.cache.map(async guild => { await rest.put( diff --git a/src/events/guild-create.ts b/src/events/guild-create.ts index 008e22b..e7a6467 100644 --- a/src/events/guild-create.ts +++ b/src/events/guild-create.ts @@ -17,7 +17,7 @@ export default async (guild: Guild): Promise => { const config = container.get(TYPES.Config); // Setup slash commands - if (!config.IS_PRODUCTION) { + if (!config.REGISTER_COMMANDS_ON_BOT) { const commands: ApplicationCommandData[] = container.getAll(TYPES.Command) .filter(command => command.slashCommand?.name) .map(command => command.slashCommand as ApplicationCommandData); diff --git a/src/services/config.ts b/src/services/config.ts index ae7ef4b..34e612c 100644 --- a/src/services/config.ts +++ b/src/services/config.ts @@ -12,7 +12,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, - IS_PRODUCTION: process.env.NODE_ENV === 'production', + 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,7 +24,7 @@ export default class Config { readonly YOUTUBE_API_KEY!: string; readonly SPOTIFY_CLIENT_ID!: string; readonly SPOTIFY_CLIENT_SECRET!: string; - readonly IS_PRODUCTION!: boolean; + readonly REGISTER_COMMANDS_ON_BOT!: boolean; readonly DATA_DIR!: string; readonly CACHE_DIR!: string; readonly CACHE_LIMIT_IN_BYTES!: number; @@ -40,6 +40,8 @@ export default class Config { this[key as ConditionalKeys] = value; } else if (typeof value === 'string') { this[key as ConditionalKeys] = value; + } else if (typeof value === 'boolean') { + this[key as ConditionalKeys] = value; } else { throw new Error(`Unsupported type for ${key}`); } -- cgit v1.2.3 From 4169104c4df909c9c700ca0481dddd74d86169ec Mon Sep 17 00:00:00 2001 From: Max Isom Date: Wed, 19 Jan 2022 13:46:32 -0600 Subject: Type fixes, remove shortcuts --- src/bot.ts | 4 +- src/commands/clear.ts | 2 +- src/commands/disconnect.ts | 2 +- src/commands/fseek.ts | 2 +- src/commands/index.ts | 10 ++-- src/commands/pause.ts | 2 +- src/commands/play.ts | 2 +- src/commands/queue.ts | 2 +- src/commands/remove.ts | 2 +- src/commands/seek.ts | 2 +- src/commands/shortcuts.ts | 128 --------------------------------------------- src/commands/shuffle.ts | 2 +- src/commands/skip.ts | 28 +--------- src/commands/unskip.ts | 2 +- src/inversify.config.ts | 2 - 15 files changed, 17 insertions(+), 175 deletions(-) delete mode 100644 src/commands/shortcuts.ts (limited to 'src') diff --git a/src/bot.ts b/src/bot.ts index 8550303..a18e344 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -69,8 +69,8 @@ export default class { return; } - if (command.executeFromInteraction) { - await command.executeFromInteraction(interaction); + if (command.execute) { + await command.execute(interaction); } } catch (error: unknown) { debug(error); diff --git a/src/commands/clear.ts b/src/commands/clear.ts index 5c1a1eb..2b258cb 100644 --- a/src/commands/clear.ts +++ b/src/commands/clear.ts @@ -19,7 +19,7 @@ export default class implements Command { this.playerManager = playerManager; } - public async executeFromInteraction(interaction: CommandInteraction) { + public async execute(interaction: CommandInteraction) { this.playerManager.get(interaction.guild!.id).clear(); await interaction.reply('clearer than a field after a fresh harvest'); diff --git a/src/commands/disconnect.ts b/src/commands/disconnect.ts index d196985..c63f9a2 100644 --- a/src/commands/disconnect.ts +++ b/src/commands/disconnect.ts @@ -20,7 +20,7 @@ export default class implements Command { this.playerManager = playerManager; } - public async executeFromInteraction(interaction: CommandInteraction) { + public async execute(interaction: CommandInteraction) { const player = this.playerManager.get(interaction.guild!.id); if (!player.voiceConnection) { diff --git a/src/commands/fseek.ts b/src/commands/fseek.ts index 5a46a17..f4f1172 100644 --- a/src/commands/fseek.ts +++ b/src/commands/fseek.ts @@ -25,7 +25,7 @@ export default class implements Command { this.playerManager = playerManager; } - public async executeFromInteraction(interaction: CommandInteraction): Promise { + public async execute(interaction: CommandInteraction): Promise { const player = this.playerManager.get(interaction.guild!.id); const currentSong = player.getCurrent(); diff --git a/src/commands/index.ts b/src/commands/index.ts index 1cd927b..b9f5877 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -1,14 +1,10 @@ import {SlashCommandBuilder} from '@discordjs/builders'; import {ButtonInteraction, CommandInteraction} from 'discord.js'; -export default class Command { - // TODO: remove - name?: string; - aliases?: string[]; - examples?: string[][]; - readonly slashCommand?: Partial & Pick; +export default interface Command { + readonly slashCommand: Partial & Pick; readonly handledButtonIds?: readonly string[]; readonly requiresVC?: boolean; - executeFromInteraction?: (interaction: CommandInteraction) => Promise; + execute: (interaction: CommandInteraction) => Promise; handleButtonInteraction?: (interaction: ButtonInteraction) => Promise; } diff --git a/src/commands/pause.ts b/src/commands/pause.ts index c3e8c24..5d87b87 100644 --- a/src/commands/pause.ts +++ b/src/commands/pause.ts @@ -21,7 +21,7 @@ export default class implements Command { this.playerManager = playerManager; } - public async executeFromInteraction(interaction: CommandInteraction) { + public async execute(interaction: CommandInteraction) { const player = this.playerManager.get(interaction.guild!.id); if (player.status !== STATUS.PLAYING) { diff --git a/src/commands/play.ts b/src/commands/play.ts index 4ac566b..619c18f 100644 --- a/src/commands/play.ts +++ b/src/commands/play.ts @@ -40,7 +40,7 @@ export default class implements Command { } // eslint-disable-next-line complexity - public async executeFromInteraction(interaction: CommandInteraction): Promise { + public async execute(interaction: CommandInteraction): Promise { const [targetVoiceChannel] = getMemberVoiceChannel(interaction.member as GuildMember) ?? getMostPopularVoiceChannel(interaction.guild!); const settings = await prisma.setting.findUnique({where: {guildId: interaction.guild!.id}}); diff --git a/src/commands/queue.ts b/src/commands/queue.ts index 479bc33..9768f58 100644 --- a/src/commands/queue.ts +++ b/src/commands/queue.ts @@ -23,7 +23,7 @@ export default class implements Command { this.updatingQueueEmbedManager = updatingQueueEmbedManager; } - public async executeFromInteraction(interaction: CommandInteraction) { + public async execute(interaction: CommandInteraction) { const embed = this.updatingQueueEmbedManager.get(interaction.guild!.id); await embed.createFromInteraction(interaction); diff --git a/src/commands/remove.ts b/src/commands/remove.ts index 76ba901..c58fbdf 100644 --- a/src/commands/remove.ts +++ b/src/commands/remove.ts @@ -27,7 +27,7 @@ export default class implements Command { this.playerManager = playerManager; } - public async executeFromInteraction(interaction: CommandInteraction): Promise { + public async execute(interaction: CommandInteraction): Promise { const player = this.playerManager.get(interaction.guild!.id); const position = interaction.options.getInteger('position') ?? 1; diff --git a/src/commands/seek.ts b/src/commands/seek.ts index 708567f..ecfde64 100644 --- a/src/commands/seek.ts +++ b/src/commands/seek.ts @@ -26,7 +26,7 @@ export default class implements Command { this.playerManager = playerManager; } - public async executeFromInteraction(interaction: CommandInteraction): Promise { + public async execute(interaction: CommandInteraction): Promise { const player = this.playerManager.get(interaction.guild!.id); const currentSong = player.getCurrent(); 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 { - 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 f560e41..9c0a664 100644 --- a/src/commands/shuffle.ts +++ b/src/commands/shuffle.ts @@ -20,7 +20,7 @@ export default class implements Command { this.playerManager = playerManager; } - public async executeFromInteraction(interaction: CommandInteraction): Promise { + public async execute(interaction: CommandInteraction): Promise { const player = this.playerManager.get(interaction.guild!.id); if (player.isQueueEmpty()) { diff --git a/src/commands/skip.ts b/src/commands/skip.ts index 93b8bc3..f8900da 100644 --- a/src/commands/skip.ts +++ b/src/commands/skip.ts @@ -1,9 +1,8 @@ -import {CommandInteraction, 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'; @@ -32,7 +31,7 @@ export default class implements Command { this.playerManager = playerManager; } - public async executeFromInteraction(interaction: CommandInteraction): Promise { + public async execute(interaction: CommandInteraction): Promise { const numToSkip = interaction.options.getInteger('skip') ?? 1; if (numToSkip < 1) { @@ -48,27 +47,4 @@ export default class implements Command { await interaction.reply({content: errorMsg('invalid number of songs to skip'), ephemeral: true}); } } - - public async execute(msg: Message, args: string []): Promise { - let numToSkip = 1; - - if (args.length === 1) { - if (!Number.isNaN(parseInt(args[0], 10))) { - numToSkip = parseInt(args[0], 10); - } - } - - const player = this.playerManager.get(msg.guild!.id); - - const loader = new LoadingMessage(msg.channel as TextChannel); - - try { - await loader.start(); - await player.forward(numToSkip); - - await loader.stop('keep \'er movin\''); - } catch (_: unknown) { - await loader.stop(errorMsg('no song to skip to')); - } - } } diff --git a/src/commands/unskip.ts b/src/commands/unskip.ts index 6842498..746cdf9 100644 --- a/src/commands/unskip.ts +++ b/src/commands/unskip.ts @@ -20,7 +20,7 @@ export default class implements Command { this.playerManager = playerManager; } - public async executeFromInteraction(interaction: CommandInteraction): Promise { + public async execute(interaction: CommandInteraction): Promise { const player = this.playerManager.get(interaction.guild!.id); try { diff --git a/src/inversify.config.ts b/src/inversify.config.ts index 623e631..5714d6f 100644 --- a/src/inversify.config.ts +++ b/src/inversify.config.ts @@ -23,7 +23,6 @@ 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'; @@ -63,7 +62,6 @@ container.bind(TYPES.Services.NaturalLanguage).to(NaturalLangua QueueCommand, Remove, Seek, - Shortcuts, Shuffle, Skip, Unskip, -- cgit v1.2.3 From 43baa57c51ce25aadf7b9d5a75a992e6c1edc7da Mon Sep 17 00:00:00 2001 From: Max Isom Date: Wed, 19 Jan 2022 14:00:50 -0600 Subject: Remove unnecessary properties --- src/commands/skip.ts | 7 ------- 1 file changed, 7 deletions(-) (limited to 'src') diff --git a/src/commands/skip.ts b/src/commands/skip.ts index f8900da..dd24eb2 100644 --- a/src/commands/skip.ts +++ b/src/commands/skip.ts @@ -8,13 +8,6 @@ import {SlashCommandBuilder} from '@discordjs/builders'; @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') -- cgit v1.2.3 From 7901fcce3d7d0ce2ec91ba36a3ba9107e8709bff Mon Sep 17 00:00:00 2001 From: Max Isom Date: Wed, 19 Jan 2022 18:15:12 -0600 Subject: =?UTF-8?q?=E2=9C=A8=20add=20autocomplete?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/bot.ts | 41 +++++++++++++++++++++----------- src/commands/index.ts | 3 ++- src/commands/play.ts | 19 +++++++++++++-- src/utils/get-youtube-suggestions-for.ts | 15 ++++++++++++ 4 files changed, 61 insertions(+), 17 deletions(-) create mode 100644 src/utils/get-youtube-suggestions-for.ts (limited to 'src') diff --git a/src/bot.ts b/src/bot.ts index a18e344..c51caf9 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -87,27 +87,40 @@ export default class { }); this.client.on('interactionCreate', async interaction => { - if (!interaction.isButton()) { - return; - } + try { + if (interaction.isButton()) { + const command = this.commandsByButtonId.get(interaction.customId); - const command = this.commandsByButtonId.get(interaction.customId); + if (!command) { + return; + } - if (!command) { - return; - } + if (command.handleButtonInteraction) { + await command.handleButtonInteraction(interaction); + } + } - try { - if (command.handleButtonInteraction) { - await command.handleButtonInteraction(interaction); + if (interaction.isAutocomplete()) { + const command = this.commandsByName.get(interaction.commandName); + + if (!command) { + return; + } + + if (command.handleAutocompleteInteraction) { + await command.handleAutocompleteInteraction(interaction); + } } } catch (error: unknown) { debug(error); - if (interaction.replied || interaction.deferred) { - await interaction.editReply(errorMsg('something went wrong')); - } else { - await interaction.reply({content: errorMsg(error as Error), ephemeral: true}); + // Can't reply with errors for autocomplete queries + if (interaction.isButton()) { + if (interaction.replied || interaction.deferred) { + await interaction.editReply(errorMsg('something went wrong')); + } else { + await interaction.reply({content: errorMsg(error as Error), ephemeral: true}); + } } } }); diff --git a/src/commands/index.ts b/src/commands/index.ts index b9f5877..1d1646f 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -1,5 +1,5 @@ import {SlashCommandBuilder} from '@discordjs/builders'; -import {ButtonInteraction, CommandInteraction} from 'discord.js'; +import {AutocompleteInteraction, ButtonInteraction, CommandInteraction} from 'discord.js'; export default interface Command { readonly slashCommand: Partial & Pick; @@ -7,4 +7,5 @@ export default interface Command { readonly requiresVC?: boolean; execute: (interaction: CommandInteraction) => Promise; handleButtonInteraction?: (interaction: ButtonInteraction) => Promise; + handleAutocompleteInteraction?: (interaction: AutocompleteInteraction) => Promise; } diff --git a/src/commands/play.ts b/src/commands/play.ts index 619c18f..7e5dee1 100644 --- a/src/commands/play.ts +++ b/src/commands/play.ts @@ -1,4 +1,4 @@ -import {CommandInteraction, GuildMember} from 'discord.js'; +import {AutocompleteInteraction, CommandInteraction, GuildMember} from 'discord.js'; import {URL} from 'url'; import {Except} from 'type-fest'; import {SlashCommandBuilder} from '@discordjs/builders'; @@ -12,6 +12,7 @@ import {getMostPopularVoiceChannel, getMemberVoiceChannel} from '../utils/channe import errorMsg from '../utils/error-msg.js'; import GetSongs from '../services/get-songs.js'; import {prisma} from '../utils/db.js'; +import getYouTubeSuggestionsFor from '../utils/get-youtube-suggestions-for.js'; @injectable() export default class implements Command { @@ -21,7 +22,8 @@ export default class implements Command { .setDescription('play a song or resume playback') .addStringOption(option => option .setName('query') - .setDescription('YouTube URL, Spotify URL, or search query')) + .setDescription('YouTube URL, Spotify URL, or search query') + .setAutocomplete(true)) .addBooleanOption(option => option .setName('immediate') .setDescription('adds track to the front of the queue')) @@ -191,4 +193,17 @@ export default class implements Command { await interaction.editReply(`u betcha, **${firstSong.title}** and ${newSongs.length - 1} other songs were added to the queue${extraMsg}`); } } + + public async handleAutocompleteInteraction(interaction: AutocompleteInteraction): Promise { + const query = interaction.options.getString('query')?.trim(); + + if (!query || query.length === 0) { + return interaction.respond([]); + } + + await interaction.respond((await getYouTubeSuggestionsFor(query)).map(s => ({ + name: s, + value: s, + }))); + } } 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 => { + 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; -- cgit v1.2.3 From 09665af53ee1b1903fc9ea719722aa5dfdc26325 Mon Sep 17 00:00:00 2001 From: Max Isom Date: Fri, 21 Jan 2022 19:57:51 -0600 Subject: Refine autocomplete --- src/commands/play.ts | 27 +++++++-- src/services/get-songs.ts | 4 +- src/utils/constants.ts | 2 + .../get-youtube-and-spotify-suggestions-for.ts | 70 ++++++++++++++++++++++ 4 files changed, 94 insertions(+), 9 deletions(-) create mode 100644 src/utils/constants.ts create mode 100644 src/utils/get-youtube-and-spotify-suggestions-for.ts (limited to 'src') diff --git a/src/commands/play.ts b/src/commands/play.ts index 7e5dee1..5ef4c1d 100644 --- a/src/commands/play.ts +++ b/src/commands/play.ts @@ -4,6 +4,7 @@ import {Except} from 'type-fest'; import {SlashCommandBuilder} from '@discordjs/builders'; import shuffle from 'array-shuffle'; import {inject, injectable} from 'inversify'; +import Spotify from 'spotify-web-api-node'; import Command from '.'; import {TYPES} from '../types.js'; import {QueuedSong, STATUS} from '../services/player.js'; @@ -12,7 +13,10 @@ import {getMostPopularVoiceChannel, getMemberVoiceChannel} from '../utils/channe import errorMsg from '../utils/error-msg.js'; import GetSongs from '../services/get-songs.js'; import {prisma} from '../utils/db.js'; -import getYouTubeSuggestionsFor from '../utils/get-youtube-suggestions-for.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'; @injectable() export default class implements Command { @@ -35,10 +39,14 @@ export default class implements Command { private readonly playerManager: PlayerManager; private readonly getSongs: GetSongs; + private readonly spotify: Spotify; + private readonly cache: KeyValueCacheProvider; - constructor(@inject(TYPES.Managers.Player) playerManager: PlayerManager, @inject(TYPES.Services.GetSongs) getSongs: GetSongs) { + constructor(@inject(TYPES.Managers.Player) playerManager: PlayerManager, @inject(TYPES.Services.GetSongs) getSongs: GetSongs, @inject(TYPES.ThirdParty) thirdParty: ThirdParty, @inject(TYPES.KeyValueCache) cache: KeyValueCacheProvider) { this.playerManager = playerManager; this.getSongs = getSongs; + this.spotify = thirdParty.spotify; + this.cache = cache; } // eslint-disable-next-line complexity @@ -201,9 +209,16 @@ export default class implements Command { return interaction.respond([]); } - await interaction.respond((await getYouTubeSuggestionsFor(query)).map(s => ({ - name: s, - value: s, - }))); + const suggestions = await this.cache.wrap( + getYouTubeAndSpotifySuggestionsFor, + query, + this.spotify, + 10, + { + expiresIn: ONE_HOUR_IN_SECONDS, + key: `autocomplete:${query}`, + }); + + await interaction.respond(suggestions); } } diff --git a/src/services/get-songs.ts b/src/services/get-songs.ts index 780f7ec..996a638 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 QueuedSongWithoutChannel = Except; -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/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/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 = (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 => { + 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; -- cgit v1.2.3 From 2e5e509b3233b1eb6c2b5834308d0cecfbb58634 Mon Sep 17 00:00:00 2001 From: Max Isom Date: Wed, 26 Jan 2022 22:30:58 -0500 Subject: Throw errors in command handlers --- src/commands/disconnect.ts | 8 +------- src/commands/fseek.ts | 29 ++++------------------------- src/commands/pause.ts | 7 +------ src/commands/remove.ts | 11 ++--------- src/commands/seek.ts | 19 +++---------------- src/commands/shuffle.ts | 7 +------ src/commands/skip.ts | 5 ++--- src/commands/unskip.ts | 6 +----- src/services/player.ts | 20 +++----------------- 9 files changed, 18 insertions(+), 94 deletions(-) (limited to 'src') diff --git a/src/commands/disconnect.ts b/src/commands/disconnect.ts index c63f9a2..4df76db 100644 --- a/src/commands/disconnect.ts +++ b/src/commands/disconnect.ts @@ -3,7 +3,6 @@ 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() @@ -24,12 +23,7 @@ export default class implements Command { const player = this.playerManager.get(interaction.guild!.id); if (!player.voiceConnection) { - await interaction.reply({ - content: errorMsg('not connected'), - ephemeral: true, - }); - - return; + throw new Error('not connected'); } player.disconnect(); diff --git a/src/commands/fseek.ts b/src/commands/fseek.ts index f4f1172..985a7c4 100644 --- a/src/commands/fseek.ts +++ b/src/commands/fseek.ts @@ -3,7 +3,6 @@ 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 '.'; import {prettyTime} from '../utils/time.js'; @@ -31,41 +30,21 @@ export default class implements Command { const currentSong = player.getCurrent(); if (!currentSong) { - await interaction.reply({ - content: errorMsg('nothing is playing'), - ephemeral: true, - }); - - return; + throw new Error('nothing is playing'); } if (currentSong.isLive) { - await interaction.reply({ - content: errorMsg('can\'t seek in a livestream'), - ephemeral: true, - }); - - return; + throw new Error('can\'t seek in a livestream'); } const seekTime = interaction.options.getNumber('seconds'); if (!seekTime) { - await interaction.reply({ - content: errorMsg('missing number of seconds to seek'), - ephemeral: true, - }); - - return; + throw new Error('missing number of seconds to seek'); } if (seekTime + player.getPosition() > currentSong.length) { - await interaction.reply({ - content: errorMsg('can\'t seek past the end of the song'), - ephemeral: true, - }); - - return; + throw new Error('can\'t seek past the end of the song'); } await Promise.all([ diff --git a/src/commands/pause.ts b/src/commands/pause.ts index 5d87b87..fc98bdf 100644 --- a/src/commands/pause.ts +++ b/src/commands/pause.ts @@ -4,7 +4,6 @@ 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() @@ -25,11 +24,7 @@ export default class implements Command { const player = this.playerManager.get(interaction.guild!.id); if (player.status !== STATUS.PLAYING) { - await interaction.reply({ - content: errorMsg('not currently playing'), - ephemeral: true, - }); - return; + throw new Error('not currently playing'); } player.pause(); diff --git a/src/commands/remove.ts b/src/commands/remove.ts index c58fbdf..55c416f 100644 --- a/src/commands/remove.ts +++ b/src/commands/remove.ts @@ -3,7 +3,6 @@ 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() @@ -34,17 +33,11 @@ export default class implements Command { const range = interaction.options.getInteger('range') ?? 1; if (position < 1) { - await interaction.reply({ - content: errorMsg('position must be greater than 0'), - ephemeral: true, - }); + throw new Error('position must be at least 1'); } if (range < 1) { - await interaction.reply({ - content: errorMsg('range must be greater than 0'), - ephemeral: true, - }); + throw new Error('range must be at least 1'); } player.removeFromQueue(position, range); diff --git a/src/commands/seek.ts b/src/commands/seek.ts index ecfde64..07f6590 100644 --- a/src/commands/seek.ts +++ b/src/commands/seek.ts @@ -2,7 +2,6 @@ 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 {parseTime, prettyTime} from '../utils/time.js'; import {SlashCommandBuilder} from '@discordjs/builders'; @@ -32,19 +31,11 @@ export default class implements Command { const currentSong = player.getCurrent(); if (!currentSong) { - await interaction.reply({ - content: errorMsg('nothing is playing'), - ephemeral: true, - }); - return; + throw new Error('nothing is playing'); } if (currentSong.isLive) { - await interaction.reply({ - content: errorMsg('can\'t seek in a livestream'), - ephemeral: true, - }); - return; + throw new Error('can\'t seek in a livestream'); } const time = interaction.options.getString('time')!; @@ -58,11 +49,7 @@ export default class implements Command { } if (seekTime > currentSong.length) { - await interaction.reply({ - content: errorMsg('can\'t seek past the end of the song'), - ephemeral: true, - }); - return; + throw new Error('can\'t seek past the end of the song'); } await Promise.all([ diff --git a/src/commands/shuffle.ts b/src/commands/shuffle.ts index 9c0a664..e27f1e2 100644 --- a/src/commands/shuffle.ts +++ b/src/commands/shuffle.ts @@ -2,7 +2,6 @@ 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'; @@ -24,11 +23,7 @@ export default class implements Command { const player = this.playerManager.get(interaction.guild!.id); if (player.isQueueEmpty()) { - await interaction.reply({ - content: errorMsg('not enough songs to shuffle'), - ephemeral: true, - }); - return; + throw new Error('not enough songs to shuffle'); } player.shuffle(); diff --git a/src/commands/skip.ts b/src/commands/skip.ts index cfcd605..4c51e77 100644 --- a/src/commands/skip.ts +++ b/src/commands/skip.ts @@ -3,7 +3,6 @@ import {TYPES} from '../types.js'; import {inject, injectable} from 'inversify'; import PlayerManager from '../managers/player.js'; import Command from '.'; -import errorMsg from '../utils/error-msg.js'; import {SlashCommandBuilder} from '@discordjs/builders'; import {buildPlayingMessageEmbed} from '../utils/build-embed.js'; @@ -29,7 +28,7 @@ export default class implements Command { const numToSkip = interaction.options.getInteger('skip') ?? 1; if (numToSkip < 1) { - await interaction.reply({content: errorMsg('invalid number of songs to skip'), ephemeral: true}); + throw new Error('invalid number of songs to skip'); } const player = this.playerManager.get(interaction.guild!.id); @@ -41,7 +40,7 @@ export default class implements Command { embeds: player.getCurrent() ? [buildPlayingMessageEmbed(player)] : [], }); } catch (_: unknown) { - await interaction.reply({content: errorMsg('no song to skip to'), ephemeral: true}); + throw new Error('no song to skip to'); } } } diff --git a/src/commands/unskip.ts b/src/commands/unskip.ts index b1947b8..17d6489 100644 --- a/src/commands/unskip.ts +++ b/src/commands/unskip.ts @@ -2,7 +2,6 @@ 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'; @@ -31,10 +30,7 @@ export default class implements Command { embeds: player.getCurrent() ? [buildPlayingMessageEmbed(player)] : [], }); } catch (_: unknown) { - await interaction.reply({ - content: errorMsg('no song to go back to'), - ephemeral: true, - }); + throw new Error('no song to go back to'); } } } diff --git a/src/services/player.ts b/src/services/player.ts index 9257d98..871b1c1 100644 --- a/src/services/player.ts +++ b/src/services/player.ts @@ -1,7 +1,5 @@ import {VoiceChannel, Snowflake, Client, TextChannel} from 'discord.js'; import {Readable} from 'stream'; -import EventEmitter from 'events'; -import TypedEmitter from 'typed-emitter'; import hasha from 'hasha'; import ytdl from 'ytdl-core'; import {WriteStream} from 'fs-capacitor'; @@ -37,8 +35,10 @@ export interface PlayerEvents { statusChange: (oldStatus: STATUS, newStatus: STATUS) => void; } -export default class extends (EventEmitter as new () => TypedEmitter) { +export default class { public voiceConnection: VoiceConnection | null = null; + public status = STATUS.PAUSED; + private queue: QueuedSong[] = []; private queuePosition = 0; private audioPlayer: AudioPlayer | null = null; @@ -47,14 +47,11 @@ export default class extends (EventEmitter as new () => TypedEmitter TypedEmitter Date: Wed, 26 Jan 2022 22:34:51 -0500 Subject: Remove natural langauge handlers --- src/inversify.config.ts | 2 - src/services/natural-language-commands.ts | 131 ------------------------------ 2 files changed, 133 deletions(-) delete mode 100644 src/services/natural-language-commands.ts (limited to 'src') diff --git a/src/inversify.config.ts b/src/inversify.config.ts index b2a18fb..a1187a9 100644 --- a/src/inversify.config.ts +++ b/src/inversify.config.ts @@ -10,7 +10,6 @@ import PlayerManager from './managers/player.js'; // Helpers import GetSongs from './services/get-songs.js'; -import NaturalLanguage from './services/natural-language-commands.js'; // Comands import Command from './commands'; @@ -48,7 +47,6 @@ container.bind(TYPES.Managers.Player).to(PlayerManager).inSinglet // Helpers container.bind(TYPES.Services.GetSongs).to(GetSongs).inSingletonScope(); -container.bind(TYPES.Services.NaturalLanguage).to(NaturalLanguage).inSingletonScope(); // Commands [ 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 { - 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 { - 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); - } - }); - } -} -- cgit v1.2.3 From 8e00726dc2c8179c7aa03f72e96544e78b4fb001 Mon Sep 17 00:00:00 2001 From: Max Isom Date: Thu, 27 Jan 2022 21:26:00 -0500 Subject: Add /favorites --- src/bot.ts | 30 ++++-- src/commands/favorites.ts | 191 +++++++++++++++++++++++++++++++++++ src/commands/index.ts | 6 +- src/commands/play.ts | 178 +++----------------------------- src/events/guild-create.ts | 103 ++----------------- src/inversify.config.ts | 8 +- src/managers/player.ts | 2 +- src/scripts/run-with-database-url.ts | 6 +- src/services/add-query-to-queue.ts | 155 ++++++++++++++++++++++++++++ src/services/player.ts | 4 +- src/types.ts | 2 +- 11 files changed, 409 insertions(+), 276 deletions(-) create mode 100644 src/commands/favorites.ts create mode 100644 src/services/add-query-to-queue.ts (limited to 'src') diff --git a/src/bot.ts b/src/bot.ts index f89fad5..3ba15bc 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -35,16 +35,25 @@ export default class { public async register(): Promise { // Load in commands - container.getAll(TYPES.Command).forEach(command => { - // TODO: remove ! - if (command.slashCommand?.name) { + for (const command of container.getAll(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 (command.slashCommand.name) { this.commandsByName.set(command.slashCommand.name, command); } if (command.handledButtonIds) { - command.handledButtonIds.forEach(id => this.commandsByButtonId.set(id, command)); + for (const buttonId of command.handledButtonIds) { + this.commandsByButtonId.set(buttonId, command); + } } - }); + } // Register event handlers this.client.on('interactionCreate', async interaction => { @@ -61,7 +70,9 @@ export default class { return; } - if (command.requiresVC && interaction.member && !isUserInVoice(interaction.guild, interaction.member.user as User)) { + 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; } @@ -122,13 +133,16 @@ export default class { } else { spinner.text = '📡 updating commands in all guilds...'; - await Promise.all( - this.client.guilds.cache.map(async guild => { + 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: []}), + ], ); } diff --git a/src/commands/favorites.ts b/src/commands/favorites.ts new file mode 100644 index 0000000..b15a5c9 --- /dev/null +++ b/src/commands/favorites.ts @@ -0,0 +1,191 @@ +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 query = interaction.options.getString('name')!.trim(); + + const favorites = await prisma.favoriteQuery.findMany({ + where: { + guildId: interaction.guild!.id, + }, + }); + + const names = favorites.map(favorite => favorite.name); + + const results = query === '' ? names : names.filter(name => name.startsWith(query)); + + await interaction.respond(results.map(r => ({ + name: r, + value: r, + }))); + } + + 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/index.ts b/src/commands/index.ts index 1d1646f..02349d2 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -1,10 +1,10 @@ -import {SlashCommandBuilder} from '@discordjs/builders'; +import {SlashCommandBuilder, SlashCommandSubcommandsOnlyBuilder} from '@discordjs/builders'; import {AutocompleteInteraction, ButtonInteraction, CommandInteraction} from 'discord.js'; export default interface Command { - readonly slashCommand: Partial & Pick; + readonly slashCommand: Partial & Pick; readonly handledButtonIds?: readonly string[]; - readonly requiresVC?: boolean; + readonly requiresVC?: boolean | ((interaction: CommandInteraction) => boolean); execute: (interaction: CommandInteraction) => Promise; handleButtonInteraction?: (interaction: ButtonInteraction) => Promise; handleAutocompleteInteraction?: (interaction: AutocompleteInteraction) => Promise; diff --git a/src/commands/play.ts b/src/commands/play.ts index d1ab940..e8d565c 100644 --- a/src/commands/play.ts +++ b/src/commands/play.ts @@ -1,22 +1,15 @@ -import {AutocompleteInteraction, CommandInteraction, GuildMember} from 'discord.js'; +import {AutocompleteInteraction, CommandInteraction} from 'discord.js'; import {URL} from 'url'; -import {Except} from 'type-fest'; import {SlashCommandBuilder} from '@discordjs/builders'; -import shuffle from 'array-shuffle'; import {inject, injectable} from 'inversify'; import Spotify from 'spotify-web-api-node'; import Command from '.'; import {TYPES} from '../types.js'; -import {QueuedSong, STATUS} from '../services/player.js'; -import PlayerManager from '../managers/player.js'; -import {getMostPopularVoiceChannel, getMemberVoiceChannel} from '../utils/channels.js'; -import GetSongs from '../services/get-songs.js'; -import {prisma} from '../utils/db.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 {buildPlayingMessageEmbed} from '../utils/build-embed.js'; +import AddQueryToQueue from '../services/add-query-to-queue.js'; @injectable() export default class implements Command { @@ -30,178 +23,31 @@ export default class implements Command { .setAutocomplete(true)) .addBooleanOption(option => option .setName('immediate') - .setDescription('adds track to the front of the queue')) + .setDescription('add track to the front of the queue')) .addBooleanOption(option => option .setName('shuffle') - .setDescription('shuffles the input if it\'s a playlist')); + .setDescription('shuffle the input if you\'re adding multiple tracks')); public requiresVC = true; - private readonly playerManager: PlayerManager; - private readonly getSongs: GetSongs; private readonly spotify: Spotify; private readonly cache: KeyValueCacheProvider; + private readonly addQueryToQueue: AddQueryToQueue; - constructor(@inject(TYPES.Managers.Player) playerManager: PlayerManager, @inject(TYPES.Services.GetSongs) getSongs: GetSongs, @inject(TYPES.ThirdParty) thirdParty: ThirdParty, @inject(TYPES.KeyValueCache) cache: KeyValueCacheProvider) { - this.playerManager = playerManager; - this.getSongs = getSongs; + constructor(@inject(TYPES.ThirdParty) thirdParty: ThirdParty, @inject(TYPES.KeyValueCache) cache: KeyValueCacheProvider, @inject(TYPES.Services.AddQueryToQueue) addQueryToQueue: AddQueryToQueue) { this.spotify = thirdParty.spotify; this.cache = cache; + this.addQueryToQueue = addQueryToQueue; } // eslint-disable-next-line complexity public async execute(interaction: CommandInteraction): Promise { - const [targetVoiceChannel] = getMemberVoiceChannel(interaction.member as GuildMember) ?? getMostPopularVoiceChannel(interaction.guild!); - - const settings = await prisma.setting.findUnique({where: {guildId: interaction.guild!.id}}); - - if (!settings) { - throw new Error('Could not find settings for guild'); - } - - const {playlistLimit} = settings; - - const player = this.playerManager.get(interaction.guild!.id); - const wasPlayingSong = player.getCurrent() !== null; - - const query = interaction.options.getString('query'); - - if (!query) { - if (player.status === STATUS.PLAYING) { - throw new Error('already playing, give me a song name'); - } - - // Must be resuming play - if (!wasPlayingSong) { - throw new Error('nothing to play'); - } - - await player.connect(targetVoiceChannel); - await player.play(); - - await interaction.reply({ - content: 'the stop-and-go light is now green', - embeds: [buildPlayingMessageEmbed(player)], - }); - - return; - } - - const addToFrontOfQueue = interaction.options.getBoolean('immediate'); - const shuffleAdditions = interaction.options.getBoolean('shuffle'); - - await interaction.deferReply(); - - let newSongs: Array> = []; - 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}); + await this.addQueryToQueue.addToQueue({ + interaction, + query: interaction.options.getString('query')!.trim(), + addToFrontOfQueue: interaction.options.getBoolean('immediate') ?? false, + shuffleAdditions: interaction.options.getBoolean('shuffle') ?? 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}`); - } } public async handleAutocompleteInteraction(interaction: AutocompleteInteraction): Promise { diff --git a/src/events/guild-create.ts b/src/events/guild-create.ts index 3cf94ea..8db7e2f 100644 --- a/src/events/guild-create.ts +++ b/src/events/guild-create.ts @@ -1,15 +1,11 @@ -import {Guild, TextChannel, Message, MessageReaction, User, ApplicationCommandData, -} 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 => { await prisma.setting.upsert({ @@ -18,99 +14,22 @@ export default async (guild: Guild): Promise => { }, create: { guildId: guild.id, - prefix: DEFAULT_PREFIX, - }, - update: { - prefix: DEFAULT_PREFIX, }, + update: {}, }); const config = container.get(TYPES.Config); // Setup slash commands if (!config.REGISTER_COMMANDS_ON_BOT) { - const commands: ApplicationCommandData[] = container.getAll(TYPES.Command) - .filter(command => command.slashCommand?.name) - .map(command => command.slashCommand as ApplicationCommandData); - - await guild.commands.set(commands); - } - - const owner = await guild.client.users.fetch(guild.ownerId); - - 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'; - - const firstStepMsg = await owner.send(firstStep); - - // Show emoji selector - interface EmojiChannel { - name: string; - id: string; - emoji: string; - } + const token = container.get(TYPES.Config).DISCORD_TOKEN; + const client = container.get(TYPES.Client); - const emojiChannels: EmojiChannel[] = []; + const rest = new REST({version: '9'}).setToken(token); - for (const [channelId, channel] of guild.channels.cache) { - if (channel.type === 'GUILD_TEXT') { - emojiChannels.push({ - name: channel.name, - id: channelId, - emoji: emoji.random().emoji, - }); - } + await rest.put( + Routes.applicationGuildCommands(client.user!.id, guild.id), + {body: container.getAll(TYPES.Command).map(command => command.slashCommand.toJSON())}, + ); } - - 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 \`\\play https://www.youtube.com/watch?v=dQw4w9WgXcQ\``); - - await firstStepMsg.channel.send(`Sounds good. Check out **#${chosenChannel.name}** to get started.`); }; diff --git a/src/inversify.config.ts b/src/inversify.config.ts index a1187a9..f423614 100644 --- a/src/inversify.config.ts +++ b/src/inversify.config.ts @@ -8,13 +8,15 @@ 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'; // Comands import Command from './commands'; import Clear from './commands/clear.js'; import Disconnect from './commands/disconnect.js'; +import Favorites from './commands/favorites.js'; import ForwardSeek from './commands/fseek.js'; import Pause from './commands/pause.js'; import Play from './commands/play.js'; @@ -45,13 +47,15 @@ container.bind(TYPES.Client).toConstantValue(new Client({intents})); // Managers container.bind(TYPES.Managers.Player).to(PlayerManager).inSingletonScope(); -// Helpers +// Services container.bind(TYPES.Services.GetSongs).to(GetSongs).inSingletonScope(); +container.bind(TYPES.Services.AddQueryToQueue).to(AddQueryToQueue).inSingletonScope(); // Commands [ Clear, Disconnect, + Favorites, ForwardSeek, Pause, Play, diff --git a/src/managers/player.ts b/src/managers/player.ts index 5d816b8..218a0b2 100644 --- a/src/managers/player.ts +++ b/src/managers/player.ts @@ -20,7 +20,7 @@ export default class { let player = this.guildPlayers.get(guildId); if (!player) { - player = new Player(this.discordClient, this.fileCache); + player = new Player(this.discordClient, 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 { + 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> = []; + 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/player.ts b/src/services/player.ts index 871b1c1..8255119 100644 --- a/src/services/player.ts +++ b/src/services/player.ts @@ -38,6 +38,7 @@ export interface PlayerEvents { export default class { public voiceConnection: VoiceConnection | null = null; public status = STATUS.PAUSED; + public guildId: string; private queue: QueuedSong[] = []; private queuePosition = 0; @@ -51,9 +52,10 @@ export default class { private readonly discordClient: Client; private readonly fileCache: FileCacheProvider; - constructor(client: Client, fileCache: FileCacheProvider) { + constructor(client: Client, fileCache: FileCacheProvider, guildId: string) { this.discordClient = client; this.fileCache = fileCache; + this.guildId = guildId; } async connect(channel: VoiceChannel): Promise { diff --git a/src/types.ts b/src/types.ts index 19c734d..47108b9 100644 --- a/src/types.ts +++ b/src/types.ts @@ -11,7 +11,7 @@ export const TYPES = { UpdatingQueueEmbed: Symbol('UpdatingQueueEmbed'), }, Services: { + AddQueryToQueue: Symbol('AddQueryToQueue'), GetSongs: Symbol('GetSongs'), - NaturalLanguage: Symbol('NaturalLanguage'), }, }; -- cgit v1.2.3 From 1621b2c2815f7458df19320361a4a5a41c9cf4d3 Mon Sep 17 00:00:00 2001 From: Max Isom Date: Sat, 29 Jan 2022 11:20:40 -0500 Subject: Add permissions system --- src/bot.ts | 5 ++ src/commands/config.ts | 103 ++++++++++++++++++++++++++++++ src/commands/favorites.ts | 12 ++-- src/inversify.config.ts | 2 + src/utils/update-permissions-for-guild.ts | 44 +++++++++++++ 5 files changed, 162 insertions(+), 4 deletions(-) create mode 100644 src/commands/config.ts create mode 100644 src/utils/update-permissions-for-guild.ts (limited to 'src') diff --git a/src/bot.ts b/src/bot.ts index 3ba15bc..d6bf02f 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -13,6 +13,7 @@ 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 { @@ -146,6 +147,10 @@ export default class { ); } + // 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=2184236096`); }); diff --git a/src/commands/config.ts b/src/commands/config.ts new file mode 100644 index 0000000..65aa36b --- /dev/null +++ b/src/commands/config.ts @@ -0,0 +1,103 @@ +import {SlashCommandBuilder} from '@discordjs/builders'; +import {CommandInteraction, MessageEmbed} from 'discord.js'; +import {injectable} from 'inversify'; +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 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'); + } + + await prisma.setting.update({ + where: { + guildId: interaction.guild!.id, + }, + data: { + playlistLimit: limit, + }, + }); + + await interaction.reply('👍 limit updated'); + + break; + } + + case 'set-role': { + const role = interaction.options.getRole('role')!; + + await prisma.setting.update({ + where: { + guildId: interaction.guild!.id, + }, + data: { + roleId: role.id, + }, + }); + + await updatePermissionsForGuild(interaction.guild!); + + await interaction.reply('👍 role updated'); + + break; + } + + case 'get': { + const embed = new MessageEmbed().setTitle('Config'); + + const config = await prisma.setting.findUnique({where: {guildId: interaction.guild!.id}}); + + if (!config) { + throw new Error('no config found'); + } + + const settingsToShow = { + 'Playlist Limit': config.playlistLimit, + Role: config.roleId ? `<@&${config.roleId}>` : 'not set', + }; + + let description = ''; + for (const [key, value] of Object.entries(settingsToShow)) { + description += `**${key}**: ${value}\n`; + } + + embed.setDescription(description); + + await interaction.reply({embeds: [embed]}); + + break; + } + + default: + throw new Error('unknown subcommand'); + } + } +} diff --git a/src/commands/favorites.ts b/src/commands/favorites.ts index b15a5c9..98f1ba9 100644 --- a/src/commands/favorites.ts +++ b/src/commands/favorites.ts @@ -75,6 +75,7 @@ export default class implements Command { } async handleAutocompleteInteraction(interaction: AutocompleteInteraction) { + const subcommand = interaction.options.getSubcommand(); const query = interaction.options.getString('name')!.trim(); const favorites = await prisma.favoriteQuery.findMany({ @@ -83,13 +84,16 @@ export default class implements Command { }, }); - const names = favorites.map(favorite => favorite.name); + let results = query === '' ? favorites : favorites.filter(f => f.name.startsWith(query)); - const results = query === '' ? names : names.filter(name => 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, - value: r, + name: r.name, + value: r.name, }))); } diff --git a/src/inversify.config.ts b/src/inversify.config.ts index f423614..d29d3de 100644 --- a/src/inversify.config.ts +++ b/src/inversify.config.ts @@ -15,6 +15,7 @@ import GetSongs from './services/get-songs.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'; @@ -54,6 +55,7 @@ container.bind(TYPES.Services.AddQueryToQueue).to(AddQueryToQue // Commands [ Clear, + Config, Disconnect, Favorites, ForwardSeek, 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; -- cgit v1.2.3 From fc5c1ee002260335971855eb31589d5aed25620a Mon Sep 17 00:00:00 2001 From: Max Isom Date: Sat, 29 Jan 2022 11:27:39 -0500 Subject: Handle ownership transfer events --- src/bot.ts | 2 ++ src/events/handle-guild-update.ts | 10 ++++++++++ 2 files changed, 12 insertions(+) create mode 100644 src/events/handle-guild-update.ts (limited to 'src') diff --git a/src/bot.ts b/src/bot.ts index d6bf02f..29cf818 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -14,6 +14,7 @@ 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'; +import handleGuildUpdate from './events/handle-guild-update.js'; @injectable() export default class { @@ -159,6 +160,7 @@ export default class { this.client.on('guildCreate', handleGuildCreate); this.client.on('voiceStateUpdate', handleVoiceStateUpdate); + this.client.on('guildUpdate', handleGuildUpdate); await this.client.login(this.token); } diff --git a/src/events/handle-guild-update.ts b/src/events/handle-guild-update.ts new file mode 100644 index 0000000..837bbbe --- /dev/null +++ b/src/events/handle-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; -- cgit v1.2.3 From d6c9d4b1128c5cddda74b3a84575388670edf221 Mon Sep 17 00:00:00 2001 From: Max Isom Date: Sat, 29 Jan 2022 11:36:24 -0500 Subject: Update invite permissions, send message to owner --- src/bot.ts | 4 ++-- src/events/guild-create.ts | 4 ++++ src/events/guild-update.ts | 10 ++++++++++ src/events/handle-guild-update.ts | 10 ---------- 4 files changed, 16 insertions(+), 12 deletions(-) create mode 100644 src/events/guild-update.ts delete mode 100644 src/events/handle-guild-update.ts (limited to 'src') diff --git a/src/bot.ts b/src/bot.ts index 29cf818..0a041ec 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -7,6 +7,7 @@ import Command from './commands/index.js'; import debug from './utils/debug.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'; @@ -14,7 +15,6 @@ 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'; -import handleGuildUpdate from './events/handle-guild-update.js'; @injectable() export default class { @@ -152,7 +152,7 @@ export default class { 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=2184236096`); + 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); diff --git a/src/events/guild-create.ts b/src/events/guild-create.ts index 8db7e2f..630d6cb 100644 --- a/src/events/guild-create.ts +++ b/src/events/guild-create.ts @@ -32,4 +32,8 @@ export default async (guild: Guild): Promise => { {body: container.getAll(TYPES.Command).map(command => command.slashCommand.toJSON())}, ); } + + const owner = await guild.fetchOwner(); + + 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/events/handle-guild-update.ts b/src/events/handle-guild-update.ts deleted file mode 100644 index 837bbbe..0000000 --- a/src/events/handle-guild-update.ts +++ /dev/null @@ -1,10 +0,0 @@ -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; -- cgit v1.2.3 From 6eb704c5b4f7a92e254f14eab962ac8bc76a081b Mon Sep 17 00:00:00 2001 From: Max Isom Date: Sat, 29 Jan 2022 12:06:11 -0500 Subject: Fix resume playback bug --- src/commands/play.ts | 38 +++++++++++++++++++++++++++++++++++--- src/utils/log-banner.ts | 1 + 2 files changed, 36 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/commands/play.ts b/src/commands/play.ts index e8d565c..2d2fc6d 100644 --- a/src/commands/play.ts +++ b/src/commands/play.ts @@ -1,4 +1,4 @@ -import {AutocompleteInteraction, CommandInteraction} from 'discord.js'; +import {AutocompleteInteraction, CommandInteraction, GuildMember} from 'discord.js'; import {URL} from 'url'; import {SlashCommandBuilder} from '@discordjs/builders'; import {inject, injectable} from 'inversify'; @@ -10,6 +10,10 @@ import getYouTubeAndSpotifySuggestionsFor from '../utils/get-youtube-and-spotify 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 { @@ -33,18 +37,46 @@ export default class implements Command { private readonly spotify: Spotify; private readonly cache: KeyValueCacheProvider; private readonly addQueryToQueue: AddQueryToQueue; + private readonly playerManager: PlayerManager; - constructor(@inject(TYPES.ThirdParty) thirdParty: ThirdParty, @inject(TYPES.KeyValueCache) cache: KeyValueCacheProvider, @inject(TYPES.Services.AddQueryToQueue) addQueryToQueue: AddQueryToQueue) { + 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; } // eslint-disable-next-line complexity public async execute(interaction: CommandInteraction): Promise { + const query = interaction.options.getString('query'); + + const player = this.playerManager.get(interaction.guild!.id); + const [targetVoiceChannel] = getMemberVoiceChannel(interaction.member as GuildMember) ?? getMostPopularVoiceChannel(interaction.guild!); + + if (!query) { + if (player.status === STATUS.PLAYING) { + throw new Error('already playing, give me a song name'); + } + + // Must be resuming play + if (!player.getCurrent()) { + throw new Error('nothing to play'); + } + + await player.connect(targetVoiceChannel); + await player.play(); + + await interaction.reply({ + content: 'the stop-and-go light is now green', + embeds: [buildPlayingMessageEmbed(player)], + }); + + return; + } + await this.addQueryToQueue.addToQueue({ interaction, - query: interaction.options.getString('query')!.trim(), + query: query.trim(), addToFrontOfQueue: interaction.options.getBoolean('immediate') ?? false, shuffleAdditions: interaction.options.getBoolean('shuffle') ?? false, }); 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'); }; -- cgit v1.2.3 From 9d8275bbdaeb68cd5013696ef5962b0e7b04a12c Mon Sep 17 00:00:00 2001 From: Max Isom Date: Sat, 29 Jan 2022 20:12:21 -0500 Subject: Bump packages, add debug logging --- src/managers/player.ts | 7 ++----- src/services/player.ts | 21 +++++++++++---------- 2 files changed, 13 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/managers/player.ts b/src/managers/player.ts index 218a0b2..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; - 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, guildId); + player = new Player(this.fileCache, guildId); this.guildPlayers.set(guildId, player); } diff --git a/src/services/player.ts b/src/services/player.ts index 8255119..47b3cb8 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; @@ -49,11 +49,9 @@ export default class { private positionInSeconds = 0; - private readonly discordClient: Client; private readonly fileCache: FileCacheProvider; - constructor(client: Client, fileCache: FileCacheProvider, guildId: string) { - this.discordClient = client; + constructor(fileCache: FileCacheProvider, guildId: string) { this.fileCache = fileCache; this.guildId = guildId; } @@ -62,7 +60,6 @@ export default class { const conn = joinVoiceChannel({ channelId: channel.id, guildId: channel.guild.id, - // @ts-expect-error (see https://github.com/discordjs/voice/issues/166) adapterCreator: channel.guild.voiceAdapterCreator, }); @@ -150,9 +147,11 @@ export default class { const stream = await this.getStream(currentSong.url); this.audioPlayer = createAudioPlayer(); 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 +166,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; } } @@ -405,6 +403,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); -- cgit v1.2.3 From 967de2fd91b56d441d6e2239e09bd5f904937c11 Mon Sep 17 00:00:00 2001 From: Max Isom Date: Sat, 5 Feb 2022 17:10:12 -0500 Subject: Consistent verb tense --- src/commands/disconnect.ts | 2 +- src/commands/favorites.ts | 2 +- src/commands/pause.ts | 2 +- src/commands/play.ts | 1 - src/commands/shuffle.ts | 2 +- src/commands/skip.ts | 2 +- src/commands/unskip.ts | 2 +- 7 files changed, 6 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/commands/disconnect.ts b/src/commands/disconnect.ts index 4df76db..fd6b984 100644 --- a/src/commands/disconnect.ts +++ b/src/commands/disconnect.ts @@ -9,7 +9,7 @@ import Command from '.'; export default class implements Command { public readonly slashCommand = new SlashCommandBuilder() .setName('disconnect') - .setDescription('pauses and disconnects player'); + .setDescription('pause and disconnect Muse'); public requiresVC = true; diff --git a/src/commands/favorites.ts b/src/commands/favorites.ts index 98f1ba9..4dbf943 100644 --- a/src/commands/favorites.ts +++ b/src/commands/favorites.ts @@ -10,7 +10,7 @@ import {prisma} from '../utils/db.js'; export default class implements Command { public readonly slashCommand = new SlashCommandBuilder() .setName('favorites') - .setDescription('adds a song to your favorites') + .setDescription('add a song to your favorites') .addSubcommand(subcommand => subcommand .setName('use') .setDescription('use a favorite') diff --git a/src/commands/pause.ts b/src/commands/pause.ts index fc98bdf..7b9d295 100644 --- a/src/commands/pause.ts +++ b/src/commands/pause.ts @@ -10,7 +10,7 @@ import Command from '.'; export default class implements Command { public readonly slashCommand = new SlashCommandBuilder() .setName('pause') - .setDescription('pauses the current song'); + .setDescription('pause the current song'); public requiresVC = true; diff --git a/src/commands/play.ts b/src/commands/play.ts index 2d2fc6d..08436c2 100644 --- a/src/commands/play.ts +++ b/src/commands/play.ts @@ -19,7 +19,6 @@ import {getMemberVoiceChannel, getMostPopularVoiceChannel} from '../utils/channe export default class implements Command { 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') diff --git a/src/commands/shuffle.ts b/src/commands/shuffle.ts index e27f1e2..819c01c 100644 --- a/src/commands/shuffle.ts +++ b/src/commands/shuffle.ts @@ -9,7 +9,7 @@ import {SlashCommandBuilder} from '@discordjs/builders'; export default class implements Command { public readonly slashCommand = new SlashCommandBuilder() .setName('shuffle') - .setDescription('shuffles the current queue'); + .setDescription('shuffle the current queue'); public requiresVC = true; diff --git a/src/commands/skip.ts b/src/commands/skip.ts index 4c51e77..a580775 100644 --- a/src/commands/skip.ts +++ b/src/commands/skip.ts @@ -10,7 +10,7 @@ import {buildPlayingMessageEmbed} from '../utils/build-embed.js'; export default class implements Command { public readonly slashCommand = new SlashCommandBuilder() .setName('skip') - .setDescription('skips the next songs') + .setDescription('skip the next songs') .addIntegerOption(option => option .setName('number') .setDescription('number of songs to skip [default: 1]') diff --git a/src/commands/unskip.ts b/src/commands/unskip.ts index 17d6489..936f4ef 100644 --- a/src/commands/unskip.ts +++ b/src/commands/unskip.ts @@ -10,7 +10,7 @@ import {buildPlayingMessageEmbed} from '../utils/build-embed.js'; export default class implements Command { public readonly slashCommand = new SlashCommandBuilder() .setName('unskip') - .setDescription('goes back in the queue by one song'); + .setDescription('go back in the queue by one song'); public requiresVC = true; -- cgit v1.2.3