forked from GlaceYT/PrimeMusic-Lavalink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
player.js
316 lines (270 loc) Β· 12.2 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
const { Riffy } = require("riffy");
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, AttachmentBuilder } = require("discord.js");
const { queueNames, requesters } = require("./commands/play");
const { Dynamic } = require("musicard");
const config = require("./config.js");
const fs = require("fs");
const path = require("path");
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: "v4",
});
let currentTrackMessageId = null;
let collector = 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);
try {
const musicard = await Dynamic({
thumbnailImage: track.info.thumbnail || 'https://example.com/default_thumbnail.png',
backgroundColor: '#070707',
progress: 10,
progressColor: '#FF7A00',
progressBarColor: '#5F2D00',
name: track.info.title,
nameColor: '#FF7A00',
author: track.info.author || 'Unknown Artist',
authorColor: '#696969',
});
// Save the generated card to a file
const cardPath = path.join(__dirname, 'musicard.png');
fs.writeFileSync(cardPath, musicard);
// Prepare the attachment and embed
const attachment = new AttachmentBuilder(cardPath, { name: 'musicard.png' });
const embed = new EmbedBuilder()
.setAuthor({
name: 'Now Playing',
iconURL: 'https://cdn.discordapp.com/emojis/838704777436200981.gif' // Replace with actual icon URL
})
.setDescription('πΆ **Controls:**\n π `Loop`, β `Disable`, βοΈ `Skip`, π `Queue`, ποΈ `Clear`\n βΉοΈ `Stop`, βΈοΈ `Pause`, βΆοΈ `Resume`, π `Vol +`, π `Vol -`')
.setImage('attachment://musicard.png')
.setColor('#FF7A00');
// Action rows for music controls
const actionRow1 = createActionRow1(false);
const actionRow2 = createActionRow2(false);
// Send the message and set up the collector
const message = await channel.send({
embeds: [embed],
files: [attachment],
components: [actionRow1, actionRow2]
});
currentTrackMessageId = message.id;
if (collector) collector.stop(); // Stop any existing collectors
collector = setupCollector(client, player, channel, message);
} catch (error) {
console.error("Error creating or sending music card:", error.message);
const errorEmbed = new EmbedBuilder()
.setColor('#FF0000')
.setDescription("β οΈ **Unable to load track card. Continuing playback...**");
await channel.send({ embeds: [errorEmbed] });
}
});
client.riffy.on("trackEnd", async (player) => {
await disableTrackMessage(client, player);
currentTrackMessageId = null;
});
client.riffy.on("playerDisconnect", async (player) => {
await disableTrackMessage(client, player);
currentTrackMessageId = null;
});
client.riffy.on("queueEnd", async (player) => {
const channel = client.channels.cache.get(player.textChannel);
if (channel && currentTrackMessageId) {
const queueEmbed = new EmbedBuilder()
.setColor(config.embedColor)
.setDescription('**Queue Songs ended! Disconnecting Bot!**');
await channel.send({ embeds: [queueEmbed] });
}
player.destroy();
currentTrackMessageId = null;
});
async function disableTrackMessage(client, player) {
const channel = client.channels.cache.get(player.textChannel);
if (!channel || !currentTrackMessageId) return;
try {
const message = await channel.messages.fetch(currentTrackMessageId);
if (message) {
const disabledRow1 = createActionRow1(true);
const disabledRow2 = createActionRow2(true);
await message.edit({ components: [disabledRow1, disabledRow2] });
}
} catch (error) {
console.error("Failed to disable message components:", error);
}
}
}
function setupCollector(client, player, channel, message) {
const filter = i => [
'loopToggle', 'skipTrack', 'disableLoop', 'showQueue', 'clearQueue',
'stopTrack', 'pauseTrack', 'resumeTrack', 'volumeUp', 'volumeDown'
].includes(i.customId);
const collector = message.createMessageComponentCollector({ filter, time: 600000 }); // Set timeout if desired
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;
}
handleInteraction(i, player, channel);
});
collector.on('end', () => {
console.log("Collector stopped.");
});
return collector;
}
async function handleInteraction(i, player, channel) {
switch (i.customId) {
case 'loopToggle':
toggleLoop(player, channel);
break;
case 'skipTrack':
player.stop();
await sendEmbed(channel, "βοΈ **Player will play the next song!**");
break;
case 'disableLoop':
disableLoop(player, channel);
break;
case 'showQueue':
showQueue(channel);
break;
case 'clearQueue':
player.queue.clear();
await sendEmbed(channel, "ποΈ **Queue has been cleared!**");
break;
case 'stopTrack':
player.stop();
player.destroy();
await sendEmbed(channel, 'βΉοΈ **Playback has been stopped and player destroyed!**');
break;
case 'pauseTrack':
if (player.paused) {
await sendEmbed(channel, 'βΈοΈ **Playback is already paused!**');
} else {
player.pause(true);
await sendEmbed(channel, 'βΈοΈ **Playback has been paused!**');
}
break;
case 'resumeTrack':
if (!player.paused) {
await sendEmbed(channel, 'βΆοΈ **Playback is already resumed!**');
} else {
player.pause(false);
await sendEmbed(channel, 'βΆοΈ **Playback has been resumed!**');
}
break;
case 'volumeUp':
adjustVolume(player, channel, 10);
break;
case 'volumeDown':
adjustVolume(player, channel, -10);
break;
}
}
async function sendEmbed(channel, message) {
const embed = new EmbedBuilder().setColor(config.embedColor).setDescription(message);
const sentMessage = await channel.send({ embeds: [embed] });
setTimeout(() => sentMessage.delete().catch(console.error), config.embedTimeout * 1000);
}
function adjustVolume(player, channel, amount) {
const newVolume = Math.min(100, Math.max(10, player.volume + amount));
if (newVolume === player.volume) {
sendEmbed(channel, amount > 0 ? 'π **Volume is already at maximum!**' : 'π **Volume is already at minimum!**');
} else {
player.setVolume(newVolume);
sendEmbed(channel, `π **Volume changed to ${newVolume}%!**`);
}
}
function formatTrack(track) {
if (!track || typeof track !== 'string') return track;
const match = track.match(/\[(.*?) - (.*?)\]\((.*?)\)/);
if (match) {
const [, title, author, uri] = match;
return `[${title} - ${author}](${uri})`;
}
return track;
}
function toggleLoop(player, channel) {
player.setLoop(player.loop === "track" ? "queue" : "track");
sendEmbed(channel, player.loop === "track" ? "π **Track loop is activated!**" : "π **Queue loop is activated!**");
}
function disableLoop(player, channel) {
player.setLoop("none");
sendEmbed(channel, "β **Loop is disabled!**");
}
function showQueue(channel) {
if (queueNames.length === 0) {
sendEmbed(channel, "The queue is empty.");
return;
}
const nowPlaying = `π΅ **Now Playing:**\n${formatTrack(queueNames[0])}`;
const queueChunks = [];
// Split the queue into chunks of 10 songs per embed
for (let i = 1; i < queueNames.length; i += 10) {
const chunk = queueNames.slice(i, i + 10)
.map((song, index) => `${i + index}. ${formatTrack(song)}`)
.join('\n');
queueChunks.push(chunk);
}
// Send the "Now Playing" message first
channel.send({
embeds: [new EmbedBuilder().setColor(config.embedColor).setDescription(nowPlaying)]
}).catch(console.error);
// Send each chunk as a separate embed
queueChunks.forEach(async (chunk) => {
const embed = new EmbedBuilder()
.setColor(config.embedColor)
.setDescription(`π **Queue:**\n${chunk}`);
await channel.send({ embeds: [embed] }).catch(console.error);
});
}
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 };