aboutsummaryrefslogtreecommitdiff
path: root/src/commands
diff options
context:
space:
mode:
authorMax Isom <[email protected]>2022-01-27 21:26:00 -0500
committerMax Isom <[email protected]>2022-01-27 21:26:00 -0500
commit8e00726dc2c8179c7aa03f72e96544e78b4fb001 (patch)
tree621d7cc0a23a719a06654cfaad63a368aebe28d6 /src/commands
parent1f59994dc4bde748092f0286a8f303972be19785 (diff)
downloadmuse-8e00726dc2c8179c7aa03f72e96544e78b4fb001.tar.xz
muse-8e00726dc2c8179c7aa03f72e96544e78b4fb001.zip
Add /favorites
Diffstat (limited to 'src/commands')
-rw-r--r--src/commands/favorites.ts191
-rw-r--r--src/commands/index.ts6
-rw-r--r--src/commands/play.ts178
3 files changed, 206 insertions, 169 deletions
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<SlashCommandBuilder> & Pick<SlashCommandBuilder, 'toJSON'>;
+ readonly slashCommand: Partial<SlashCommandBuilder | SlashCommandSubcommandsOnlyBuilder> & Pick<SlashCommandBuilder, 'toJSON'>;
readonly handledButtonIds?: readonly string[];
- readonly requiresVC?: boolean;
+ readonly requiresVC?: boolean | ((interaction: CommandInteraction) => boolean);
execute: (interaction: CommandInteraction) => Promise<void>;
handleButtonInteraction?: (interaction: ButtonInteraction) => Promise<void>;
handleAutocompleteInteraction?: (interaction: AutocompleteInteraction) => Promise<void>;
diff --git a/src/commands/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<void> {
- 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<Except<QueuedSong, 'addedInChannelId' | 'requestedBy'>> = [];
- let extraMsg = '';
-
- // Test if it's a complete URL
- try {
- const url = new URL(query);
-
- const YOUTUBE_HOSTS = [
- 'www.youtube.com',
- 'youtu.be',
- 'youtube.com',
- 'music.youtube.com',
- 'www.music.youtube.com',
- ];
-
- if (YOUTUBE_HOSTS.includes(url.host)) {
- // YouTube source
- if (url.searchParams.get('list')) {
- // YouTube playlist
- newSongs.push(...await this.getSongs.youtubePlaylist(url.searchParams.get('list')!));
- } else {
- const song = await this.getSongs.youtubeVideo(url.href);
-
- if (song) {
- newSongs.push(song);
- } else {
- throw new Error('that doesn\'t exist');
- }
- }
- } else if (url.protocol === 'spotify:' || url.host === 'open.spotify.com') {
- const [convertedSongs, nSongsNotFound, totalSongs] = await this.getSongs.spotifySource(query, playlistLimit);
-
- if (totalSongs > playlistLimit) {
- extraMsg = `a random sample of ${playlistLimit} songs was taken`;
- }
-
- if (totalSongs > playlistLimit && nSongsNotFound !== 0) {
- extraMsg += ' and ';
- }
-
- if (nSongsNotFound !== 0) {
- if (nSongsNotFound === 1) {
- extraMsg += '1 song was not found';
- } else {
- extraMsg += `${nSongsNotFound.toString()} songs were not found`;
- }
- }
-
- newSongs.push(...convertedSongs);
- }
- } catch (_: unknown) {
- // Not a URL, must search YouTube
- const song = await this.getSongs.youtubeVideoSearch(query);
-
- if (song) {
- newSongs.push(song);
- } else {
- throw new Error('that doesn\'t exist');
- }
- }
-
- if (newSongs.length === 0) {
- throw new Error('no songs found');
- }
-
- if (shuffleAdditions) {
- newSongs = shuffle(newSongs);
- }
-
- newSongs.forEach(song => {
- player.add({...song, addedInChannelId: interaction.channel!.id, requestedBy: interaction.member!.user.id}, {immediate: addToFrontOfQueue ?? false});
+ 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<void> {