Необработанное promiserejectionwarning: ошибка типа: не удается прочитать свойство ‘voice’ неопределенного

#node.js #discord #discord.js #bots

#node.js #Discord #discord.js #боты

Вопрос:

Итак, я пытаюсь создать команду для воспроизведения музыки в vc, но вот моя проблема: всякий раз, когда я запускаю команду, она выдает мне эту ошибку (node:11) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'voice' of undefined всякий раз, когда я пытаюсь что-либо сделать с помощью этой команды, она не работает. Это просто выдает мне эту ошибку снова и снова и снова. Я пока не нашел никакого исправления, но я продолжу искать. Если кто-нибудь из вас узнает, как это исправить, пожалуйста, ответьте на мой пост.

код:

 const { Util, voice, Client } = require('discord.js');
const bot = new Client();

module.exports.run = async(message, args) => {
const channel = message.member.voice.channel.join
    if (!channel) return message.channel.send('I'm sorry but you need to be in a voice channel to play music!');
    const permissions = channel.permissionsFor(message.client.user);
    if (!permissions.has('CONNECT')) return message.channel.send('I cannot connect to your voice channel, make sure I have the proper permissions!');
    if (!permissions.has('SPEAK')) return message.channel.send('I cannot speak in this voice channel, make sure I have the proper permissions!');

    const serverQueue = message.client.queue.get(message.guild.id);
    const songInfo = await ytdl.getInfo(args[0].replace(/<(. )>/g, '$1'));
    const song = {
        id: songInfo.videoDetails.video_id,
        title: Util.escapeMarkdown(songInfo.videoDetails.title),
        url: songInfo.videoDetails.video_url
    };

    if (serverQueue) {
        serverQueue.songs.push(song);
        console.log(serverQueue.songs);
        return message.channel.send(`✅ **${song.title}** has been added to the queue!`);
    }

    const queueConstruct = {
        textChannel: message.channel,
        voiceChannel: channel,
        connection: null,
        songs: [],
        volume: 2,
        playing: true
    };
    message.client.queue.set(message.guild.id, queueConstruct);
    queueConstruct.songs.push(song);

    const play = async song => {
        const queue = message.client.queue.get(message.guild.id);
        if (!song) {
            queue.voiceChannel.leave();
            message.client.queue.delete(message.guild.id);
            return;
        }

        const dispatcher = queue.connection.play(ytdl(song.url))
            .on('finish', () => {
                queue.songs.shift();
                play(queue.songs[0]);
            })
            .on('error', error => console.error(error));
        dispatcher.setVolumeLogarithmic(queue.volume / 5);
        queue.textChannel.send(`🎶 Start playing: **${song.title}**`);
    };

    try {
        const connection = await channel.join();
        queueConstruct.connection = connection;
        play(queueConstruct.songs[0]);
    } catch (error) {
        console.error(`I could not join the voice channel: ${error}`);
        message.client.queue.delete(message.guild.id);
        await channel.leave();
        return message.channel.send(`I could not join the voice channel: ${error}`);
    }
}

module.exports.help = {
    name: "play",
    aliases: []
}```
 

Комментарии:

1. Что message содержит переменная?

Ответ №1:

 const channel = message.member.voice.channel.join
 

не существует…

Попробуйте использовать:

 const channel = message.member.voice.channel
 

Он проверяет, находится ли пользователь в каком-либо голосовом канале.
Если это не работает, то ваш message.member возвращает undefined. Попробуйте записать message.member в se, если он действительно возвращает undefined, и выясните, почему, поскольку эта часть кода должна работать нормально.