forked from GlaceYT/PrimeMusic-Lavalink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
player.js
390 lines (333 loc) · 16.9 KB
/
player.js
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
const { Riffy } = require("riffy");
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, AttachmentBuilder } = require("discord.js");
const { queueNames, requesters } = require("./commands/play");
const { mewcard } = require("mewcard");
const config = require("./config.js");
function initializePlayer(client) {
const nodes = config.nodes.map(node => ({
name: node.name,
host: node.host,
port: node.port,
password: node.password,
secure: node.secure,
reconnectTimeout: 5000,
reconnectTries: Infinity
}));
client.riffy = new Riffy(client, nodes, {
send: (payload) => {
const guildId = payload.d.guild_id;
if (!guildId) return;
const guild = client.guilds.cache.get(guildId);
if (guild) guild.shard.send(payload);
},
defaultSearchPlatform: "ytmsearch",
restVersion: "v3"
});
let currentTrackMessageId = null;
client.riffy.on("nodeConnect", node => {
console.log(`Node "${node.name}" connected.`);
});
client.riffy.on("nodeError", (node, error) => {
console.error(`Node "${node.name}" encountered an error: ${error.message}.`);
});
client.riffy.on("trackStart", async (player, track) => {
const channel = client.channels.cache.get(player.textChannel);
const trackUri = track.info.uri;
const requester = requesters.get(trackUri);
const card = new mewcard()
.setName(track.info.title)
.setAuthor(track.info.author)
.setTheme(config.musicardTheme)
.setBrightness(50)
.setThumbnail(track.info.thumbnail)
.setRequester(`${requester}`);
const buffer = await card.build();
const attachment = new AttachmentBuilder(buffer, { name: `musicard.png` });
const embed = new EmbedBuilder()
.setAuthor({
name: 'Now Playing',
iconURL: config.MusicIcon
})
.setDescription('🎶 **Controls:**\n 🔁 `Loop`, ❌ `Disable`, ⏭️ `Skip`, 📜 `Queue`, 🗑️ `Clear`\n ⏹️ `Stop`, ⏸️ `Pause`, ▶️ `Resume`, 🔊 `Vol +`, 🔉 `Vol -`')
.setImage('attachment://musicard.png')
.setColor(config.embedColor);
const actionRow1 = createActionRow1(false);
const actionRow2 = createActionRow2(false);
const message = await channel.send({ embeds: [embed], files: [attachment], components: [actionRow1, actionRow2] });
currentTrackMessageId = message.id;
const filter = i => [
'loopToggle', 'skipTrack', 'disableLoop', 'showQueue', 'clearQueue',
'stopTrack', 'pauseTrack', 'resumeTrack', 'volumeUp', 'volumeDown'
].includes(i.customId);
const collector = message.createMessageComponentCollector({ filter });
collector.on('collect', async i => {
await i.deferUpdate();
const member = i.member;
const voiceChannel = member.voice.channel;
const playerChannel = player.voiceChannel;
if (!voiceChannel || voiceChannel.id !== playerChannel) {
const vcEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setDescription('🔒 **You need to be in the same voice channel to use the controls!**');
const sentMessage = await channel.send({ embeds: [vcEmbed] });
setTimeout(() => sentMessage.delete().catch(console.error), config.embedTimeout * 1000);
return;
}
if (i.customId === 'loopToggle') {
toggleLoop(player, channel);
} else if (i.customId === 'skipTrack') {
player.stop();
const skipEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setTitle("⏭️ **Player will play the next song!**")
.setTimestamp();
const sentMessage = await channel.send({ embeds: [skipEmbed] });
setTimeout(() => sentMessage.delete().catch(console.error), config.embedTimeout * 1000);
} else if (i.customId === 'disableLoop') {
disableLoop(player, channel);
} else if (i.customId === 'showQueue') {
const queueMessage = queueNames.length > 0 ?
`🎵 **Now Playing:**\n${formatTrack(queueNames[0])}\n\n📜 **Queue:**\n${queueNames.slice(1).map((song, index) => `${index + 1}. ${formatTrack(song)}`).join('\n')}` :
"The queue is empty.";
const queueEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setTitle("📜 **Current Queue**")
.setDescription(queueMessage);
const sentMessage = await channel.send({ embeds: [queueEmbed] });
setTimeout(() => sentMessage.delete().catch(console.error), config.embedTimeout * 1000);
} else if (i.customId === 'clearQueue') {
clearQueue(player);
const clearQueueEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setTitle("🗑️ **Queue has been cleared!**")
.setTimestamp();
const sentMessage = await channel.send({ embeds: [clearQueueEmbed] });
setTimeout(() => sentMessage.delete().catch(console.error), config.embedTimeout * 1000);
} else if (i.customId === 'stopTrack') {
player.stop();
player.destroy();
const stopEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setDescription('⏹️ **Playback has been stopped and player destroyed!**');
const sentMessage = await channel.send({ embeds: [stopEmbed] });
setTimeout(() => sentMessage.delete().catch(console.error), config.embedTimeout * 1000);
} else if (i.customId === 'pauseTrack') {
if (player.paused) {
const alreadyPausedEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setDescription('⏸️ **Playback is already paused!**');
const sentMessage = await channel.send({ embeds: [alreadyPausedEmbed] });
setTimeout(() => sentMessage.delete().catch(console.error), config.embedTimeout * 1000);
} else {
player.pause(true);
const pauseEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setDescription('⏸️ **Playback has been paused!**');
const sentMessage = await channel.send({ embeds: [pauseEmbed] });
setTimeout(() => sentMessage.delete().catch(console.error), config.embedTimeout * 1000);
}
} else if (i.customId === 'resumeTrack') {
if (!player.paused) {
const alreadyResumedEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setDescription('▶️ **Playback is already resumed!**');
const sentMessage = await channel.send({ embeds: [alreadyResumedEmbed] });
setTimeout(() => sentMessage.delete().catch(console.error), config.embedTimeout * 1000);
} else {
player.pause(false);
const resumeEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setDescription('▶️ **Playback has been resumed!**');
const sentMessage = await channel.send({ embeds: [resumeEmbed] });
setTimeout(() => sentMessage.delete().catch(console.error), config.embedTimeout * 1000);
}
} else if (i.customId === 'volumeUp') {
if (player.volume < 100) {
const oldVolume = player.volume;
player.setVolume(Math.min(player.volume + 10, 100));
const volumeUpEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setDescription(`🔊 **Volume increased by ${player.volume - oldVolume}% to ${player.volume}!**`);
const sentMessage = await channel.send({ embeds: [volumeUpEmbed] });
setTimeout(() => sentMessage.delete().catch(console.error), config.embedTimeout * 1000);
} else {
const maxVolumeEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setDescription('🔊 **Volume is already at maximum!**');
const sentMessage = await channel.send({ embeds: [maxVolumeEmbed] });
setTimeout(() => sentMessage.delete().catch(console.error), config.embedTimeout * 1000);
}
} else if (i.customId === 'volumeDown') {
if (player.volume > 10) {
const oldVolume = player.volume;
player.setVolume(Math.max(player.volume - 10, 10));
const volumeDownEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setDescription(`🔉 **Volume decreased by ${oldVolume - player.volume}% to ${player.volume}!**`);
const sentMessage = await channel.send({ embeds: [volumeDownEmbed] });
setTimeout(() => sentMessage.delete().catch(console.error), config.embedTimeout * 1000);
} else {
const minVolumeEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setDescription('🔉 **Volume is already at minimum!**');
const sentMessage = await channel.send({ embeds: [minVolumeEmbed] });
setTimeout(() => sentMessage.delete().catch(console.error), config.embedTimeout * 1000);
}
}
});
collector.on('end', collected => {
console.log(`Collected ${collected.size} interactions.`);
});
});
client.riffy.on("trackEnd", async (player, track) => {
const channel = client.channels.cache.get(player.textChannel);
if (!channel || !currentTrackMessageId) return;
const message = await channel.messages.fetch(currentTrackMessageId).catch(console.error);
if (message) {
const disabledRow1 = createActionRow1(true);
const disabledRow2 = createActionRow2(true);
await message.edit({ components: [disabledRow1, disabledRow2] }).catch(console.error);
}
currentTrackMessageId = null;
});
client.riffy.on("playerDisconnect", async (player) => {
const channel = client.channels.cache.get(player.textChannel);
if (!channel || !currentTrackMessageId) return;
const message = await channel.messages.fetch(currentTrackMessageId).catch(console.error);
if (message) {
const disabledRow1 = createActionRow1(true);
const disabledRow2 = createActionRow2(true);
await message.edit({ components: [disabledRow1, disabledRow2] }).catch(console.error);
}
currentTrackMessageId = null;
});
client.riffy.on("queueEnd", async (player) => {
const channel = client.channels.cache.get(player.textChannel);
if (!channel || !currentTrackMessageId) return;
const message = await channel.messages.fetch(currentTrackMessageId).catch(console.error);
if (message) {
const disabledRow1 = createActionRow1(true);
const disabledRow2 = createActionRow2(true);
await message.edit({ components: [disabledRow1, disabledRow2] }).catch(console.error);
}
const autoplay = false;
if (autoplay) {
player.autoplay(player);
} else {
player.destroy();
const queueEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setDescription('**Queue Songs ended! Disconnecting Bot!**');
await channel.send({ embeds: [queueEmbed] });
}
currentTrackMessageId = null;
});
async function toggleLoop(player, channel) {
if (player.loop === "track") {
player.setLoop("queue");
const loopEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setTitle("🔁 **Queue loop is activated!**");
const sentMessage = await channel.send({ embeds: [loopEmbed] });
setTimeout(() => sentMessage.delete().catch(console.error), config.embedTimeout * 1000);
} else {
player.setLoop("track");
const loopEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setTitle("🔁 **Track loop is activated!**");
const sentMessage = await channel.send({ embeds: [loopEmbed] });
setTimeout(() => sentMessage.delete().catch(console.error), config.embedTimeout * 1000);
}
}
async function disableLoop(player, channel) {
player.setLoop("none");
const loopEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setTitle("❌ **Loop is disabled!**");
const sentMessage = await channel.send({ embeds: [loopEmbed] });
setTimeout(() => sentMessage.delete().catch(console.error), config.embedTimeout * 1000);
}
function setLoop(player, loopType) {
if (loopType === "track") {
player.setLoop("track");
} else if (loopType === "queue") {
player.setLoop("queue");
} else {
player.setLoop("none");
}
}
function clearQueue(player) {
player.queue.clear();
queueNames.length = 0;
}
function formatTrack(track) {
const match = track.match(/\[(.*?) - (.*?)\]\((.*?)\)/);
if (match) {
const [, title, author, uri] = match;
return `[${title} - ${author}](${uri})`;
}
return track;
}
function createActionRow1(disabled) {
return new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId("loopToggle")
.setEmoji('🔁')
.setStyle(ButtonStyle.Secondary)
.setDisabled(disabled),
new ButtonBuilder()
.setCustomId("disableLoop")
.setEmoji('❌')
.setStyle(ButtonStyle.Secondary)
.setDisabled(disabled),
new ButtonBuilder()
.setCustomId("skipTrack")
.setEmoji('⏭️')
.setStyle(ButtonStyle.Secondary)
.setDisabled(disabled),
new ButtonBuilder()
.setCustomId("showQueue")
.setEmoji('📜')
.setStyle(ButtonStyle.Secondary)
.setDisabled(disabled),
new ButtonBuilder()
.setCustomId("clearQueue")
.setEmoji('🗑️')
.setStyle(ButtonStyle.Secondary)
.setDisabled(disabled)
);
}
function createActionRow2(disabled) {
return new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId("stopTrack")
.setEmoji('⏹️')
.setStyle(ButtonStyle.Danger)
.setDisabled(disabled),
new ButtonBuilder()
.setCustomId("pauseTrack")
.setEmoji('⏸️')
.setStyle(ButtonStyle.Secondary)
.setDisabled(disabled),
new ButtonBuilder()
.setCustomId("resumeTrack")
.setEmoji('▶️')
.setStyle(ButtonStyle.Secondary)
.setDisabled(disabled),
new ButtonBuilder()
.setCustomId("volumeUp")
.setEmoji('🔊')
.setStyle(ButtonStyle.Secondary)
.setDisabled(disabled),
new ButtonBuilder()
.setCustomId("volumeDown")
.setEmoji('🔉')
.setStyle(ButtonStyle.Secondary)
.setDisabled(disabled)
);
}
module.exports = { initializePlayer, setLoop, clearQueue, formatTrack };
}
module.exports = { initializePlayer };