【问题标题】:"Cannot read property 'url' of undefined" even though it's already defined“无法读取未定义的属性‘url’”,即使它已经定义
【发布时间】:2021-03-11 03:55:42
【问题描述】:

我正在制作一个 Discord 音乐机器人,但我遇到了一个错误提示

TypeError: Cannot read property 'url' of undefined

我尝试用控制台记录它,它显示了url,所以我不明白我的代码有什么问题。

这是我的代码:

//musicBOT
const Discord = require('discord.js');
const client = new Discord.Client();
const ytdl = require('ytdl-core');
const mcPrefix = '.';

const queue = new Map();

client.on('ready', () => console.log('Music bot ready!'));

client.on('message', async message => {
    if(message.author.bot) return;
    if(!message.content.startsWith(mcPrefix)) return;

    const args = message.content.substring(mcPrefix.length).split(" ");
    const serverQueue = queue.get(message.guild.id);

    if(message.content.startsWith(`${mcPrefix}play`)) {

        const voiceChannel = message.member.voice.channel;
        if(!voiceChannel) return message.channel.send("Hang-szobában kell lenned zenelejátszáshoz.");
        const permissions = voiceChannel.permissionsFor(message.client.user);
        if(!permissions.has('CONNECT')) return message.channel.send("Nincs jogosultságom csatlakozni a hangszobához.");
        if(!permissions.has('SPEAK')) return message.channel.send("Nincs jogosultságom megszólalni ebben a hangszobában.");

        const songInfo = await ytdl.getInfo(args[1])
        const song = {
            title: songInfo.title,
            url: songInfo.videoDetails.video_url
        }

        if(!serverQueue) {
            const queueConstruct = {
                textChannel: message.channel,
                voiceChannel: voiceChannel,
                connection: null,
                songs: [],
                volume: 5,
                playing: true
            }
            queue.set(message.guild.id, queueConstruct)

            queueConstruct.songs.push(song)

            try{
                var connection = await voiceChannel.join();
                message.channel.send(`${song.title} lejátszása.`)
                queueConstruct.connection = connection
                play(message.guild, queueConstruct.songs[0])
            }catch(e){
                console.log(`Hiba csatlakozás közben itt: ${e}`);
                queue.delete(message.guild.id)
                return message.channel.send(`Hiba volt a csatlakozás közben itt: ${e}`)
            }
        } else{
            serverQueue.songs.push(song)
            return message.channel.send(`**${song.title}** hozzáadva a lejátszási listához.`)
        }
        return undefined
        

        
    }else if (message.content.startsWith(`${mcPrefix}stop`)) {
        if(!message.member.voice.channel) return message.channel.send("Hang-szobában kell lenned ahhoz, hogy leállítsd a zenét.")
        if(!serverQueue) return message.channel.send("There is nothing playing")
        serverQueue.songs= []
        serverQueue.connection.dispatcher.end()
        message.channel.send("Sikeresen megálltottad a zenét.")
        return undefined
    }else if(message.content.startsWith(`${mcPrefix}skip`)){
        if(!message.member.voice.channel) return message.channel.send("Hang-szobában kell lenned a skip parancshoz.")
        if(!serverQueue) return message.channel.send("There is nothing playing")
        serverQueue.connection.dispatcher.end()
        message.channel.send("Zene továbbléptetve.")
        message.channel.send(`${song.title} játszása.`)
        
        return undefined
    }

    function play(guild, song) {
        const serverQueue = queue.get(guild.id)
    
        if(!serverQueue.songs){
            serverQueue.voiceChannel.leave()
            queue.delete(guild.id)
            return
        }
    
        const dispatcher = serverQueue.connection.play(ytdl(song.url))
            .on('finish', () => {
                serverQueue.songs.shift()
                play(guild, serverQueue.songs[0])
            })
            .on('error', error => {
                console.log(error)
            })
            dispatcher.setVolumeLogarithmic(serverQueue.volume / 5)
    }

})
//musicBOT

这是完整的错误:

const dispatcher = serverQueue.connection.play(ytdl(songInfo.url))
                                                                     ^
TypeError: Cannot read property 'url' of undefined
    at play (C:\Users\Levi\Desktop\Discord BOT Javascript\bot.js:97:70)
    at StreamDispatcher.<anonymous> (C:\Users\Levi\Desktop\Discord BOT Javascript\bot.js:100:17)
    at StreamDispatcher.emit (node:events:388:22)
    at finish (node:internal/streams/writable:734:10)
    at processTicksAndRejections (node:internal/process/task_queues:80:21)

我开始在互联网上搜索,但一无所获,我想我的基本 javascript 知识还不够。

【问题讨论】:

  • 你检查song是在播放功能上定义的吗?
  • 刚查了一下,已经定义好了。
  • 根据您的错误,songconst dispatcher = serverQueue.connection.play(ytdl(songInfo.url)) 中未定义

标签: node.js ffmpeg discord.js ytdl


【解决方案1】:

play函数中检查的空songs数组不正确:

// This "if" clause will never be run, voice channel won't leave when there's no song
if(!serverQueue.songs){
  serverQueue.voiceChannel.leave()
  ...
}

修复:

if(serverQueue.songs.length === 0){
  ...
}

【讨论】:

    猜你喜欢
    • 2012-11-22
    • 2020-05-31
    • 1970-01-01
    • 2021-08-05
    • 2017-11-10
    • 2022-01-21
    • 1970-01-01
    • 2019-05-17
    • 2018-01-16
    相关资源
    最近更新 更多