More Fixes

- Playlists can be saved (will be server specific in the future)
- Saved playlists can be played with ~play
pull/8/head
Trivernis 6 years ago
parent 3dde5c40cb
commit 08091ba15a

@ -1,38 +1,72 @@
const Discord = require("discord.js"), const Discord = require("discord.js"),
fs = require('fs'),
logger = require('./lib/logging').getLogger(), logger = require('./lib/logging').getLogger(),
music = require('./lib/music'); music = require('./lib/music'),
cmd = require("./lib/cmd"), cmd = require("./lib/cmd"),
client = new Discord.Client(), client = new Discord.Client(),
args = require('args-parser')(process.argv), args = require('args-parser')(process.argv),
authToken = args.token, authToken = args.token;
prefix = '~';
let savedplaylists = {};
function main() { function main() {
music.setLogger(logger); music.setLogger(logger);
cmd.setLogger(logger); cmd.setLogger(logger);
cmd.init(); cmd.init();
if (fs.existsSync('./data/savedplaylists.json')) {
savedplaylists = JSON.parse(fs.readFileSync('./data/savedplaylists.json'))
}
registerCommands(); registerCommands();
client.login(authToken).then(()=> { client.login(authToken).then(()=> {
logger.debug("Logged in"); logger.debug("Logged in");
}); });
} }
function savePlaylist(url, name) {
savedplaylists[name] = url;
fs.writeFile('./data/savedplaylists.json',JSON.stringify(savedplaylists), (err) => {
if (err) logger.warn(JSON.stringify(err));
})
}
function registerCommands() { function registerCommands() {
cmd.createCommand('~', 'play', (msg, argv) => { cmd.createCommand('~', 'play', (msg, argv) => {
let gid = msg.guild.id; let vc = msg.member.voiceChannel;
let url = argv['url']; let url = argv['url'];
if (!url) return 'No url given.'; if (!url) return 'No url given.';
if (!url.match(/http/g)) {
if (savedplaylists[url]) {
url = savedplaylists[url];
}
}
try { try {
return music.play(gid, url); return music.play(vc, url);
} catch(err) { } catch(err) {
logger.error(err); logger.error(err);
msg.reply(`${JSON.stringify(err)}`); msg.reply(`${JSON.stringify(err)}`);
} }
}, ['url']); }, ['url'], "Adds the url to the YouTube video/playlist into the queue.");
cmd.createCommand('~', 'playnext', (msg, argv) => {
let vc = msg.member.voiceChannel;
let url = argv['url'];
if (!url) return 'No url given.';
if (!url.match(/http/g)) {
if (savedplaylists[url]) {
url = savedplaylists[url];
}
}
try {
return music.playnext(vc, url);
} catch(err) {
logger.error(err);
msg.reply(`${JSON.stringify(err)}`);
}
}, ['url'], "Plays the YouTube video after the currently playing song.");
cmd.createCommand('~', 'ping', () => { cmd.createCommand('~', 'ping', () => {
return 'Pong!'; return 'Pong!';
}); }, [], "Try it yourself.");
cmd.createCommand('~', 'join', (msg) => { cmd.createCommand('~', 'join', (msg) => {
if (msg.member.voiceChannel) { if (msg.member.voiceChannel) {
@ -41,54 +75,66 @@ function registerCommands() {
else { else {
msg.reply("You are not connected to a voicechannel."); msg.reply("You are not connected to a voicechannel.");
} }
}); }, [], "Joins the VC you are in.");
cmd.createCommand('~', 'stop', (msg) => { cmd.createCommand('~', 'stop', (msg) => {
let gid = msg.guild.id; let gid = msg.guild.id;
music.stop(gid); music.stop(gid);
}); }, [], "Stops playling music and leavs.");
cmd.createCommand('~', 'pause', (msg) => { cmd.createCommand('~', 'pause', (msg) => {
let gid = msg.guild.id; let gid = msg.guild.id;
music.pause(gid); music.pause(gid);
}); }, [], "Pauses playing.");
cmd.createCommand('~', 'resume', (msg) => { cmd.createCommand('~', 'resume', (msg) => {
let gid = msg.guild.id; let gid = msg.guild.id;
music.resume(gid); music.resume(gid);
}); }, [], "Resumes playing.");
cmd.createCommand('~', 'skip', (msg) => { cmd.createCommand('~', 'skip', (msg) => {
let gid = msg.guild.id; let gid = msg.guild.id;
music.skip(gid); music.skip(gid);
}); }, [], "Skips the current song.");
cmd.createCommand('~', 'plist', (msg) => { cmd.createCommand('~', 'clear', (msg) => {
let gid = msg.guild.id;
music.clearQueue(gid);
return "All songs have been deleted, commander :no_mouth: "
}, [],"Clears the playlist.");
cmd.createCommand('~', 'playlist', (msg) => {
let gid = msg.guild.id; let gid = msg.guild.id;
let songs = music.getQueue(gid); let songs = music.getQueue(gid);
logger.debug(`found ${songs.length} songs`); logger.debug(`found ${songs.length} songs`);
let songlist = "**Songs**\n"; let songlist = `**${songs.length} Songs in playlist**\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';
} }
return songlist; return songlist;
}); }, [], "Shows the next ten songs.");
cmd.createCommand('~', 'shuffle', (msg) => { cmd.createCommand('~', 'shuffle', (msg) => {
let gid = msg.guild.id; let gid = msg.guild.id;
music.shuffle(gid); music.shuffle(gid);
}); return "The queue has successfully been shuffled :slight_smile:"
}, [], "Shuffles the playlist.");
cmd.createCommand('~', 'current', (msg) => { cmd.createCommand('~', 'current', (msg) => {
let gid = msg.guild.id; let gid = msg.guild.id;
let song = music.nowPlaying(gid); let song = music.nowPlaying(gid);
return `Playing: ${song.title}\n ${song.url}`; return `Playing: ${song.title}\n ${song.url}`;
}); }, [], "Shows the currently playing song.");
cmd.createCommand('~', 'repeatafterme', (msg, argv) => {
return argv['word'];
}, ['word'], "Repeats a single word you say.");
cmd.createCommand('_', 'repeat', (msg, argv) => { cmd.createCommand('~', 'save', (msg, argv) => {
return argv['repeattext']; savePlaylist(argv['url'], argv['name']);
}, ['repeattext']); return `Saved song/playlist as ${argv['name']}`
}, ['url', 'name'], "Saves the YouTube song/playlist with a specific name. ~play [name] to play the playlist");
} }
// defining the client's handlers // defining the client's handlers

@ -14,13 +14,14 @@ exports.setLogger = function(newLogger) {
logger = newLogger; logger = newLogger;
}; };
exports.createCommand = function(prefix, command, call, argv) { exports.createCommand = function(prefix, command, call, argv, description) {
try { try {
logger.debug(`Creating command ${command} with prefix ${prefix} and arguments ${argv}`); logger.debug(`Creating command ${command} with prefix ${prefix} and arguments ${argv}`);
if (!commands[prefix]) commands[prefix] = {}; // create Object commands prefix if (!commands[prefix]) commands[prefix] = {}; // create Object commands prefix
commands[prefix][command] = { // assign the command commands[prefix][command] = { // assign the command
args: argv || [], // with arguments args: argv || [],
callback: call // and function callback: call,
description: description
}; };
logger.debug(`Created command ${prefix}${command}`); logger.debug(`Created command ${prefix}${command}`);
} catch (err) { } catch (err) {
@ -80,10 +81,13 @@ exports.init = function() {
helpstr += "Commands\n---\n"; helpstr += "Commands\n---\n";
Object.keys(commands).forEach((key) => { Object.keys(commands).forEach((key) => {
Object.keys(commands[key]).forEach((cmd) => { Object.keys(commands[key]).forEach((cmd) => {
helpstr += "\n" + key + cmd + " " + JSON.stringify(commands[key][cmd].args) + "\n"; helpstr += "\n" + key + cmd + " " + JSON.stringify(commands[key][cmd].args).replace(/"|\[\]/g, '');
if (commands[key][cmd].description) {
helpstr += '\t' + commands[key][cmd].description + '\n';
}
}); });
}); });
helpstr += "```"; helpstr += "```";
return helpstr; return helpstr;
}); }, [], "Shows this help.");
}; };

@ -4,7 +4,7 @@
let logger = require('winston'); let logger = require('winston');
/* Function Definition */ /* Function Definition */
// TODO: Class that handles file-data for a server, functions to get/set data for specific server id
/** /**
* Getting the logger * Getting the logger
* @param {Object} newLogger * @param {Object} newLogger

@ -62,7 +62,7 @@ class DJ {
* in the queue. For each song the title is saved in the queue too. * in the queue. For each song the title is saved in the queue too.
* @param url * @param url
*/ */
playYouTube(url) { playYouTube(url, playnext) {
if (!this.conn) this.connect(this.voiceChannel).then(this.playYouTube(url)); if (!this.conn) this.connect(this.voiceChannel).then(this.playYouTube(url));
let plist = url.match(/(?<=\?list=)[\w\-]+/g); let plist = url.match(/(?<=\?list=)[\w\-]+/g);
if (plist) { if (plist) {
@ -73,7 +73,7 @@ class DJ {
this.queue.push({'url': vurl, 'title': null}); this.queue.push({'url': vurl, 'title': null});
yttl(vurl.replace(/http(s)?:\/\/(www.)?youtube.com\/watch\?v=/g, ''), (err, title) => { yttl(vurl.replace(/http(s)?:\/\/(www.)?youtube.com\/watch\?v=/g, ''), (err, title) => {
if (err) { if (err) {
logger.error(err); logger.debug(JSON.stringify(err));
} else { } else {
try { try {
logger.debug(`Found title: ${title} for ${vurl}`); logger.debug(`Found title: ${title} for ${vurl}`);
@ -81,7 +81,7 @@ class DJ {
return (el.url === vurl); return (el.url === vurl);
}).title = title; }).title = title;
} catch (error) { } catch (error) {
logger.error(JSON.stringify(error)); logger.verbose(JSON.stringify(error));
} }
} }
}); });
@ -109,10 +109,14 @@ class DJ {
this.playing = true; this.playing = true;
} else { } else {
logger.debug(`Added ${url} to the queue`); logger.debug(`Added ${url} to the queue`);
this.queue.push({'url': url, 'title': null}); if (playnext) {
this.queue.unshift({'url': url, 'title': null});
} else {
this.queue.push({'url': url, 'title': null});
}
yttl(url.replace(/http(s)?:\/\/(www.)?youtube.com\/watch\?v=/g, ''), (err, title) => { yttl(url.replace(/http(s)?:\/\/(www.)?youtube.com\/watch\?v=/g, ''), (err, title) => {
if (err) { if (err) {
logger.error(err); logger.debug(JSON.stringify(err));
} else { } else {
try { try {
logger.debug(`Found title: ${title} for ${url}`); logger.debug(`Found title: ${title} for ${url}`);
@ -120,7 +124,7 @@ class DJ {
return (el.url === url); return (el.url === url);
}).title = title; }).title = title;
} catch (error) { } catch (error) {
console.error(JSON.stringify(error)); console.verbose(JSON.stringify(error));
} }
} }
}); });
@ -198,7 +202,6 @@ class DJ {
*/ */
get playlist() { get playlist() {
let songs = []; let songs = [];
logger.debug(`Playlist: ${JSON.stringify(this.queue)}`);
this.queue.forEach((entry) => { this.queue.forEach((entry) => {
songs.push(entry.title); songs.push(entry.title);
}); });
@ -219,6 +222,13 @@ class DJ {
shuffle() { shuffle() {
this.queue = shuffleArray(this.queue); this.queue = shuffleArray(this.queue);
} }
/**
* Clears the playlist
*/
clear() {
this.queue = [];
}
} }
/** /**
@ -236,8 +246,8 @@ exports.setLogger = function (newLogger) {
exports.connect = function(voiceChannel) { exports.connect = function(voiceChannel) {
let gid = voiceChannel.guild.id; let gid = voiceChannel.guild.id;
let voiceDJ = new DJ(voiceChannel); let voiceDJ = new DJ(voiceChannel);
voiceDJ.connect();
djs[gid] = voiceDJ; djs[gid] = voiceDJ;
return voiceDJ.connect();
}; };
/** /**
@ -251,11 +261,34 @@ exports.playFile = function(guildId, filename) {
/** /**
* Plays a YT Url * Plays a YT Url
* @param guildId * @param voiceChannel
* @param url
*/
exports.play = function(voiceChannel, url) {
let guildId = voiceChannel.guild.id;
if (!djs[guildId]) {
this.connect(voiceChannel).then(() => {
djs[guildId].playYouTube(url);
});
} else {
djs[guildId].playYouTube(url);
}
};
/**
* plays the given url as next song
* @param voiceChannel
* @param url * @param url
*/ */
exports.play = function(guildId, url) { exports.playnext = function(voiceChannel, url) {
djs[guildId].playYouTube(url); let guildId = voiceChannel.guild.id;
if (!djs[guildId]) {
this.connect(voiceChannel).then(() => {
djs[guildId].playYouTube(url, true);
});
} else {
djs[guildId].playYouTube(url, true);
}
}; };
/** /**
@ -299,6 +332,14 @@ exports.skip = function(guildId) {
djs[guildId].skip(); djs[guildId].skip();
}; };
/**
* Clears the playlist
* @param guildId
*/
exports.clearQueue = function(guildId) {
djs[guildId].clear();
};
/** /**
* Returns the queue * Returns the queue
* @param guildId * @param guildId

Loading…
Cancel
Save