Harden bot, storage and web API

This commit is contained in:
Shinuwa 2026-06-30 17:25:00 +02:00
parent e974bc6660
commit 20624a5c9c
43 changed files with 1265 additions and 1012 deletions

View file

@ -11,6 +11,7 @@ import {
} from "@discordjs/voice";
import { Events } from "discord.js";
import { config } from "../config.js";
import { serializeTrack, serializeTracks } from "../web/serializers.js";
import {
deleteTrackFile,
handleTrackCompletion,
@ -29,6 +30,8 @@ class MusicQueue extends EventEmitter {
this.idleDisconnectTimeout = null;
this.aloneDisconnectTimeout = null;
this.suspendedForAlone = false;
this.playNextPromise = null;
this.shuttingDown = false;
this.audioPlayer = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Play,
@ -49,13 +52,18 @@ class MusicQueue extends EventEmitter {
handleTrackCompletion(this.currentTrack);
}
this.currentTrack = null;
this.playNext();
if (!this.shuttingDown) {
void this.playNext();
}
});
this.audioPlayer.on("error", (error) => {
console.error("Audio player encountered an error", error);
handleTrackCompletion(this.currentTrack);
this.currentTrack = null;
this.playNext();
if (!this.shuttingDown) {
void this.playNext();
}
});
this.audioPlayer.on("stateChange", (oldState, newState) => {
@ -66,18 +74,27 @@ class MusicQueue extends EventEmitter {
snapshot() {
return {
current: this.currentTrack,
upcoming: this.queue,
current: serializeTrack(this.currentTrack),
upcoming: serializeTracks(this.queue),
status: this.playbackStatus,
};
}
async ensureConnection() {
if (
this.connection &&
this.connection.joinConfig.channelId === config.voiceChannelId
) {
return this.connection;
if (this.connection) {
if (
this.connection.joinConfig.channelId === config.voiceChannelId &&
this.connection.state.status === VoiceConnectionStatus.Ready
) {
return this.connection;
}
try {
this.connection.destroy();
} catch {
// The connection may already be destroyed.
}
this.connection = null;
}
let channel = this.client.channels.cache.get(config.voiceChannelId);
@ -104,7 +121,32 @@ class MusicQueue extends EventEmitter {
this.connection = connection;
connection.subscribe(this.audioPlayer);
await entersState(connection, VoiceConnectionStatus.Ready, 30_000);
connection.on(VoiceConnectionStatus.Disconnected, async () => {
try {
await Promise.race([
entersState(connection, VoiceConnectionStatus.Signalling, 5_000),
entersState(connection, VoiceConnectionStatus.Connecting, 5_000),
]);
} catch {
if (this.connection === connection) {
this.destroyConnection("voice connection lost");
}
}
});
try {
await entersState(connection, VoiceConnectionStatus.Ready, 30_000);
} catch (error) {
if (this.connection === connection) {
try {
connection.destroy();
} catch {
// The connection may have been destroyed by the voice adapter.
}
this.connection = null;
}
throw error;
}
this.evaluateAloneStatus();
return connection;
}
@ -114,13 +156,24 @@ class MusicQueue extends EventEmitter {
this.cancelIdleDisconnect();
this.emit("queueUpdate", this.snapshot());
if (!this.currentTrack) {
return this.playNext();
void this.playNext();
}
return track;
}
async playNext() {
playNext() {
if (this.playNextPromise) {
return this.playNextPromise;
}
this.playNextPromise = this.runPlayNext().finally(() => {
this.playNextPromise = null;
});
return this.playNextPromise;
}
async runPlayNext() {
if (this.suspendedForAlone) {
return;
}
@ -132,32 +185,43 @@ class MusicQueue extends EventEmitter {
}
this.cancelIdleDisconnect();
const nextTrack = this.queue.shift();
this.emit("queueUpdate", this.snapshot());
const nextTrack = this.queue[0];
try {
await this.ensureConnection();
} catch (error) {
console.error("Unable to connect to the configured voice channel", error);
deleteTrackFile(nextTrack);
this.currentTrack = null;
return;
}
if (
this.shuttingDown ||
this.suspendedForAlone ||
this.queue[0]?.id !== nextTrack.id
) {
return;
}
try {
this.queue.shift();
const stream = fs.createReadStream(nextTrack.path);
const resource = createAudioResource(stream, {
inlineVolume: true,
});
this.currentTrack = nextTrack;
this.currentTrack = {
...nextTrack,
startedAt: new Date().toISOString(),
};
this.audioPlayer.play(resource);
this.emit("trackStart", nextTrack);
this.emit("trackStart", this.currentTrack);
this.emit("queueUpdate", this.snapshot());
} catch (error) {
console.error("Unable to play track", error);
deleteTrackFile(nextTrack);
this.currentTrack = null;
return this.playNext();
return this.runPlayNext();
}
}
@ -194,7 +258,7 @@ class MusicQueue extends EventEmitter {
}
skip() {
this.audioPlayer.stop(true);
return this.audioPlayer.stop(true);
}
stop() {
@ -262,6 +326,9 @@ class MusicQueue extends EventEmitter {
this.cancelIdleDisconnect();
this.cancelAloneDisconnect();
const interruptedTrack = this.currentTrack;
this.currentTrack = null;
if (this.connection) {
try {
this.connection.destroy();
@ -277,7 +344,7 @@ class MusicQueue extends EventEmitter {
console.error("Failed to stop audio player", error);
}
this.currentTrack = null;
handleTrackCompletion(interruptedTrack);
this.emit("queueUpdate", this.snapshot());
console.log(
`[${new Date().toLocaleString()}] MusicQueue disconnected (${reason})`
@ -342,7 +409,7 @@ class MusicQueue extends EventEmitter {
this.suspendedForAlone = false;
this.cancelAloneDisconnect();
if (wasSuspended && !this.currentTrack && this.queue.length > 0) {
this.playNext();
void this.playNext();
}
}
}
@ -365,6 +432,17 @@ class MusicQueue extends EventEmitter {
const others = channel.members.filter((member) => member.id !== clientId);
return others.size === 0;
}
shutdown() {
this.shuttingDown = true;
this.cancelIdleDisconnect();
this.cancelAloneDisconnect();
this.client.off(Events.VoiceStateUpdate, this.voiceStateListener);
this.queue.forEach((track) => deleteTrackFile(track));
this.queue = [];
this.destroyConnection("shutdown");
}
}
export { MusicQueue };