“无法读取未定义的属性‘url’”,即使它已经定义

Posted

技术标签:

【中文标题】“无法读取未定义的属性‘url’”,即使它已经定义【英文标题】:"Cannot read property 'url' of undefined" even though it's already defined 【发布时间】: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(`$mcPrefixplay`)) 

        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(`$mcPrefixstop`)) 
        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(`$mcPrefixskip`))
        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)) 中未定义 【参考方案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)
  ...

【讨论】:

以上是关于“无法读取未定义的属性‘url’”,即使它已经定义的主要内容,如果未能解决你的问题,请参考以下文章

无法读取未定义的属性“URL” - 访问 JSON 对象

Node.js 和 jdbc:TypeError:无法读取未定义的属性“url”

即使已经定义了变量,所需的代码也无法找到它们

Sass错误:未定义变量,即使它已声明

安装 bff,即使它已经安装

错误:在 cakephp 的非对象上调用成员函数 create(),即使模型的名称已经定义