diff options
| author | Max Isom <[email protected]> | 2021-12-12 20:22:21 -0500 |
|---|---|---|
| committer | Max Isom <[email protected]> | 2021-12-12 20:22:21 -0500 |
| commit | dcb1351791e23165b23a8b549aabbb38294f55a5 (patch) | |
| tree | 4f195076d33bb8886461cb7520f3810a1a143869 /src | |
| parent | fa4ba0bb9acd1c5208c1ff844823706b26f56165 (diff) | |
| download | muse-dcb1351791e23165b23a8b549aabbb38294f55a5.tar.xz muse-dcb1351791e23165b23a8b549aabbb38294f55a5.zip | |
Migrate play command to slash command
Diffstat (limited to 'src')
| -rw-r--r-- | src/bot.ts | 90 | ||||
| -rw-r--r-- | src/commands/help.ts | 66 | ||||
| -rw-r--r-- | src/commands/index.ts | 13 | ||||
| -rw-r--r-- | src/commands/play.ts | 72 | ||||
| -rw-r--r-- | src/inversify.config.ts | 2 | ||||
| -rw-r--r-- | src/services/player.ts | 2 |
6 files changed, 76 insertions, 169 deletions
@@ -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<string, Command>; - 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<string> { + public async listen(): Promise<void> { // Load in commands container.getAll<Command>(TYPES.Command).forEach(command => { - const commandNames = [command.name, ...command.aliases]; - - commandNames.forEach(commandName => this.commands.set(commandName, command)); - }); - - this.client.on('messageCreate', async (msg: Message) => { - // Get guild settings - if (!msg.guild) { - return; + // 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<void> { - if (this.commands.length === 0) { - // Lazy load to avoid circular dependencies - this.commands = container.getAll<Command>(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<SlashCommandBuilder> & Pick<SlashCommandBuilder, 'toJSON'>; requiresVC?: boolean; - execute: (msg: Message, args: string[]) => Promise<void>; + executeFromInteraction?: (interaction: CommandInteraction) => Promise<void>; } 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<void> { - 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<void> { + 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<Except<QueuedSong, 'addedInChannelId'>> = []; 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<NaturalLanguage>(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 { |
