简体   繁体   English

Discord.js | 类型错误:无法读取未定义的属性“声音”

[英]Discord.js | TypeError: Cannot read property 'voice' of undefined

recently i've been working on my custom discord bot in discord.js.最近我一直在 discord.js 中开发我的自定义 discord bot。

Today i modified my command handler and got into this error while trying to use my .play command that plays music through my bot:今天,我修改了我的命令处理程序,并在尝试使用我的 .play 命令通过我的机器人播放音乐时遇到了这个错误:

(node:481) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'voice' of undefined
    at Object.execute (/home/runner/MaikuBot/commands/play.js:14:46)
    at Client.<anonymous> (/home/runner/MaikuBot/index.js:29:34)
    at Client.emit (events.js:314:20)
    at Client.EventEmitter.emit (domain.js:483:12)
    at MessageCreateAction.handle (/home/runner/MaikuBot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14) at Object.module.exports [as MESSAGE_CREATE] (/home/runner/MaikuBot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32) at WebSocketManager.handlePacket (/home/runner/MaikuBot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31) at WebSocketShard.onPacket (/home/runner/MaikuBot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22) at WebSocketShard.onMessage (/home/runner/MaikuBot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10) at WebSocket.onMessage (/home/runner/MaikuBot/node_modules/ws/lib/event-target.js:132:16) (node:481) UnhandledPromiseRejectionWarning: Unhandled promise rejection. 
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). 
To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

So here is my .play command code:所以这是我的 .play 命令代码:

const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const { MessageEmbed } = require('discord.js');
var volume = 0.5;

const queue = new Map();
module.exports = {
    name: 'play',
    aliases: ['p', 'skip', 'clear', 'volUp', 'volDown'],
    cooldown: 0,
    description: "Play music trought bot",
    async execute(client, message, args, cmd, Discord) {
        const voice_channel = message.member.voice.channel;
        if (voice_channel != null) {
            if (!voice_channel) {
                return message.reply("Devi essere in un canale vocale.");
            }
            const server_queue = queue.get(message.guild.id);

        //If the user has used the play command
        if (cmd === 'play' || cmd === 'p'){
            if (!args.length) return message.reply('Per favore completa il comando!');
            let song = {};

            //If the first argument is a link. Set the song object to have two keys. Title and URl.
            if (ytdl.validateURL(args[0])) {
                const song_info = await ytdl.getInfo(args[0]);
                song = { title: song_info.videoDetails.title, url: song_info.videoDetails.video_url }
            } else {
                //If there was no link, we use keywords to search for a video. Set the song object to have two keys. Title and URl.
                const video_finder = async (query) =>{
                    const video_result = await ytSearch(query);
                    return (video_result.videos.length > 1) ? video_result.videos[0] : null;
                }

                const video = await video_finder(args.join(' '));
                if (video){
                    song = { title: video.title, url: video.url }
                } else {
                     message.channel.send('Non ho trovato il video...');
                }
            }

            //If the server queue does not exist (which doesn't for the first video queued) then create a constructor to be added to our global queue.
            if (!server_queue){

                const queue_constructor = {
                    voice_channel: voice_channel,
                    text_channel: message.channel,
                    connection: null,
                    songs: []
                }
                
                //Add our key and value pair into the global queue. We then use this to get our server queue.
                queue.set(message.guild.id, queue_constructor);
                queue_constructor.songs.push(song);
    
                //Establish a connection and play the song with the vide_player function.
                try {
                    const connection = await voice_channel.join();
                    queue_constructor.connection = connection;
                    video_player(message.guild, queue_constructor.songs[0]);
                } catch (err) {
                    queue.delete(message.guild.id);
                    message.channel.send("C'è stato un errore durante la connessione al canale...");
                    throw err;
                }
            } else{
                server_queue.songs.push(song);
                const Embed = new MessageEmbed()
                .setTitle(`🎶 Ho aggiunto "**${song.title}**" alla coda`)
                .setColor('#36393F')
                .setAuthor('maiku', 'https://i.ibb.co/MCkG7wV/M-ROSSA-500.png', 'https://discord.gg/QNhpmbG3Sm')
                .setDescription(`[**Brano aggiunto alla coda corretamente**]`);
                await server_queue.text_channel.send(Embed);
                console.log(`[ll] Ho aggiunto "${song.title}" alla coda`);
            }
        }
            else if(cmd === 'skip') skip_song(message, server_queue);
            else if(cmd === 'clear') clear_song(message, server_queue);
            else if(cmd === 'volUp') volUp(message, server_queue);
            else if(cmd === 'volDown') volDown(message, server_queue);
        }
        
  }
    
}

const video_player = async (guild, song) => {
    const song_queue = queue.get(guild.id);

    //If no song is left in the server queue. Leave the voice channel and delete the key and value pair from the global queue.
    if (!song) {
        song_queue.voice_channel.leave();
        queue.delete(guild.id);
        return;
    }
    const stream = ytdl(song.url, { filter: 'audioonly' });
    song_queue.connection.play(stream, { seek: 0, volume: volume })
    .on('finish', () => {
        song_queue.songs.shift();
        video_player(guild, song_queue.songs[0]);
    });
    const Embed = new MessageEmbed()
        .setTitle(`🎶 Sto riproducendo "**${song.title}**"`)
        .setColor(0xFF0000)
        .setAuthor('maiku', 'https://i.ibb.co/MCkG7wV/M-ROSSA-500.png', 'https://discord.gg/QNhpmbG3Sm')
        .setDescription(`[**Brano riprodotto correttamente**]`);
    await song_queue.text_channel.send(Embed);
    console.log(`[>] Sto riproducendo "${song.title}"`);
}

const skip_song = (message, server_queue) => {
    if (!message.member.voice.channel) return message.channel.send('Devi essere in un canale vocale.');
    if(!server_queue){
        return message.channel.send(`Non ci sono canzoni da skippare`);
    }
    message.react('👍');
    console.log(`[!] Brano skippato con successo`);
    server_queue.connection.dispatcher.end();
}

const clear_song = (message, server_queue) => {
    if (!message.member.voice.channel) return message.channel.send('Devi essere in un canale vocale.');
    message.react('👍');
    server_queue.connection.dispatcher.end();
    server_queue.songs = [];
    console.log(`[!] Coda azzerata`);
}

const volUp = (message, server_queue) => {
    if (!message.member.voice.channel) return message.channel.send('Devi essere in un canale vocale.');
    message.react('👍');
    volume = volume + 0.5;
    console.log(`[?] Volume aumentato di 0.5`);
}

const volDown = (message, server_queue) => {
    if (!message.member.voice.channel) return message.channel.send('Devi essere in un canale vocale.');
    message.react('👍');
    if (volume > 0.5) {
        volume = volume - 0.5;
        console.log(`[?] Volume diminuito di 0.5`);
    }
    console.log(`[?] Volume non diminuito [valore minimo raggiunto]`);
}

I tried looking at similar errors but on different codes but none of those fixes worked for me.我尝试查看类似的错误,但使用不同的代码,但这些修复程序都不适用于我。 Can you help me fix this?你能帮我解决这个问题吗? Thanks谢谢

also take a look on the command handler也看看命令处理程序

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);
}
client.on('message', message => {
  if (!message.content.startsWith(prefix) || message.author.bot) return;
  const args = message.content.slice(prefix.length).trim().split(/ +/);
  const command = args.shift().toLowerCase();

  if (!client.commands.has(command)) return; 

  try {
    client.commands.get(command).execute(message, args, client, Discord);
  } catch (error) {
    console.error(error);
    message.reply(`Si è verificato un errore durante l'esecuzione del comando...`);
  }
})

I don't know what Discord.js library actually do, but the error tells you that the param member in message it's undefined .我不知道 Discord.js 库实际上做了什么,但错误告诉你message中的 param memberundefined Maybe it's because the first param that you send on the execute is not the client , it's message .也许是因为您在执行时发送的第一个参数不是client ,而是message

I think that it should be:我认为应该是:

client.commands.get(command).execute(client, message, args, command, Discord);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Discord.js - 无法读取未定义的属性“声音” - Discord.js - Cannot read property 'voice' of undefined 类型错误:无法读取未定义 Discord.js javascript 的属性“添加” - TypeError: Cannot read property 'add' of undefined Discord.js javascript 类型错误:无法读取未定义的属性 &#39;has&#39; // Discord.js - TypeError: Cannot read property 'has' of undefined // Discord.js 遇到 TypeError:无法读取 Discord.JS 中未定义的属性“0” - Encountering TypeError: Cannot read property '0' of undefined in Discord.JS Discord.JS UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“startsWith” - Discord.JS UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startsWith' of undefined TypeError:无法读取未定义的属性“数据”| discord.js - TypeError: Cannot read property 'data' of undefined | discord.js 类型错误:无法读取未定义的属性“角色”|| Discord.js - TypeError: Cannot read property 'roles' of undefined || Discord.js (Discord.js)TypeError:无法读取未定义的属性“添加” - (Discord.js) TypeError: Cannot read property 'add' of undefined Discord.js:类型错误:无法读取未定义的属性“删除” - Discord.js : TypeError: Cannot read property 'remove' of undefined Discord.js“类型错误:无法读取未定义的属性‘有’” - Discord.js "TypeError: Cannot read property 'has' of undefined"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM