title: How to make loop command in discord.js?
body: <p>I'm trying to make a <code>discord.js</code> bot that plays music and runs the looping command.</p>
  
  <p>I'm now stuck trying to use it as it's not working.</p>
  
  <p>My code:</p>
  
  <p><strong>Server.js</strong></p>
  
  <pre><code>const http = require('http');
  const express = require('express');
  const app = express();
  app.get("/", (request, response) =&gt; {
    response.sendStatus(200);
  });
  app.listen(process.env.PORT);
  setInterval(() =&gt; {
    http.get(`http://rgrap.glitch.me/`);
  }, 280000);
  
  // ßá ÇáÈßÌÇÊ Çáí ããßä ÊÍÊÌåÇ Ýí Çí ÈæÊ 
  const { Client, RichEmbed } = require("discord.js");
  var { Util } = require('discord.js');
  const {TOKEN, YT_API_KEY, prefix, devs} = require('./config')
  const client = new Client({ disableEveryone: true})
  const ytdl = require("ytdl-core");
  const canvas = require("canvas");
  const Canvas = require("canvas");
  const convert = require("hh-mm-ss")
  const fetchVideoInfo = require("youtube-info");
  const botversion = require('./package.json').version;
  const simpleytapi = require('simple-youtube-api')
  const moment = require("moment");
  const fs = require('fs');
  const util = require("util")
  const gif = require("gif-search");
  const opus = require("node-opus");
  const ms = require("ms");
  const jimp = require("jimp");
  const { get } = require('snekfetch');
  const guild = require('guild');
  const dateFormat = require('dateformat');//npm i dateformat
  const YouTube = require('simple-youtube-api');
  const youtube = new YouTube('AIzaSyAdORXg7UZUo7sePv97JyoDqtQVi3Ll0b8');
  const hastebins = require('hastebin-gen');
  const getYoutubeID = require('get-youtube-id');
  const yt_api_key = "AIzaSyDeoIH0u1e72AtfpwSKKOSy3IPp2UHzqi4";
  const pretty = require("pretty-ms");
  client.login(TOKEN);
  const queue = new Map();
  var table = require('table').table
  const Discord = require('discord.js');
  client.on('ready', () =&gt; { 
    console.log(`Logged in as ${client.user.tag}!`);
  });
  
  
   //ßæÏ ááÊÌÑÈÉ 
  
  
  
  
  
  
  
  
  /////////////////////////
  ////////////////////////
  
  client.on('message', async msg =&gt;{
      if (msg.author.bot) return undefined;
      if (!msg.content.startsWith(prefix)) return undefined;
  
      let args = msg.content.split(' ');
  
      let command = msg.content.toLowerCase().split(" ")[0];
      command = command.slice(prefix.length)
  
      if(command === `ping`) {
      let embed = new Discord.RichEmbed()
      .setColor(3447003)
      .setTitle("Pong!!")
      .setDescription(`${client.ping} ms,`)
      .setFooter(`Requested by | ${msg.author.tag}`);
      msg.delete().catch(O_o=&gt;{})
      msg.channel.send(embed);
      }
  });
  /////////////////////////
  ////////////////////////
  //////////////////////
  client.on('message', async msg =&gt;{
      if (msg.author.bot) return undefined;
      if (!msg.content.startsWith(prefix)) return undefined;
  
      let args = msg.content.split(' ');
  
      let command = msg.content.toLowerCase().split(" ")[0];
      command = command.slice(prefix.length)
  
      if(command === `avatar`){
      if(msg.channel.type === 'dm') return msg.channel.send("Nope Nope!! u can't use avatar command in DMs (:")
          let mentions = msg.mentions.members.first()
          if(!mentions) {
            let sicon = msg.author.avatarURL
            let embed = new Discord.RichEmbed()
            .setImage(msg.author.avatarURL)
            .setColor("#5074b3")
            msg.channel.send({embed})
          } else {
            let sicon = mentions.user.avatarURL
            let embed = new Discord.RichEmbed()
            .setColor("#5074b3")
            .setImage(sicon)
            msg.channel.send({embed})
          }
      };
  });
  /////////////////////////
  ////////////////////////
  //////////////////////
  /////////////////////////
  ////////////////////////
  //////////////////////
  
  /////////////////////////
  ////////////////////////
  //////////////////////
  /////////////////////////
  ////////////////////////
  //////////////////////
  client.on('message', async msg =&gt; { 
      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(/&lt;(.+)&gt;/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("Ø§Ù†Øª Ù„Ù… ØªØ¯Ø®Ù„ Ø±ÙˆÙ… ØµÙˆØªÙŠ");
  
          const permissions = voiceChannel.permissionsFor(msg.client.user);
  
          if (!permissions.has('CONNECT')) {
  
              return msg.channel.send("Ù„ÙŠØ³Øª Ù„Ø¯ÙŠ ØµÙ„Ø§Ø­ÙŠØ§Øª Ù„Ù„Ø¯Ø®ÙˆÙ„ Ø§Ù„Ù‰ Ø§Ù„Ø±ÙˆÙ…");
          }
  
          if (!permissions.has('SPEAK')) {
  
              return msg.channel.send("Ø§Ù†Ø§ Ù„Ø§ ÙŠÙ…ÙƒÙ†Ù†ÙŠ Ø§Ù„ØªÙƒÙ„Ù… ÙÙŠ Ù‡Ø§Ø°Ù‡ Ø§Ù„Ø±ÙˆÙ…");
          }
  
          if (!permissions.has('EMBED_LINKS')) {
  
              return msg.channel.sendMessage("Ø§Ù†Ø§ Ù„Ø§ Ø§Ù…Ù„Ùƒ ØµÙ„Ø§Ø­ÙŠØ§Øª Ø§Ø±Ø³Ø§Ù„ Ø±ÙˆØ§Ø¨Ø·")
          }
  
          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); 
                  await handleVideo(video2, msg, voiceChannel, true); 
              }
              return msg.channel.send(`**${playlist.title}**, Just added to the queue!`);
          } else {
  
              try {
  
                  var video = await youtube.getVideo(url);
  
              } catch (error) {
                  try {
  
                      var videos = await youtube.searchVideos(searchString, 5);
                      let index = 0;
                      const embed1 = new Discord.RichEmbed()
                      .setTitle(":mag_right:  YouTube Search Results :")
                      .setDescription(`
                      ${videos.map(video2 =&gt; `${++index}. **${video2.title}**`).join('\n')}`)
  
                      .setColor("#f7abab")
                      msg.channel.sendEmbed(embed1).then(message =&gt;{message.delete(20000)})
  
  /////////////////                   
                      try {
  
                          var response = await msg.channel.awaitMessages(msg2 =&gt; msg2.content &gt; 0 &amp;&amp; msg2.content &lt; 11, {
                              maxMatches: 1,
                              time: 15000,
                              errors: ['time']
                          });
                      } catch (err) {
                          console.error(err);
                          return msg.channel.send('Ù„Ù… ÙŠØªÙ… Ø§Ø®ØªÙŠØ§Ø± Ø§Ù„Ø§ØºÙ†ÙŠØ©');
                      }
  
                      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 didn't find any results!");
                  }
              }
  
              return handleVideo(video, msg, voiceChannel);
  
          }
  
      } else if (command === `skip`) {
  
          if (!msg.member.voiceChannel) return msg.channel.send("ÙŠØ¬Ø¨ Ø§Ù† ØªÙƒÙˆÙ† ÙÙŠ Ø±ÙˆÙ… ØµÙˆØªÙŠ");
          if (!serverQueue) return msg.channel.send("Ù„ÙŠØ³Øª Ù‡Ù†Ø§Ùƒ Ø§ØºØ§Ù†ÙŠ Ù„ÙŠØªÙ… Ø§Ù„ØªØ®Ø·ÙŠ");
  
          serverQueue.connection.dispatcher.end('ØªÙ… ØªØ®Ø·ÙŠ Ø§Ù„Ø§ØºÙ†ÙŠØ©');
          return undefined;
  
      } else if (command === `stop`) {
  
          if (!msg.member.voiceChannel) return msg.channel.send("ÙŠØ¬Ø¨ Ø§Ù† ØªÙƒÙˆÙ† ÙÙŠ Ø±ÙˆÙ… ØµÙˆØªÙŠ");
          if (!serverQueue) return msg.channel.send("There is no Queue to stop!!");
  
          serverQueue.songs = [];
          serverQueue.connection.dispatcher.end('ØªÙ… Ø§ÙŠÙ‚Ø§Ù Ø§Ù„Ø§ØºÙ†ÙŠØ© Ù„Ù‚Ø¯ Ø®Ø±Ø¬Øª Ù…Ù† Ø§Ù„Ø±ÙˆÙ… Ø§Ù„ØµÙˆØªÙŠ');
          return undefined;
  
      } else if (command === `vol`) {
  
          if (!msg.member.voiceChannel) return msg.channel.send("ÙŠØ¬Ø¨ Ø§Ù† ØªÙƒÙˆÙ† ÙÙŠ Ø±ÙˆÙ… ØµÙˆØªÙŠ");
          if (!serverQueue) return msg.channel.send('ÙŠØ¹Ù…Ù„ Ø§Ù„Ø§Ù…Ø± ÙÙ‚Ø· Ø¹Ù†Ø¯ ØªØ´ØºÙŠÙ„ Ù…Ù‚Ø·Ø¹ ØµÙˆØªÙŠ');
          if (!args[1]) return msg.channel.send(`Ù„Ù‚Ø¯ ØªÙ… ØªØºÙŠØ± Ø¯Ø±Ø¬Ø© Ø§Ù„ØµÙˆØª Ø§Ù„Ù‰**${serverQueue.volume}**`);
  
          serverQueue.volume = args[1];
          serverQueue.connection.dispatcher.setVolumeLogarithmic(args[1] / 50);
  
          return msg.channel.send(`Ø¯Ø±Ø¬Ø© Ø§Ù„ØµÙˆØª Ø§Ù„Ø§Ù†**${args[1]}**`);
  
      } else if (command === `np`) {
  
          if (!serverQueue) return msg.channel.send('There is no Queue!');
          const embedNP = new Discord.RichEmbed()
          .setDescription(`Now playing **${serverQueue.songs[0].title}**`)
          return msg.channel.sendEmbed(embedNP);
  
      } else if (command === `queue`) {
  
          if (!serverQueue) return msg.channel.send('There is no Queue!!');
          let index = 0;
  //  //  //
          const embedqu = new Discord.RichEmbed()
          .setTitle("The Queue Songs :")
          .setDescription(`
          ${serverQueue.songs.map(song =&gt; `${++index}. **${song.title}**`).join('\n')}
  **Now playing :** **${serverQueue.songs[0].title}**`)
          .setColor("#f7abab")
          return msg.channel.sendEmbed(embedqu);
      } else if (command === `pause`) {
          if (serverQueue &amp;&amp; serverQueue.playing) {
              serverQueue.playing = false;
              serverQueue.connection.dispatcher.pause();
              return msg.channel.send('ØªÙ… Ø§Ù„Ø§ÙŠÙ‚Ø§Ù');
          }
          return msg.channel.send('ÙÙŠ Ø§Ù†ØªØ¸Ø§Ø± ØªØ´ØºÙŠÙ„ Ø§Ù„Ù…Ù‚Ø·Ø¹');
      } else if (command === "resume") {
  
          if (serverQueue &amp;&amp; !serverQueue.playing) {
              serverQueue.playing = true;
              serverQueue.connection.dispatcher.resume();
              return msg.channel.send('ØªÙ… Ø§Ù„ØªØ´ØºÙŠÙ„');
  
          }
          return msg.channel.send('Queue is empty!');
      }
  
      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(`Can't join this channel: ${error}!`);
          }
      } else {
          serverQueue.songs.push(song);
          console.log(serverQueue.songs);
          if (playlist) return undefined;
          else return msg.channel.send(`**${song.title}**, ØªÙ…Øª Ø§Ø¶Ø§ÙØ© Ø§Ù„Ù…Ù‚Ø·Ø¹ Ø§Ù„Ù‰ Ù‚Ø§Ø¦Ù…Ø© Ø§Ù„Ø§Ù†ØªØ¸Ø§Ø± `);
      } 
      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 =&gt; {
              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 =&gt; console.error(error));
      dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
  
      serverQueue.textChannel.send(`**${song.title}**, is now playing!`);
  
  
  }  
  
  
  client.on('message', message =&gt; {
      if (message.content === 'help') {
          let helpEmbed = new Discord.RichEmbed()
          .setTitle('**Ø£ÙˆØ§Ù…Ø± Ø§Ù„Ù…ÙŠÙˆØ²Ùƒ...**')
          .setDescription('**Ø¨Ø±ÙÙƒØ³ Ø§Ù„Ø¨ÙˆØª (!)**')
          .addField('play', 'Ù„ØªØ´ØºÙŠÙ„ Ø§ØºÙ†ÙŠØ©')
          .addField('join', 'Ø¯Ø®ÙˆÙ„ Ø±ÙˆÙ…Ùƒ Ø§Ù„ØµÙˆØªÙŠ')
          .addField('disconnect', 'Ø§Ù„Ø®Ø±ÙˆØ¬ Ù…Ù† Ø±ÙˆÙ…Ùƒ Ø§Ù„ØµÙˆØªÙŠ')
          .addField('skip', 'ØªØ®Ø·ÙŠ Ø§Ù„Ø£ØºÙ†ÙŠØ©')
          .addField('pause', 'Ø§ÙŠÙ‚Ø§Ù Ø§Ù„Ø§ØºÙ†ÙŠØ© Ù…Ø¤Ù‚ØªØ§')
          .addField('resume', 'ØªÙƒÙ…Ù„Ø© Ø§Ù„Ø§ØºÙ†ÙŠØ©')
          .addField('queue', 'Ø§Ø¸Ù‡Ø§Ø± Ù‚Ø§Ø¦Ù…Ø© Ø§Ù„ØªØ´ØºÙŠÙ„')
          .addField('np', 'Ø§Ø¸Ù‡Ø§Ø± Ø§Ù„Ø§ØºÙ†ÙŠØ© Ø§Ù„Ù„ÙŠ Ø§Ù†Øª Ù…Ø´ØºÙ„Ù‡Ø§ Ø­Ø§Ù„ÙŠØ§')
          .setFooter('(general_commands) Ù„Ø§Ø¸Ù‡Ø§Ø± Ø§Ù„Ø§ÙˆØ§Ù…Ø± Ø§Ù„Ø¹Ø§Ù…Ø©')
        message.channel.send(helpEmbed);
      }
  });
  
  client.on('message', message =&gt; {
      if (message.content === 'general_commands') {
          let helpEmbed = new Discord.RichEmbed()
          .setTitle('**Ø£ÙˆØ§Ù…Ø± Ø¹Ø§Ù…Ø©...**')
          .addField('avatar', "Ø§ÙØ§ØªØ§Ø± Ø§Ù„Ø´Ø®Øµ Ø§Ù„Ù…Ø·Ù„ÙˆØ¨")
          .addField('gif', 'Ø§Ù„Ø¨Ø­Ø« Ø¹Ù† Ø¬ÙŠÙ Ø§Ù†Øª ØªØ·Ù„Ø¨Ù‡')
          .addField('ping', 'Ù…Ø¹Ø±ÙØ© ping Ø§Ù„Ø¨ÙˆØª')
          .setFooter('Ø§Ù„Ù…Ø²ÙŠØ¯ Ù‚Ø±ÙŠØ¨Ø§ Ø§Ù† Ø´Ø§Ø¡ Ø§Ù„Ù„Ù‡!')
        message.channel.send(helpEmbed);
      }
  });
  
  client.on('ready', () =&gt; {
     console.log(`----------------`);
        console.log(`Desert Bot- Script By : EX Clan`);
          console.log(`----------------`);
        console.log(`ON ${client.guilds.size} Servers '     Script By : EX Clan ' `);
      console.log(`----------------`);
    console.log(`Logged in as ${client.user.tag}!`);
  client.user.setGame(`1play | Last Music`,"http://twitch.tv/Death Shop")
  client.user.setStatus("dnd")
  });
  
  </code></pre>
  
  <p><strong><em>Package.json</em></strong></p>
  
  <pre><code>{
    "name": "simple-music",
    "version": "1.0.0",
    "description": "Simple shitty music",
    "main": "server.js",
    "repository": {
      "type": "git",
      "url": "git+https://github.com/Abady321x123/simple-music.git"
    },
    "author": "Abady",
    "license": "MIT",
    "bugs": {
      "url": "https://github.com/Abady321x123/simple-music/issues"
    },
    "homepage": "https://github.com/Abady321x123/simple-music#readme",
    "dependencies": {
      "anti-spam": "^0.2.7",
      "array-sort": "^1.0.0",
      "ascii-data-table": "^2.1.1",
      "common-tags": "^1.8.0",
      "math-expression-evaluator": "^1.2.17",
      "canvas": "^2.4.1",
      "fs-nextra": "^0.4.4",
      "canvas-prebuilt": "^1.6.11",
      "cleverbot.io": "^1.0.4",
      "get": "1.4.0",
      "hero": "^0.0.1",
      "steam-search": "^1.0.0",
      "hypixel-api": "1.1.0",
      "name": "^0.0.2",
      "3amyah": "^1.0.0",
      "google-translate-api": "^2.3.0",
      "dateformat": "^3.0.3",
      "discord-anti-spam": "^2.0.0",
      "discord.js": "11.4.2",
      "express": "^4.16.4",
      "ffmpeg": "^0.0.4",
      "better-sqlite-pool": "^0.2.2",
      "guild": "^1.2.2",
      "delay": "^4.1.0",
      "enmap": "^4.8.1",
      "ffmpeg-binaries": "^4.0.0",
      "figlet": "^1.2.1",
      "file-system": "^2.2.2",
      "forever": "^0.15.3",
      "fortnite": "^4.3.2",
      "node-emoji": "^1.10.0",
      "fortnite-api": "^3.2.0",
      "get-youtube-id": "^1.0.1",
      "gif-search": "^2.0.1",
      "giphy-api": "^2.0.1",
      "goo.gl": "^0.1.4",
      "google-it": "^1.1.3",
      "hastebin-gen": "^1.3.1",
      "hh-mm-ss": "^1.2.0",
      "jimp": "^0.6.0",
      "message": "0.0.1",
      "moment": "^2.24.0",
      "ms": "^2.1.1",
      "new": "0.1.1",
      "node-opus": "^0.3.1",
      "npm": "^6.5.0",
      "opusscript": "0.0.6",
      "path": "0.12.7",
      "pretty-ms": "^4.0.0",
      "queue": "^6.0.1",
      "quick.db": "^6.3.2",
      "replace": "^1.1.0",
      "short-number": "^1.0.6",
      "simple-youtube-api": "^5.1.1",
      "sqlite": "^3.0.3",
      "sqlite3": "^4.0.6",
      "stackos": "1.1.0",
      "superagent": "4.1.0",
      "table": "^5.2.2",
      "until": "^0.1.1",
      "ustat": "0.0.2",
      "winston": "^3.2.1",
      "youtube-info": "^1.3.2",
      "ytdl-core": "^0.29.0"
    },
    "scripts": {
      "start": "node server.js"
    }
  }
  </code></pre>
  
  <p><strong><em>Config.js</em></strong></p>
  
  <pre><code>module.exports = {
      TOKEN: 'Already In',    
      YT_API_KEY: 'api ', 
      prefix: '!',
      devs: ['Already In']
  }
  </code></pre>