Joshua_Dent_Scripts

Discord.JS Youtube Search Play (READ TOP IT IS IMPORTANT)

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