Disconnect discord bot from voice channel

117 views Asked by At

I have a problem with my code in discord js v14 and distube v4, it always show this error.

node:events:491
      throw er; // Unhandled 'error' event
      ^

TypeError: Cannot read properties of undefined (reading 'cache')
    at Client.<anonymous> (C:\Users\Alberto\Desktop\Bot discord\index.js:119:32)
    at Client.emit (node:events:513:28)
    at MessageCreateAction.handle (C:\Users\Alberto\Desktop\Bot discord\node_modules\discord.js\src\client\actions\MessageCreate.js:28:14)
    at module.exports [as MESSAGE_CREATE] (C:\Users\Alberto\Desktop\Bot discord\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\Alberto\Desktop\Bot discord\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31)
    at WebSocketShard.onPacket (C:\Users\Alberto\Desktop\Bot discord\node_modules\discord.js\src\client\websocket\WebSocketShard.js:494:22)
    at WebSocketShard.onMessage (C:\Users\Alberto\Desktop\Bot discord\node_modules\discord.js\src\client\websocket\WebSocketShard.js:328:10)
    at callListener (C:\Users\Alberto\Desktop\Bot discord\node_modules\ws\lib\event-target.js:290:14)
    at WebSocket.onMessage (C:\Users\Alberto\Desktop\Bot discord\node_modules\ws\lib\event-target.js:209:9)
    at WebSocket.emit (node:events:513:28)
Emitted 'error' event on Client instance at:
    at emitUnhandledRejectionOrErr (node:events:394:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:84:21)

Here's my code:

else if (command === 'leave') {
  
  const guild = message.guilds.cache.get('guild-id');
  const voiceChannel = guild.guild.channels.cache.get('voice-channel-id');
  
  const channel = message.member.voice.channel;
  
  if (!channel) return message.channel.send('You need to be in a voice channel to do this');
  if (voiceChannel && voiceChannel.members.has(client.user.id)) console.log('The bot is connected to the voice channel.');
  else {return message.channel.send("I'm not in a voice channel")}

  const channelId = connection.packets.state.channel_id

  if (channel.id !== channelId) return message.channel.send('You need to be in the same voice channel as me')

  try{await
    connection.destroy()
    message.channel.send('Sono uscito dalla chat vocale');
  } catch(error){
  console.error(error);}
  
}

I want to disconnect the discord bot and check if the author i on a voice channel and the bot is a voice channel.

1

There are 1 answers

0
John nielsen On

try to replace

const guild = message.guilds.cache.get('guild-id'); with const guild = message.guild;