TypeError: Cannot read properties of undefined (reading '0') discord.js v13

TypeError: Cannot read properties of undefined (reading '0') discord.js v13

出于某些愚蠢的原因,我正在使用 Discord.JS v13。自从我收到这些我不知道存在的奇怪错误以来。每次我 运行 命令它只是给出一个错误并关闭机器人。我尝试添加 try and catch,但我认为这些不再适用于 v13。如果你们能帮忙的话,这是我的代码。

错误在第 32 行 btw

const Discord = require('discord.js')
const { MessageEmbed } = require('discord.js')
const https = require('https')
const url = 'https://www.reddit.com/r/catpics/hot/.json?limit=300'
module.exports = {
    name: "cat",
    description: "meow",
     execute(message, args, client) {
        message.reply("I am loading the image, if it does not come up try again later due to errors.")
        https.get(url, (result) => {
            var body = ''
            result.on('data', (chunk) => {
                body += chunk
            })

            result.on('end', () => {
                var response = JSON.parse(body)
                var index = response.data.children[Math.floor(Math.random() * 99) + 1].data

                if (index.post_hint !== 'image') {

                    var text = index.selftext
                    const textembed = new Discord.MessageEmbed()
                        .setTitle("cute")
                        .setColor(9384170)
                        .setDescription(`[${title}](${link})\n\n${text}`)
                        .setURL(`https://reddit.com/${subRedditName}`)

                    message.channel.send({embeds: [textembed]})
                }

                var image = index.preview.image[0].source.url.replace('&', '&')
                var title = index.title
                var link = 'https://reddit.com' + index.permalink
                var subRedditName = index.subreddit_name_prefixed

                if (index.post_hint !== 'image') {
                    const textembed = new Discord.MessageEmbed()
                        .setTitle("cute")
                        .setColor(9384170)
                        .setDescription(`[${title}](${link})\n\n${text}`)
                        .setURL(`https://reddit.com/${subRedditName}`)

                    message.channel.send({embeds: [textembed]})
                }
                console.log(image);
                const imageembed = new Discord.MessageEmbed()
                    .setTitle("cute")
                    .setImage(image)
                    .setColor(9384170)
                    .setDescription(`[${title}](${link})`)
                    .setURL(`https://reddit.com/${subRedditName}`)
                message.channel.send({embeds: [imageembed]})
            }).on('error', function (e) {
                console.log('Got an error: ', e)
            })
        })

     }
}

输出:

TypeError: Cannot read properties of undefined (reading '0')

因为我猜你没有编程背景,我将通过一个适合你需要的例子 and/or 来检查你可能 copy-pasted 的代码的每一部分,并尝试解释 in-depth 当任何错误出现时你应该采取什么行为。一旦我们到达错误行,我就会停下来,line 32

请记住,这不是地方,但我会把它作为一件 one-time 的事情来做。合适的位置是 Stack Exchange's Code Review.

首先,鉴于 urlhttps 模块的存在,我假设您尝试从 Reddit 检索有关猫图片的信息。

让我们直接深入讨论有代码的地方。 result.on('end') 函数将在没有更多要解析的正文时执行,但我想你明白了。

然后,您尝试检索有关随机选择的特定图像的数据:

var index = response.data.children[Math.floor(Math.random() * 99) + 1].data

这里有两件事:

  • Math.random() 只有 returns 01 之间的数字,使得整行选择 1 到 100 之间的数字。然后你就错过了选择的机会元素 0,因为 JS 中的数组是 zero-based 索引的。此外,您可以将 Reddit URL 中的限制从 300 减少到 100。
  • 您假设了两件事:children 确实是 response Reddit 发给您的密钥,并且 children 数组最多包含 100 个元素。

如果 children 数组只有 15 个元素(如果它存在的话)会怎样?您将遇到另一个错误。我会留给你想出一个解决方案来检查这两件事。

那里:

var image = index.preview.image[0].source.url.replace('&', '&')

你再次假设 previewimage(作为数组)、sourceurl存在.

现在我已经开始 copy-pasted URL https://www.reddit.com/r/catpics/hot/.json?limit=100JSON Beautifier 中的结果 preview '要求第 32 行存在,但是 image 不存在。

您只是忘记了一个 s,因为 images 存在于 preview 下。

事实上,您的错误归结为两件事:

  1. 变量 index 可能未定义,因为您可能会尝试访问具有无法访问索引的 response.data.children 数组(例如 response.data.children 只有 15 个元素,而您的 Math.random 给出你 55)
  2. image 字段在 preview 中不存在,只有 images 存在。

最后,说明一下你得到的TypeError,这就像叫人给你读一张白纸,或者给盲人一篇作文,让他给你读。

不管怎样,在这里提问之前,你应该再努力一点。如果您尝试在每一行之间登录直到缩小错误范围,您可能已经自己弄明白了。

此外,如果这些是 weird errors that I had no idea exists,那么您还没有真正准备好编码。如果不是更多的话,我每天 TypeError 次 half-dozen 次。这听起来可能很苛刻,但您不能因为遇到任何不便就来寻求帮助,否则您将学不到任何东西。更何况你没有 post minimum reproducible example.

综上所述,如果我提到的您应该解决的两件事没有解决问题,我会在评论中留下来。


根据对此答案的评论,我将添加更多详细信息。我也将介绍如何解决该问题,以便 OP 可以将类似的思维和过程应用于其他问题。

如果你继续 this page,这是你的代码中出现的 URL,只是不是 JSON 形式,你会看到有 post你想排除的。通常,我不认为 TrendingBot 中的 post 很有趣,因此您可以将它们排除在外。这就是为什么你有 /r/catpics enters TOP 5000 subreddits。任何有 index.author === 'TrendingBot' 的东西都不是 bueno。

对于其他问题,您可以通过 JSON 美化器(我在上面 link 编辑的)检查键和值。

看着JSON美化了自己,我觉得你不是在找image的正确键值。您可能要显示的图像是 index.url 键下的图像,也就是实际 post 的图像。我真的不认为 preview 是您应该搜索的内容。

最后,对于 link,同样,我认为您没有在搜索正确的密钥。我认为你应该抓住 index.permalink 而不是 index.subreddit_name_prefixed.

您的最终消息应如下所示:

const image = index.url.replace('&', '&');
const title = index.title;
const link = 'https://reddit.com' + index.permalink;
const subRedditName = index.subreddit_name_prefixed;

const imageembed = new Discord.MessageEmbed()
                    .setTitle("cute")
                    .setImage(image)
                    .setColor(9384170)
                    .setDescription(`[${title}](${link})`)
                    .setURL(link);