Advertisement
Guest User

Untitled

a guest
Jun 19th, 2018
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const { Client, Util } = require('discord.js');
  2. const { TOKEN, PREFIX, GOOGLE_API_KEY } = require('./config');
  3. const YouTube = require('simple-youtube-api');
  4. const ytdl = require('ytdl-core');
  5.  
  6.  
  7. const client = new Client({ disableEveryone: true });
  8.  
  9. const youtube = new YouTube(GOOGLE_API_KEY);
  10.  
  11. const queue = new Map();
  12.  
  13. client.on('warn', console.warn);
  14.  
  15. client.on('error', console.error);
  16.  
  17. client.on('ready', () => console.log('Yo this ready!'));
  18.  
  19. client.on('disconnect', () => console.log('I just disconnected, making sure you know, I will reconnect now...'));
  20.  
  21. client.on('reconnecting', () => console.log('I am reconnecting now!'));
  22.  
  23. client.on('message', async msg => { // eslint-disable-line
  24.     if (msg.author.bot) return undefined;
  25.     if (!msg.content.startsWith(PREFIX)) return undefined;
  26.  
  27.     const args = msg.content.split(' ');
  28.     const searchString = args.slice(1).join(' ');
  29.     const url = args[1] ? args[1].replace(/<(.+)>/g, '$1') : '';
  30.     const serverQueue = queue.get(msg.guild.id);
  31.  
  32.     let command = msg.content.toLowerCase().split(' ')[0];
  33.     command = command.slice(PREFIX.length)
  34.  
  35.     if (command === 'play') {
  36.         const voiceChannel = msg.member.voiceChannel;
  37.         if (!voiceChannel) return msg.channel.send('I\'m sorry but you need to be in a voice channel to play music!');
  38.         const permissions = voiceChannel.permissionsFor(msg.client.user);
  39.         if (!permissions.has('CONNECT')) {
  40.             return msg.channel.send('I cannot connect to your voice channel, make sure I have the proper permissions!');
  41.         }
  42.         if (!permissions.has('SPEAK')) {
  43.             return msg.channel.send('I cannot speak in this voice channel, make sure I have the proper permissions!');
  44.         }
  45.  
  46.         if (url.match(/^https?:\/\/(www.youtube.com|youtube.com)\/playlist(.*)$/)) {
  47.             const playlist = await youtube.getPlaylist(url);
  48.             const videos = await playlist.getVideos();
  49.             for (const video of Object.values(videos)) {
  50.                 const video2 = await youtube.getVideoByID(video.id); // eslint-disable-line no-await-in-loop
  51.                 await handleVideo(video2, msg, voiceChannel, true); // eslint-disable-line no-await-in-loop
  52.             }
  53.             return msg.channel.send(`Playlist: **${playlist.title}** has been added to the queue!`);
  54.         } else {
  55.             try {
  56.                 var video = await youtube.getVideo(url);
  57.             } catch (error) {
  58.                 try {
  59.                     var videos = await youtube.searchVideos(searchString, 10);
  60.                     let index = 0;
  61.                     msg.channel.send(`
  62. __**Song selection:**__
  63. ${videos.map(video2 => `**${++index} -** ${video2.title}`).join('\n')}
  64. Please provide a value to select one of the search results ranging from 1-10.
  65.                     `);
  66.                     // eslint-disable-next-line max-depth
  67.                     try {
  68.                         var response = await msg.channel.awaitMessages(msg2 => msg2.content > 0 && msg2.content < 11, {
  69.                             maxMatches: 1,
  70.                             time: 10000,
  71.                             errors: ['time']
  72.                         });
  73.                     } catch (err) {
  74.                         console.error(err);
  75.                         return msg.channel.send('No or invalid value entered, cancelling video selection.');
  76.                     }
  77.                     const videoIndex = parseInt(response.first().content);
  78.                     var video = await youtube.getVideoByID(videos[videoIndex - 1].id);
  79.                 } catch (err) {
  80.                     console.error(err);
  81.                     return msg.channel.send('I could not obtain any search results.');
  82.                 }
  83.             }
  84.             return handleVideo(video, msg, voiceChannel);
  85.         }
  86.     } else if (command === 'skip') {
  87.         if (!msg.member.voiceChannel) return msg.channel.send('You are not in a voice channel!');
  88.         if (!serverQueue) return msg.channel.send('There is nothing playing that I could skip for you.');
  89.         serverQueue.connection.dispatcher.end('Skip command has been used!');
  90.         return undefined;
  91.     } else if (command === 'stop') {
  92.         if (!msg.member.voiceChannel) return msg.channel.send('You are not in a voice channel!');
  93.         if (!serverQueue) return msg.channel.send('There is nothing playing that I could stop for you.');
  94.         serverQueue.songs = [];
  95.         serverQueue.connection.dispatcher.end('Stop command has been used!');
  96.         return undefined;
  97.     } else if (command === 'volume') {
  98.         if (!msg.member.voiceChannel) return msg.channel.send('You are not in a voice channel!');
  99.         if (!serverQueue) return msg.channel.send('There is nothing playing.');
  100.         if (!args[1]) return msg.channel.send(`The current volume is: **${serverQueue.volume}**`);
  101.         serverQueue.volume = args[1];
  102.         serverQueue.connection.dispatcher.setVolumeLogarithmic(args[1] / 5);
  103.         return msg.channel.send(`I set the volume to: **${args[1]}**`);
  104.     } else if (command === 'np') {
  105.         if (!serverQueue) return msg.channel.send('There is nothing playing.');
  106.         return msg.channel.send(`🎶 Now playing: **${serverQueue.songs[0].title}**`);
  107.     } else if (command === 'queue') {
  108.         if (!serverQueue) return msg.channel.send('There is nothing playing.');
  109.         return msg.channel.send(`
  110. __**Song queue:**__
  111. ${serverQueue.songs.map(song => `**-** ${song.title}`).join('\n')}
  112. **Now playing:** ${serverQueue.songs[0].title}
  113.         `);
  114.     } else if (command === 'pause') {
  115.         if (serverQueue && serverQueue.playing) {
  116.             serverQueue.playing = false;
  117.             serverQueue.connection.dispatcher.pause();
  118.             return msg.channel.send('Paused the music for you!');
  119.         }
  120.         return msg.channel.send('There is nothing playing.');
  121.     } else if (command === 'resume') {
  122.         if (serverQueue && !serverQueue.playing) {
  123.             serverQueue.playing = true;
  124.             serverQueue.connection.dispatcher.resume();
  125.             return msg.channel.send('Resumed the music for you!');
  126.         }
  127.         return msg.channel.send('There is nothing playing.');
  128.     }
  129.  
  130.     return undefined;
  131. });
  132.  
  133. async function handleVideo(video, msg, voiceChannel, playlist = false) {
  134.     const serverQueue = queue.get(msg.guild.id);
  135.     console.log(video);
  136.     const song = {
  137.         id: video.id,
  138.         title: Util.escapeMarkdown(video.title),
  139.         url: `https://www.youtube.com/watch?v=${video.id}`,
  140.                 requestedBy: msg.author
  141.     };
  142.     if (!serverQueue) {
  143.         const queueConstruct = {
  144.             textChannel: msg.channel,
  145.             voiceChannel: voiceChannel,
  146.             connection: null,
  147.             songs: [],
  148.             volume: 5,
  149.             playing: true
  150.         };
  151.         queue.set(msg.guild.id, queueConstruct);
  152.  
  153.         queueConstruct.songs.push(song);
  154.  
  155.         try {
  156.             var connection = await voiceChannel.join();
  157.             queueConstruct.connection = connection;
  158.             play(msg.guild, queueConstruct.songs[0]);
  159.         } catch (error) {
  160.             console.error(`I could not join the voice channel: ${error}`);
  161.             queue.delete(msg.guild.id);
  162.             return msg.channel.send(`I could not join the voice channel: ${error}`);
  163.         }
  164.     } else {
  165.         serverQueue.songs.push(song);
  166.         console.log(serverQueue.songs);
  167.         if (playlist) return undefined;
  168.         else return msg.channel.send(`**${song.title}** has been added to the queue!`);
  169.     }
  170.     return undefined;
  171. }
  172.  
  173. function play(guild, song) {
  174.     const serverQueue = queue.get(guild.id);
  175.  
  176.     console.log(serverQueue.songs);
  177.  
  178.     const dispatcher = serverQueue.connection.playStream(ytdl(song.url))
  179.         .on('end', reason => {
  180.             if (reason === 'Stream is not generating quickly enough.') console.log('Song ended.');
  181.             else console.log(reason);
  182.             serverQueue.songs.shift();
  183.             play(guild, serverQueue.songs[0]);
  184.         })
  185.         .on('error', error => console.error(error));
  186.     dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
  187.  
  188.     serverQueue.textChannel.send(`Start playing: **${song.title}**`);
  189. }
  190.  
  191. client.login(TOKEN);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement