0

I have Discord Music bot and it's been running for almost a year. Since yesterday, I got an issue that says:

Unable to play a music: 
Error: WebSocket was closed before the connection was established

Here is my code:

    try {
      var connection = await voiceChannel.join();
      if(guild.me.hasPermission("DEAFEN_MEMBERS")) guild.me.voice.setDeaf(true);
      queueContruct.connection = connection;
      play(message.guild, queueContruct.songs[0], message);
    } catch (err) {
      queue.delete(message.guild.id);
      errorMessage(message, "1058");
      console.error("Unable to play a music: ");
      return console.error(err);
    }

play function:

async function play(guild, song, message) {
  const serverQueue = queue.get(guild.id);

  if (!song) {
    if(serverQueue.voiceChannel){
      serverQueue.voiceChannel.leave();
    }
    else {
      guild.voice.channel.leave();
    }
    queue.delete(guild.id);
    return;
  }

  try {
    let player = await ytdl(song.url, {filter: 'audioonly', quality: 'highestaudio', highWaterMark: 1 << 25, opusEncoded: true, encoderArgs: ['-af', 'bass=g=0']});
    const dispatcher = serverQueue.connection.play(player, { type: 'opus', highWaterMark: 1, bitrate: 'auto', fec: true, volume: false })
      .on("finish", () => {
        serverQueue.songs.shift();
        play(guild, serverQueue.songs[0], message);
      })
      .on("error", error => {
        console.error(error);
      });

      dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
    } catch(err){
      errorMessage(message, "1060");
    }
}

I have no idea what's the issue. Any ideas? And what does this error exactly mean?

Sanchir
  • 99
  • 1
  • 8

1 Answers1

0

It happens when you call close() on websocket when connection is not established. The code you include in the question does not include a close(); check for a close(), and make sure you don't call it if connection is not established.

discord.js uses ws, this is the place error is thrown:

https://github.com/websockets/ws/blob/a2c0d447af711ca245cb534159fa7c4d9ae67e64/lib/websocket.js#L222

so if websocket is in CONNECTING state and you call close() the error is thrown.

References: https://stackoverflow.com/a/12503628/9483495

srknzl
  • 776
  • 5
  • 13
  • Thank you for your answer! But I pretty sure that didn't call any close() function at all. – Sanchir Apr 11 '21 at 08:24
  • Discord.js can be calling it behind the scenes. I am not sure when it calls it though. – srknzl Apr 11 '21 at 08:25
  • I also got this error: `Error [VOICE_CONNECTION_TIMEOUT]: Connection not established within 15 seconds.` – Sanchir Apr 11 '21 at 08:32
  • 1
    I think your main issue is connectivity issue, not sure why, maybe due to discord servers. Where this call opens a connection to? `var connection = await voiceChannel.join();` – srknzl Apr 11 '21 at 08:34
  • Yeah, I think the issue is connectivity issue. Thank you! – Sanchir Apr 11 '21 at 09:23