0
votes

I'm making a discord bot and I came across a problem, if I type $join into chat, I want the bot to join the voice channel I'm in and play a sound. That is working but when the bot is already in the voice channel and I type $join again, it just plays the sound again and I want it to play the sound only once when it connects to the channel. I tried to solve it with some if, else and return functions but it didn't work, thanks for help.

This is my code working like I described.

message.delete({
  timeout: 5000
})
const voiceChannel = message.member.voice.channel
if (voiceChannel) {
  const connection = await voiceChannel.join()
  const dispatcher = connection.play("./sounds/xxx.mp3")
  dispatcher.setVolume(0.5)
} else {
  message.reply("you need to be in a voice channel!").then(message => {
    message.delete({
      timeout: 5000
    })
  })
}
1

1 Answers

1
votes

You need to check whether the channel of your voice connection is the same you're about to join: if so, you don't need to do anything (you're already in the channel), otherwise you join, make the sound etc...
You can do this with VoiceConnection.channel

Here's how I would do it:

const voiceChannel = message.member.voice.channel
if (voiceChannel) { 
  // Check if any of the ALREADY EXISTING connections are in that channel, if not connect
  if (!client.voice.connections.some(conn => conn.channel.id == voiceChannel.id)) {
    const connection = await voiceChannel.join()
    const dispatcher = connection.play("./sounds/xxx.mp3")
    dispatcher.setVolume(0.5)
  } // else: you're already in the channel
} else {
  let m = await message.reply("You need to be in a voice channel!")
  m.delete({ timeout: 5000 })
}