Skip to content

Commit

Permalink
[Enhancement] wrapped the play command in a class
Browse files Browse the repository at this point in the history
  • Loading branch information
naseif committed Nov 23, 2021
1 parent b1c0e28 commit 1df6eda
Show file tree
Hide file tree
Showing 3 changed files with 166 additions and 143 deletions.
2 changes: 1 addition & 1 deletion commands/Admin/addrole.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ module.exports = {
(role) => role.name === `${roleName}`
);

if (!roleToGive) return await interaction.followUp("No such role");
if (!roleToGive) return await interaction.followUp({embeds: [embedMessage("RED", `❌ | Role does not exist!`)]});
if (!interaction.member.permissions.has([Permissions.FLAGS.ADMINISTRATOR]))
return await interaction.followUp({
embeds: [
Expand Down
150 changes: 8 additions & 142 deletions commands/Music/play.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const { SlashCommandBuilder } = require("@discordjs/builders");
const { embedMessage } = require("../../modules/embedSimple");
const { Music } = require("../../modules/Music.js");
const playdl = require("play-dl");
const { QueryType } = require("discord-player");

Expand All @@ -11,8 +12,9 @@ module.exports = {
usage: "p <YouTube URL | Song Name | Spotify URL | Soundcloud URL |>",
async run(message, args, client, prefix) {
const songString = args.join(" ");

if (!songString)
return await message.channel.send({
return await message.reply({
embeds: [
embedMessage(
"RED",
Expand All @@ -29,7 +31,7 @@ module.exports = {
!userRoles.includes(checkdj) &&
message.guild.ownerId !== message.author.id
) {
return await message.channel.send({
return await message.reply({
embeds: [
embedMessage(
"RED",
Expand All @@ -39,7 +41,7 @@ module.exports = {
});
}
if (!message.member.voice.channelId)
return message.channel.send({
return message.reply({
embeds: [
embedMessage(
"RED",
Expand All @@ -52,148 +54,12 @@ module.exports = {
message.guild.me.voice.channelId &&
message.member.voice.channelId !== message.guild.me.voice.channelId
)
return await message.channel.send({
return await message.reply({
embeds: [embedMessage("RED", `❌ | You must be in my voice channel!`)],
});
const user = message.member.user;

const searchSong = await client.player.search(songString, {
requestedBy: message.member.user,
searchEngine: QueryType.AUTO,
});

if (!searchSong.tracks.length || !searchSong)
return message.channel.send({
embeds: [
embedMessage(
"RED",
`❌ | Song not found, Maybe its age restricted or flagged as offensive by Youtube`
),
],
});

let queue = await client.player.createQueue(message.guildId, {
leaveOnEnd: false,
leaveOnStop: true,
initialVolume: 80,
leaveOnEmptyCooldown: 60 * 1000 * 3,
bufferingTimeout: 200,
leaveOnEmpty: true,
metadata: {
channel: message,
},
async onBeforeCreateStream(track, source, _queue) {
if (source === "soundcloud") {
const client_id = await playdl.getFreeClientID();
playdl.setToken({
soundcloud: {
client_id: client_id,
},
});
if (await playdl.so_validate(track.url)) {
let soundCloudInfo = await playdl.soundcloud(track.url);
return (await playdl.stream_from_info(soundCloudInfo)).stream;
}
return;
}

if (source === "youtube") {
const validateSP = playdl.sp_validate(track.url);
const spotifyList = ["track", "album", "playlist"];
if (spotifyList.includes(validateSP)) {
if (playdl.is_expired()) {
await playdl.refreshToken();
}
let spotifyInfo = await playdl.spotify(track.url);
let youtube = await playdl.search(`${spotifyInfo.name}`, {
limit: 2,
});
return (await playdl.stream(youtube[0].url)).stream;
}

return (await playdl.stream(track.url)).stream;
}
},
});

try {
if (!queue.connection) await queue.connect(message.member.voice.channel);
} catch {
client.player.deleteQueue(message.guildId);
queue.destroy(true);
return await message.channel.send({
content: "Could not join your voice channel!",
});
}

searchSong.playlist
? queue.addTracks(searchSong.tracks)
: queue.addTrack(searchSong.tracks[0]);

const musicEmbed = {
color: "#9dcc37",
title: `${queue.playing ? "✅ Added to Queue" : "🎵 Playing"}`,
author: {
name: `${message.member.user.username}`,
icon_url: `${
message.member.user.avatarURL() || client.user.avatarURL()
}`,
},
description: `Song: **[${searchSong.tracks[0].title}](${searchSong.tracks[0].url})**`,
thumbnail: {
url: `${searchSong.tracks[0].thumbnail}`,
},
fields: [
{
name: "Author",
value: `${searchSong.tracks[0].author}`,
inline: true,
},
{
name: "🕓 Duration",
value: `${searchSong.tracks[0].duration}`,
inline: true,
},
],

timestamp: new Date(),
};

let playlistEmbed = {
color: "#9dcc37",
description: `✅ | Queued ${queue.tracks.length} Songs`,
};

if (!queue.playing) {
try {
await queue.play();
searchSong.playlist
? await message.channel.send({
embeds: [playlistEmbed, musicEmbed],
})
: await message.channel.send({
embeds: [musicEmbed],
});
return;
} catch (err) {
client.logger(err.message, "error");
console.log(err);
await message.channel.send({
embeds: [
embedMessage(
"RED",
`❌ | An error occurred while trying to play this song! \nError Message: ${err.message}`
),
],
});
}
}

if (queue.playing) {
searchSong.playlist
? await message.channel.send({ embeds: [playlistEmbed, musicEmbed] })
: await message.channel.send({ embeds: [musicEmbed] });
return;
}
await new Music().play(songString, message, client, user);
},
data: new SlashCommandBuilder()
.setName("play")
Expand Down
157 changes: 157 additions & 0 deletions modules/Music.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
const { embedMessage } = require("./embedSimple.js");
const playdl = require("play-dl");
const { QueryType } = require("discord-player");
const { logger } = require("./logger.js");

class Music {
async play(query, command, client, user = null) {
if (!query) throw new Error("No search Query Provided!");

const searchSong = await client.player.search(query, {
requestedBy: user ?? undefined,
searchEngine: QueryType.AUTO,
});

if (!searchSong.tracks.length || !searchSong)
return command.reply({
embeds: [
embedMessage(
"RED",
`❌ | Song not found, Maybe its age restricted or flagged as offensive by Youtube`
),
],
});

let queue = await client.player.createQueue(command.guildId, {
leaveOnEnd: false,
leaveOnStop: true,
initialVolume: 80,
leaveOnEmptyCooldown: 60 * 1000 * 3,
bufferingTimeout: 200,
leaveOnEmpty: true,
metadata: {
channel: command ?? undefined,
},
async onBeforeCreateStream(track, source, _queue) {
if (source === "soundcloud") {
const client_id = await playdl.getFreeClientID();
playdl.setToken({
soundcloud: {
client_id: client_id,
},
});
if (await playdl.so_validate(track.url)) {
let soundCloudInfo = await playdl.soundcloud(track.url);
return (await playdl.stream_from_info(soundCloudInfo)).stream;
}
return;
}

if (source === "youtube") {
const validateSP = playdl.sp_validate(track.url);
const spotifyList = ["track", "album", "playlist"];
if (spotifyList.includes(validateSP)) {
if (playdl.is_expired()) {
await playdl.refreshToken();
}
let spotifyInfo = await playdl.spotify(track.url);
let youtube = await playdl.search(`${spotifyInfo.name}`, {
limit: 2,
});
return (await playdl.stream(youtube[0].url)).stream;
}

return (await playdl.stream(track.url)).stream;
}
},
});

try {
if (!queue.connection) await queue.connect(command.member.voice.channel);
} catch {
client.player.deleteQueue(command.guildId);
queue.destroy(true);
return await command.reply({
content: "Could not join your voice channel!",
});
}

searchSong.playlist
? queue.addTracks(searchSong.tracks)
: queue.addTrack(searchSong.tracks[0]);

const username = command.member.user.username
? command.member.user.username
: command.user.username;

const avatar = command.member.user.avatarURL()
? command.member.user.avatarURL()
: command.user.avatarURL();

const musicEmbed = {
color: "#9dcc37",
title: `${queue.playing ? "✅ Added to Queue" : "🎵 Playing"}`,
author: {
name: `${username}`,
icon_url: `${avatar || client.user.avatarURL()}`,
},
description: `Song: **[${searchSong.tracks[0].title}](${searchSong.tracks[0].url})**`,
thumbnail: {
url: `${searchSong.tracks[0].thumbnail}`,
},
fields: [
{
name: "Author",
value: `${searchSong.tracks[0].author}`,
inline: true,
},
{
name: "🕓 Duration",
value: `${searchSong.tracks[0].duration}`,
inline: true,
},
],

timestamp: new Date(),
};

let playlistEmbed = {
color: "#9dcc37",
description: `✅ | Queued ${queue.tracks.length} Songs`,
};

if (!queue.playing) {
try {
await queue.play();
searchSong.playlist
? await command.reply({
embeds: [playlistEmbed, musicEmbed],
})
: await command.reply({
embeds: [musicEmbed],
});
return;
} catch (err) {
logger(err.message, "error");
console.log(err);
await command.reply({
embeds: [
embedMessage(
"RED",
`❌ | An error occurred while trying to play this song! \nError Message: ${err.message}`
),
],
});
}
}

if (queue.playing) {
searchSong.playlist
? await command.reply({ embeds: [playlistEmbed, musicEmbed] })
: await command.reply({ embeds: [musicEmbed] });
return;
}
}
}

module.exports = { Music };

0 comments on commit 1df6eda

Please sign in to comment.