discwoofer 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +215 -2
- package/dist/index.cjs +1884 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +368 -0
- package/dist/index.d.mts +368 -0
- package/dist/index.mjs +1883 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +94 -4
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1884 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let node_events = require("node:events");
|
|
3
|
+
let discord_js = require("discord.js");
|
|
4
|
+
let node_crypto = require("node:crypto");
|
|
5
|
+
let youtubei_js = require("youtubei.js");
|
|
6
|
+
let node_child_process = require("node:child_process");
|
|
7
|
+
let _discordjs_voice = require("@discordjs/voice");
|
|
8
|
+
//#region src/commands/definitions.ts
|
|
9
|
+
const COMMAND_SPECS = {
|
|
10
|
+
play: {
|
|
11
|
+
description: "Play a song or playlist from a URL or search query",
|
|
12
|
+
options: [{
|
|
13
|
+
type: discord_js.ApplicationCommandOptionType.String,
|
|
14
|
+
name: "query",
|
|
15
|
+
description: "URL or search terms",
|
|
16
|
+
required: true,
|
|
17
|
+
autocomplete: true
|
|
18
|
+
}, {
|
|
19
|
+
type: discord_js.ApplicationCommandOptionType.Boolean,
|
|
20
|
+
name: "next",
|
|
21
|
+
description: "Put it at the front of the queue"
|
|
22
|
+
}]
|
|
23
|
+
},
|
|
24
|
+
skip: {
|
|
25
|
+
description: "Skip the current song",
|
|
26
|
+
options: [{
|
|
27
|
+
type: discord_js.ApplicationCommandOptionType.Integer,
|
|
28
|
+
name: "to",
|
|
29
|
+
description: "Jump to this queue position",
|
|
30
|
+
min_value: 1
|
|
31
|
+
}]
|
|
32
|
+
},
|
|
33
|
+
stop: { description: "Stop playback and clear the queue" },
|
|
34
|
+
pause: { description: "Pause playback" },
|
|
35
|
+
resume: { description: "Resume playback" },
|
|
36
|
+
queue: {
|
|
37
|
+
description: "Show the queue",
|
|
38
|
+
options: [{
|
|
39
|
+
type: discord_js.ApplicationCommandOptionType.Integer,
|
|
40
|
+
name: "page",
|
|
41
|
+
description: "Page number",
|
|
42
|
+
min_value: 1
|
|
43
|
+
}]
|
|
44
|
+
},
|
|
45
|
+
nowplaying: { description: "Show the current song" },
|
|
46
|
+
volume: {
|
|
47
|
+
description: "Show or set the volume",
|
|
48
|
+
options: [{
|
|
49
|
+
type: discord_js.ApplicationCommandOptionType.Integer,
|
|
50
|
+
name: "level",
|
|
51
|
+
description: "Volume in percent (0-200)",
|
|
52
|
+
min_value: 0,
|
|
53
|
+
max_value: 200
|
|
54
|
+
}]
|
|
55
|
+
},
|
|
56
|
+
loop: {
|
|
57
|
+
description: "Set the loop mode",
|
|
58
|
+
options: [{
|
|
59
|
+
type: discord_js.ApplicationCommandOptionType.String,
|
|
60
|
+
name: "mode",
|
|
61
|
+
description: "Loop mode (cycles when omitted)",
|
|
62
|
+
choices: [
|
|
63
|
+
{
|
|
64
|
+
name: "Off",
|
|
65
|
+
value: "off"
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
name: "Track",
|
|
69
|
+
value: "track"
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
name: "Queue",
|
|
73
|
+
value: "queue"
|
|
74
|
+
}
|
|
75
|
+
]
|
|
76
|
+
}]
|
|
77
|
+
},
|
|
78
|
+
shuffle: { description: "Shuffle the queue" },
|
|
79
|
+
remove: {
|
|
80
|
+
description: "Remove a song from the queue",
|
|
81
|
+
options: [{
|
|
82
|
+
type: discord_js.ApplicationCommandOptionType.Integer,
|
|
83
|
+
name: "position",
|
|
84
|
+
description: "Queue position",
|
|
85
|
+
min_value: 1,
|
|
86
|
+
required: true
|
|
87
|
+
}]
|
|
88
|
+
},
|
|
89
|
+
clear: { description: "Clear the queue (keeps the current song)" },
|
|
90
|
+
leave: { description: "Disconnect from the voice channel" }
|
|
91
|
+
};
|
|
92
|
+
const COMMAND_KEYS = Object.keys(COMMAND_SPECS);
|
|
93
|
+
const NAME = /^[-_\p{L}\p{N}]{1,32}$/u;
|
|
94
|
+
/** Builds command JSON and maps incoming interactions back to command keys. */
|
|
95
|
+
var CommandSet = class {
|
|
96
|
+
keys;
|
|
97
|
+
group;
|
|
98
|
+
nameToKey = /* @__PURE__ */ new Map();
|
|
99
|
+
keyToName = /* @__PURE__ */ new Map();
|
|
100
|
+
constructor(options = {}) {
|
|
101
|
+
const disabled = new Set(options.disabled ?? []);
|
|
102
|
+
this.keys = COMMAND_KEYS.filter((k) => !disabled.has(k));
|
|
103
|
+
this.group = options.group;
|
|
104
|
+
if (this.group !== void 0) assertName(this.group);
|
|
105
|
+
for (const key of this.keys) {
|
|
106
|
+
const name = options.names?.[key] ?? key;
|
|
107
|
+
assertName(name);
|
|
108
|
+
if (this.nameToKey.has(name)) throw new Error(`Duplicate command name "${name}"`);
|
|
109
|
+
this.nameToKey.set(name, key);
|
|
110
|
+
this.keyToName.set(key, name);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
has(key) {
|
|
114
|
+
return this.keyToName.has(key);
|
|
115
|
+
}
|
|
116
|
+
/** User-facing invocation, e.g. `/play` or `/music play`. */
|
|
117
|
+
mention(key) {
|
|
118
|
+
const name = this.keyToName.get(key) ?? key;
|
|
119
|
+
return this.group ? `/${this.group} ${name}` : `/${name}`;
|
|
120
|
+
}
|
|
121
|
+
/** Resolve a chat input command (name + optional subcommand) to a command key. */
|
|
122
|
+
resolve(commandName, subcommand) {
|
|
123
|
+
if (this.group !== void 0) return commandName === this.group && subcommand ? this.nameToKey.get(subcommand) ?? null : null;
|
|
124
|
+
return this.nameToKey.get(commandName) ?? null;
|
|
125
|
+
}
|
|
126
|
+
toJSON() {
|
|
127
|
+
const base = {
|
|
128
|
+
type: discord_js.ApplicationCommandType.ChatInput,
|
|
129
|
+
contexts: [discord_js.InteractionContextType.Guild]
|
|
130
|
+
};
|
|
131
|
+
if (this.group !== void 0) {
|
|
132
|
+
const options = this.keys.map((key) => ({
|
|
133
|
+
type: discord_js.ApplicationCommandOptionType.Subcommand,
|
|
134
|
+
name: this.keyToName.get(key),
|
|
135
|
+
description: COMMAND_SPECS[key].description,
|
|
136
|
+
options: COMMAND_SPECS[key].options
|
|
137
|
+
}));
|
|
138
|
+
return [{
|
|
139
|
+
...base,
|
|
140
|
+
name: this.group,
|
|
141
|
+
description: "Music player",
|
|
142
|
+
options
|
|
143
|
+
}];
|
|
144
|
+
}
|
|
145
|
+
return this.keys.map((key) => ({
|
|
146
|
+
...base,
|
|
147
|
+
name: this.keyToName.get(key),
|
|
148
|
+
description: COMMAND_SPECS[key].description,
|
|
149
|
+
options: COMMAND_SPECS[key].options
|
|
150
|
+
}));
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
function assertName(name) {
|
|
154
|
+
if (!NAME.test(name) || name !== name.toLowerCase()) throw new Error(`Invalid command name "${name}": 1-32 lowercase letters, digits, "-" or "_"`);
|
|
155
|
+
}
|
|
156
|
+
//#endregion
|
|
157
|
+
//#region src/sources/urls.ts
|
|
158
|
+
const YOUTUBE_HOSTS = new Set([
|
|
159
|
+
"youtube.com",
|
|
160
|
+
"www.youtube.com",
|
|
161
|
+
"m.youtube.com",
|
|
162
|
+
"music.youtube.com",
|
|
163
|
+
"youtu.be",
|
|
164
|
+
"www.youtube-nocookie.com"
|
|
165
|
+
]);
|
|
166
|
+
const VIDEO_ID = /^[\w-]{11}$/;
|
|
167
|
+
/** Parse user input as a link. Returns `null` for plain text. */
|
|
168
|
+
function parseUrl(input) {
|
|
169
|
+
const text = input.trim();
|
|
170
|
+
if (/\s/.test(text) || !URL.canParse(text)) return null;
|
|
171
|
+
const url = new URL(text);
|
|
172
|
+
return [
|
|
173
|
+
"http:",
|
|
174
|
+
"https:",
|
|
175
|
+
"spotify:"
|
|
176
|
+
].includes(url.protocol) ? url : null;
|
|
177
|
+
}
|
|
178
|
+
function detectPlatform(url) {
|
|
179
|
+
if (url.protocol === "spotify:" || url.hostname === "open.spotify.com") return "spotify";
|
|
180
|
+
if (YOUTUBE_HOSTS.has(url.hostname)) return "youtube";
|
|
181
|
+
if (url.hostname === "soundcloud.com" || url.hostname.endsWith(".soundcloud.com")) return "soundcloud";
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
/** A `v` param wins over `list`, so links into mixes play the single video. */
|
|
185
|
+
function parseYouTubeUrl(url) {
|
|
186
|
+
if (!YOUTUBE_HOSTS.has(url.hostname)) return null;
|
|
187
|
+
const list = url.searchParams.get("list");
|
|
188
|
+
if (url.hostname === "youtu.be") {
|
|
189
|
+
const id = url.pathname.slice(1).split("/")[0] ?? "";
|
|
190
|
+
return VIDEO_ID.test(id) ? {
|
|
191
|
+
type: "video",
|
|
192
|
+
id
|
|
193
|
+
} : null;
|
|
194
|
+
}
|
|
195
|
+
if (url.pathname === "/playlist" && list) return {
|
|
196
|
+
type: "playlist",
|
|
197
|
+
id: list
|
|
198
|
+
};
|
|
199
|
+
const v = url.searchParams.get("v");
|
|
200
|
+
if (v && VIDEO_ID.test(v)) return {
|
|
201
|
+
type: "video",
|
|
202
|
+
id: v
|
|
203
|
+
};
|
|
204
|
+
const path = /^\/(?:shorts|live|embed|v)\/([\w-]{11})/.exec(url.pathname);
|
|
205
|
+
if (path) return {
|
|
206
|
+
type: "video",
|
|
207
|
+
id: path[1]
|
|
208
|
+
};
|
|
209
|
+
return list ? {
|
|
210
|
+
type: "playlist",
|
|
211
|
+
id: list
|
|
212
|
+
} : null;
|
|
213
|
+
}
|
|
214
|
+
/** `https://open.spotify.com/(intl-xx/)<type>/<id>` and `spotify:<type>:<id>`. */
|
|
215
|
+
function parseSpotifyUrl(url) {
|
|
216
|
+
let parts;
|
|
217
|
+
if (url.protocol === "spotify:") parts = url.pathname.split(":");
|
|
218
|
+
else if (url.hostname === "open.spotify.com") parts = url.pathname.split("/").filter(Boolean);
|
|
219
|
+
else return null;
|
|
220
|
+
if (parts[0]?.startsWith("intl-")) parts.shift();
|
|
221
|
+
const [type, id] = parts;
|
|
222
|
+
if ((type === "track" || type === "album" || type === "playlist") && id && /^[A-Za-z0-9]+$/.test(id)) return {
|
|
223
|
+
type,
|
|
224
|
+
id
|
|
225
|
+
};
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
//#endregion
|
|
229
|
+
//#region src/ui/format.ts
|
|
230
|
+
const PLATFORM_LABELS = {
|
|
231
|
+
youtube: "YouTube",
|
|
232
|
+
soundcloud: "SoundCloud",
|
|
233
|
+
spotify: "Spotify"
|
|
234
|
+
};
|
|
235
|
+
function formatDuration(seconds, isLive = false) {
|
|
236
|
+
if (isLive) return "LIVE";
|
|
237
|
+
if (!seconds || seconds < 0) return "0:00";
|
|
238
|
+
const s = Math.floor(seconds % 60);
|
|
239
|
+
const m = Math.floor(seconds / 60 % 60);
|
|
240
|
+
const h = Math.floor(seconds / 3600);
|
|
241
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
242
|
+
return h > 0 ? `${h}:${pad(m)}:${pad(s)}` : `${m}:${pad(s)}`;
|
|
243
|
+
}
|
|
244
|
+
function truncate(text, max) {
|
|
245
|
+
return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
|
|
246
|
+
}
|
|
247
|
+
/** Markdown-safe title, linked when the URL is http(s). Works for tracks and playlists. */
|
|
248
|
+
function trackTitle(track, max = 80) {
|
|
249
|
+
const title = (0, discord_js.escapeMarkdown)(truncate(track.title, max)).replace(/[[\]]/g, "");
|
|
250
|
+
return /^https?:\/\//.test(track.url) ? `[${title}](<${track.url}>)` : `**${title}**`;
|
|
251
|
+
}
|
|
252
|
+
function trackLine(track, max = 80) {
|
|
253
|
+
const by = track.author ? ` · ${(0, discord_js.escapeMarkdown)(truncate(track.author, 40))}` : "";
|
|
254
|
+
return `${trackTitle(track, max)}${by} \`${formatDuration(track.duration, track.isLive)}\``;
|
|
255
|
+
}
|
|
256
|
+
/** Plain text (no markdown) label, e.g. for select menus and autocomplete. */
|
|
257
|
+
function trackLabel(track, max = 100) {
|
|
258
|
+
const suffix = ` (${formatDuration(track.duration, track.isLive)})`;
|
|
259
|
+
const by = track.author ? ` — ${track.author}` : "";
|
|
260
|
+
return truncate(`${track.title}${by}`, max - suffix.length) + suffix;
|
|
261
|
+
}
|
|
262
|
+
function progressBar(position, duration, size = 16) {
|
|
263
|
+
if (!duration) return "▬".repeat(size);
|
|
264
|
+
const filled = Math.min(size - 1, Math.floor(position / duration * size));
|
|
265
|
+
return `${"▬".repeat(filled)}🔘${"▬".repeat(size - filled - 1)}`;
|
|
266
|
+
}
|
|
267
|
+
const LOOP_LABELS = {
|
|
268
|
+
off: "Off",
|
|
269
|
+
track: "Track",
|
|
270
|
+
queue: "Queue"
|
|
271
|
+
};
|
|
272
|
+
const nextLoopMode = (mode) => mode === "off" ? "queue" : mode === "queue" ? "track" : "off";
|
|
273
|
+
//#endregion
|
|
274
|
+
//#region src/commands/autocomplete.ts
|
|
275
|
+
const TTL = 5 * 6e4;
|
|
276
|
+
const MAX_ENTRIES = 200;
|
|
277
|
+
/** Recent autocomplete results: saves searching on every keystroke and re-resolving the picked link. */
|
|
278
|
+
var SuggestionCache = class {
|
|
279
|
+
entries = /* @__PURE__ */ new Map();
|
|
280
|
+
get(query) {
|
|
281
|
+
const entry = this.entries.get(query.toLowerCase());
|
|
282
|
+
return entry && entry.expires > Date.now() ? entry.tracks : void 0;
|
|
283
|
+
}
|
|
284
|
+
set(query, tracks) {
|
|
285
|
+
const now = Date.now();
|
|
286
|
+
for (const [key, entry] of this.entries) if (entry.expires < now || this.entries.size >= MAX_ENTRIES) this.entries.delete(key);
|
|
287
|
+
this.entries.set(query.toLowerCase(), {
|
|
288
|
+
tracks,
|
|
289
|
+
expires: now + TTL
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
/** A track recently suggested under this URL, if any. */
|
|
293
|
+
findByUrl(url) {
|
|
294
|
+
const now = Date.now();
|
|
295
|
+
for (const { tracks, expires } of this.entries.values()) {
|
|
296
|
+
if (expires < now) continue;
|
|
297
|
+
const hit = tracks.find((t) => t.url === url);
|
|
298
|
+
if (hit) return hit;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
async function autocomplete({ music, suggestions }, i) {
|
|
303
|
+
const query = i.options.getFocused().trim();
|
|
304
|
+
try {
|
|
305
|
+
if (!query || parseUrl(query)) {
|
|
306
|
+
await i.respond(query && query.length <= 100 ? [{
|
|
307
|
+
name: query,
|
|
308
|
+
value: query
|
|
309
|
+
}] : []);
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
let tracks = suggestions.get(query);
|
|
313
|
+
if (!tracks) {
|
|
314
|
+
tracks = await music.sources.autocomplete(query, music.options.searchLimit);
|
|
315
|
+
if (tracks.length) suggestions.set(query, tracks);
|
|
316
|
+
}
|
|
317
|
+
await i.respond(tracks.map((t) => ({
|
|
318
|
+
name: trackLabel(t, 100),
|
|
319
|
+
value: t.url.length <= 100 ? t.url : t.title.slice(0, 100)
|
|
320
|
+
})));
|
|
321
|
+
} catch (error) {
|
|
322
|
+
music.reportError(error);
|
|
323
|
+
await i.respond([]).catch(() => {});
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
function nowPlayingEmbed(player, color) {
|
|
327
|
+
const track = player.current;
|
|
328
|
+
const embed = new discord_js.EmbedBuilder().setColor(color);
|
|
329
|
+
if (!track) return embed.setDescription("Nothing is playing.");
|
|
330
|
+
const status = player.isLoading && !player.isPlaying ? "⏳ Loading" : player.isPaused ? "⏸️ Paused" : "🎶 Now playing";
|
|
331
|
+
const pos = player.position;
|
|
332
|
+
const timeline = track.isLive ? "🔴 LIVE" : `\`${formatDuration(pos)}\` ${progressBar(pos, track.duration)} \`${formatDuration(track.duration)}\``;
|
|
333
|
+
embed.setAuthor({ name: status }).setDescription(`### ${trackTitle(track, 200)}\n${track.author ? `${(0, discord_js.escapeMarkdown)(track.author)}\n` : ""}${timeline}`).addFields({
|
|
334
|
+
name: "Requested by",
|
|
335
|
+
value: track.requestedBy ? `<@${track.requestedBy.id}>` : "—",
|
|
336
|
+
inline: true
|
|
337
|
+
}, {
|
|
338
|
+
name: "Loop",
|
|
339
|
+
value: LOOP_LABELS[player.loop],
|
|
340
|
+
inline: true
|
|
341
|
+
}, {
|
|
342
|
+
name: "Volume",
|
|
343
|
+
value: `${player.volume}%`,
|
|
344
|
+
inline: true
|
|
345
|
+
});
|
|
346
|
+
if (track.thumbnail) embed.setThumbnail(track.thumbnail);
|
|
347
|
+
const next = player.queue.upcoming[0];
|
|
348
|
+
if (next) {
|
|
349
|
+
const more = player.queue.size > 1 ? `\n+${player.queue.size - 1} more · ${formatDuration(player.queue.totalDuration)} total` : "";
|
|
350
|
+
embed.addFields({
|
|
351
|
+
name: "Up next",
|
|
352
|
+
value: `${trackLine(next, 60)}${more}`
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
return embed;
|
|
356
|
+
}
|
|
357
|
+
function controlRows(player, prefix) {
|
|
358
|
+
const id = (action) => `${prefix}:ctl:${action}`;
|
|
359
|
+
const disabled = !player.current;
|
|
360
|
+
const button = (action, emoji, style = discord_js.ButtonStyle.Secondary, label) => {
|
|
361
|
+
const b = new discord_js.ButtonBuilder().setCustomId(id(action)).setEmoji(emoji).setStyle(style).setDisabled(disabled);
|
|
362
|
+
return label ? b.setLabel(label) : b;
|
|
363
|
+
};
|
|
364
|
+
return [new discord_js.ActionRowBuilder().addComponents(button("toggle", player.isPaused ? "▶️" : "⏸️", discord_js.ButtonStyle.Primary), button("skip", "⏭️"), button("stop", "⏹️", discord_js.ButtonStyle.Danger), button("shuffle", "🔀"), button("loop", player.loop === "track" ? "🔂" : "🔁", player.loop === "off" ? discord_js.ButtonStyle.Secondary : discord_js.ButtonStyle.Success)), new discord_js.ActionRowBuilder().addComponents(button("voldown", "🔉"), button("volup", "🔊"), button("queue", "📜", discord_js.ButtonStyle.Secondary, `Queue (${player.queue.size})`))];
|
|
365
|
+
}
|
|
366
|
+
function queueEmbed(player, page, color) {
|
|
367
|
+
const { upcoming } = player.queue;
|
|
368
|
+
const pages = Math.max(1, Math.ceil(upcoming.length / 10));
|
|
369
|
+
page = Math.min(Math.max(1, page), pages);
|
|
370
|
+
const start = (page - 1) * 10;
|
|
371
|
+
const lines = upcoming.slice(start, start + 10).map((t, i) => `\`${start + i + 1}.\` ${trackLine(t, 60)}`);
|
|
372
|
+
const current = player.current ? `**Now:** ${trackLine(player.current, 80)}\n\n` : "";
|
|
373
|
+
const body = lines.length ? lines.join("\n") : "*The queue is empty.*";
|
|
374
|
+
return {
|
|
375
|
+
embed: new discord_js.EmbedBuilder().setColor(color).setTitle("Queue").setDescription(truncate(current + body, 4096)).setFooter({ text: `Page ${page}/${pages} · ${upcoming.length} tracks · ${formatDuration(player.queue.totalDuration)} · Loop: ${LOOP_LABELS[player.loop]}` }),
|
|
376
|
+
page,
|
|
377
|
+
pages
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
function queuePager(prefix, page, pages) {
|
|
381
|
+
return new discord_js.ActionRowBuilder().addComponents(new discord_js.ButtonBuilder().setCustomId(`${prefix}:queue:${page - 1}`).setEmoji("◀️").setStyle(discord_js.ButtonStyle.Secondary).setDisabled(page <= 1), new discord_js.ButtonBuilder().setCustomId(`${prefix}:queue:${page + 1}`).setEmoji("▶️").setStyle(discord_js.ButtonStyle.Secondary).setDisabled(page >= pages));
|
|
382
|
+
}
|
|
383
|
+
function searchPicker(tracks, prefix, key) {
|
|
384
|
+
return new discord_js.ActionRowBuilder().addComponents(new discord_js.StringSelectMenuBuilder().setCustomId(`${prefix}:pick:${key}`).setPlaceholder("Choose a track").addOptions(tracks.slice(0, 25).map((t, i) => ({
|
|
385
|
+
label: trackLabel(t, 100),
|
|
386
|
+
description: truncate(`${PLATFORM_LABELS[t.platform]}${t.author ? ` · ${t.author}` : ""}`, 100),
|
|
387
|
+
value: String(i)
|
|
388
|
+
}))));
|
|
389
|
+
}
|
|
390
|
+
//#endregion
|
|
391
|
+
//#region src/commands/respond.ts
|
|
392
|
+
/** A message for the user (shown ephemerally), not an error to report. */
|
|
393
|
+
var Refusal = class extends Error {};
|
|
394
|
+
/**
|
|
395
|
+
* Reply, or edit the deferred reply. In widgets mode replies are ephemeral, since the panel
|
|
396
|
+
* already shows the state to everyone.
|
|
397
|
+
*/
|
|
398
|
+
async function reply(music, i, payload) {
|
|
399
|
+
const body = {
|
|
400
|
+
allowedMentions: { parse: [] },
|
|
401
|
+
...typeof payload === "string" ? { content: payload } : payload
|
|
402
|
+
};
|
|
403
|
+
if (i.deferred || i.replied) await i.editReply(body);
|
|
404
|
+
else await i.reply({
|
|
405
|
+
...body,
|
|
406
|
+
flags: music.options.ui === "widgets" ? discord_js.MessageFlags.Ephemeral : void 0
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
/** Show an error or refusal, whatever state the interaction is in. */
|
|
410
|
+
async function replyError(i, content) {
|
|
411
|
+
try {
|
|
412
|
+
if (i.deferred && !i.replied) await i.editReply({
|
|
413
|
+
content,
|
|
414
|
+
components: [],
|
|
415
|
+
embeds: []
|
|
416
|
+
});
|
|
417
|
+
else if (i.replied) await i.followUp({
|
|
418
|
+
content,
|
|
419
|
+
flags: discord_js.MessageFlags.Ephemeral
|
|
420
|
+
});
|
|
421
|
+
else await i.reply({
|
|
422
|
+
content,
|
|
423
|
+
flags: discord_js.MessageFlags.Ephemeral
|
|
424
|
+
});
|
|
425
|
+
} catch {}
|
|
426
|
+
}
|
|
427
|
+
//#endregion
|
|
428
|
+
//#region src/commands/guard.ts
|
|
429
|
+
async function checkChannelRule(rule, channel) {
|
|
430
|
+
if (!rule) return true;
|
|
431
|
+
return typeof rule === "function" ? rule(channel) : rule.includes(channel.id);
|
|
432
|
+
}
|
|
433
|
+
/** Text channel restriction and the `canUse` hook. */
|
|
434
|
+
async function checkAccess(music, i) {
|
|
435
|
+
const { channels, canUse } = music.options;
|
|
436
|
+
if (i.channel && !await checkChannelRule(channels.text, i.channel)) {
|
|
437
|
+
const allowed = Array.isArray(channels.text) ? channels.text.map((id) => `<#${id}>`).join(", ") : "";
|
|
438
|
+
throw new Refusal(allowed ? `🚫 Music commands can only be used in ${allowed}.` : "🚫 Music commands can’t be used here.");
|
|
439
|
+
}
|
|
440
|
+
if (canUse) {
|
|
441
|
+
const verdict = await canUse(i);
|
|
442
|
+
if (verdict !== true) throw new Refusal(typeof verdict === "string" ? verdict : "🚫 You can’t use the music player.");
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
/** The user must be in a voice channel, and in the bot's channel if it is already connected. */
|
|
446
|
+
function requireSameVoice(music, i) {
|
|
447
|
+
const voice = i.member.voice.channel;
|
|
448
|
+
if (!voice) throw new Refusal("🔇 Join a voice channel first.");
|
|
449
|
+
const botChannel = music.get(i.guildId)?.voiceChannelId;
|
|
450
|
+
if (botChannel && botChannel !== voice.id) throw new Refusal(`🔇 You need to be in <#${botChannel}> to control the music.`);
|
|
451
|
+
return voice;
|
|
452
|
+
}
|
|
453
|
+
function requireConnected(music, guildId) {
|
|
454
|
+
const player = music.get(guildId);
|
|
455
|
+
if (!player) throw new Refusal("🔇 I’m not in a voice channel.");
|
|
456
|
+
return player;
|
|
457
|
+
}
|
|
458
|
+
function requirePlaying(music, guildId) {
|
|
459
|
+
const player = music.get(guildId);
|
|
460
|
+
if (!player?.current) throw new Refusal("🔇 Nothing is playing.");
|
|
461
|
+
return player;
|
|
462
|
+
}
|
|
463
|
+
//#endregion
|
|
464
|
+
//#region src/sources/soundcloud.ts
|
|
465
|
+
/** SoundCloud search and links through yt-dlp. */
|
|
466
|
+
var SoundCloud = class {
|
|
467
|
+
constructor(ytdlp, maxPlaylistSize) {
|
|
468
|
+
this.ytdlp = ytdlp;
|
|
469
|
+
this.maxPlaylistSize = maxPlaylistSize;
|
|
470
|
+
}
|
|
471
|
+
search(query, limit) {
|
|
472
|
+
return this.ytdlp.search("soundcloud", query, limit);
|
|
473
|
+
}
|
|
474
|
+
resolve(url) {
|
|
475
|
+
return this.ytdlp.resolve(url, "soundcloud", this.maxPlaylistSize);
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
//#endregion
|
|
479
|
+
//#region src/sources/spotify.ts
|
|
480
|
+
/**
|
|
481
|
+
* Spotify link metadata. Audio is never streamed from Spotify: the player searches the configured
|
|
482
|
+
* sources for each track.
|
|
483
|
+
*
|
|
484
|
+
* Reads Spotify's public embed page, which needs no credentials but caps playlists and albums at
|
|
485
|
+
* 100 tracks. With credentials, playlists and albums come from the Web API instead (no cap).
|
|
486
|
+
*/
|
|
487
|
+
var Spotify = class {
|
|
488
|
+
api;
|
|
489
|
+
constructor(credentials, maxPlaylistSize, onError) {
|
|
490
|
+
this.maxPlaylistSize = maxPlaylistSize;
|
|
491
|
+
this.onError = onError;
|
|
492
|
+
this.api = credentials ? new SpotifyApi(credentials) : null;
|
|
493
|
+
}
|
|
494
|
+
async resolve(url) {
|
|
495
|
+
const target = parseSpotifyUrl(url);
|
|
496
|
+
if (!target) return null;
|
|
497
|
+
if (this.api && target.type !== "track") try {
|
|
498
|
+
return await this.api.collection(target, this.maxPlaylistSize);
|
|
499
|
+
} catch (error) {
|
|
500
|
+
this.onError(error);
|
|
501
|
+
}
|
|
502
|
+
return fromEmbed(target, this.maxPlaylistSize);
|
|
503
|
+
}
|
|
504
|
+
};
|
|
505
|
+
const BROWSER_UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36";
|
|
506
|
+
async function fromEmbed(target, limit) {
|
|
507
|
+
const res = await fetch(`https://open.spotify.com/embed/${target.type}/${target.id}`, { headers: { "User-Agent": BROWSER_UA } });
|
|
508
|
+
if (!res.ok) throw new Error(`Spotify embed returned ${res.status} for ${target.type} ${target.id}`);
|
|
509
|
+
const html = await res.text();
|
|
510
|
+
const json = /<script id="__NEXT_DATA__" type="application\/json">([^<]+)<\/script>/.exec(html)?.[1];
|
|
511
|
+
const entity = json && JSON.parse(json).props?.pageProps?.state?.data?.entity;
|
|
512
|
+
if (!entity) throw new Error("Could not read Spotify embed data (page format changed?)");
|
|
513
|
+
const cover = largestImage(entity.visualIdentity?.image ?? entity.coverArt?.sources);
|
|
514
|
+
const name = entity.name ?? entity.title ?? "Unknown";
|
|
515
|
+
if (target.type === "track") return { tracks: [{
|
|
516
|
+
title: name,
|
|
517
|
+
url: trackUrl(target.id),
|
|
518
|
+
author: entity.artists?.map((a) => a.name).join(", "),
|
|
519
|
+
duration: msToSeconds(entity.duration),
|
|
520
|
+
thumbnail: cover,
|
|
521
|
+
platform: "spotify"
|
|
522
|
+
}] };
|
|
523
|
+
return {
|
|
524
|
+
tracks: (entity.trackList ?? []).filter((t) => t.isPlayable !== false).slice(0, limit).map((t) => ({
|
|
525
|
+
title: t.title,
|
|
526
|
+
url: trackUrl(t.uri.split(":").pop()),
|
|
527
|
+
author: t.subtitle,
|
|
528
|
+
duration: msToSeconds(t.duration),
|
|
529
|
+
thumbnail: target.type === "album" ? cover : void 0,
|
|
530
|
+
platform: "spotify"
|
|
531
|
+
})),
|
|
532
|
+
playlist: {
|
|
533
|
+
title: name,
|
|
534
|
+
url: `https://open.spotify.com/${target.type}/${target.id}`,
|
|
535
|
+
thumbnail: cover,
|
|
536
|
+
author: entity.subtitle
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
var SpotifyApi = class {
|
|
541
|
+
token;
|
|
542
|
+
constructor(credentials) {
|
|
543
|
+
this.credentials = credentials;
|
|
544
|
+
}
|
|
545
|
+
async collection(target, limit) {
|
|
546
|
+
if (target.type === "album") {
|
|
547
|
+
const album = await this.get(`/albums/${target.id}`);
|
|
548
|
+
const cover = album.images[0]?.url;
|
|
549
|
+
return {
|
|
550
|
+
tracks: (await this.collect(album.tracks, limit)).map((t) => apiTrackToTrack(t, cover)).filter((t) => t !== null),
|
|
551
|
+
playlist: this.info(target, album.name, cover, album.artists.map((a) => a.name).join(", "))
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
const playlist = await this.get(`/playlists/${target.id}?fields=name,images,owner(display_name)`);
|
|
555
|
+
const first = await this.get(`/playlists/${target.id}/items?limit=100`).catch(() => this.get(`/playlists/${target.id}/tracks?limit=100`));
|
|
556
|
+
return {
|
|
557
|
+
tracks: (await this.collect(first, limit)).map((e) => e.item ?? e.track).filter((t) => t != null).map((t) => apiTrackToTrack(t)).filter((t) => t !== null),
|
|
558
|
+
playlist: this.info(target, playlist.name, playlist.images?.[0]?.url, playlist.owner?.display_name)
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
info(target, title, thumbnail, author) {
|
|
562
|
+
return {
|
|
563
|
+
title,
|
|
564
|
+
url: `https://open.spotify.com/${target.type}/${target.id}`,
|
|
565
|
+
thumbnail,
|
|
566
|
+
author
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
async collect(first, limit) {
|
|
570
|
+
const items = [...first.items];
|
|
571
|
+
let next = first.next;
|
|
572
|
+
while (next && items.length < limit) {
|
|
573
|
+
const page = await this.get(next);
|
|
574
|
+
items.push(...page.items);
|
|
575
|
+
next = page.next;
|
|
576
|
+
}
|
|
577
|
+
return items.slice(0, limit);
|
|
578
|
+
}
|
|
579
|
+
async get(path) {
|
|
580
|
+
const url = path.startsWith("http") ? path : `https://api.spotify.com/v1${path}`;
|
|
581
|
+
const res = await fetch(url, { headers: { Authorization: `Bearer ${await this.accessToken()}` } });
|
|
582
|
+
if (!res.ok) throw new Error(`Spotify API returned ${res.status} for ${url}`);
|
|
583
|
+
return await res.json();
|
|
584
|
+
}
|
|
585
|
+
async accessToken() {
|
|
586
|
+
if (this.token && this.token.expires > Date.now() + 6e4) return this.token.value;
|
|
587
|
+
const { clientId, clientSecret } = this.credentials;
|
|
588
|
+
const res = await fetch("https://accounts.spotify.com/api/token", {
|
|
589
|
+
method: "POST",
|
|
590
|
+
headers: {
|
|
591
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
592
|
+
Authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`
|
|
593
|
+
},
|
|
594
|
+
body: "grant_type=client_credentials"
|
|
595
|
+
});
|
|
596
|
+
if (!res.ok) throw new Error(`Spotify auth failed with ${res.status}`);
|
|
597
|
+
const body = await res.json();
|
|
598
|
+
this.token = {
|
|
599
|
+
value: body.access_token,
|
|
600
|
+
expires: Date.now() + body.expires_in * 1e3
|
|
601
|
+
};
|
|
602
|
+
return this.token.value;
|
|
603
|
+
}
|
|
604
|
+
};
|
|
605
|
+
function apiTrackToTrack(t, cover) {
|
|
606
|
+
if (!t.id || t.is_local || t.type && t.type !== "track") return null;
|
|
607
|
+
return {
|
|
608
|
+
title: t.name,
|
|
609
|
+
url: trackUrl(t.id),
|
|
610
|
+
author: t.artists.map((a) => a.name).join(", "),
|
|
611
|
+
duration: msToSeconds(t.duration_ms),
|
|
612
|
+
thumbnail: t.album?.images[0]?.url ?? cover,
|
|
613
|
+
platform: "spotify"
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
const trackUrl = (id) => `https://open.spotify.com/track/${id}`;
|
|
617
|
+
const msToSeconds = (ms) => ms ? Math.round(ms / 1e3) : void 0;
|
|
618
|
+
function largestImage(images) {
|
|
619
|
+
return images?.reduce((best, img) => (img.maxWidth ?? 0) >= (best?.maxWidth ?? 0) ? img : best, void 0)?.url;
|
|
620
|
+
}
|
|
621
|
+
//#endregion
|
|
622
|
+
//#region src/sources/youtube.ts
|
|
623
|
+
const watchUrl = (id) => `https://www.youtube.com/watch?v=${id}`;
|
|
624
|
+
/**
|
|
625
|
+
* YouTube metadata via youtubei.js (fast, good for autocomplete).
|
|
626
|
+
* Falls back to yt-dlp when YouTube changes break youtubei.js.
|
|
627
|
+
*/
|
|
628
|
+
var YouTube = class {
|
|
629
|
+
client;
|
|
630
|
+
constructor(ytdlp, maxPlaylistSize) {
|
|
631
|
+
this.ytdlp = ytdlp;
|
|
632
|
+
this.maxPlaylistSize = maxPlaylistSize;
|
|
633
|
+
}
|
|
634
|
+
async search(query, limit) {
|
|
635
|
+
try {
|
|
636
|
+
return (await (await this.innertube()).search(query, { type: "video" })).results.filterType(youtubei_js.YTNodes.Video).slice(0, limit).map((v) => ({
|
|
637
|
+
title: v.title.toString(),
|
|
638
|
+
url: watchUrl(v.video_id),
|
|
639
|
+
author: v.author?.name,
|
|
640
|
+
duration: v.is_live ? void 0 : v.duration.seconds || void 0,
|
|
641
|
+
thumbnail: v.best_thumbnail?.url,
|
|
642
|
+
isLive: v.is_live,
|
|
643
|
+
platform: "youtube"
|
|
644
|
+
}));
|
|
645
|
+
} catch {
|
|
646
|
+
return this.ytdlp.search("youtube", query, limit);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
async resolve(url) {
|
|
650
|
+
const target = parseYouTubeUrl(url);
|
|
651
|
+
if (!target) return null;
|
|
652
|
+
try {
|
|
653
|
+
return target.type === "video" ? await this.video(target.id) : await this.playlist(target.id);
|
|
654
|
+
} catch {
|
|
655
|
+
return this.ytdlp.resolve(url, "youtube", this.maxPlaylistSize);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
async video(id) {
|
|
659
|
+
const { basic_info: info } = await (await this.innertube()).getBasicInfo(id);
|
|
660
|
+
return { tracks: [{
|
|
661
|
+
title: info.title ?? "Unknown title",
|
|
662
|
+
url: watchUrl(id),
|
|
663
|
+
author: info.author,
|
|
664
|
+
duration: info.is_live ? void 0 : info.duration || void 0,
|
|
665
|
+
thumbnail: info.thumbnail?.[0]?.url,
|
|
666
|
+
isLive: info.is_live ?? false,
|
|
667
|
+
platform: "youtube"
|
|
668
|
+
}] };
|
|
669
|
+
}
|
|
670
|
+
async playlist(id) {
|
|
671
|
+
let page = await (await this.innertube()).getPlaylist(id);
|
|
672
|
+
const { title, thumbnails } = page.info;
|
|
673
|
+
const items = [...page.items];
|
|
674
|
+
while (items.length < this.maxPlaylistSize && page.has_continuation) {
|
|
675
|
+
page = await page.getContinuation();
|
|
676
|
+
items.push(...page.items);
|
|
677
|
+
}
|
|
678
|
+
const tracks = [];
|
|
679
|
+
for (const item of items.slice(0, this.maxPlaylistSize)) if (item.is(youtubei_js.YTNodes.PlaylistVideo) && item.is_playable) tracks.push({
|
|
680
|
+
title: item.title.toString(),
|
|
681
|
+
url: watchUrl(item.id),
|
|
682
|
+
author: item.author?.name,
|
|
683
|
+
duration: item.duration.seconds || void 0,
|
|
684
|
+
thumbnail: item.thumbnails[0]?.url,
|
|
685
|
+
isLive: item.is_live,
|
|
686
|
+
platform: "youtube"
|
|
687
|
+
});
|
|
688
|
+
else if (item.is(youtubei_js.YTNodes.LockupView) && item.content_type === "VIDEO" && item.content_id) {
|
|
689
|
+
const image = item.content_image && "image" in item.content_image ? item.content_image.image : [];
|
|
690
|
+
tracks.push({
|
|
691
|
+
title: item.metadata?.title?.toString() ?? "Unknown title",
|
|
692
|
+
url: watchUrl(item.content_id),
|
|
693
|
+
author: item.metadata?.metadata?.metadata_rows?.[0]?.metadata_parts?.[0]?.text?.toString(),
|
|
694
|
+
duration: item.duration.seconds || void 0,
|
|
695
|
+
thumbnail: image[0]?.url,
|
|
696
|
+
platform: "youtube"
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
return {
|
|
700
|
+
tracks,
|
|
701
|
+
playlist: {
|
|
702
|
+
title: title ?? "Playlist",
|
|
703
|
+
url: `https://www.youtube.com/playlist?list=${id}`,
|
|
704
|
+
thumbnail: thumbnails?.[0]?.url
|
|
705
|
+
}
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
innertube() {
|
|
709
|
+
this.client ??= youtubei_js.Innertube.create({ retrieve_player: false }).catch((error) => {
|
|
710
|
+
this.client = void 0;
|
|
711
|
+
throw error;
|
|
712
|
+
});
|
|
713
|
+
return this.client;
|
|
714
|
+
}
|
|
715
|
+
};
|
|
716
|
+
//#endregion
|
|
717
|
+
//#region src/sources/ytdlp.ts
|
|
718
|
+
const SEARCH_PREFIX = {
|
|
719
|
+
youtube: "ytsearch",
|
|
720
|
+
soundcloud: "scsearch"
|
|
721
|
+
};
|
|
722
|
+
const UNAVAILABLE = /^\[(private|deleted|unavailable) video\]$/i;
|
|
723
|
+
/** Runs the yt-dlp binary for metadata and audio. */
|
|
724
|
+
var YtDlp = class {
|
|
725
|
+
constructor(binary, extraArgs = [], timeoutMs = 3e4) {
|
|
726
|
+
this.binary = binary;
|
|
727
|
+
this.extraArgs = extraArgs;
|
|
728
|
+
this.timeoutMs = timeoutMs;
|
|
729
|
+
}
|
|
730
|
+
async search(platform, query, limit) {
|
|
731
|
+
return toTracks((await this.json(`${SEARCH_PREFIX[platform]}${limit}:${query}`)).entries, platform);
|
|
732
|
+
}
|
|
733
|
+
async resolve(url, platform, maxEntries) {
|
|
734
|
+
const data = await this.json(url.href, ["--playlist-end", String(maxEntries)]);
|
|
735
|
+
if (data._type === "playlist" || data.entries) return {
|
|
736
|
+
tracks: toTracks(data.entries, platform),
|
|
737
|
+
playlist: {
|
|
738
|
+
title: data.title ?? "Playlist",
|
|
739
|
+
url: data.webpage_url ?? url.href,
|
|
740
|
+
thumbnail: data.thumbnail ?? bestThumbnail(data.thumbnails),
|
|
741
|
+
author: data.channel ?? data.uploader
|
|
742
|
+
}
|
|
743
|
+
};
|
|
744
|
+
const track = entryToTrack({
|
|
745
|
+
...data,
|
|
746
|
+
webpage_url: data.webpage_url ?? url.href
|
|
747
|
+
}, platform);
|
|
748
|
+
return track ? { tracks: [track] } : null;
|
|
749
|
+
}
|
|
750
|
+
/** Start streaming audio. Resolves once data flows, rejects if yt-dlp fails first. */
|
|
751
|
+
async stream(url) {
|
|
752
|
+
const proc = (0, node_child_process.spawn)(this.binary, [
|
|
753
|
+
"-f",
|
|
754
|
+
"bestaudio/best",
|
|
755
|
+
"-o",
|
|
756
|
+
"-",
|
|
757
|
+
"--no-playlist",
|
|
758
|
+
"--quiet",
|
|
759
|
+
"--no-warnings",
|
|
760
|
+
...this.extraArgs,
|
|
761
|
+
"--",
|
|
762
|
+
url
|
|
763
|
+
], { stdio: [
|
|
764
|
+
"ignore",
|
|
765
|
+
"pipe",
|
|
766
|
+
"pipe"
|
|
767
|
+
] });
|
|
768
|
+
await this.firstData(proc);
|
|
769
|
+
const stdout = proc.stdout;
|
|
770
|
+
stdout.once("close", () => proc.kill());
|
|
771
|
+
return stdout;
|
|
772
|
+
}
|
|
773
|
+
json(target, args = []) {
|
|
774
|
+
const proc = (0, node_child_process.spawn)(this.binary, [
|
|
775
|
+
"-J",
|
|
776
|
+
"--flat-playlist",
|
|
777
|
+
"--no-warnings",
|
|
778
|
+
...args,
|
|
779
|
+
...this.extraArgs,
|
|
780
|
+
"--",
|
|
781
|
+
target
|
|
782
|
+
], { stdio: [
|
|
783
|
+
"ignore",
|
|
784
|
+
"pipe",
|
|
785
|
+
"pipe"
|
|
786
|
+
] });
|
|
787
|
+
const stderr = collectErrors(proc);
|
|
788
|
+
const chunks = [];
|
|
789
|
+
proc.stdout.on("data", (c) => chunks.push(c));
|
|
790
|
+
return new Promise((resolve, reject) => {
|
|
791
|
+
const timer = setTimeout(() => {
|
|
792
|
+
proc.kill();
|
|
793
|
+
reject(/* @__PURE__ */ new Error(`yt-dlp timed out after ${this.timeoutMs}ms`));
|
|
794
|
+
}, this.timeoutMs);
|
|
795
|
+
proc.once("error", (e) => {
|
|
796
|
+
clearTimeout(timer);
|
|
797
|
+
reject(this.spawnError(e));
|
|
798
|
+
});
|
|
799
|
+
proc.once("close", (code) => {
|
|
800
|
+
clearTimeout(timer);
|
|
801
|
+
if (code !== 0) return reject(new Error(stderr() || `yt-dlp exited with code ${code}`));
|
|
802
|
+
try {
|
|
803
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
804
|
+
} catch (e) {
|
|
805
|
+
reject(e);
|
|
806
|
+
}
|
|
807
|
+
});
|
|
808
|
+
});
|
|
809
|
+
}
|
|
810
|
+
firstData(proc) {
|
|
811
|
+
const stderr = collectErrors(proc);
|
|
812
|
+
const stdout = proc.stdout;
|
|
813
|
+
return new Promise((resolve, reject) => {
|
|
814
|
+
const done = () => {
|
|
815
|
+
clearTimeout(timer);
|
|
816
|
+
stdout.off("readable", onReadable);
|
|
817
|
+
proc.off("error", onError);
|
|
818
|
+
proc.off("exit", onExit);
|
|
819
|
+
};
|
|
820
|
+
const fail = (error) => {
|
|
821
|
+
done();
|
|
822
|
+
proc.kill();
|
|
823
|
+
reject(error);
|
|
824
|
+
};
|
|
825
|
+
const onReadable = () => {
|
|
826
|
+
if (stdout.readableLength === 0) return;
|
|
827
|
+
done();
|
|
828
|
+
resolve();
|
|
829
|
+
};
|
|
830
|
+
const onError = (e) => fail(this.spawnError(e));
|
|
831
|
+
const onExit = (code) => {
|
|
832
|
+
if (code === 0 && stdout.readableLength > 0) return onReadable();
|
|
833
|
+
fail(new Error(stderr() || `yt-dlp exited with code ${code} before streaming`));
|
|
834
|
+
};
|
|
835
|
+
const timer = setTimeout(() => fail(/* @__PURE__ */ new Error(`yt-dlp produced no audio within ${this.timeoutMs}ms`)), this.timeoutMs);
|
|
836
|
+
stdout.on("readable", onReadable);
|
|
837
|
+
proc.once("error", onError);
|
|
838
|
+
proc.once("exit", onExit);
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
spawnError(error) {
|
|
842
|
+
if (error.code !== "ENOENT") return error;
|
|
843
|
+
return /* @__PURE__ */ new Error(`yt-dlp not found ("${this.binary}"). Install it or set the \`ytdlp.path\` option / YTDLP_PATH.`);
|
|
844
|
+
}
|
|
845
|
+
};
|
|
846
|
+
function entryToTrack(e, platform) {
|
|
847
|
+
if (!e.title || UNAVAILABLE.test(e.title)) return null;
|
|
848
|
+
let url = e.webpage_url ?? e.url;
|
|
849
|
+
const isYouTube = (e.ie_key ?? e.extractor_key) === "Youtube";
|
|
850
|
+
if ((!url || !/^https?:/.test(url)) && isYouTube && e.id) url = `https://www.youtube.com/watch?v=${e.id}`;
|
|
851
|
+
if (!url) return null;
|
|
852
|
+
const isLive = e.live_status === "is_live" || e.is_live === true;
|
|
853
|
+
return {
|
|
854
|
+
title: e.title,
|
|
855
|
+
url,
|
|
856
|
+
author: e.channel ?? e.uploader ?? e.artist,
|
|
857
|
+
duration: !isLive && e.duration ? Math.round(e.duration) : void 0,
|
|
858
|
+
thumbnail: e.thumbnail ?? bestThumbnail(e.thumbnails),
|
|
859
|
+
isLive,
|
|
860
|
+
platform
|
|
861
|
+
};
|
|
862
|
+
}
|
|
863
|
+
function toTracks(entries, platform) {
|
|
864
|
+
return (entries ?? []).map((e) => entryToTrack(e, platform)).filter((t) => t !== null);
|
|
865
|
+
}
|
|
866
|
+
function bestThumbnail(thumbs) {
|
|
867
|
+
if (!thumbs?.length) return void 0;
|
|
868
|
+
const score = (t) => [t.preference ?? 0, t.width ?? 0];
|
|
869
|
+
return [...thumbs].sort((a, b) => score(a)[0] - score(b)[0] || score(a)[1] - score(b)[1]).at(-1)?.url;
|
|
870
|
+
}
|
|
871
|
+
/** Collect stderr and return the ERROR lines (or everything if there are none). */
|
|
872
|
+
function collectErrors(proc) {
|
|
873
|
+
let stderr = "";
|
|
874
|
+
proc.stderr?.setEncoding("utf8").on("data", (chunk) => {
|
|
875
|
+
if (stderr.length < 4096) stderr += chunk;
|
|
876
|
+
});
|
|
877
|
+
return () => stderr.trim().split("\n").filter((l) => l.startsWith("ERROR")).join("\n") || stderr.trim();
|
|
878
|
+
}
|
|
879
|
+
//#endregion
|
|
880
|
+
//#region src/sources/Sources.ts
|
|
881
|
+
var UnsupportedUrlError = class extends Error {
|
|
882
|
+
constructor(url) {
|
|
883
|
+
super(`Unsupported link: ${url}`);
|
|
884
|
+
this.url = url;
|
|
885
|
+
this.name = "UnsupportedUrlError";
|
|
886
|
+
}
|
|
887
|
+
};
|
|
888
|
+
var NoStreamError = class extends Error {
|
|
889
|
+
constructor(track) {
|
|
890
|
+
super(`No source could play "${track.title}"`);
|
|
891
|
+
this.track = track;
|
|
892
|
+
this.name = "NoStreamError";
|
|
893
|
+
}
|
|
894
|
+
};
|
|
895
|
+
/** Turns user input into tracks and tracks into audio, honoring the `sources` fallback order. */
|
|
896
|
+
var Sources = class Sources {
|
|
897
|
+
/** Stand-ins found on another platform, so a looping track isn't searched again. */
|
|
898
|
+
substitutes = /* @__PURE__ */ new WeakMap();
|
|
899
|
+
constructor(order, backends, onError = () => {}) {
|
|
900
|
+
this.order = order;
|
|
901
|
+
this.backends = backends;
|
|
902
|
+
this.onError = onError;
|
|
903
|
+
}
|
|
904
|
+
static create(options, onError) {
|
|
905
|
+
const ytdlp = new YtDlp(options.ytdlp.path, options.ytdlp.args);
|
|
906
|
+
const backends = {
|
|
907
|
+
youtube: new YouTube(ytdlp, options.maxPlaylistSize),
|
|
908
|
+
soundcloud: new SoundCloud(ytdlp, options.maxPlaylistSize),
|
|
909
|
+
spotify: new Spotify(options.spotify, options.maxPlaylistSize, onError),
|
|
910
|
+
stream: (url) => ytdlp.stream(url)
|
|
911
|
+
};
|
|
912
|
+
return new Sources(options.sources, backends, onError);
|
|
913
|
+
}
|
|
914
|
+
/** Links resolve on their own platform; anything else is searched and the top result used. */
|
|
915
|
+
async resolve(input) {
|
|
916
|
+
const url = parseUrl(input);
|
|
917
|
+
if (!url) return { tracks: (await this.search(input, 1)).slice(0, 1) };
|
|
918
|
+
const platform = detectPlatform(url);
|
|
919
|
+
if (!platform) throw new UnsupportedUrlError(url.href);
|
|
920
|
+
return await this.backends[platform].resolve(url) ?? { tracks: [] };
|
|
921
|
+
}
|
|
922
|
+
/** Search each source in order and return the first non-empty results. */
|
|
923
|
+
async search(query, limit) {
|
|
924
|
+
for (const source of this.order) {
|
|
925
|
+
const results = await this.searchOn(source, query, limit);
|
|
926
|
+
if (results.length > 0) return results;
|
|
927
|
+
}
|
|
928
|
+
return [];
|
|
929
|
+
}
|
|
930
|
+
/** Like `search`, but gives up after `timeoutMs` (Discord allows ~3s for autocomplete). */
|
|
931
|
+
async autocomplete(query, limit, timeoutMs = 2500) {
|
|
932
|
+
if (!query.trim()) return [];
|
|
933
|
+
let timer;
|
|
934
|
+
const timeout = new Promise((resolve) => timer = setTimeout(resolve, timeoutMs, []));
|
|
935
|
+
try {
|
|
936
|
+
return await Promise.race([this.search(query, limit), timeout]);
|
|
937
|
+
} finally {
|
|
938
|
+
clearTimeout(timer);
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
/**
|
|
942
|
+
* Stream a track: YouTube and SoundCloud tracks play directly first. If that fails, or the
|
|
943
|
+
* track is from Spotify, the song is searched on the other sources in order.
|
|
944
|
+
*/
|
|
945
|
+
async stream(track) {
|
|
946
|
+
if (track.platform !== "spotify") {
|
|
947
|
+
const direct = await this.tryStream(track);
|
|
948
|
+
if (direct) return direct;
|
|
949
|
+
}
|
|
950
|
+
const known = this.substitutes.get(track);
|
|
951
|
+
const knownStream = known && await this.tryStream(known);
|
|
952
|
+
if (knownStream) return knownStream;
|
|
953
|
+
const query = searchQuery(track);
|
|
954
|
+
for (const source of this.order) {
|
|
955
|
+
if (source === track.platform) continue;
|
|
956
|
+
for (const match of await this.searchOn(source, query, FALLBACK_CANDIDATES)) {
|
|
957
|
+
const stream = await this.tryStream(match);
|
|
958
|
+
if (stream) {
|
|
959
|
+
this.substitutes.set(track, match);
|
|
960
|
+
return stream;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
throw new NoStreamError(track);
|
|
965
|
+
}
|
|
966
|
+
async searchOn(source, query, limit) {
|
|
967
|
+
try {
|
|
968
|
+
return await this.backends[source].search(query, limit);
|
|
969
|
+
} catch (error) {
|
|
970
|
+
this.onError(new Error(`${source} search failed: ${errorMessage(error)}`, { cause: error }));
|
|
971
|
+
return [];
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
async tryStream(track) {
|
|
975
|
+
try {
|
|
976
|
+
return await this.backends.stream(track.url);
|
|
977
|
+
} catch (error) {
|
|
978
|
+
this.onError(new Error(`Streaming "${track.title}" from ${track.platform} failed: ${errorMessage(error)}`, { cause: error }));
|
|
979
|
+
return null;
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
};
|
|
983
|
+
const FALLBACK_CANDIDATES = 3;
|
|
984
|
+
const NOISE = /\s*[([][^)\]]*\b(official|video|audio|lyrics?|visualizer|remaster(ed)?|hd|4k)\b[^)\]]*[)\]]/gi;
|
|
985
|
+
/** Search terms for finding the same song elsewhere: "Artist - Title" without "(Official Video)" etc. */
|
|
986
|
+
function searchQuery(track) {
|
|
987
|
+
const title = track.title.replace(NOISE, "").trim() || track.title;
|
|
988
|
+
const artist = track.author?.split(", ")[0]?.replace(/\s*-\s*Topic$/, "");
|
|
989
|
+
if (!artist || title.toLowerCase().includes(artist.toLowerCase())) return title;
|
|
990
|
+
return `${artist} - ${title}`;
|
|
991
|
+
}
|
|
992
|
+
function errorMessage(error) {
|
|
993
|
+
return error instanceof Error ? error.message.split("\n")[0] : String(error);
|
|
994
|
+
}
|
|
995
|
+
//#endregion
|
|
996
|
+
//#region src/commands/play.ts
|
|
997
|
+
const PICK_TTL = 10 * 6e4;
|
|
998
|
+
const MAX_PICKS = 500;
|
|
999
|
+
/** Search results waiting for the user to choose one in the picker menu. */
|
|
1000
|
+
var PickStore = class {
|
|
1001
|
+
picks = /* @__PURE__ */ new Map();
|
|
1002
|
+
add(tracks, next, userId) {
|
|
1003
|
+
const now = Date.now();
|
|
1004
|
+
for (const [key, pick] of this.picks) if (pick.expires < now || this.picks.size >= MAX_PICKS) this.picks.delete(key);
|
|
1005
|
+
const key = (0, node_crypto.randomUUID)().slice(0, 8);
|
|
1006
|
+
this.picks.set(key, {
|
|
1007
|
+
tracks,
|
|
1008
|
+
next,
|
|
1009
|
+
userId,
|
|
1010
|
+
expires: now + PICK_TTL
|
|
1011
|
+
});
|
|
1012
|
+
return key;
|
|
1013
|
+
}
|
|
1014
|
+
/** Remove and return a pick, or `null` when it expired. */
|
|
1015
|
+
take(key) {
|
|
1016
|
+
const pick = this.picks.get(key);
|
|
1017
|
+
this.picks.delete(key);
|
|
1018
|
+
return pick && pick.expires > Date.now() ? pick : null;
|
|
1019
|
+
}
|
|
1020
|
+
};
|
|
1021
|
+
async function play(ctx, i, voice) {
|
|
1022
|
+
const { music } = ctx;
|
|
1023
|
+
const query = i.options.getString("query", true);
|
|
1024
|
+
const next = i.options.getBoolean("next") ?? false;
|
|
1025
|
+
if (!await checkChannelRule(music.options.channels.voice, voice)) throw new Refusal(`🚫 I’m not allowed to play music in <#${voice.id}>.`);
|
|
1026
|
+
if (!voice.joinable) throw new Refusal(`🚫 I can’t join <#${voice.id}>.`);
|
|
1027
|
+
const widgets = music.options.ui === "widgets";
|
|
1028
|
+
await i.deferReply({ flags: widgets ? discord_js.MessageFlags.Ephemeral : void 0 });
|
|
1029
|
+
const isLink = parseUrl(query) !== null;
|
|
1030
|
+
if (!isLink && widgets && music.options.searchLimit > 1) return showPicker(ctx, i, query, next);
|
|
1031
|
+
const suggested = isLink ? ctx.suggestions.findByUrl(query) : void 0;
|
|
1032
|
+
const result = suggested ? { tracks: [suggested] } : await resolve(ctx, query);
|
|
1033
|
+
if (result.tracks.length === 0) throw new Refusal(`🔍 Nothing found for **${query.slice(0, 100)}**.`);
|
|
1034
|
+
await enqueue(ctx, i, voice, result, next);
|
|
1035
|
+
}
|
|
1036
|
+
/** Queue tracks for the user who ran the interaction and reply with what happened. */
|
|
1037
|
+
async function enqueue({ music }, i, voice, result, next) {
|
|
1038
|
+
const player = await connect(music, i, voice);
|
|
1039
|
+
const requestedBy = {
|
|
1040
|
+
id: i.user.id,
|
|
1041
|
+
name: i.member.displayName
|
|
1042
|
+
};
|
|
1043
|
+
const tracks = result.tracks.slice(0, music.options.maxPlaylistSize).map((t) => ({
|
|
1044
|
+
...t,
|
|
1045
|
+
requestedBy
|
|
1046
|
+
}));
|
|
1047
|
+
const startsNow = !player.current && !player.isLoading;
|
|
1048
|
+
if (startsNow && music.options.ui === "commands") music.ui.suppressNextAnnouncement(player);
|
|
1049
|
+
const added = player.add(tracks, next);
|
|
1050
|
+
if (added.length === 0) throw new Refusal(`📛 The queue is full (${music.options.maxQueueSize} tracks).`);
|
|
1051
|
+
music.emit("trackAdd", player, added, result.playlist);
|
|
1052
|
+
const skipped = tracks.length - added.length;
|
|
1053
|
+
let content;
|
|
1054
|
+
if (result.playlist) {
|
|
1055
|
+
const full = skipped > 0 ? ` (${skipped} skipped, queue full)` : "";
|
|
1056
|
+
content = `📃 Added **${added.length}** tracks from ${trackTitle(result.playlist)}${full}.`;
|
|
1057
|
+
} else if (startsNow) content = `🎶 Now playing ${trackLine(added[0])}`;
|
|
1058
|
+
else content = `➕ Queued ${trackLine(added[0])} at position **${next ? 1 : player.queue.size}**.`;
|
|
1059
|
+
await reply(music, i, {
|
|
1060
|
+
content,
|
|
1061
|
+
components: []
|
|
1062
|
+
});
|
|
1063
|
+
}
|
|
1064
|
+
async function showPicker(ctx, i, query, next) {
|
|
1065
|
+
const tracks = await ctx.music.sources.search(query, ctx.music.options.searchLimit);
|
|
1066
|
+
if (tracks.length === 0) throw new Refusal(`🔍 Nothing found for **${query.slice(0, 100)}**.`);
|
|
1067
|
+
const key = ctx.picks.add(tracks, next, i.user.id);
|
|
1068
|
+
await i.editReply({
|
|
1069
|
+
content: "🔍 Pick a track:",
|
|
1070
|
+
components: [searchPicker(tracks, ctx.music.options.customIdPrefix, key)]
|
|
1071
|
+
});
|
|
1072
|
+
}
|
|
1073
|
+
async function resolve({ music }, query) {
|
|
1074
|
+
try {
|
|
1075
|
+
return await music.sources.resolve(query);
|
|
1076
|
+
} catch (error) {
|
|
1077
|
+
if (error instanceof UnsupportedUrlError) throw new Refusal("🔗 Only YouTube, SoundCloud and Spotify links are supported.");
|
|
1078
|
+
throw error;
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
async function connect(music, i, voice) {
|
|
1082
|
+
try {
|
|
1083
|
+
return await music.join(voice, i.channel?.isSendable() ? i.channel : null);
|
|
1084
|
+
} catch (error) {
|
|
1085
|
+
music.reportError(error);
|
|
1086
|
+
throw new Refusal(`🔇 Couldn’t connect to <#${voice.id}>.`);
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
//#endregion
|
|
1090
|
+
//#region src/commands/components.ts
|
|
1091
|
+
const VOLUME_STEP = 10;
|
|
1092
|
+
/** Buttons and menus. Custom ids look like `<prefix>:<kind>:<arg>`. */
|
|
1093
|
+
async function handleComponent(ctx, i) {
|
|
1094
|
+
const [, kind, arg = ""] = i.customId.split(":");
|
|
1095
|
+
await checkAccess(ctx.music, i);
|
|
1096
|
+
if (kind === "queue" && i.isButton()) return showQueuePage(ctx, i, Number(arg) || 1);
|
|
1097
|
+
if (kind === "pick" && i.isStringSelectMenu()) return pickTrack(ctx, i, arg);
|
|
1098
|
+
if (kind === "ctl" && i.isButton()) return control(ctx, i, arg);
|
|
1099
|
+
await i.deferUpdate();
|
|
1100
|
+
}
|
|
1101
|
+
async function showQueuePage({ music }, i, page) {
|
|
1102
|
+
const player = music.get(i.guildId);
|
|
1103
|
+
if (!player) return void await i.update({ components: [] });
|
|
1104
|
+
const view = queueEmbed(player, page, music.options.embedColor);
|
|
1105
|
+
const components = view.pages > 1 ? [queuePager(music.options.customIdPrefix, view.page, view.pages)] : [];
|
|
1106
|
+
await i.update({
|
|
1107
|
+
embeds: [view.embed],
|
|
1108
|
+
components
|
|
1109
|
+
});
|
|
1110
|
+
}
|
|
1111
|
+
async function pickTrack(ctx, i, key) {
|
|
1112
|
+
const pick = ctx.picks.take(key);
|
|
1113
|
+
if (!pick) return void await i.update({
|
|
1114
|
+
content: "⌛ This search expired, run the command again.",
|
|
1115
|
+
components: []
|
|
1116
|
+
});
|
|
1117
|
+
if (pick.userId !== i.user.id) throw new Refusal("This menu isn’t yours.");
|
|
1118
|
+
const voice = requireSameVoice(ctx.music, i);
|
|
1119
|
+
const track = pick.tracks[Number(i.values[0])];
|
|
1120
|
+
if (!track) throw new Refusal("Unknown choice.");
|
|
1121
|
+
await i.update({
|
|
1122
|
+
content: `⏳ Adding ${trackTitle(track)}…`,
|
|
1123
|
+
components: []
|
|
1124
|
+
});
|
|
1125
|
+
await enqueue(ctx, i, voice, { tracks: [track] }, pick.next);
|
|
1126
|
+
}
|
|
1127
|
+
/** Now-playing panel buttons. */
|
|
1128
|
+
async function control({ music }, i, action) {
|
|
1129
|
+
const player = music.get(i.guildId);
|
|
1130
|
+
if (action === "queue") {
|
|
1131
|
+
if (!player) throw new Refusal("📭 The queue is empty.");
|
|
1132
|
+
const view = queueEmbed(player, 1, music.options.embedColor);
|
|
1133
|
+
const components = view.pages > 1 ? [queuePager(music.options.customIdPrefix, view.page, view.pages)] : [];
|
|
1134
|
+
await i.reply({
|
|
1135
|
+
embeds: [view.embed],
|
|
1136
|
+
components,
|
|
1137
|
+
flags: discord_js.MessageFlags.Ephemeral
|
|
1138
|
+
});
|
|
1139
|
+
return;
|
|
1140
|
+
}
|
|
1141
|
+
requireSameVoice(music, i);
|
|
1142
|
+
if (!player?.current) return void await i.update({ components: [] });
|
|
1143
|
+
switch (action) {
|
|
1144
|
+
case "skip":
|
|
1145
|
+
player.skip();
|
|
1146
|
+
await i.deferUpdate();
|
|
1147
|
+
return;
|
|
1148
|
+
case "stop":
|
|
1149
|
+
player.stop();
|
|
1150
|
+
await i.deferUpdate();
|
|
1151
|
+
return;
|
|
1152
|
+
case "toggle":
|
|
1153
|
+
if (player.isPaused) player.resume();
|
|
1154
|
+
else player.pause();
|
|
1155
|
+
break;
|
|
1156
|
+
case "shuffle":
|
|
1157
|
+
player.shuffle();
|
|
1158
|
+
break;
|
|
1159
|
+
case "loop":
|
|
1160
|
+
player.setLoop(nextLoopMode(player.loop));
|
|
1161
|
+
break;
|
|
1162
|
+
case "voldown":
|
|
1163
|
+
player.setVolume(player.volume - VOLUME_STEP);
|
|
1164
|
+
break;
|
|
1165
|
+
case "volup":
|
|
1166
|
+
player.setVolume(player.volume + VOLUME_STEP);
|
|
1167
|
+
break;
|
|
1168
|
+
}
|
|
1169
|
+
await i.update(music.ui.panelPayload(player));
|
|
1170
|
+
}
|
|
1171
|
+
//#endregion
|
|
1172
|
+
//#region src/commands/slash.ts
|
|
1173
|
+
/** Commands anyone may use without joining the bot's voice channel. */
|
|
1174
|
+
const READ_ONLY = new Set(["queue", "nowplaying"]);
|
|
1175
|
+
async function runCommand(ctx, key, i) {
|
|
1176
|
+
await checkAccess(ctx.music, i);
|
|
1177
|
+
if (key === "play") return play(ctx, i, requireSameVoice(ctx.music, i));
|
|
1178
|
+
if (!READ_ONLY.has(key)) requireSameVoice(ctx.music, i);
|
|
1179
|
+
return handlers[key](ctx, i);
|
|
1180
|
+
}
|
|
1181
|
+
const handlers = {
|
|
1182
|
+
async skip({ music }, i) {
|
|
1183
|
+
const player = requirePlaying(music, i.guildId);
|
|
1184
|
+
const to = i.options.getInteger("to") ?? void 0;
|
|
1185
|
+
if (to && to > player.queue.size) throw new Refusal(`The queue only has ${player.queue.size} tracks.`);
|
|
1186
|
+
const skipped = player.skip(to);
|
|
1187
|
+
await reply(music, i, `⏭️ Skipped ${skipped ? trackTitle(skipped) : "the track"}.`);
|
|
1188
|
+
},
|
|
1189
|
+
async stop({ music }, i) {
|
|
1190
|
+
requirePlaying(music, i.guildId).stop();
|
|
1191
|
+
await reply(music, i, "⏹️ Stopped and cleared the queue.");
|
|
1192
|
+
},
|
|
1193
|
+
async pause({ music }, i) {
|
|
1194
|
+
await reply(music, i, requirePlaying(music, i.guildId).pause() ? "⏸️ Paused." : "Already paused.");
|
|
1195
|
+
},
|
|
1196
|
+
async resume({ music }, i) {
|
|
1197
|
+
await reply(music, i, requirePlaying(music, i.guildId).resume() ? "▶️ Resumed." : "Not paused.");
|
|
1198
|
+
},
|
|
1199
|
+
async queue({ music }, i) {
|
|
1200
|
+
const player = music.get(i.guildId);
|
|
1201
|
+
if (!player?.current && !player?.queue.size) throw new Refusal("📭 The queue is empty.");
|
|
1202
|
+
const { embed, page, pages } = queueEmbed(player, i.options.getInteger("page") ?? 1, music.options.embedColor);
|
|
1203
|
+
const pager = music.options.ui === "widgets" && pages > 1;
|
|
1204
|
+
await reply(music, i, {
|
|
1205
|
+
embeds: [embed],
|
|
1206
|
+
components: pager ? [queuePager(music.options.customIdPrefix, page, pages)] : []
|
|
1207
|
+
});
|
|
1208
|
+
},
|
|
1209
|
+
async nowplaying({ music }, i) {
|
|
1210
|
+
await reply(music, i, { embeds: [nowPlayingEmbed(requirePlaying(music, i.guildId), music.options.embedColor)] });
|
|
1211
|
+
},
|
|
1212
|
+
async volume({ music }, i) {
|
|
1213
|
+
const player = requireConnected(music, i.guildId);
|
|
1214
|
+
const level = i.options.getInteger("level");
|
|
1215
|
+
if (level === null) return reply(music, i, `🔊 Volume: **${player.volume}%**`);
|
|
1216
|
+
await reply(music, i, `🔊 Volume set to **${player.setVolume(level)}%**.`);
|
|
1217
|
+
},
|
|
1218
|
+
async loop({ music }, i) {
|
|
1219
|
+
const player = requirePlaying(music, i.guildId);
|
|
1220
|
+
const mode = i.options.getString("mode") ?? nextLoopMode(player.loop);
|
|
1221
|
+
player.setLoop(mode);
|
|
1222
|
+
await reply(music, i, `🔁 Loop: **${LOOP_LABELS[mode]}**`);
|
|
1223
|
+
},
|
|
1224
|
+
async shuffle({ music }, i) {
|
|
1225
|
+
const player = requirePlaying(music, i.guildId);
|
|
1226
|
+
if (player.queue.size < 2) throw new Refusal("Not enough tracks in the queue to shuffle.");
|
|
1227
|
+
player.shuffle();
|
|
1228
|
+
await reply(music, i, `🔀 Shuffled ${player.queue.size} tracks.`);
|
|
1229
|
+
},
|
|
1230
|
+
async remove({ music }, i) {
|
|
1231
|
+
const removed = requirePlaying(music, i.guildId).remove(i.options.getInteger("position", true));
|
|
1232
|
+
if (!removed) throw new Refusal("No track at that position.");
|
|
1233
|
+
await reply(music, i, `🗑️ Removed ${trackTitle(removed)}.`);
|
|
1234
|
+
},
|
|
1235
|
+
async clear({ music }, i) {
|
|
1236
|
+
const player = requirePlaying(music, i.guildId);
|
|
1237
|
+
const count = player.queue.size;
|
|
1238
|
+
player.clear();
|
|
1239
|
+
await reply(music, i, `🧹 Cleared ${count} tracks.`);
|
|
1240
|
+
},
|
|
1241
|
+
async leave({ music }, i) {
|
|
1242
|
+
requireConnected(music, i.guildId).destroy();
|
|
1243
|
+
await reply(music, i, "👋 Left the voice channel.");
|
|
1244
|
+
}
|
|
1245
|
+
};
|
|
1246
|
+
//#endregion
|
|
1247
|
+
//#region src/commands/router.ts
|
|
1248
|
+
const GUILD_ONLY = "Music commands only work in servers.";
|
|
1249
|
+
/** Sends interactions that belong to the music player to their handlers. */
|
|
1250
|
+
var InteractionRouter = class {
|
|
1251
|
+
ctx;
|
|
1252
|
+
constructor(music) {
|
|
1253
|
+
this.ctx = {
|
|
1254
|
+
music,
|
|
1255
|
+
picks: new PickStore(),
|
|
1256
|
+
suggestions: new SuggestionCache()
|
|
1257
|
+
};
|
|
1258
|
+
}
|
|
1259
|
+
/** Returns `true` when the interaction belonged to the music player. */
|
|
1260
|
+
async handle(i) {
|
|
1261
|
+
const { commands, options } = this.ctx.music;
|
|
1262
|
+
if (i.isAutocomplete()) {
|
|
1263
|
+
if (commands.resolve(i.commandName, i.options.getSubcommand(false)) !== "play") return false;
|
|
1264
|
+
await autocomplete(this.ctx, i);
|
|
1265
|
+
return true;
|
|
1266
|
+
}
|
|
1267
|
+
if (i.isChatInputCommand()) {
|
|
1268
|
+
const key = commands.resolve(i.commandName, i.options.getSubcommand(false));
|
|
1269
|
+
if (!key) return false;
|
|
1270
|
+
await this.safely(i, () => {
|
|
1271
|
+
if (!i.inCachedGuild()) throw new Refusal(GUILD_ONLY);
|
|
1272
|
+
return runCommand(this.ctx, key, i);
|
|
1273
|
+
});
|
|
1274
|
+
return true;
|
|
1275
|
+
}
|
|
1276
|
+
if ((i.isButton() || i.isStringSelectMenu()) && i.customId.startsWith(`${options.customIdPrefix}:`)) {
|
|
1277
|
+
await this.safely(i, () => {
|
|
1278
|
+
if (!i.inCachedGuild()) throw new Refusal(GUILD_ONLY);
|
|
1279
|
+
return handleComponent(this.ctx, i);
|
|
1280
|
+
});
|
|
1281
|
+
return true;
|
|
1282
|
+
}
|
|
1283
|
+
return false;
|
|
1284
|
+
}
|
|
1285
|
+
/** Run a handler, turning refusals and errors into ephemeral replies. */
|
|
1286
|
+
async safely(i, run) {
|
|
1287
|
+
try {
|
|
1288
|
+
await run();
|
|
1289
|
+
} catch (error) {
|
|
1290
|
+
if (error instanceof Refusal) return replyError(i, error.message);
|
|
1291
|
+
this.ctx.music.reportError(error, i.guildId ? this.ctx.music.get(i.guildId) : void 0);
|
|
1292
|
+
await replyError(i, "❌ Something went wrong.");
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
};
|
|
1296
|
+
//#endregion
|
|
1297
|
+
//#region src/options.ts
|
|
1298
|
+
function resolveOptions(options) {
|
|
1299
|
+
const sources = options.sources ?? ["youtube", "soundcloud"];
|
|
1300
|
+
if (sources.length === 0) throw new Error("`sources` needs at least one entry");
|
|
1301
|
+
for (const s of sources) if (s !== "youtube" && s !== "soundcloud") throw new Error(`Unknown source "${String(s)}"`);
|
|
1302
|
+
const customIdPrefix = options.customIdPrefix ?? "dw";
|
|
1303
|
+
if (customIdPrefix.includes(":")) throw new Error("`customIdPrefix` must not contain \":\"");
|
|
1304
|
+
return {
|
|
1305
|
+
sources: [...new Set(sources)],
|
|
1306
|
+
ui: options.ui ?? "commands",
|
|
1307
|
+
channels: options.channels ?? {},
|
|
1308
|
+
commands: options.commands ?? {},
|
|
1309
|
+
spotify: options.spotify,
|
|
1310
|
+
ytdlp: {
|
|
1311
|
+
path: options.ytdlp?.path || process.env.YTDLP_PATH || "yt-dlp",
|
|
1312
|
+
args: options.ytdlp?.args ?? []
|
|
1313
|
+
},
|
|
1314
|
+
listen: options.listen ?? true,
|
|
1315
|
+
canUse: options.canUse,
|
|
1316
|
+
defaultVolume: clamp(options.defaultVolume ?? 80, 0, 200),
|
|
1317
|
+
maxQueueSize: options.maxQueueSize ?? 500,
|
|
1318
|
+
maxPlaylistSize: options.maxPlaylistSize ?? 200,
|
|
1319
|
+
searchLimit: clamp(options.searchLimit ?? 5, 1, 25),
|
|
1320
|
+
leaveOnEmpty: options.leaveOnEmpty ?? 60,
|
|
1321
|
+
leaveOnFinish: options.leaveOnFinish ?? 300,
|
|
1322
|
+
announceTracks: options.announceTracks ?? true,
|
|
1323
|
+
embedColor: options.embedColor ?? 5793266,
|
|
1324
|
+
customIdPrefix
|
|
1325
|
+
};
|
|
1326
|
+
}
|
|
1327
|
+
function clamp(n, min, max) {
|
|
1328
|
+
return Math.max(min, Math.min(max, n));
|
|
1329
|
+
}
|
|
1330
|
+
//#endregion
|
|
1331
|
+
//#region src/player/TrackQueue.ts
|
|
1332
|
+
/** Pure queue state: no voice, no Discord. */
|
|
1333
|
+
var TrackQueue = class {
|
|
1334
|
+
current = null;
|
|
1335
|
+
upcoming = [];
|
|
1336
|
+
loop = "off";
|
|
1337
|
+
constructor(maxSize = Infinity) {
|
|
1338
|
+
this.maxSize = maxSize;
|
|
1339
|
+
}
|
|
1340
|
+
get size() {
|
|
1341
|
+
return this.upcoming.length;
|
|
1342
|
+
}
|
|
1343
|
+
/** Free slots left before `maxSize` is reached. */
|
|
1344
|
+
get remaining() {
|
|
1345
|
+
return Math.max(0, this.maxSize - this.upcoming.length);
|
|
1346
|
+
}
|
|
1347
|
+
/**
|
|
1348
|
+
* Add tracks to the end, or right after the current track when `next` is true.
|
|
1349
|
+
* Returns the tracks that were actually added (may be truncated by `maxSize`).
|
|
1350
|
+
*/
|
|
1351
|
+
add(tracks, next = false) {
|
|
1352
|
+
const added = tracks.slice(0, this.remaining).map((t) => ({
|
|
1353
|
+
...t,
|
|
1354
|
+
uid: t.uid ?? (0, node_crypto.randomUUID)()
|
|
1355
|
+
}));
|
|
1356
|
+
if (next) this.upcoming.unshift(...added);
|
|
1357
|
+
else this.upcoming.push(...added);
|
|
1358
|
+
return added;
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1361
|
+
* Advance to the next track according to the loop mode and return it.
|
|
1362
|
+
* `skip` ignores `loop = 'track'` (a manual skip should move on).
|
|
1363
|
+
*/
|
|
1364
|
+
advance(skip = false) {
|
|
1365
|
+
const prev = this.current;
|
|
1366
|
+
if (prev && this.loop === "track" && !skip) return prev;
|
|
1367
|
+
if (prev && this.loop === "queue") this.upcoming.push(prev);
|
|
1368
|
+
this.current = this.upcoming.shift() ?? null;
|
|
1369
|
+
return this.current;
|
|
1370
|
+
}
|
|
1371
|
+
/** Skip ahead so that the track at 1-based `position` plays next. Returns the dropped tracks. */
|
|
1372
|
+
skipTo(position) {
|
|
1373
|
+
const dropped = this.upcoming.splice(0, Math.max(0, position - 1));
|
|
1374
|
+
if (this.loop === "queue") this.upcoming.push(...dropped);
|
|
1375
|
+
return dropped;
|
|
1376
|
+
}
|
|
1377
|
+
/** Remove the track at 1-based `position`. */
|
|
1378
|
+
remove(position) {
|
|
1379
|
+
if (position < 1 || position > this.upcoming.length) return null;
|
|
1380
|
+
return this.upcoming.splice(position - 1, 1)[0] ?? null;
|
|
1381
|
+
}
|
|
1382
|
+
/** Move a track from one 1-based position to another. */
|
|
1383
|
+
move(from, to) {
|
|
1384
|
+
if (from < 1 || from > this.upcoming.length || to < 1 || to > this.upcoming.length) return false;
|
|
1385
|
+
const [track] = this.upcoming.splice(from - 1, 1);
|
|
1386
|
+
this.upcoming.splice(to - 1, 0, track);
|
|
1387
|
+
return true;
|
|
1388
|
+
}
|
|
1389
|
+
shuffle(random = Math.random) {
|
|
1390
|
+
const a = this.upcoming;
|
|
1391
|
+
for (let i = a.length - 1; i > 0; i--) {
|
|
1392
|
+
const j = Math.floor(random() * (i + 1));
|
|
1393
|
+
[a[i], a[j]] = [a[j], a[i]];
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
clear() {
|
|
1397
|
+
this.upcoming.length = 0;
|
|
1398
|
+
}
|
|
1399
|
+
reset() {
|
|
1400
|
+
this.clear();
|
|
1401
|
+
this.current = null;
|
|
1402
|
+
this.loop = "off";
|
|
1403
|
+
}
|
|
1404
|
+
/** Total duration in seconds of upcoming tracks with known length. */
|
|
1405
|
+
get totalDuration() {
|
|
1406
|
+
return this.upcoming.reduce((sum, t) => sum + (t.duration ?? 0), 0);
|
|
1407
|
+
}
|
|
1408
|
+
};
|
|
1409
|
+
//#endregion
|
|
1410
|
+
//#region src/player/GuildPlayer.ts
|
|
1411
|
+
/** Music state and playback for one guild. Create through `MusicPlayer`, not directly. */
|
|
1412
|
+
var GuildPlayer = class {
|
|
1413
|
+
queue;
|
|
1414
|
+
audio;
|
|
1415
|
+
connection = null;
|
|
1416
|
+
/** Where announcements and widgets go. Updated to the channel of the latest /play. */
|
|
1417
|
+
textChannel = null;
|
|
1418
|
+
volume;
|
|
1419
|
+
/** Playing resource. `null` while idle or while the next track is loading. */
|
|
1420
|
+
resource = null;
|
|
1421
|
+
failedResource = null;
|
|
1422
|
+
/** Incremented on every load; a stale load discards its stream. */
|
|
1423
|
+
loadId = 0;
|
|
1424
|
+
loading = false;
|
|
1425
|
+
emptyTimer;
|
|
1426
|
+
finishTimer;
|
|
1427
|
+
destroyed = false;
|
|
1428
|
+
constructor(manager, guild) {
|
|
1429
|
+
this.manager = manager;
|
|
1430
|
+
this.guild = guild;
|
|
1431
|
+
this.queue = new TrackQueue(manager.options.maxQueueSize);
|
|
1432
|
+
this.volume = manager.options.defaultVolume;
|
|
1433
|
+
this.audio = (0, _discordjs_voice.createAudioPlayer)({ behaviors: { noSubscriber: _discordjs_voice.NoSubscriberBehavior.Pause } });
|
|
1434
|
+
this.audio.on(_discordjs_voice.AudioPlayerStatus.Idle, (oldState) => {
|
|
1435
|
+
if (oldState.status === _discordjs_voice.AudioPlayerStatus.Idle) return;
|
|
1436
|
+
if (oldState.resource !== this.resource) return;
|
|
1437
|
+
const failed = oldState.resource === this.failedResource;
|
|
1438
|
+
const prev = this.queue.current;
|
|
1439
|
+
this.resource = null;
|
|
1440
|
+
if (prev) this.manager.emit("trackEnd", this, prev);
|
|
1441
|
+
this.queue.advance(failed);
|
|
1442
|
+
this.startCurrent();
|
|
1443
|
+
});
|
|
1444
|
+
this.audio.on("error", (error) => {
|
|
1445
|
+
this.failedResource = error.resource;
|
|
1446
|
+
this.manager.reportError(error, this, error.resource.metadata);
|
|
1447
|
+
});
|
|
1448
|
+
}
|
|
1449
|
+
get guildId() {
|
|
1450
|
+
return this.guild.id;
|
|
1451
|
+
}
|
|
1452
|
+
get current() {
|
|
1453
|
+
return this.queue.current;
|
|
1454
|
+
}
|
|
1455
|
+
get voiceChannelId() {
|
|
1456
|
+
return this.connection?.joinConfig.channelId ?? null;
|
|
1457
|
+
}
|
|
1458
|
+
get isPlaying() {
|
|
1459
|
+
return this.queue.current !== null && this.audio.state.status !== _discordjs_voice.AudioPlayerStatus.Idle;
|
|
1460
|
+
}
|
|
1461
|
+
get isPaused() {
|
|
1462
|
+
const s = this.audio.state.status;
|
|
1463
|
+
return s === _discordjs_voice.AudioPlayerStatus.Paused || s === _discordjs_voice.AudioPlayerStatus.AutoPaused;
|
|
1464
|
+
}
|
|
1465
|
+
get isLoading() {
|
|
1466
|
+
return this.loading;
|
|
1467
|
+
}
|
|
1468
|
+
/** Playback position of the current track in seconds. */
|
|
1469
|
+
get position() {
|
|
1470
|
+
return this.resource ? Math.floor(this.resource.playbackDuration / 1e3) : 0;
|
|
1471
|
+
}
|
|
1472
|
+
get loop() {
|
|
1473
|
+
return this.queue.loop;
|
|
1474
|
+
}
|
|
1475
|
+
/** Join (or move to) a voice channel. */
|
|
1476
|
+
async connect(channel) {
|
|
1477
|
+
if (this.connection && this.voiceChannelId === channel.id && this.connection.state.status !== _discordjs_voice.VoiceConnectionStatus.Destroyed) return;
|
|
1478
|
+
const connection = (0, _discordjs_voice.joinVoiceChannel)({
|
|
1479
|
+
channelId: channel.id,
|
|
1480
|
+
guildId: channel.guild.id,
|
|
1481
|
+
adapterCreator: channel.guild.voiceAdapterCreator,
|
|
1482
|
+
group: this.manager.voiceGroup,
|
|
1483
|
+
selfDeaf: true
|
|
1484
|
+
});
|
|
1485
|
+
if (connection !== this.connection) {
|
|
1486
|
+
this.connection = connection;
|
|
1487
|
+
connection.subscribe(this.audio);
|
|
1488
|
+
connection.on(_discordjs_voice.VoiceConnectionStatus.Disconnected, async () => {
|
|
1489
|
+
try {
|
|
1490
|
+
await Promise.race([(0, _discordjs_voice.entersState)(connection, _discordjs_voice.VoiceConnectionStatus.Signalling, 5e3), (0, _discordjs_voice.entersState)(connection, _discordjs_voice.VoiceConnectionStatus.Connecting, 5e3)]);
|
|
1491
|
+
} catch {
|
|
1492
|
+
this.destroy();
|
|
1493
|
+
}
|
|
1494
|
+
});
|
|
1495
|
+
connection.on(_discordjs_voice.VoiceConnectionStatus.Destroyed, () => this.destroy());
|
|
1496
|
+
connection.on("error", (error) => this.manager.reportError(error, this));
|
|
1497
|
+
}
|
|
1498
|
+
try {
|
|
1499
|
+
await (0, _discordjs_voice.entersState)(connection, _discordjs_voice.VoiceConnectionStatus.Ready, 2e4);
|
|
1500
|
+
} catch (error) {
|
|
1501
|
+
this.destroy();
|
|
1502
|
+
throw new Error(`Could not connect to voice channel ${channel.name}`, { cause: error });
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
/**
|
|
1506
|
+
* Queue tracks. Starts playback when nothing is playing.
|
|
1507
|
+
* Returns the tracks actually added (can be fewer when the queue is full).
|
|
1508
|
+
*/
|
|
1509
|
+
add(tracks, next = false) {
|
|
1510
|
+
const added = this.queue.add(tracks, next);
|
|
1511
|
+
clearTimeout(this.finishTimer);
|
|
1512
|
+
if (!this.queue.current && !this.loading) {
|
|
1513
|
+
this.queue.advance(true);
|
|
1514
|
+
this.startCurrent();
|
|
1515
|
+
} else this.manager.ui.refresh(this);
|
|
1516
|
+
return added;
|
|
1517
|
+
}
|
|
1518
|
+
/** Skip the current track, or jump to the 1-based queue `position`. */
|
|
1519
|
+
skip(position) {
|
|
1520
|
+
const skipped = this.queue.current;
|
|
1521
|
+
if (!skipped) return null;
|
|
1522
|
+
if (position && position > 1) this.queue.skipTo(position);
|
|
1523
|
+
this.resource = null;
|
|
1524
|
+
this.manager.emit("trackEnd", this, skipped);
|
|
1525
|
+
if (this.queue.advance(true)) this.startCurrent();
|
|
1526
|
+
else {
|
|
1527
|
+
this.audio.stop(true);
|
|
1528
|
+
this.onQueueEnd();
|
|
1529
|
+
}
|
|
1530
|
+
return skipped;
|
|
1531
|
+
}
|
|
1532
|
+
/** Stop playback and clear the queue. Stays connected until `leaveOnFinish` passes. */
|
|
1533
|
+
stop() {
|
|
1534
|
+
this.loadId++;
|
|
1535
|
+
this.loading = false;
|
|
1536
|
+
this.queue.reset();
|
|
1537
|
+
this.resource = null;
|
|
1538
|
+
this.audio.stop(true);
|
|
1539
|
+
this.onQueueEnd();
|
|
1540
|
+
}
|
|
1541
|
+
pause() {
|
|
1542
|
+
const ok = this.audio.pause();
|
|
1543
|
+
if (ok) this.manager.ui.refresh(this);
|
|
1544
|
+
return ok;
|
|
1545
|
+
}
|
|
1546
|
+
resume() {
|
|
1547
|
+
const ok = this.audio.unpause();
|
|
1548
|
+
if (ok) this.manager.ui.refresh(this);
|
|
1549
|
+
return ok;
|
|
1550
|
+
}
|
|
1551
|
+
/** Set volume in percent, 0-200. */
|
|
1552
|
+
setVolume(volume) {
|
|
1553
|
+
this.volume = Math.max(0, Math.min(200, Math.round(volume)));
|
|
1554
|
+
this.resource?.volume?.setVolumeLogarithmic(this.volume / 100);
|
|
1555
|
+
this.manager.ui.refresh(this);
|
|
1556
|
+
return this.volume;
|
|
1557
|
+
}
|
|
1558
|
+
setLoop(mode) {
|
|
1559
|
+
this.queue.loop = mode;
|
|
1560
|
+
this.manager.ui.refresh(this);
|
|
1561
|
+
}
|
|
1562
|
+
shuffle() {
|
|
1563
|
+
this.queue.shuffle();
|
|
1564
|
+
this.manager.ui.refresh(this);
|
|
1565
|
+
}
|
|
1566
|
+
remove(position) {
|
|
1567
|
+
const removed = this.queue.remove(position);
|
|
1568
|
+
if (removed) this.manager.ui.refresh(this);
|
|
1569
|
+
return removed;
|
|
1570
|
+
}
|
|
1571
|
+
clear() {
|
|
1572
|
+
this.queue.clear();
|
|
1573
|
+
this.manager.ui.refresh(this);
|
|
1574
|
+
}
|
|
1575
|
+
/** Disconnect and forget this guild's state. */
|
|
1576
|
+
destroy() {
|
|
1577
|
+
if (this.destroyed) return;
|
|
1578
|
+
this.destroyed = true;
|
|
1579
|
+
this.loadId++;
|
|
1580
|
+
clearTimeout(this.emptyTimer);
|
|
1581
|
+
clearTimeout(this.finishTimer);
|
|
1582
|
+
this.queue.reset();
|
|
1583
|
+
this.resource = null;
|
|
1584
|
+
this.audio.stop(true);
|
|
1585
|
+
if (this.connection && this.connection.state.status !== _discordjs_voice.VoiceConnectionStatus.Destroyed) this.connection.destroy();
|
|
1586
|
+
this.connection = null;
|
|
1587
|
+
this.manager.players.delete(this.guildId);
|
|
1588
|
+
this.manager.ui.disconnect(this);
|
|
1589
|
+
this.manager.emit("disconnect", this);
|
|
1590
|
+
}
|
|
1591
|
+
/** Called by MusicPlayer when listeners in the voice channel change. */
|
|
1592
|
+
setChannelEmpty(empty) {
|
|
1593
|
+
clearTimeout(this.emptyTimer);
|
|
1594
|
+
const delay = this.manager.options.leaveOnEmpty;
|
|
1595
|
+
if (empty && delay !== false) this.emptyTimer = setTimeout(() => this.destroy(), delay * 1e3);
|
|
1596
|
+
}
|
|
1597
|
+
/** Stream and play `queue.current`, skipping tracks that fail to load. */
|
|
1598
|
+
async startCurrent() {
|
|
1599
|
+
const id = ++this.loadId;
|
|
1600
|
+
const failed = /* @__PURE__ */ new Set();
|
|
1601
|
+
this.loading = true;
|
|
1602
|
+
try {
|
|
1603
|
+
while (!this.destroyed) {
|
|
1604
|
+
const track = this.queue.current;
|
|
1605
|
+
if (!track) return this.onQueueEnd();
|
|
1606
|
+
if (failed.has(track.uid)) {
|
|
1607
|
+
this.queue.reset();
|
|
1608
|
+
return this.onQueueEnd();
|
|
1609
|
+
}
|
|
1610
|
+
try {
|
|
1611
|
+
const stream = await this.manager.sources.stream(track);
|
|
1612
|
+
if (id !== this.loadId) {
|
|
1613
|
+
stream.destroy();
|
|
1614
|
+
return;
|
|
1615
|
+
}
|
|
1616
|
+
const resource = (0, _discordjs_voice.createAudioResource)(stream, {
|
|
1617
|
+
inputType: _discordjs_voice.StreamType.Arbitrary,
|
|
1618
|
+
inlineVolume: true,
|
|
1619
|
+
metadata: track
|
|
1620
|
+
});
|
|
1621
|
+
resource.volume?.setVolumeLogarithmic(this.volume / 100);
|
|
1622
|
+
this.resource = resource;
|
|
1623
|
+
this.failedResource = null;
|
|
1624
|
+
this.audio.play(resource);
|
|
1625
|
+
this.manager.emit("trackStart", this, track);
|
|
1626
|
+
this.manager.ui.trackStart(this, track);
|
|
1627
|
+
return;
|
|
1628
|
+
} catch (error) {
|
|
1629
|
+
if (id !== this.loadId) return;
|
|
1630
|
+
this.manager.reportError(error, this, track);
|
|
1631
|
+
this.manager.ui.trackFailed(this, track, error);
|
|
1632
|
+
failed.add(track.uid);
|
|
1633
|
+
this.queue.advance(true);
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
} finally {
|
|
1637
|
+
if (id === this.loadId) this.loading = false;
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
onQueueEnd() {
|
|
1641
|
+
this.resource = null;
|
|
1642
|
+
this.audio.stop(true);
|
|
1643
|
+
this.manager.emit("queueEnd", this);
|
|
1644
|
+
this.manager.ui.queueEnd(this);
|
|
1645
|
+
clearTimeout(this.finishTimer);
|
|
1646
|
+
const delay = this.manager.options.leaveOnFinish;
|
|
1647
|
+
if (delay !== false) this.finishTimer = setTimeout(() => this.destroy(), delay * 1e3);
|
|
1648
|
+
}
|
|
1649
|
+
};
|
|
1650
|
+
//#endregion
|
|
1651
|
+
//#region src/ui/UiController.ts
|
|
1652
|
+
const REFRESH_DELAY = 750;
|
|
1653
|
+
/** Sends announcements and keeps the widgets panel up to date. */
|
|
1654
|
+
var UiController = class {
|
|
1655
|
+
panels = /* @__PURE__ */ new Map();
|
|
1656
|
+
timers = /* @__PURE__ */ new Map();
|
|
1657
|
+
silenced = /* @__PURE__ */ new Set();
|
|
1658
|
+
constructor(mp) {
|
|
1659
|
+
this.mp = mp;
|
|
1660
|
+
}
|
|
1661
|
+
get widgets() {
|
|
1662
|
+
return this.mp.options.ui === "widgets";
|
|
1663
|
+
}
|
|
1664
|
+
trackStart(player, track) {
|
|
1665
|
+
if (this.widgets) this.showPanel(player);
|
|
1666
|
+
else if (this.silenced.delete(player.guildId)) {} else if (this.mp.options.announceTracks) {
|
|
1667
|
+
const by = track.requestedBy ? ` · requested by <@${track.requestedBy.id}>` : "";
|
|
1668
|
+
this.send(player, { content: `🎶 Now playing ${trackLine(track)}${by}` });
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
/** Skip the next "Now playing" message for this guild (commands mode). */
|
|
1672
|
+
suppressNextAnnouncement(player) {
|
|
1673
|
+
this.silenced.add(player.guildId);
|
|
1674
|
+
}
|
|
1675
|
+
trackFailed(player, track, error) {
|
|
1676
|
+
this.silenced.delete(player.guildId);
|
|
1677
|
+
const reason = error instanceof Error ? `: ${error.message.split("\n")[0].slice(0, 200)}` : "";
|
|
1678
|
+
this.send(player, { content: `⚠️ Could not play ${trackTitle(track)}${reason}` });
|
|
1679
|
+
}
|
|
1680
|
+
queueEnd(player) {
|
|
1681
|
+
if (this.widgets) {
|
|
1682
|
+
this.cancelRefresh(player);
|
|
1683
|
+
const panel = this.panels.get(player.guildId);
|
|
1684
|
+
if (panel) {
|
|
1685
|
+
const embed = new discord_js.EmbedBuilder().setColor(this.mp.options.embedColor).setDescription("⏹️ Queue finished.");
|
|
1686
|
+
panel.edit({
|
|
1687
|
+
embeds: [embed],
|
|
1688
|
+
components: []
|
|
1689
|
+
}).catch(() => this.panels.delete(player.guildId));
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
}
|
|
1693
|
+
/** Schedule a (debounced) panel update after a state change. */
|
|
1694
|
+
refresh(player) {
|
|
1695
|
+
if (!this.widgets || !this.panels.has(player.guildId) || this.timers.has(player.guildId)) return;
|
|
1696
|
+
this.timers.set(player.guildId, setTimeout(() => {
|
|
1697
|
+
this.timers.delete(player.guildId);
|
|
1698
|
+
this.editPanel(player);
|
|
1699
|
+
}, REFRESH_DELAY));
|
|
1700
|
+
}
|
|
1701
|
+
disconnect(player) {
|
|
1702
|
+
this.cancelRefresh(player);
|
|
1703
|
+
this.silenced.delete(player.guildId);
|
|
1704
|
+
const panel = this.panels.get(player.guildId);
|
|
1705
|
+
this.panels.delete(player.guildId);
|
|
1706
|
+
panel?.delete().catch(() => {});
|
|
1707
|
+
}
|
|
1708
|
+
/** Render the panel payload (also used to answer button presses with an in-place update). */
|
|
1709
|
+
panelPayload(player) {
|
|
1710
|
+
return {
|
|
1711
|
+
embeds: [nowPlayingEmbed(player, this.mp.options.embedColor)],
|
|
1712
|
+
components: player.current ? controlRows(player, this.mp.options.customIdPrefix) : []
|
|
1713
|
+
};
|
|
1714
|
+
}
|
|
1715
|
+
isPanel(player, messageId) {
|
|
1716
|
+
return this.panels.get(player.guildId)?.id === messageId;
|
|
1717
|
+
}
|
|
1718
|
+
/** Post a fresh panel for a new track; reuse the old one if it is still the latest message. */
|
|
1719
|
+
async showPanel(player) {
|
|
1720
|
+
this.cancelRefresh(player);
|
|
1721
|
+
const old = this.panels.get(player.guildId);
|
|
1722
|
+
const channel = player.textChannel;
|
|
1723
|
+
if (old && channel && "lastMessageId" in channel && channel.lastMessageId === old.id) return this.editPanel(player);
|
|
1724
|
+
this.panels.delete(player.guildId);
|
|
1725
|
+
old?.delete().catch(() => {});
|
|
1726
|
+
const msg = await this.send(player, this.panelPayload(player));
|
|
1727
|
+
if (msg) this.panels.set(player.guildId, msg);
|
|
1728
|
+
}
|
|
1729
|
+
async editPanel(player) {
|
|
1730
|
+
const panel = this.panels.get(player.guildId);
|
|
1731
|
+
if (!panel) return;
|
|
1732
|
+
try {
|
|
1733
|
+
await panel.edit(this.panelPayload(player));
|
|
1734
|
+
} catch {
|
|
1735
|
+
this.panels.delete(player.guildId);
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
cancelRefresh(player) {
|
|
1739
|
+
clearTimeout(this.timers.get(player.guildId));
|
|
1740
|
+
this.timers.delete(player.guildId);
|
|
1741
|
+
}
|
|
1742
|
+
async send(player, payload) {
|
|
1743
|
+
if (!player.textChannel) return null;
|
|
1744
|
+
try {
|
|
1745
|
+
return await player.textChannel.send({
|
|
1746
|
+
allowedMentions: { parse: [] },
|
|
1747
|
+
...payload
|
|
1748
|
+
});
|
|
1749
|
+
} catch (error) {
|
|
1750
|
+
this.mp.reportError(error, player);
|
|
1751
|
+
return null;
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
};
|
|
1755
|
+
//#endregion
|
|
1756
|
+
//#region src/MusicPlayer.ts
|
|
1757
|
+
/**
|
|
1758
|
+
* Adds a music player to a discord.js client.
|
|
1759
|
+
*
|
|
1760
|
+
* ```ts
|
|
1761
|
+
* const music = new MusicPlayer(client, { sources: ['youtube', 'soundcloud'] });
|
|
1762
|
+
* client.once('ready', () => music.registerCommands());
|
|
1763
|
+
* ```
|
|
1764
|
+
*/
|
|
1765
|
+
var MusicPlayer = class extends node_events.EventEmitter {
|
|
1766
|
+
options;
|
|
1767
|
+
players = new discord_js.Collection();
|
|
1768
|
+
/** @internal */
|
|
1769
|
+
sources;
|
|
1770
|
+
/** @internal */
|
|
1771
|
+
commands;
|
|
1772
|
+
/** @internal */
|
|
1773
|
+
ui;
|
|
1774
|
+
router;
|
|
1775
|
+
clientListeners = [];
|
|
1776
|
+
constructor(client, options = {}) {
|
|
1777
|
+
super();
|
|
1778
|
+
this.client = client;
|
|
1779
|
+
this.options = resolveOptions(options);
|
|
1780
|
+
this.sources = Sources.create(this.options, (error) => this.reportError(error));
|
|
1781
|
+
this.commands = new CommandSet(this.options.commands);
|
|
1782
|
+
this.ui = new UiController(this);
|
|
1783
|
+
this.router = new InteractionRouter(this);
|
|
1784
|
+
warnAboutIntents(client);
|
|
1785
|
+
this.listen(discord_js.Events.VoiceStateUpdate, (_old, state) => this.onVoiceState(state));
|
|
1786
|
+
if (this.options.listen) this.listen(discord_js.Events.InteractionCreate, (i) => void this.handleInteraction(i));
|
|
1787
|
+
this.registerOnReady();
|
|
1788
|
+
}
|
|
1789
|
+
/** Command JSON, for merging into your own command registration. */
|
|
1790
|
+
get commandData() {
|
|
1791
|
+
return this.commands.toJSON();
|
|
1792
|
+
}
|
|
1793
|
+
/**
|
|
1794
|
+
* Create or update the music commands, leaving your other commands alone.
|
|
1795
|
+
* Pass server ids for instant per-server registration, or nothing for global commands.
|
|
1796
|
+
*/
|
|
1797
|
+
async registerCommands(guildIds) {
|
|
1798
|
+
const app = this.client.application;
|
|
1799
|
+
if (!app) throw new Error("The client is not ready yet; call registerCommands() after the \"ready\" event");
|
|
1800
|
+
for (const guildId of guildIds ?? [void 0]) for (const command of this.commandData) await app.commands.create(command, guildId);
|
|
1801
|
+
}
|
|
1802
|
+
/**
|
|
1803
|
+
* Handle an interaction if it belongs to the music player.
|
|
1804
|
+
* Resolves to `true` when it did, `false` when your bot should handle it.
|
|
1805
|
+
*/
|
|
1806
|
+
handleInteraction(interaction) {
|
|
1807
|
+
return this.router.handle(interaction);
|
|
1808
|
+
}
|
|
1809
|
+
get(guildId) {
|
|
1810
|
+
return this.players.get(guildId);
|
|
1811
|
+
}
|
|
1812
|
+
/** Get or create the server's player and connect it to `channel`. */
|
|
1813
|
+
async join(channel, textChannel) {
|
|
1814
|
+
let player = this.players.get(channel.guild.id);
|
|
1815
|
+
if (!player) {
|
|
1816
|
+
player = new GuildPlayer(this, channel.guild);
|
|
1817
|
+
this.players.set(channel.guild.id, player);
|
|
1818
|
+
}
|
|
1819
|
+
if (textChannel) player.textChannel = textChannel;
|
|
1820
|
+
await player.connect(channel);
|
|
1821
|
+
player.setChannelEmpty(!hasListeners(channel));
|
|
1822
|
+
return player;
|
|
1823
|
+
}
|
|
1824
|
+
/** Play a link or search query in `channel` from code. Returns the queued tracks. */
|
|
1825
|
+
async play(channel, query, options = {}) {
|
|
1826
|
+
const result = await this.sources.resolve(query);
|
|
1827
|
+
if (result.tracks.length === 0) throw new Error(`Nothing found for "${query}"`);
|
|
1828
|
+
const player = await this.join(channel, options.textChannel);
|
|
1829
|
+
const tracks = result.tracks.slice(0, this.options.maxPlaylistSize).map((t) => options.requestedBy ? {
|
|
1830
|
+
...t,
|
|
1831
|
+
requestedBy: options.requestedBy
|
|
1832
|
+
} : t);
|
|
1833
|
+
const added = player.add(tracks, options.next);
|
|
1834
|
+
this.emit("trackAdd", player, added, result.playlist);
|
|
1835
|
+
return {
|
|
1836
|
+
player,
|
|
1837
|
+
tracks: added,
|
|
1838
|
+
playlist: result.playlist
|
|
1839
|
+
};
|
|
1840
|
+
}
|
|
1841
|
+
/** Leave all voice channels and detach from the client. */
|
|
1842
|
+
destroy() {
|
|
1843
|
+
for (const player of [...this.players.values()]) player.destroy();
|
|
1844
|
+
for (const [event, fn] of this.clientListeners) this.client.off(event, fn);
|
|
1845
|
+
this.clientListeners.length = 0;
|
|
1846
|
+
}
|
|
1847
|
+
/** @internal Emit `error` if anyone listens, otherwise log it. */
|
|
1848
|
+
reportError(error, player, track) {
|
|
1849
|
+
if (this.listenerCount("error") > 0) this.emit("error", error, player, track);
|
|
1850
|
+
else console.error("[discwoofer]", error);
|
|
1851
|
+
}
|
|
1852
|
+
/** @internal Voice connection group, so several bots can share one process. */
|
|
1853
|
+
get voiceGroup() {
|
|
1854
|
+
return this.client.user?.id ?? "default";
|
|
1855
|
+
}
|
|
1856
|
+
listen(event, fn) {
|
|
1857
|
+
this.client.on(event, fn);
|
|
1858
|
+
this.clientListeners.push([event, fn]);
|
|
1859
|
+
}
|
|
1860
|
+
registerOnReady() {
|
|
1861
|
+
const { register } = this.options.commands;
|
|
1862
|
+
if (!register) return;
|
|
1863
|
+
const run = () => this.registerCommands(register === "global" ? void 0 : register.guildIds).catch((e) => this.reportError(e));
|
|
1864
|
+
if (this.client.isReady()) run();
|
|
1865
|
+
else this.client.once(discord_js.Events.ClientReady, () => void run());
|
|
1866
|
+
}
|
|
1867
|
+
onVoiceState(state) {
|
|
1868
|
+
const player = this.players.get(state.guild.id);
|
|
1869
|
+
if (!player?.voiceChannelId) return;
|
|
1870
|
+
const channel = state.guild.channels.cache.get(player.voiceChannelId);
|
|
1871
|
+
if (channel?.isVoiceBased()) player.setChannelEmpty(!hasListeners(channel));
|
|
1872
|
+
}
|
|
1873
|
+
};
|
|
1874
|
+
function hasListeners(channel) {
|
|
1875
|
+
return channel.members.some((m) => !m.user.bot);
|
|
1876
|
+
}
|
|
1877
|
+
function warnAboutIntents(client) {
|
|
1878
|
+
const required = [[discord_js.GatewayIntentBits.Guilds, "Guilds"], [discord_js.GatewayIntentBits.GuildVoiceStates, "GuildVoiceStates"]];
|
|
1879
|
+
for (const [flag, name] of required) if (!client.options.intents.has(flag)) console.warn(`[discwoofer] The client is missing the ${name} intent; the music player won't work properly.`);
|
|
1880
|
+
}
|
|
1881
|
+
//#endregion
|
|
1882
|
+
exports.MusicPlayer = MusicPlayer;
|
|
1883
|
+
|
|
1884
|
+
//# sourceMappingURL=index.cjs.map
|