Mat Darwin
Mat Darwin

Reputation: 17

Discord.js a music loop

I want to have my bot who play music for ever in Vocal but I am really bad in javascript. I have take a While but this is not work... If someone can help me.

My code :

client.on('message', async message => {

messagesansfiltre = message.content;
var messagevar = message.content ;
message.content = cleanmessage(message.content);


 if (message.content.startsWith("jukebox play ")) {
    const args = messagesansfiltre.split(' ')
    console.log(`${args[2]}`);
    const voiceChannel = message.member.voice.channel;
    if (!voiceChannel) return message.channel.send('I\'m sorry but you need to be in a voice channel to play music!');
    while ( "1" === "1" ){
        voiceChannel.join()
            .then(connection => {

                const dispatcher = connection.play(ytdl(args[2]))
                console.log(dispatcher.time)

                })
        .catch(console.log)

        //await delay(3600000);
    }
}

Upvotes: 1

Views: 2352

Answers (1)

Lauren Yim
Lauren Yim

Reputation: 14098

I'm assuming you want to be able to stop the music as well.

// This stores the voice channel that the bot is connected to for each guild
// mapped by the guild ID so that we can stop the music by leaving the channel.
const voiceChannels = new Map()

if (message.content.startsWith('jukebox play ')) {
  const args = messagesansfiltre.split(' ')
  console.log(args[2])
  const voiceChannel = message.member.voice.channel
  if (!voiceChannel) return message.channel.send("I'm sorry but you need to be in a voice channel to play music!")
  voiceChannel.join()
    .then(connection => {
      // Stores the voice channel
      voiceChannels.set(message.guild.id, voiceChannel)
      // A recursive function that plays the music continuously.
      const play = () => {
        const dispatcher = connection
          .play(ytdl(args[2]))
          // When the song is finished, play it again.
          .on('finish', play)
        // Note that in Discord.js v12 StreamDispatcher has pauseTime, streamTime,
        // and totalStreamTime
        console.log(dispatcher.time)
      }
      play()
    })
    .catch(console.log)
} else if (message.content.startsWith('jukebox stop')) {
  // You can send 'jukebox stop' to stop the music.
  const voiceChannel = voiceChannels.get(message.guild.id)
  if (!voiceChannel) return message.channel.send('No music is playing!')
  // Leave the channel.
  voiceChannel.leave()
  // Remove the channel from voiceChannels.
  voiceChannels.delete(message.guild.id)
}

I haven't tested this so let me know if it doesn't work.

Upvotes: 2

Related Questions