简体   繁体   中英

cannot read properties of undefined (reading 'voice')

I am trying to make https://coderadio.freecodecamp.org/ play in a discord voice channel. I want to add a command called /coderadio that calls the bot into the current voice channel and streams the current song on the radio.

Here is the repo I used originally - https://github.com/TannerGabriel/discord-bot

I have added a new file to the commands folder, play-coderadio.js. I am hoping to have one slash command to play the radio and another to stop it.

index.js -

const fs = require('fs');
const Discord = require('discord.js');
const Client = require('./client/Client');
const config = require('./config.json');
const {Player} = require('discord-player');

const client = new Client();
client.commands = new Discord.Collection();

const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
  const command = require(`./commands/${file}`);
  client.commands.set(command.name, command);
}

console.log(client.commands);

const player = new Player(client);

player.on('error', (queue, error) => {
  console.log(`[${queue.guild.name}] Error emitted from the queue: ${error.message}`);
});

player.on('connectionError', (queue, error) => {
  console.log(`[${queue.guild.name}] Error emitted from the connection: ${error.message}`);
});

player.on('trackStart', (queue, track) => {
  queue.metadata.send(`▶ | Started playing: **${track.title}** in **${queue.connection.channel.name}**!`);
});

player.on('trackAdd', (queue, track) => {
  queue.metadata.send(`🎶 | Track **${track.title}** queued!`);
});

player.on('botDisconnect', queue => {
  queue.metadata.send('❌ | I was manually disconnected from the voice channel, clearing queue!');
});

player.on('channelEmpty', queue => {
  queue.metadata.send('❌ | Nobody is in the voice channel, leaving...');
});

player.on('queueEnd', queue => {
  queue.metadata.send('✅ | Queue finished!');
});

client.once('ready', async () => {
  console.log('Ready!');
});

client.on('ready', function() {
  client.user.setActivity(config.activity, { type: config.activityType });
});

client.once('reconnecting', () => {
  console.log('Reconnecting!');
});

client.once('disconnect', () => {
  console.log('Disconnect!');
});

client.on('messageCreate', async message => {
  if (message.author.bot || !message.guild) return;
  if (!client.application?.owner) await client.application?.fetch();

  if (message.content === '!deploy' && message.author.id === client.application?.owner?.id) {
    await message.guild.commands
      .set(client.commands)
      .then(() => {
        message.reply('Deployed!');
      })
      .catch(err => {
        message.reply('Could not deploy commands! Make sure the bot has the application.commands permission!');
        console.error(err);
      });
  }
});

client.on('interactionCreate', async interaction => {
  const command = client.commands.get(interaction.commandName.toLowerCase());

  try {
    if (interaction.commandName == 'ban' || interaction.commandName == 'userinfo') {
      command.execute(interaction, client);
    } else {
      command.execute(interaction, player);
    }
  } catch (error) {
    console.error(error);
    interaction.followUp({
      content: 'There was an error trying to execute that command!',
    });
  }
});

client.login(config.token);

play-coderadio.js -

const Discord = require('discord.js')
const { MessageEmbed } = require('discord.js')
module.exports = {
    name: 'coderadio',
    description: 'play FCC radio',
    async execute(client, message, args) {
        
    const voiceChannel = message.member.voice.channel;
    if(!voiceChannel)
    return message.channel.send("You must be in a voice channel!"); 
    
    const permissions = voiceChannel.permissionsFor(message.client.user);
    if(!permissions.has('CONNECT') || !permissions.has('SPEAK')) return message.reply('I am missing permission!');    

    var connection = await voiceChannel.join();
    await connection.voice.setSelfDeaf(true);
    connection.play("https://coderadio-relay-blr.freecodecamp.org/radio/8010/radio.mp3").setVolumeLogarithmic(1);
    const embed =  new MessageEmbed()
    .setTitle(`Radio Now Playing!`)
    .setDescription(`Now Playing radio!\n\nPlaying into ${voiceChannel.name}`)
    message.channel.send(embed)
}
}

Here is the error I am getting when I run /coderadio -

C:\Users\Rudy\musicbot\discord-bot\commands\play-coderadio.js:9 const voiceChannel = message.member.voice.channel; ^ TypeError: Cannot read properties of undefined (reading 'voice') at Object.execute (C:\Users--\musicbot\discord-bot\commands\play-coderadio.js:9:41) at module.exports. (C:\Users--\musicbot\discord-bot\index.js:89:15) at module.exports.emit (node:events:527:28) at InteractionCreateAction.handle (C:\Users--\musicbot\discord-bot\node_modules\discord.js\src\client\actions\InteractionCreate.js:74:12) at module.exports [as INTERACTION_CREATE] (C:\Users--\musicbot\discord-bot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36) at WebSocketManager.handlePacket (C:\Users--\musicbot\discord-bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:351:31) at WebSocketShard.onPacket (C:\Users--\musicbot\discord-bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22) at WebSocketShard.onMessage (C:\Users--\musicbot\discord-bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10) at WebSocket.onMessage (C:\Users--\musicbot\discord-bot\node_modules\ws\lib\event-target.js:199:18) at WebSocket.emit (node:events:527:28)

Try using optional chaining for your assignment to voiceChannel.

Something like const voiceChannel = message?.member?.voice?.channel;

In cases where there is no message, voiceChannel will render false and you will send the error message you stated in your if statement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM