aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorBobby <[email protected]>2024-11-06 09:42:25 -0500
committerGitHub <[email protected]>2024-11-06 09:42:25 -0500
commitd92fd2a29796c9c5d6ddeb9718bf6fcd6ee5958a (patch)
tree81961cc995661448794669617f1ed439cbe84a3d /src
parentb605bf220859acd767533e0ab9436ced771bb8e2 (diff)
parent716d6d9f4f2cd1a6872e463e9877203a259478a3 (diff)
downloadmuse-d92fd2a29796c9c5d6ddeb9718bf6fcd6ee5958a.tar.xz
muse-d92fd2a29796c9c5d6ddeb9718bf6fcd6ee5958a.zip
Merge branch 'museofficial:master' into masterHEADmaster
Diffstat (limited to 'src')
-rw-r--r--src/commands/config.ts78
-rw-r--r--src/commands/play.ts56
-rw-r--r--src/commands/queue.ts19
-rw-r--r--src/inversify.config.ts16
-rw-r--r--src/services/add-query-to-queue.ts70
-rw-r--r--src/services/config.ts6
-rw-r--r--src/services/get-songs.ts102
-rw-r--r--src/services/player.ts66
-rw-r--r--src/services/youtube-api.ts2
-rw-r--r--src/utils/build-embed.ts10
-rw-r--r--src/utils/get-youtube-and-spotify-suggestions-for.ts79
11 files changed, 348 insertions, 156 deletions
diff --git a/src/commands/config.ts b/src/commands/config.ts
index f866e82..01d9fe9 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -41,6 +41,22 @@ export default class implements Command {
.setDescription('whether bot responses to queue additions are only displayed to the requester')
.setRequired(true)))
.addSubcommand(subcommand => subcommand
+ .setName('set-reduce-vol-when-voice')
+ .setDescription('set whether to turn down the volume when people speak')
+ .addBooleanOption(option => option
+ .setName('value')
+ .setDescription('whether to turn down the volume when people speak')
+ .setRequired(true)))
+ .addSubcommand(subcommand => subcommand
+ .setName('set-reduce-vol-when-voice-target')
+ .setDescription('set the target volume when people speak')
+ .addIntegerOption(option => option
+ .setName('volume')
+ .setDescription('volume percentage (0 is muted, 100 is max & default)')
+ .setMinValue(0)
+ .setMaxValue(100)
+ .setRequired(true)))
+ .addSubcommand(subcommand => subcommand
.setName('set-auto-announce-next-song')
.setDescription('set whether to announce the next song in the queue automatically')
.addBooleanOption(option => option
@@ -57,6 +73,15 @@ export default class implements Command {
.setMaxValue(100)
.setRequired(true)))
.addSubcommand(subcommand => subcommand
+ .setName('set-default-queue-page-size')
+ .setDescription('set the default page size of the /queue command')
+ .addIntegerOption(option => option
+ .setName('page-size')
+ .setDescription('page size of the /queue command')
+ .setMinValue(1)
+ .setMaxValue(30)
+ .setRequired(true)))
+ .addSubcommand(subcommand => subcommand
.setName('get')
.setDescription('show all settings'));
@@ -171,6 +196,57 @@ export default class implements Command {
break;
}
+ case 'set-default-queue-page-size': {
+ const value = interaction.options.getInteger('page-size')!;
+
+ await prisma.setting.update({
+ where: {
+ guildId: interaction.guild!.id,
+ },
+ data: {
+ defaultQueuePageSize: value,
+ },
+ });
+
+ await interaction.reply('👍 default queue page size updated');
+
+ break;
+ }
+
+ case 'set-reduce-vol-when-voice': {
+ const value = interaction.options.getBoolean('value')!;
+
+ await prisma.setting.update({
+ where: {
+ guildId: interaction.guild!.id,
+ },
+ data: {
+ turnDownVolumeWhenPeopleSpeak: value,
+ },
+ });
+
+ await interaction.reply('👍 turn down volume setting updated');
+
+ break;
+ }
+
+ case 'set-reduce-vol-when-voice-target': {
+ const value = interaction.options.getInteger('volume')!;
+
+ await prisma.setting.update({
+ where: {
+ guildId: interaction.guild!.id,
+ },
+ data: {
+ turnDownVolumeWhenPeopleSpeakTarget: value,
+ },
+ });
+
+ await interaction.reply('👍 turn down volume target setting updated');
+
+ break;
+ }
+
case 'get': {
const embed = new EmbedBuilder().setTitle('Config');
@@ -185,6 +261,8 @@ export default class implements Command {
'Auto announce next song in queue': config.autoAnnounceNextSong ? 'yes' : 'no',
'Add to queue reponses show for requester only': config.autoAnnounceNextSong ? 'yes' : 'no',
'Default Volume': config.defaultVolume,
+ 'Default queue page size': config.defaultQueuePageSize,
+ 'Reduce volume when people speak': config.turnDownVolumeWhenPeopleSpeak ? 'yes' : 'no',
};
let description = '';
diff --git a/src/commands/play.ts b/src/commands/play.ts
index 25aef1c..c87ccd5 100644
--- a/src/commands/play.ts
+++ b/src/commands/play.ts
@@ -1,7 +1,7 @@
import {AutocompleteInteraction, ChatInputCommandInteraction} from 'discord.js';
import {URL} from 'url';
-import {SlashCommandBuilder} from '@discordjs/builders';
-import {inject, injectable} from 'inversify';
+import {SlashCommandBuilder, SlashCommandSubcommandsOnlyBuilder} from '@discordjs/builders';
+import {inject, injectable, optional} from 'inversify';
import Spotify from 'spotify-web-api-node';
import Command from './index.js';
import {TYPES} from '../types.js';
@@ -13,37 +13,43 @@ import AddQueryToQueue from '../services/add-query-to-queue.js';
@injectable()
export default class implements Command {
- public readonly slashCommand = new SlashCommandBuilder()
- .setName('play')
- .setDescription('play a song')
- .addStringOption(option => option
- .setName('query')
- .setDescription('YouTube URL, Spotify URL, or search query')
- .setAutocomplete(true)
- .setRequired(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'))
- .addBooleanOption(option => option
- .setName('split')
- .setDescription('if a track has chapters, split it'))
- .addBooleanOption(option => option
- .setName('skip')
- .setDescription('skip the currently playing track'));
+ public readonly slashCommand: Partial<SlashCommandBuilder | SlashCommandSubcommandsOnlyBuilder> & Pick<SlashCommandBuilder, 'toJSON'>;
public requiresVC = true;
- private readonly spotify: Spotify;
+ private readonly spotify?: Spotify;
private readonly cache: KeyValueCacheProvider;
private readonly addQueryToQueue: AddQueryToQueue;
- constructor(@inject(TYPES.ThirdParty) thirdParty: ThirdParty, @inject(TYPES.KeyValueCache) cache: KeyValueCacheProvider, @inject(TYPES.Services.AddQueryToQueue) addQueryToQueue: AddQueryToQueue) {
- this.spotify = thirdParty.spotify;
+ constructor(@inject(TYPES.ThirdParty) @optional() thirdParty: ThirdParty, @inject(TYPES.KeyValueCache) cache: KeyValueCacheProvider, @inject(TYPES.Services.AddQueryToQueue) addQueryToQueue: AddQueryToQueue) {
+ this.spotify = thirdParty?.spotify;
this.cache = cache;
this.addQueryToQueue = addQueryToQueue;
+
+ const queryDescription = thirdParty === undefined
+ ? 'YouTube URL or search query'
+ : 'YouTube URL, Spotify URL, or search query';
+
+ this.slashCommand = new SlashCommandBuilder()
+ .setName('play')
+ .setDescription('play a song')
+ .addStringOption(option => option
+ .setName('query')
+ .setDescription(queryDescription)
+ .setAutocomplete(true)
+ .setRequired(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'))
+ .addBooleanOption(option => option
+ .setName('split')
+ .setDescription('if a track has chapters, split it'))
+ .addBooleanOption(option => option
+ .setName('skip')
+ .setDescription('skip the currently playing track'));
}
public async execute(interaction: ChatInputCommandInteraction): Promise<void> {
diff --git a/src/commands/queue.ts b/src/commands/queue.ts
index 5196ca9..fd36e43 100644
--- a/src/commands/queue.ts
+++ b/src/commands/queue.ts
@@ -5,6 +5,7 @@ import {TYPES} from '../types.js';
import PlayerManager from '../managers/player.js';
import Command from './index.js';
import {buildQueueEmbed} from '../utils/build-embed.js';
+import {getGuildSettings} from '../utils/get-guild-settings.js';
@injectable()
export default class implements Command {
@@ -14,6 +15,12 @@ export default class implements Command {
.addIntegerOption(option => option
.setName('page')
.setDescription('page of queue to show [default: 1]')
+ .setRequired(false))
+ .addIntegerOption(option => option
+ .setName('page-size')
+ .setDescription('how many items to display per page [default: 10, max: 30]')
+ .setMinValue(1)
+ .setMaxValue(30)
.setRequired(false));
private readonly playerManager: PlayerManager;
@@ -23,9 +30,17 @@ export default class implements Command {
}
public async execute(interaction: ChatInputCommandInteraction) {
- const player = this.playerManager.get(interaction.guild!.id);
+ const guildId = interaction.guild!.id;
+ const player = this.playerManager.get(guildId);
+
+ const pageSizeFromOptions = interaction.options.getInteger('page-size');
+ const pageSize = pageSizeFromOptions ?? (await getGuildSettings(guildId)).defaultQueuePageSize;
- const embed = buildQueueEmbed(player, interaction.options.getInteger('page') ?? 1);
+ const embed = buildQueueEmbed(
+ player,
+ interaction.options.getInteger('page') ?? 1,
+ pageSize,
+ );
await interaction.reply({embeds: [embed]});
}
diff --git a/src/inversify.config.ts b/src/inversify.config.ts
index 2f2005e..8e621cb 100644
--- a/src/inversify.config.ts
+++ b/src/inversify.config.ts
@@ -57,11 +57,20 @@ container.bind<Client>(TYPES.Client).toConstantValue(new Client({intents}));
// Managers
container.bind<PlayerManager>(TYPES.Managers.Player).to(PlayerManager).inSingletonScope();
+// Config values
+container.bind(TYPES.Config).toConstantValue(new ConfigProvider());
+
// Services
container.bind<GetSongs>(TYPES.Services.GetSongs).to(GetSongs).inSingletonScope();
container.bind<AddQueryToQueue>(TYPES.Services.AddQueryToQueue).to(AddQueryToQueue).inSingletonScope();
container.bind<YoutubeAPI>(TYPES.Services.YoutubeAPI).to(YoutubeAPI).inSingletonScope();
-container.bind<SpotifyAPI>(TYPES.Services.SpotifyAPI).to(SpotifyAPI).inSingletonScope();
+
+// Only instanciate spotify dependencies if the Spotify client ID and secret are set
+const config = container.get<ConfigProvider>(TYPES.Config);
+if (config.SPOTIFY_CLIENT_ID !== '' && config.SPOTIFY_CLIENT_SECRET !== '') {
+ container.bind<SpotifyAPI>(TYPES.Services.SpotifyAPI).to(SpotifyAPI).inSingletonScope();
+ container.bind(TYPES.ThirdParty).to(ThirdParty);
+}
// Commands
[
@@ -91,12 +100,7 @@ container.bind<SpotifyAPI>(TYPES.Services.SpotifyAPI).to(SpotifyAPI).inSingleton
container.bind<Command>(TYPES.Command).to(command).inSingletonScope();
});
-// Config values
-container.bind(TYPES.Config).toConstantValue(new ConfigProvider());
-
// Static libraries
-container.bind(TYPES.ThirdParty).to(ThirdParty);
-
container.bind(TYPES.FileCache).to(FileCacheProvider);
container.bind(TYPES.KeyValueCache).to(KeyValueCacheProvider);
diff --git a/src/services/add-query-to-queue.ts b/src/services/add-query-to-queue.ts
index 401ad90..95e16ff 100644
--- a/src/services/add-query-to-queue.ts
+++ b/src/services/add-query-to-queue.ts
@@ -1,6 +1,5 @@
/* eslint-disable complexity */
import {ChatInputCommandInteraction, GuildMember} from 'discord.js';
-import {URL} from 'node:url';
import {inject, injectable} from 'inversify';
import shuffle from 'array-shuffle';
import {TYPES} from '../types.js';
@@ -60,74 +59,7 @@ export default class AddQueryToQueue {
await interaction.deferReply({ephemeral: queueAddResponseEphemeral});
- let newSongs: SongMetadata[] = [];
- 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')!, shouldSplitChapters));
- } else {
- const songs = await this.getSongs.youtubeVideo(url.href, shouldSplitChapters);
-
- if (songs) {
- newSongs.push(...songs);
- } 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, shouldSplitChapters);
-
- 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);
- } else {
- const song = await this.getSongs.httpLiveStream(query);
-
- if (song) {
- newSongs.push(song);
- } else {
- throw new Error('that doesn\'t exist');
- }
- }
- } catch (_: unknown) {
- // Not a URL, must search YouTube
- const songs = await this.getSongs.youtubeVideoSearch(query, shouldSplitChapters);
-
- if (songs) {
- newSongs.push(...songs);
- } else {
- throw new Error('that doesn\'t exist');
- }
- }
+ let [newSongs, extraMsg] = await this.getSongs.getSongs(query, playlistLimit, shouldSplitChapters);
if (newSongs.length === 0) {
throw new Error('no songs found');
diff --git a/src/services/config.ts b/src/services/config.ts
index b6b9aea..3941a3c 100644
--- a/src/services/config.ts
+++ b/src/services/config.ts
@@ -5,15 +5,15 @@ import path from 'path';
import xbytes from 'xbytes';
import {ConditionalKeys} from 'type-fest';
import {ActivityType, PresenceStatusData} from 'discord.js';
-dotenv.config();
+dotenv.config({path: process.env.ENV_FILE ?? path.resolve(process.cwd(), '.env')});
export const DATA_DIR = path.resolve(process.env.DATA_DIR ? process.env.DATA_DIR : './data');
const CONFIG_MAP = {
DISCORD_TOKEN: process.env.DISCORD_TOKEN,
YOUTUBE_API_KEY: process.env.YOUTUBE_API_KEY,
- SPOTIFY_CLIENT_ID: process.env.SPOTIFY_CLIENT_ID,
- SPOTIFY_CLIENT_SECRET: process.env.SPOTIFY_CLIENT_SECRET,
+ SPOTIFY_CLIENT_ID: process.env.SPOTIFY_CLIENT_ID ?? '',
+ SPOTIFY_CLIENT_SECRET: process.env.SPOTIFY_CLIENT_SECRET ?? '',
REGISTER_COMMANDS_ON_BOT: process.env.REGISTER_COMMANDS_ON_BOT === 'true',
DATA_DIR,
CACHE_DIR: path.join(DATA_DIR, 'cache'),
diff --git a/src/services/get-songs.ts b/src/services/get-songs.ts
index b957734..c48d87d 100644
--- a/src/services/get-songs.ts
+++ b/src/services/get-songs.ts
@@ -1,34 +1,120 @@
-import {inject, injectable} from 'inversify';
+import {inject, injectable, optional} from 'inversify';
import * as spotifyURI from 'spotify-uri';
import {SongMetadata, QueuedPlaylist, MediaSource} from './player.js';
import {TYPES} from '../types.js';
import ffmpeg from 'fluent-ffmpeg';
import YoutubeAPI from './youtube-api.js';
import SpotifyAPI, {SpotifyTrack} from './spotify-api.js';
+import {URL} from 'node:url';
@injectable()
export default class {
private readonly youtubeAPI: YoutubeAPI;
- private readonly spotifyAPI: SpotifyAPI;
+ private readonly spotifyAPI?: SpotifyAPI;
- constructor(@inject(TYPES.Services.YoutubeAPI) youtubeAPI: YoutubeAPI, @inject(TYPES.Services.SpotifyAPI) spotifyAPI: SpotifyAPI) {
+ constructor(@inject(TYPES.Services.YoutubeAPI) youtubeAPI: YoutubeAPI, @inject(TYPES.Services.SpotifyAPI) @optional() spotifyAPI?: SpotifyAPI) {
this.youtubeAPI = youtubeAPI;
this.spotifyAPI = spotifyAPI;
}
- async youtubeVideoSearch(query: string, shouldSplitChapters: boolean): Promise<SongMetadata[]> {
+ async getSongs(query: string, playlistLimit: number, shouldSplitChapters: boolean): Promise<[SongMetadata[], string]> {
+ const newSongs: SongMetadata[] = [];
+ 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.youtubePlaylist(url.searchParams.get('list')!, shouldSplitChapters));
+ } else {
+ const songs = await this.youtubeVideo(url.href, shouldSplitChapters);
+
+ if (songs) {
+ newSongs.push(...songs);
+ } else {
+ throw new Error('that doesn\'t exist');
+ }
+ }
+ } else if (url.protocol === 'spotify:' || url.host === 'open.spotify.com') {
+ if (this.spotifyAPI === undefined) {
+ throw new Error('Spotify is not enabled!');
+ }
+
+ const [convertedSongs, nSongsNotFound, totalSongs] = await this.spotifySource(query, playlistLimit, shouldSplitChapters);
+
+ 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);
+ } else {
+ const song = await this.httpLiveStream(query);
+
+ if (song) {
+ newSongs.push(song);
+ } else {
+ throw new Error('that doesn\'t exist');
+ }
+ }
+ } catch (err: any) {
+ if (err instanceof Error && err.message === 'Spotify is not enabled!') {
+ throw err;
+ }
+
+ // Not a URL, must search YouTube
+ const songs = await this.youtubeVideoSearch(query, shouldSplitChapters);
+
+ if (songs) {
+ newSongs.push(...songs);
+ } else {
+ throw new Error('that doesn\'t exist');
+ }
+ }
+
+ return [newSongs, extraMsg];
+ }
+
+ private async youtubeVideoSearch(query: string, shouldSplitChapters: boolean): Promise<SongMetadata[]> {
return this.youtubeAPI.search(query, shouldSplitChapters);
}
- async youtubeVideo(url: string, shouldSplitChapters: boolean): Promise<SongMetadata[]> {
+ private async youtubeVideo(url: string, shouldSplitChapters: boolean): Promise<SongMetadata[]> {
return this.youtubeAPI.getVideo(url, shouldSplitChapters);
}
- async youtubePlaylist(listId: string, shouldSplitChapters: boolean): Promise<SongMetadata[]> {
+ private async youtubePlaylist(listId: string, shouldSplitChapters: boolean): Promise<SongMetadata[]> {
return this.youtubeAPI.getPlaylist(listId, shouldSplitChapters);
}
- async spotifySource(url: string, playlistLimit: number, shouldSplitChapters: boolean): Promise<[SongMetadata[], number, number]> {
+ private async spotifySource(url: string, playlistLimit: number, shouldSplitChapters: boolean): Promise<[SongMetadata[], number, number]> {
+ if (this.spotifyAPI === undefined) {
+ return [[], 0, 0];
+ }
+
const parsed = spotifyURI.parse(url);
switch (parsed.type) {
@@ -58,7 +144,7 @@ export default class {
}
}
- async httpLiveStream(url: string): Promise<SongMetadata> {
+ private async httpLiveStream(url: string): Promise<SongMetadata> {
return new Promise((resolve, reject) => {
ffmpeg(url).ffprobe((err, _) => {
if (err) {
diff --git a/src/services/player.ts b/src/services/player.ts
index 5e284a6..b833022 100644
--- a/src/services/player.ts
+++ b/src/services/player.ts
@@ -20,6 +20,7 @@ import FileCacheProvider from './file-cache.js';
import debug from '../utils/debug.js';
import {getGuildSettings} from '../utils/get-guild-settings.js';
import {buildPlayingMessageEmbed} from '../utils/build-embed.js';
+import {Setting} from '@prisma/client';
export enum MediaSource {
Youtube,
@@ -82,6 +83,8 @@ export default class {
private readonly fileCache: FileCacheProvider;
private disconnectTimer: NodeJS.Timeout | null = null;
+ private readonly channelToSpeakingUsers: Map<string, Set<string>> = new Map();
+
constructor(fileCache: FileCacheProvider, guildId: string) {
this.fileCache = fileCache;
this.guildId = guildId;
@@ -96,9 +99,12 @@ export default class {
this.voiceConnection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
+ selfDeaf: false,
adapterCreator: channel.guild.voiceAdapterCreator as DiscordGatewayAdapterCreator,
});
+ const guildSettings = await getGuildSettings(this.guildId);
+
// Workaround to disable keepAlive
this.voiceConnection.on('stateChange', (oldState, newState) => {
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call */
@@ -115,6 +121,9 @@ export default class {
/* eslint-enable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call */
this.currentChannel = channel;
+ if (newState.status === VoiceConnectionStatus.Ready) {
+ this.registerVoiceActivityListener(guildSettings);
+ }
});
}
@@ -302,6 +311,63 @@ export default class {
}
}
+ registerVoiceActivityListener(guildSettings: Setting) {
+ const {turnDownVolumeWhenPeopleSpeak, turnDownVolumeWhenPeopleSpeakTarget} = guildSettings;
+ if (!turnDownVolumeWhenPeopleSpeak || !this.voiceConnection) {
+ return;
+ }
+
+ this.voiceConnection.receiver.speaking.on('start', (userId: string) => {
+ if (!this.currentChannel) {
+ return;
+ }
+
+ const member = this.currentChannel.members.get(userId);
+ const channelId = this.currentChannel?.id;
+
+ if (member) {
+ if (!this.channelToSpeakingUsers.has(channelId)) {
+ this.channelToSpeakingUsers.set(channelId, new Set());
+ }
+
+ this.channelToSpeakingUsers.get(channelId)?.add(member.id);
+ }
+
+ this.suppressVoiceWhenPeopleAreSpeaking(turnDownVolumeWhenPeopleSpeakTarget);
+ });
+
+ this.voiceConnection.receiver.speaking.on('end', (userId: string) => {
+ if (!this.currentChannel) {
+ return;
+ }
+
+ const member = this.currentChannel.members.get(userId);
+ const channelId = this.currentChannel.id;
+ if (member) {
+ if (!this.channelToSpeakingUsers.has(channelId)) {
+ this.channelToSpeakingUsers.set(channelId, new Set());
+ }
+
+ this.channelToSpeakingUsers.get(channelId)?.delete(member.id);
+ }
+
+ this.suppressVoiceWhenPeopleAreSpeaking(turnDownVolumeWhenPeopleSpeakTarget);
+ });
+ }
+
+ suppressVoiceWhenPeopleAreSpeaking(turnDownVolumeWhenPeopleSpeakTarget: number): void {
+ if (!this.currentChannel) {
+ return;
+ }
+
+ const speakingUsers = this.channelToSpeakingUsers.get(this.currentChannel.id);
+ if (speakingUsers && speakingUsers.size > 0) {
+ this.setVolume(turnDownVolumeWhenPeopleSpeakTarget);
+ } else {
+ this.setVolume(this.defaultVolume);
+ }
+ }
+
canGoForward(skip: number) {
return (this.queuePosition + skip - 1) < this.queue.length;
}
diff --git a/src/services/youtube-api.ts b/src/services/youtube-api.ts
index 143033a..216a2c0 100644
--- a/src/services/youtube-api.ts
+++ b/src/services/youtube-api.ts
@@ -95,7 +95,7 @@ export default class {
}
if (!firstVideo) {
- throw new Error('No video found.');
+ return [];
}
return this.getVideo(firstVideo.url, shouldSplitChapters);
diff --git a/src/utils/build-embed.ts b/src/utils/build-embed.ts
index b8e725c..23db0b9 100644
--- a/src/utils/build-embed.ts
+++ b/src/utils/build-embed.ts
@@ -5,8 +5,6 @@ import getProgressBar from './get-progress-bar.js';
import {prettyTime} from './time.js';
import {truncate} from './string.js';
-const PAGE_SIZE = 10;
-
const getMaxSongTitleLength = (title: string) => {
// eslint-disable-next-line no-control-regex
const nonASCII = /[^\x00-\x7F]+/;
@@ -77,7 +75,7 @@ export const buildPlayingMessageEmbed = (player: Player): EmbedBuilder => {
return message;
};
-export const buildQueueEmbed = (player: Player, page: number): EmbedBuilder => {
+export const buildQueueEmbed = (player: Player, page: number, pageSize: number): EmbedBuilder => {
const currentlyPlaying = player.getCurrent();
if (!currentlyPlaying) {
@@ -85,14 +83,14 @@ export const buildQueueEmbed = (player: Player, page: number): EmbedBuilder => {
}
const queueSize = player.queueSize();
- const maxQueuePage = Math.ceil((queueSize + 1) / PAGE_SIZE);
+ const maxQueuePage = Math.ceil((queueSize + 1) / pageSize);
if (page > maxQueuePage) {
throw new Error('the queue isn\'t that big');
}
- const queuePageBegin = (page - 1) * PAGE_SIZE;
- const queuePageEnd = queuePageBegin + PAGE_SIZE;
+ const queuePageBegin = (page - 1) * pageSize;
+ const queuePageEnd = queuePageBegin + pageSize;
const queuedSongs = player
.getQueue()
.slice(queuePageBegin, queuePageEnd)
diff --git a/src/utils/get-youtube-and-spotify-suggestions-for.ts b/src/utils/get-youtube-and-spotify-suggestions-for.ts
index 6594b52..bd6f1c8 100644
--- a/src/utils/get-youtube-and-spotify-suggestions-for.ts
+++ b/src/utils/get-youtube-and-spotify-suggestions-for.ts
@@ -14,28 +14,18 @@ const filterDuplicates = <T extends {name: string}>(items: T[]) => {
return results;
};
-const getYouTubeAndSpotifySuggestionsFor = async (query: string, spotify: SpotifyWebApi, limit = 10): Promise<APIApplicationCommandOptionChoice[]> => {
- const [youtubeSuggestions, spotifyResults] = await Promise.all([
- getYouTubeSuggestionsFor(query),
- spotify.search(query, ['track', 'album'], {limit: 5}),
- ]);
+const getYouTubeAndSpotifySuggestionsFor = async (query: string, spotify?: SpotifyWebApi, limit = 10): Promise<APIApplicationCommandOptionChoice[]> => {
+ // Only search Spotify if enabled
+ const spotifySuggestionPromise = spotify === undefined
+ ? undefined
+ : spotify.search(query, ['album', 'track'], {limit});
- const totalYouTubeResults = youtubeSuggestions.length;
-
- const spotifyAlbums = filterDuplicates(spotifyResults.body.albums?.items ?? []);
- const spotifyTracks = filterDuplicates(spotifyResults.body.tracks?.items ?? []);
-
- const totalSpotifyResults = spotifyAlbums.length + spotifyTracks.length;
+ const youtubeSuggestions = await getYouTubeSuggestionsFor(query);
- // 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 totalYouTubeResults = youtubeSuggestions.length;
+ const numOfYouTubeSuggestions = Math.min(limit, totalYouTubeResults);
- const suggestions: APIApplicationCommandOptionChoice[] = [];
+ let suggestions: APIApplicationCommandOptionChoice[] = [];
suggestions.push(
...youtubeSuggestions
@@ -46,23 +36,40 @@ const getYouTubeAndSpotifySuggestionsFor = async (query: string, spotify: Spotif
}),
));
- 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}`,
- })),
- );
+ if (spotify !== undefined && spotifySuggestionPromise !== undefined) {
+ const spotifyResponse = (await spotifySuggestionPromise).body;
+ const spotifyAlbums = filterDuplicates(spotifyResponse.albums?.items ?? []);
+ const spotifyTracks = filterDuplicates(spotifyResponse.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 maxSpotifyAlbums = Math.floor(numOfSpotifySuggestions / 2);
+ const numOfSpotifyAlbums = Math.min(maxSpotifyAlbums, spotifyResponse.albums?.items.length ?? 0);
+ const maxSpotifyTracks = numOfSpotifySuggestions - numOfSpotifyAlbums;
+
+ // Make room for spotify results
+ const maxYouTubeSuggestions = limit - numOfSpotifySuggestions;
+ suggestions = suggestions.slice(0, maxYouTubeSuggestions);
+
+ 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;
};