Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
329 lines (286 loc) · 11.6 KB
/
Copy pathindex.js
File metadata and controls
329 lines (286 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
// index.js — CommonJS build that pairs with public/index.html (no Socket.IO)
require('dotenv').config();
const fs = require('fs');
const path = require('path');
const express = require('express');
const multer = require('multer');
const {
Client,
GatewayIntentBits,
Partials,
REST,
Routes,
} = require('discord.js');
const {
joinVoiceChannel,
createAudioPlayer,
createAudioResource,
NoSubscriberBehavior,
AudioPlayerStatus,
getVoiceConnection,
} = require('@discordjs/voice');
// ---------- env / paths
const TOKEN = process.env.DISCORD_TOKEN;
const GUILD_ID= process.env.GUILD_ID;
const WEB_PORT= Number(process.env.WEB_PORT || process.env.PORT || 3000);
const WEB_SHARED_SECRET = process.env.WEB_SHARED_SECRET || 'bug';
const __dirnameResolved = __dirname; // CommonJS has __dirname
const SOUNDS_DIR = path.join(__dirnameResolved, 'sounds');
if (!fs.existsSync(SOUNDS_DIR)) fs.mkdirSync(SOUNDS_DIR, { recursive: true });
// ---------- discord client
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates],
partials: [Partials.Channel],
});
// register slash commands (listsounds, playsound, stop, removesound, rename, join)
const slashCommands = [
{ name: 'listsounds', description: 'Show sounds (with indexes)' },
{
name: 'playsound',
description: 'Play by file name or /listsounds index',
options: [
{ name: 'name', description: 'Exact file name (e.g. beep.mp3)', type: 3, required: false },
{ name: 'index', description: 'Index from /listsounds (1-based)', type: 4, required: false },
{ name: 'timeout', description: 'Auto-stop after N seconds', type: 4, required: false },
],
},
{ name: 'stop', description: 'Stop playback (stays in VC)' },
{
name: 'removesound', description: 'Remove a sound',
options: [
{ name: 'index', description: 'Index from /listsounds (1-based)', type: 4, required: false },
{ name: 'name', description: 'Exact file name', type: 3, required: false },
],
},
{
name: 'rename', description: 'Rename a sound',
options: [
{ name: 'index', description: 'Index from /listsounds (1-based)', type: 4, required: true },
{ name: 'newname', description: 'New file name incl. extension', type: 3, required: true },
],
},
{ name: 'join', description: 'Have the bot join your VC (or busiest VC)' },
];
client.once('ready', async () => {
console.log(`Logged in as ${client.user.tag}`);
try {
const rest = new REST({ version: '10' }).setToken(TOKEN);
await rest.put(
Routes.applicationGuildCommands(client.user.id, GUILD_ID),
{ body: slashCommands }
);
console.log('Slash commands registered.');
} catch (e) {
console.error('Slash registration failed:', e);
}
});
// ---------- audio + queue
const player = createAudioPlayer({
behaviors: { noSubscriber: NoSubscriberBehavior.Pause },
});
let isPlaying = false;
let currentFile = null;
let queue = [];
player.on(AudioPlayerStatus.Idle, () => {
isPlaying = false;
playNext().catch(console.error);
});
player.on('error', (err) => {
console.error('Audio error:', err);
isPlaying = false;
playNext().catch(console.error);
});
function listSounds() {
return fs.readdirSync(SOUNDS_DIR)
.filter(f => /\.(mp3|wav|ogg|m4a|flac|webm)$/i.test(f))
.sort((a, b) => a.localeCompare(b))
.map((file, i) => ({ idx: i + 1, file, abs: path.join(SOUNDS_DIR, file) }));
}
async function playNext() {
if (isPlaying) return;
const next = queue.shift();
if (!next) return;
if (!fs.existsSync(next)) return playNext();
const resource = createAudioResource(next);
currentFile = next;
isPlaying = true;
player.play(resource);
}
async function getActiveVoiceChannel() {
const guild = await client.guilds.fetch(GUILD_ID);
await guild.channels.fetch();
const counts = new Map();
guild.voiceStates.cache.forEach(vs => {
const id = vs.channelId;
if (!id) return;
counts.set(id, (counts.get(id) || 0) + 1);
});
let bestId = null, bestCount = -1;
counts.forEach((cnt, id) => { if (cnt > bestCount) { bestCount = cnt; bestId = id; } });
return bestId ? guild.channels.cache.get(bestId) : null;
}
async function joinVC(targetId) {
const existing = getVoiceConnection(GUILD_ID);
if (existing) return existing;
let channelId = targetId;
if (!channelId) {
const top = await getActiveVoiceChannel();
if (top) channelId = top.id;
}
if (!channelId) return null;
const guild = await client.guilds.fetch(GUILD_ID);
const conn = joinVoiceChannel({
channelId,
guildId: GUILD_ID,
adapterCreator: guild.voiceAdapterCreator,
selfDeaf: false,
});
conn.subscribe(player);
return conn;
}
// ---------- slash handling
function seconds(n){ return Math.max(0, Number(n)||0); }
client.on('interactionCreate', async (interaction) => {
if (!interaction.isChatInputCommand()) return;
const name = interaction.commandName;
if (name === 'listsounds') {
const all = listSounds();
if (!all.length) return interaction.reply({ content: 'No sounds yet.', flags: 64 });
const lines = all.map(s => `${String(s.idx).padStart(2,' ')}. \`${s.file}\``);
const chunks = [];
let cur=[], len=0;
for (const l of lines) {
if (len + l.length > 1800) { chunks.push(cur.join('\n')); cur=[]; len=0; }
cur.push(l); len += l.length + 1;
}
if (cur.length) chunks.push(cur.join('\n'));
await interaction.reply({ content: chunks[0] || '(empty)', flags: 64 });
for (let i=1;i<chunks.length;i++) await interaction.followUp({ content: chunks[i], flags: 64 });
return;
}
if (name === 'join') {
const member = await interaction.guild.members.fetch(interaction.user.id);
const vc = member.voice?.channelId || null;
const conn = await joinVC(vc);
return interaction.reply({ content: conn ? 'Joined voice.' : 'No voice channel found.', flags: 64 });
}
if (name === 'playsound') {
let idx = interaction.options.getInteger('index');
const given = interaction.options.getString('name');
const timeoutSec = interaction.options.getInteger('timeout');
const all = listSounds();
if (!all.length) return interaction.reply({ content: 'No sounds found.', flags: 64 });
let chosen;
if (idx != null) {
if (idx < 1 || idx > all.length) return interaction.reply({ content: `Index out of range (1–${all.length}).`, flags: 64 });
chosen = all[idx-1];
} else if (given) {
chosen = all.find(s => s.file === given);
if (!chosen) return interaction.reply({ content: `No file named \`${given}\`.`, flags: 64 });
} else {
return interaction.reply({ content: 'Provide either a name or an index.', flags: 64 });
}
const member = await interaction.guild.members.fetch(interaction.user.id);
const vc = member.voice?.channelId || null;
const conn = await joinVC(vc);
if (!conn) return interaction.reply({ content: 'Could not join a voice channel.', flags: 64 });
queue.push(chosen.abs);
playNext().catch(console.error);
if (timeoutSec && timeoutSec > 0) {
setTimeout(() => { try { player.stop(true); isPlaying=false; } catch {} }, seconds(timeoutSec)*1000);
}
return interaction.reply({ content: `▶️ Queued **${chosen.file}**`, flags: 64 });
}
if (name === 'stop') {
try { player.stop(true); } catch {}
isPlaying=false; currentFile=null;
return interaction.reply({ content: '⏹️ Stopped.', flags: 64 });
}
if (name === 'removesound') {
const idx = interaction.options.getInteger('index');
const fname = interaction.options.getString('name');
const all = listSounds();
if (!all.length) return interaction.reply({ content:'No sounds to remove.', flags:64 });
let target;
if (idx != null) {
if (idx < 1 || idx > all.length) return interaction.reply({ content:`Index out of range (1–${all.length}).`, flags:64 });
target = all[idx-1];
} else if (fname) {
target = all.find(s => s.file === fname);
if (!target) return interaction.reply({ content:`Not found: \`${fname}\``, flags:64 });
} else {
return interaction.reply({ content:'Give an index or a name.', flags:64 });
}
queue = queue.filter(absPath => absPath !== target.abs);
if (currentFile === target.abs) { try { player.stop(true); } catch {} isPlaying=false; currentFile=null; }
try { fs.unlinkSync(target.abs); }
catch (e) { return interaction.reply({ content:`Couldn’t remove \`${target.file}\`: ${e.message}`, flags:64 }); }
return interaction.reply({ content:`🗑️ Removed **${target.file}**`, flags:64 });
}
if (name === 'rename') {
const idx = interaction.options.getInteger('index', true);
const newname = interaction.options.getString('newname', true);
const all = listSounds();
if (!all.length) return interaction.reply({ content:'No sounds to rename.', flags:64 });
if (idx < 1 || idx > all.length) return interaction.reply({ content:`Index out of range (1–${all.length}).`, flags:64 });
if (!/\.(mp3|wav|ogg|m4a|flac|webm)$/i.test(newname))
return interaction.reply({ content:'New name must include a supported extension (e.g. wow.mp3).', flags:64 });
const target = all[idx-1];
const dest = path.join(SOUNDS_DIR, newname);
if (fs.existsSync(dest)) return interaction.reply({ content:'A file with that name already exists.', flags:64 });
if (currentFile === target.abs) return interaction.reply({ content:'Stop playback before renaming this file.', flags:64 });
queue = queue.map(absPath => (absPath === target.abs ? dest : absPath));
try { fs.renameSync(target.abs, dest); }
catch (e) { return interaction.reply({ content:`Couldn’t rename: ${e.message}`, flags:64 }); }
return interaction.reply({ content:`✏️ Renamed **${target.file}** → **${newname}**`, flags:64 });
}
});
// ---------- web (REST) + upload
const app = express();
app.use(express.json());
const upload = multer({
storage: multer.diskStorage({
destination: (_, __, cb) => cb(null, SOUNDS_DIR),
filename: (_req, file, cb) => {
const safe = file.originalname.replace(/[^\w.\- ]+/g, '_');
cb(null, safe);
},
}),
});
// simple auth: allow favicon + healthz without key, else require ?key= or x-key
app.use((req, res, next) => {
const u = req.originalUrl || req.url;
if (u === '/favicon.ico' || u.startsWith('/healthz')) return next();
const key = req.query.key || req.headers['x-key'];
if (key !== WEB_SHARED_SECRET) return res.status(401).json({ ok:false, error:'unauthorized' });
next();
});
app.get('/healthz', (_req, res) => res.type('text/plain').send('ok'));
app.get('/api/sounds', (_req, res) => {
res.json(listSounds().map(s => ({ idx:s.idx, file:s.file })));
});
app.post('/api/upload', upload.array('file', 50), (_req, res) => {
res.json({ ok: true });
});
app.post('/api/play', async (req, res) => {
const { name } = req.body || {};
if (!name) return res.status(400).json({ ok:false, error:'missing name' });
const found = listSounds().find(s => s.file === name);
if (!found) return res.status(404).json({ ok:false, error:'not found' });
const conn = await joinVC(null);
if (!conn) return res.status(500).json({ ok:false, error:'could not join VC' });
queue.push(found.abs);
playNext().catch(console.error);
res.json({ ok:true });
});
app.post('/api/join', async (_req, res) => {
const conn = await joinVC(null);
res.json({ ok: !!conn });
});
// static last, so API/auth runs first
app.use(express.static(path.join(__dirnameResolved, 'public')));
app.listen(WEB_PORT, () => {
console.log(`web on http://localhost:${WEB_PORT}/?key=${WEB_SHARED_SECRET}`);
});
// ----- login bot
client.login(TOKEN);