Improved music.js

- Added DJ class
pull/8/head
Trivernis 6 years ago
parent c14f95030b
commit ec888aa5b7

@ -12,7 +12,6 @@ function main() {
cmd.setLogger(logger); cmd.setLogger(logger);
cmd.init(); cmd.init();
registerCommands(); registerCommands();
music.setClient(client);
client.login(authToken).then(()=> { client.login(authToken).then(()=> {
logger.debug("Logged in"); logger.debug("Logged in");
}); });
@ -20,11 +19,11 @@ function main() {
function registerCommands() { function registerCommands() {
cmd.createCommand('~', 'play', (msg, argv) => { cmd.createCommand('~', 'play', (msg, argv) => {
let vc = msg.member.voiceChannel; let gid = msg.guild.id;
let url = argv['url']; let url = argv['url'];
if (!url) return 'No url given.'; if (!url) return 'No url given.';
try { try {
return music.play(vc, url); return music.play(gid, url);
} catch(err) { } catch(err) {
logger.error(err); logger.error(err);
msg.reply(`${JSON.stringify(err)}`); msg.reply(`${JSON.stringify(err)}`);
@ -45,47 +44,45 @@ function registerCommands() {
}); });
cmd.createCommand('~', 'stop', (msg) => { cmd.createCommand('~', 'stop', (msg) => {
let vc = msg.member.voiceChannel; let gid = msg.guild.id;
music.stop(vc); music.stop(gid);
}); });
cmd.createCommand('~', 'pause', (msg) => { cmd.createCommand('~', 'pause', (msg) => {
let vc = msg.member.voiceChannel; let gid = msg.guild.id;
music.pause(vc); music.pause(gid);
}); });
cmd.createCommand('~', 'resume', (msg) => { cmd.createCommand('~', 'resume', (msg) => {
let vc = msg.member.voiceChannel; let gid = msg.guild.id;
music.resume(vc); music.resume(gid);
}); });
cmd.createCommand('~', 'skip', (msg) => { cmd.createCommand('~', 'skip', (msg) => {
let vc = msg.member.voiceChannel; let gid = msg.guild.id;
music.skip(vc); music.skip(gid);
}); });
cmd.createCommand('~', 'plist', (msg) => { cmd.createCommand('~', 'plist', (msg) => {
let vc = msg.member.voiceChannel; let gid = msg.guild.id;
music.getQueue(vc, (songs) => { let songs = music.getQueue(gid);
let songlist = "**Songs**\n"; let songlist = "**Songs**\n";
for (let i = 0; i < songs.length; i++) { for (let i = 0; i < songs.length; i++) {
if (i > 10) break; if (i > 10) break;
songlist += songs[i] + '\n'; songlist += songs[i] + '\n';
} }
msg.reply(songlist); return songlist;
});
}); });
cmd.createCommand('~', 'shuffle', (msg) => { cmd.createCommand('~', 'shuffle', (msg) => {
let vc = msg.member.voiceChannel; let gid = msg.guild.id;
music.shuffle(vc); music.shuffle(gid);
}); });
cmd.createCommand('~', 'current', (msg) => { cmd.createCommand('~', 'current', (msg) => {
let vc = msg.member.voiceChannel; let gid = msg.guild.id;
music.nowPlaying(vc, (title, url) => { let song = music.nowPlaying(gid);
msg.reply(`Playing: ${title}\n ${url}`); return `Playing: ${song.title}\n ${song.url}`;
});
}); });
cmd.createCommand('_', 'repeat', (msg, argv) => { cmd.createCommand('_', 'repeat', (msg, argv) => {

@ -5,218 +5,251 @@ const Discord = require("discord.js"),
ytapiKey = "AIzaSyBLF20r-c4mXoAT2qBFB5YlCgT0D-izOaU"; ytapiKey = "AIzaSyBLF20r-c4mXoAT2qBFB5YlCgT0D-izOaU";
/* Variable Definition */ /* Variable Definition */
let logger = require('winston'); let logger = require('winston');
let client = null; let djs = {};
let connections = {}; let connections = {};
/* Function Definition */ /* Function Definition */
// TODO: initCommands function that takes the cmd.js module as variable and uses it to create commands // TODO: initCommands function that takes the cmd.js module as variable and uses it to create commands
/** class DJ {
* Getting the logger; constructor(voiceChannel) {
* @param {Object} newLogger this.conn = null;
*/ this.disp = null;
exports.setLogger = function (newLogger) { this.queue = [];
logger = newLogger; this.playing = false;
}; this.current = null;
this.volume = 0.5;
/** this.voiceChannel = voiceChannel;
* Sets the discord Client for the module }
* @param newClient
*/
exports.setClient = function(newClient) {
client = newClient;
};
/** connect() {
* Connects to a voicechannel logger.verbose(`Connecting to voiceChannel ${this.voiceChannel.name}`);
* @param voiceChannel return this.voiceChannel.join().then(connection => {
*/ logger.info(`Connected to Voicechannel ${this.voiceChannel.name}`);
exports.connect = function(voiceChannel) { this.conn = connection;
logger.debug(JSON.stringify());
logger.verbose(`Connecting to voiceChannel ${voiceChannel.name}`);
if (client !== null) {
voiceChannel.join().then(connection => {
logger.info(`Connected to Voicechannel ${voiceChannel.name}`);
connections[voiceChannel.guild.id] = {
'conn': connection,
'disp': null,
'queue': [],
'playing': false,
current: null
};
}); });
} else {
logger.error("Client is null");
} }
};
/** playFile(filename) {
* Plays a file if (this.conn !== null) {
* @param filename this.disp = this.conn.playFile(filename);
*/ this.playing = true;
exports.playFile = function(voiceChannel, filename) { } else {
let gid = voiceChannel.guild.id; logger.warn("Not connected to a voicechannel. Connection now.");
let conn = connections[gid].conn; this.connect(this.voiceChannel).then(() => {
if (conn !== null) { this.playFile(filename);
connections[gid].disp = conn.playFile(filename); });
connections[gid].playing = true; }
} else {
this.connect(voiceChannel);
logger.warn("Not connected to a voicechannel");
} }
};
exports.play = function(voiceChannel, url) { playYouTube(url) {
let gid = voiceChannel.guild.id; if (!this.conn) this.connect(this.voiceChannel).then(this.playYouTube(url));
if (!connections[gid]) this.connect(voiceChannel);
let conn = connections[gid].conn;
if (conn !== null) {
let plist = url.match(/(?<=\?list=)[\w\-]+/g); let plist = url.match(/(?<=\?list=)[\w\-]+/g);
if (plist) { if (plist) {
logger.debug(`Adding playlist ${plist} to queue`); logger.debug(`Adding playlist ${plist} to queue`);
ypi(ytapiKey, plist).then(items => { ypi(ytapiKey, plist).then(items => {
for (let i = 0; i < items.length; i++) { for (let i = 0; i < items.length; i++) {
let vurl = `https://www.youtube.com/watch?v=${items[i].resourceId.videoId}`; let vurl = `https://www.youtube.com/watch?v=${items[i].resourceId.videoId}`;
connections[gid].queue.push(vurl); this.queue.push({'url': vurl, 'title': null});
yttl(vurl.replace(/http(s)?:\/\/(www.)?youtube.com\/watch\?v=/g, ''), (err, title) => {
if (err) {
logger.error(err);
} else {
this.queue.find((el) => {
return (el.url === vurl);
}).title = title;
}
});
} }
this.play(voiceChannel, connections[gid].queue.shift()); this.playYouTube(this.queue.shift().url);
}); });
return; return;
} }
if (!connections[gid].playing) { if (!this.playing) {
logger.debug(`Playing ${url}`); logger.debug(`Playing ${url}`);
connections[gid].disp = conn.playStream(ytdl(url, { this.disp = this.conn.playStream(ytdl(url, {
filter: "audioonly" filter: "audioonly"
}), {seek: 0, volume: 0.5}); }), {seek: 0, volume: this.volume});
connections[gid].disp.on('end', () => { this.disp.on('end', () => {
connections[gid].playing = false; this.playing = false;
connections[gid].current = null; this.current = null;
if (connections[gid].queue.length > 0) { if (this.queue.length > 0) {
this.play(voiceChannel, connections[gid].queue.shift()); this.current = this.queue.shift()
this.playYouTube(this.current.url);
} else {
this.stop();
} }
}); });
connections[gid].playing = true; this.playing = true;
connections[gid].current = url;
} else { } else {
logger.debug(`Added ${url} to the queue`); logger.debug(`Added ${url} to the queue`);
connections[gid].queue.push(url); this.queue.push(url);
}
}
setVolume(percentage) {
logger.verbose(`Setting volume to ${percentage}`);
if (this.disp !== null) {
this.disp.setVolume(percentage);
} else {
logger.warn("No dispatcher found.")
}
}
pause() {
logger.verbose("Pausing music...");
if (this.disp !== null) {
this.disp.pause();
} else {
logger.warn("No dispatcher found");
}
}
resume() {
logger.verbose("Resuming music...");
if (this.disp !== null) {
this.disp.resume();
} else {
logger.warn("No dispatcher found");
}
}
stop() {
logger.verbose("Stopping music...");
if (this.disp !== null) {
this.disp.end();
logger.debug("Ended dispatcher");
}
if (this.conn !== null) {
this.conn.disconnect();
logger.debug("Ended connection");
}
}
skip () {
logger.debug("Skipping song");
if (this.disp !== null) {
this.disp.end();
} }
} else {
logger.warn("Not connected to a voicechannel");
} }
get playlist() {
let songs = [];
this.queue.forEach((entry) => {
songs.push(entry.title);
});
return songs;
}
get song() {
return this.current.title;
}
shuffle() {
this.queue = shuffleArray(this.queue);
}
}
/**
* Getting the logger;
* @param {Object} newLogger
*/
exports.setLogger = function (newLogger) {
logger = newLogger;
};
/**
* Connects to a voicechannel
* @param voiceChannel
*/
exports.connect = function(voiceChannel) {
let gid = voiceChannel.guild.id;
let voiceDJ = new DJ(voiceChannel);
voiceDJ.connect();
djs[gid] = voiceDJ;
};
/**
* Plays a file
* @param filename
* @param guildId
*/
exports.playFile = function(guildId, filename) {
djs[guildId].playFile(filename);
};
/**
* Plays a YT Url
* @param guildId
* @param url
*/
exports.play = function(guildId, url) {
djs[guildId].playYouTube(url);
}; };
/** /**
* Sets the volume of the music * Sets the volume of the music
* @param percentage * @param percentage
* @param voiceChannel * @param guildId
*/ */
exports.setVolume = function(voiceChannel, percentage) { exports.setVolume = function(guildId, percentage) {
let disp = connections[voiceChannel.guild.id].disp; djs[guildId].setVolume(percentage);
logger.verbose(`Setting volume to ${percentage}`);
if (disp !== null) {
disp.setVolume(percentage);
} else {
logger.warn("No dispatcher found.")
}
}; };
/** /**
* pauses the music * pauses the music
*/ */
exports.pause = function(voiceChannel) { exports.pause = function(guildId) {
let disp = connections[voiceChannel.guild.id].disp; djs[guildId].pause();
logger.verbose("Pausing music...");
if (disp !== null) {
disp.pause();
} else {
logger.warn("No dispatcher found");
}
}; };
/** /**
* Resumes the music * Resumes the music
* @param guildId
*/ */
exports.resume = function(voiceChannel) { exports.resume = function(guildId) {
let disp = connections[voiceChannel.guild.id].disp; djs[guildId].resume();
logger.verbose("Resuming music...");
if (disp !== null) {
disp.resume();
} else {
logger.warn("No dispatcher found");
}
}; };
/** /**
* Stops the music * Stops the music
* @param guildId
*/ */
exports.stop = function(voiceChannel) { exports.stop = function(guildId) {
let gid = voiceChannel.guild.id; djs[guildId].stop();
let disp = connections[gid].disp; delete djs[guildId];
let conn = connections[gid].conn;
logger.verbose("Stopping music...");
if (disp !== null) {
disp.end();
logger.debug("Ended dispatcher");
}
if (conn !== null) {
conn.disconnect();
logger.debug("Ended connection");
}
connections[gid].playing = false;
}; };
/** /**
* Skips the song * Skips the song
* @param guildId
*/ */
exports.skip = function(voiceChannel) { exports.skip = function(guildId) {
let disp = connections[voiceChannel.guild.id].disp; djs[guildId].skip();
logger.debug("Skipping song");
if (disp !== null) {
disp.end();
}
}; };
/** /**
* executes the callback when the titlelist is finished * Returns the queue
* @param guildId
*/ */
exports.getQueue = function(voiceChannel, callback) { exports.getQueue = function(guildId) {
let titles = []; return djs[guildId].playlist;
connections[voiceChannel.guild.id].queue.forEach((url) => {
yttl(url.replace(/http(s)?:\/\/(www.)?youtube.com\/watch\?v=/g, ''), (err, title) => {
if (err) {
logger.error(err);
} else {
titles.push(title);
}
});
});
setTimeout(() => callback(titles), 2000 );
}; };
/** /**
* evokes the callback function with the title of the current song * evokes the callback function with the title of the current song
* @param callback * @param guildId
* @param voiceChannel
*/ */
exports.nowPlaying = function(voiceChannel, callback) { exports.nowPlaying = function(guildId) {
let gid = voiceChannel.guild.id; return djs[guildId].song;
if (connections[gid].queue.length > 0) {
yttl(connections[gid].current.replace(/http(s)?:\/\/(www.)?youtube.com\/watch\?v=/g, ''), (err, title) => {
if (err) {
logger.error(err);
} else {
callback(title, connections[gid].current);
}
});
}
}; };
/** /**
* shuffles the queue * shuffles the queue
* @param guildId
*/ */
exports.shuffle = function(voiceChannel) { exports.shuffle = function(guildId) {
connections[voiceChannel.guild.id].queue = shuffle(connections[voiceChannel.guild.id].queue); djs[guildId].shuffle();
}; };
/** /**
@ -224,7 +257,7 @@ exports.shuffle = function(voiceChannel) {
* @param array * @param array
* @returns {Array} * @returns {Array}
*/ */
function shuffle(array) { function shuffleArray(array) {
let currentIndex = array.length, temporaryValue, randomIndex; let currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle... // While there remain elements to shuffle...

Loading…
Cancel
Save