const { Client, Util } = require('discord.js');
const { TOKEN, PREFIX, GOOGLE_API_KEY } = require('./Config.js');
const YouTube = require('simple-youtube-api');
const ytdl = require('ytdl-core');
const ffmpeg = require('ffmpeg')
const client = new Client({ disableEveryone: true });
const youtube = new YouTube(GOOGLE_API_KEY);
const queue = new Map();
client.on('ready', () => {
client.user.setActivity(`--help | GreenShadows's Music`, { type:'WATCHING'});
})
client.on('warn', console.warn);
client.on('error', console.error);
client.on('ready', () => console.log('- - - - - - - - - - - - -\n - - GreenShadows Bot - - \n- - - Music Edition - - -\n - - - Je Suis Prêt - - -\n- - - - - - - - - - - - -'));
client.on('disconnect', () => console.log('I just disconnected, making sure you know, I will reconnect now...'));
client.on('reconnecting', () => console.log('I am reconnecting now!'));
client.on('message', async msg => {
if (msg.author.bot) return undefined;
if (!msg.content.startsWith(PREFIX)) return undefined;
const args = msg.content.split(' ');
const searchString = args.slice(1).join(' ');
const url = args[1] ? args[1].replace(/<(.+)>/g, '$1') : '';
const serverQueue = queue.get(msg.guild.id);
let command = msg.content.toLowerCase().split(' ')[0];
command = command.slice(PREFIX.length)
if (command === 'play') {
const voiceChannel = msg.member.voiceChannel;
if (!voiceChannel) return msg.channel.send('Si tu n\'est pas dans un channel vocal, ca ne marche pas ^^');
const permissions = voiceChannel.permissionsFor(msg.client.user);
if (!permissions.has('CONNECT')) {
return msg.channel.send('Je n\'ai pas la permission de venir dans ton channel :/');
}
if (!permissions.has('SPEAK')) {s
return msg.channel.send('Je n\'ai pas la permission de parler dans ton channel :/');
}
if (url.match(/^https?:\/\/(www.youtube.com|youtube.com)\/playlist(.*)$/)) {
const playlist = await youtube.getPlaylist(url);
const videos = await playlist.getVideos();
for (const video of Object.values(videos)) {
const video2 = await youtube.getVideoByID(video.id); // eslint-disable-line no-await-in-loop
await handleVideo(video2, msg, voiceChannel, true); // eslint-disable-line no-await-in-loop
}
return msg.channel.send(`✅ Playlist: **${playlist.title}** has been added to the queue!`);
} else {
try {
var video = await youtube.getVideo(url);
} catch (error) {
try {
var videos = await youtube.searchVideos(searchString, 10);
let index = 0;
msg.channel.send(`
__**Séléction de la musique :**__
${videos.map(video2 => `**${++index} -** ${video2.title}`).join('\n--------------------------------------------------------------------------------------------------\n')}
\nEcrit le chiffre correspondant à la vidéo que tu souhaite. Entre **1** et **10**
`);
// eslint-disable-next-line max-depth
try {
var response = await msg.channel.awaitMessages(msg2 => msg2.content > 0 && msg2.content < 11, {
maxMatches: 1,
time: 10000,
errors: ['time']
});
} catch (err) {
console.error(err);
return msg.channel.send("Tu n'as pas rentré le numéro de la vidéo voulu. J'arrête tout ducoup..");
}
const videoIndex = parseInt(response.first().content);
var video = await youtube.getVideoByID(videos[videoIndex - 1].id);
} catch (err) {
console.error(err);
return msg.channel.send('🆘 I could not obtain any search results.');
}
}
return handleVideo(video, msg, voiceChannel);
}
} else if (command === 'skip') {
if (!msg.member.voiceChannel) return msg.channel.send('Tu n\'est pas dans un channel vocal..');
if (!serverQueue) return msg.channel.send('Faudrait que il y\'est de la musique pour que je la skip..');
serverQueue.connection.dispatcher.end('Tu as bien skip la musique actuel.');
return undefined;
} else if (command === 'stop') {
if (!msg.member.voiceChannel) return msg.channel.send('Tu n\'est pas dans un channel vocal..');
if (!serverQueue) return msg.channel.send('Faudrait que il y\'est de la musique pour que je l\'arrete..');
serverQueue.songs = [];
serverQueue.connection.dispatcher.end('J\'arrete, Ok');
return undefined;
} else if (command === 'volume') {
if (!msg.member.voiceChannel) return msg.channel.send('Tu n\'est pas dans un channel vocal..');
if (!serverQueue) return msg.channel.send('Il n\'y a rien en cours de lecture..');
if (!args[1]) return msg.channel.send(`Volume actuel : **${serverQueue.volume}**`);
serverQueue.volume = args[1];
serverQueue.connection.dispatcher.setVolumeLogarithmic(args[1] / 5);
return msg.channel.send(`Le volume est désormais de : **${args[1]}**`);
} else if (command === 'np') {
if (!serverQueue) return msg.channel.send('Il n\'y a rien en cours de lecture..');
return msg.channel.send(`🎶 Je joue désormais : **${serverQueue.songs[0].title}**`);
} else if (command === 'queue') {
if (!serverQueue) return msg.channel.send('Il n\'y a rien en cours de lecture..');
return msg.channel.send(`
__**Song queue:**__
${serverQueue.songs.map(song => `**-** ${song.title}`).join('\n')}
**Now playing:** ${serverQueue.songs[0].title}
`);
} else if (command === 'pause') {
if (serverQueue && serverQueue.playing) {
serverQueue.playing = false;
serverQueue.connection.dispatcher.pause();
return msg.channel.send('⏸ Paused the music for you!');
}
return msg.channel.send('Il n\'y a rien en cours de lecture..');
} else if (command === 'resume') {
if (serverQueue && !serverQueue.playing) {
serverQueue.playing = true;
serverQueue.connection.dispatcher.resume();
return msg.channel.send('▶ Remise en marche de la musique :D');
}
return msg.channel.send('Il n\'y a rien en cours de lecture..');
} else if (command === 'help') {
msg.reply("Liste des commandes envoyés par message privés !");
let help = [
"Prefix is `~`",
"**help** = Renvoie ce même message.",
"**play** = Je te rejoins et te fait écouter le titre que tu m'as envoyé.",
"**skip** = Pour zapper cette musique",
"**pause** = Pour mettre en pause la musique",
"**resume** = Pour relancer la musique. ",
"**stop** = Pour arrêter la musique et que je parte de ton channel.",
"**volume** = Volume.",
"**queue** = Pour voir le contenu de la playlist.",
"**np** = Affiche le titre en cours."
];
msg.author.sendMessage(help);
}
return undefined;
});
async function handleVideo(video, msg, voiceChannel, playlist = false) {
const serverQueue = queue.get(msg.guild.id);
console.log(video);
const song = {
id: video.id,
title: Util.escapeMarkdown(video.title),
url: `https://www.youtube.com/watch?v=${video.id}`
};
if (!serverQueue) {
const queueConstruct = {
textChannel: msg.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 5,
playing: true
};
queue.set(msg.guild.id, queueConstruct);
queueConstruct.songs.push(song);
try {
var connection = await voiceChannel.join();
queueConstruct.connection = connection;
play(msg.guild, queueConstruct.songs[0]);
} catch (error) {
console.error(`I could not join the voice channel: ${error}`);
queue.delete(msg.guild.id);
return msg.channel.send(`I could not join the voice channel: ${error}`);
}
} else {
serverQueue.songs.push(song);
console.log(serverQueue.songs);
if (playlist) return undefined;
else return msg.channel.send(`✅ **${song.title}** has been added to the queue!`);
}
return undefined;
}
function play(guild, song) {
const serverQueue = queue.get(guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
queue.delete(guild.id);
return;
}
console.log(serverQueue.songs);
const dispatcher = serverQueue.connection.playStream(ytdl(song.url))
.on('end', reason => {
if (reason === 'Stream is not generating quickly enough.') console.log('Song ended.');
else console.log(reason);
serverQueue.songs.shift();
play(guild, serverQueue.songs[0]);
})
.on('error', error => console.error(error));
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
serverQueue.textChannel.send(`🎶 Start playing: **${song.title}**`);
}
client.login(TOKEN);