Sync with deployed version: Opus cache, !fplay, !drop game; add README

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
KqandClaude Opus 5.5 committed 2026-11-21 10:28:02 +01:00
1 parent 0f3842234a
commit 16ec4537ca
7 files changed
+1233 -34

No files matched your search

+234 -34
View File
@@ -25,7 +25,18 @@ const PREFIX = '!';
const VOLUME = 0.3; // 0.0 - 1.0
// Cookies: set to '' to disable, or e.g. 'firefox', 'firefox:default', etc.
const YTDL_COOKIES_FROM_BROWSER = 'firefox'; // <-- add/change this line only
const YTDL_COOKIES_FROM_BROWSER = 'firefox';
// Extra yt-dlp extractor args. Forcing default+web_embedded clients works
// around the current YouTube "The page needs to be reloaded." error that
// shows up specifically when --cookies-from-browser is used with the
// default client selection (see yt-dlp/yt-dlp#17389).
const YTDLP_EXTRACTOR_ARGS = ['--extractor-args', 'youtube:player_client=default,web_embedded'];
// Cached tracks shorter than this are considered junk (usually a broken/
// truncated download rather than real content) and get deleted after
// caching, instead of being kept around.
const MIN_CACHE_DURATION_SECONDS = 10;
// ─── Cache setup ─────────────────────────────────────────────────────────────
const CACHE_DIR = path.join(__dirname, 'cache');
@@ -33,20 +44,6 @@ if (!fs.existsSync(CACHE_DIR)) fs.mkdirSync(CACHE_DIR);
const MIN_VALID_CACHE_BYTES = 4096;
for (const f of fs.readdirSync(CACHE_DIR)) {
const full = path.join(CACHE_DIR, f);
if (f.endsWith('.tmp')) {
try { fs.unlinkSync(full); } catch {}
} else if (f.endsWith('.opus')) {
try {
if (fs.statSync(full).size < MIN_VALID_CACHE_BYTES) {
fs.unlinkSync(full);
console.log(`[Cache] Removed corrupt cache file on startup: ${f}`);
}
} catch {}
}
}
const META_FILE = path.join(CACHE_DIR, 'metadata.json');
let metaCache = {};
if (fs.existsSync(META_FILE)) {
@@ -64,6 +61,20 @@ function saveMetaCache() {
}
}
function invalidateMetaByUrl(url) {
let changed = false;
for (const key of Object.keys(metaCache)) {
if (metaCache[key]?.url === url) {
delete metaCache[key];
changed = true;
}
}
if (changed) {
saveMetaCache();
console.log(`[Meta] Invalidated cached metadata pointing to failed URL: ${url}`);
}
}
function getAudioCachePath(url) {
const hash = crypto.createHash('md5').update(url).digest('hex');
return path.join(CACHE_DIR, `${hash}.opus`);
@@ -84,6 +95,69 @@ function evictIfInvalid(cachePath) {
}
}
// Probe a cached file's real audio duration in seconds using ffprobe.
// Resolves to null if it can't be determined.
function getAudioDurationSeconds(filePath) {
return new Promise((resolve) => {
const proc = spawn('ffprobe', [
'-v', 'error',
'-show_entries', 'format=duration',
'-of', 'default=noprint_wrappers=1:nokey=1',
filePath,
]);
let stdout = '';
proc.stdout.on('data', (d) => stdout += d.toString());
proc.on('close', () => {
const seconds = parseFloat(stdout.trim());
resolve(Number.isFinite(seconds) ? seconds : null);
});
proc.on('error', () => resolve(null));
});
}
// Remove a cache file if it's under the minimum acceptable duration.
async function purgeIfTooShort(cachePath, label) {
const duration = await getAudioDurationSeconds(cachePath);
if (duration !== null && duration < MIN_CACHE_DURATION_SECONDS) {
try {
fs.unlinkSync(cachePath);
console.log(`[Cache] Removed too-short cache file${label ? ` (${label})` : ''} (${duration.toFixed(1)}s): ${path.basename(cachePath)}`);
} catch (err) {
console.error('[Cache] Failed to remove too-short cache file:', err.message);
}
return true;
}
return false;
}
// Startup pass: drop leftover .tmp files, drop corrupt/empty .opus files,
// and drop .opus files that are valid but too short to bother keeping.
async function cleanupCacheOnStartup() {
const files = fs.readdirSync(CACHE_DIR);
for (const f of files) {
const full = path.join(CACHE_DIR, f);
if (f.endsWith('.tmp')) {
try { fs.unlinkSync(full); } catch {}
continue;
}
if (!f.endsWith('.opus')) continue;
if (!isCacheFileValid(full)) {
try {
fs.unlinkSync(full);
console.log(`[Cache] Removed corrupt cache file on startup: ${f}`);
} catch {}
continue;
}
await purgeIfTooShort(full, 'startup');
}
}
cleanupCacheOnStartup().catch((err) => console.error('[Cache] Startup cleanup failed:', err.message));
// ─── State (per guild) ────────────────────────────────────────────────────────
const guilds = new Map();
@@ -113,23 +187,25 @@ class DownloadJob {
this._start();
}
_start() {
const ytdlpArgs = [
'-f', 'ba/b', // <-- changed from 'bestaudio'
'--no-playlist',
];
_start() {
const ytdlpArgs = [
'-f', 'ba/b',
'--no-playlist',
];
if (YTDL_COOKIES_FROM_BROWSER) {
ytdlpArgs.push('--cookies-from-browser', YTDL_COOKIES_FROM_BROWSER);
}
if (YTDL_COOKIES_FROM_BROWSER) {
ytdlpArgs.push('--cookies-from-browser', YTDL_COOKIES_FROM_BROWSER);
}
ytdlpArgs.push(
'-o', '-',
'--',
this.url
);
ytdlpArgs.push(...YTDLP_EXTRACTOR_ARGS);
const ytdlp = spawn('yt-dlp', ytdlpArgs, { stdio: ['ignore', 'pipe', 'pipe'] });
ytdlpArgs.push(
'-o', '-',
'--',
this.url
);
const ytdlp = spawn('yt-dlp', ytdlpArgs, { stdio: ['ignore', 'pipe', 'pipe'] });
const ffmpeg = spawn('ffmpeg', [
'-hide_banner', '-loglevel', 'error',
@@ -208,12 +284,13 @@ _start() {
fs.unlink(this.tmpPath, () => {});
return;
}
fs.rename(this.tmpPath, this.cachePath, (err) => {
fs.rename(this.tmpPath, this.cachePath, async (err) => {
if (err) {
console.error('[Cache] Rename failed:', err.message);
} else {
console.log(`[Cache] Saved: ${path.basename(this.cachePath)}`);
return;
}
console.log(`[Cache] Saved: ${path.basename(this.cachePath)}`);
await purgeIfTooShort(this.cachePath, 'fresh download');
});
});
}
@@ -231,6 +308,7 @@ _start() {
}
this.subscribers.clear();
activeDownloads.delete(this.url);
invalidateMetaByUrl(this.url);
}
subscribe() {
@@ -256,6 +334,21 @@ function getOrStartDownload(url) {
return job;
}
// Silently warm the cache for the next queued track while the current one
// plays, so there's no gap waiting for a download between songs.
function prefetchNextInQueue(guildId) {
const state = getState(guildId);
const next = state.queue[0];
if (!next) return;
const cachePath = getAudioCachePath(next.url);
if (isCacheFileValid(cachePath)) return;
if (activeDownloads.has(next.url)) return;
console.log(`[Prefetch] Warming cache for next track: ${next.title}`);
getOrStartDownload(next.url);
}
// ─── Discord client ───────────────────────────────────────────────────────────
const client = new Client({
intents: [
@@ -300,6 +393,9 @@ client.on('messageCreate', async (message) => {
} else if (command === 'leave') {
await cmdLeave(message);
} else if (command === 'drop') {
await cmdDrop(message, args);
} else if (command === 'help') {
await message.channel.send(
'🎵 **Komendy:**\n' +
@@ -308,7 +404,8 @@ client.on('messageCreate', async (message) => {
'`!skip` – pomiń aktualny utwór\n' +
'`!queue` – pokaż kolejkę\n' +
'`!stop` – zatrzymaj i wyczyść kolejkę\n' +
'`!leave` – rozłącz bota'
'`!leave` – rozłącz bota\n' +
'`!drop start @a @b @c @d` – losuj token/złoty strój co sekundę (`!drop stop`, `!drop stats`)'
);
}
} catch (err) {
@@ -317,6 +414,83 @@ client.on('messageCreate', async (message) => {
}
});
// ─── Drop lottery (!drop) ─────────────────────────────────────────────────────
// Co sekundę każda z (max 4) osób losuje każdy drop osobno. Wygrana = ping.
const DROPS = [
{ key: 'token', emoji: '🪙', name: 'TOKEN', odds: 137500 },
{ key: 'gold', emoji: '👑', name: 'ZŁOTY STRÓJ', odds: 1562500 },
];
const dropGames = new Map(); // guildId -> { interval, channel, players, rolls, wins, startedAt }
function startDrop(message, players) {
stopDrop(message.guildId);
const game = {
channel: message.channel,
players,
rolls: 0,
wins: new Map(players.map(p => [p.id, Object.fromEntries(DROPS.map(d => [d.key, 0]))])),
startedAt: Date.now(),
interval: null,
};
game.interval = setInterval(() => {
game.rolls++;
for (const p of game.players) {
for (const d of DROPS) {
if (crypto.randomInt(d.odds) !== 0) continue;
game.wins.get(p.id)[d.key]++;
const secs = Math.round((Date.now() - game.startedAt) / 1000);
game.channel.send(
`🎉 <@${p.id}> **WYGRAŁEŚ ${d.name}!** ${d.emoji} Szansa **1 na ${d.odds.toLocaleString('pl-PL')}** ` +
`(${(100 / d.odds).toPrecision(3)}%) — losowanie #${game.rolls}, po ${secs}s.`
).catch(err => console.error('[drop] send failed', err));
}
}
}, 1000);
dropGames.set(message.guildId, game);
}
function stopDrop(guildId) {
const game = dropGames.get(guildId);
if (!game) return null;
clearInterval(game.interval);
dropGames.delete(guildId);
return game;
}
function dropStats(game) {
const lines = game.players.map(p => {
const w = game.wins.get(p.id);
return `• <@${p.id}> – ` + DROPS.map(d => `${d.emoji} ${w[d.key]}`).join(' · ');
});
const odds = DROPS.map(d => `${d.emoji} 1 na ${d.odds.toLocaleString('pl-PL')}`).join(', ');
return `📊 Losowań: **${game.rolls}** (${odds})\n` + lines.join('\n');
}
async function cmdDrop(message, args) {
const sub = (args.shift() || '').toLowerCase();
if (sub === 'start') {
const players = [...message.mentions.users.values()].filter(u => !u.bot).slice(0, 4);
if (players.length === 0) return message.channel.send('❌ Oznacz od 1 do 4 osób, np. `!drop start @a @b @c @d`');
startDrop(message, players);
const odds = DROPS.map(d => `${d.emoji} ${d.name.toLowerCase()} **1 na ${d.odds.toLocaleString('pl-PL')}**`).join(', ');
return message.channel.send({
content: `🎰 Drop wystartował! Co sekundę losuję dla: ${players.map(p => `<@${p.id}>`).join(', ')} — ${odds}. \`!drop stop\` żeby zatrzymać.`,
allowedMentions: { users: [] },
});
}
if (sub === 'stop') {
const game = stopDrop(message.guildId);
if (!game) return message.channel.send('❌ Drop nie jest uruchomiony.');
return message.channel.send({ content: '🛑 Drop zatrzymany.\n' + dropStats(game), allowedMentions: { users: [] } });
}
if (sub === 'stats') {
const game = dropGames.get(message.guildId);
if (!game) return message.channel.send('❌ Drop nie jest uruchomiony.');
return message.channel.send({ content: dropStats(game), allowedMentions: { users: [] } });
}
return message.channel.send('🎰 `!drop start @a @b @c @d` · `!drop stop` · `!drop stats`');
}
// ─── Commands ─────────────────────────────────────────────────────────────────
async function cmdPlay(message, query, { force = false } = {}) {
@@ -426,7 +600,7 @@ async function cmdQueue(message) {
return message.channel.send('📭 Kolejka jest pusta.');
}
const list = state.queue
.map((s, i) => `${i + 1}. **${s.title}** [${song.duration}]`)
.map((s, i) => `${i + 1}. **${s.title}** [${s.duration}]`)
.join('\n');
await message.channel.send(`📜 **Kolejka:**\n${list}`);
}
@@ -467,6 +641,7 @@ function playNext(guildId) {
try {
const resource = buildAudioResource(song.url);
state.player.play(resource);
prefetchNextInQueue(guildId);
} catch (err) {
console.error('[playNext error]', err);
state.textChannel?.send(`⚠️ Nie można odtworzyć: ${err.message}`);
@@ -517,6 +692,8 @@ function resolveSong(query) {
ytdlpArgs.push('--cookies-from-browser', YTDL_COOKIES_FROM_BROWSER);
}
ytdlpArgs.push(...YTDLP_EXTRACTOR_ARGS);
ytdlpArgs.push(
'--print', '%(title)s|||%(duration_string)s|||%(webpage_url)s',
'--', ytQuery
@@ -553,5 +730,28 @@ function resolveSong(query) {
return promise;
}
// ─── Graceful shutdown ────────────────────────────────────────────────────────
function shutdown(signal) {
console.log(`[Shutdown] Received ${signal}, cleaning up…`);
for (const job of activeDownloads.values()) {
try { job.ytdlp?.kill(); } catch {}
try { job.ffmpeg?.kill(); } catch {}
try { job.cacheStream?.destroy(); } catch {}
try { if (fs.existsSync(job.tmpPath)) fs.unlinkSync(job.tmpPath); } catch {}
}
for (const state of guilds.values()) {
try { state.connection?.destroy(); } catch {}
}
client.destroy();
process.exit(0);
}
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGTERM', () => shutdown('SIGTERM'));
// ─── Start ────────────────────────────────────────────────────────────────────
client.login(TOKEN);