开发者问题收集

TypeError:无法读取未定义的属性“数据”| discord.js

2021-02-22
309

因此,我正在制作一个 Discord 机器人,并且我有一个 meme 命令,可以从 r/memes 获取 meme,但是有时它会给出一个 meme,有时代码会崩溃并在控制台中给出此错误:

TypeError: Cannot read property 'data' of undefined

我不太确定这可能是什么,所以如果有人能帮助我,那将会很有帮助。

这是我的 !meme 命令代码:

const https = require('https');
const Discord = require('discord.js');
const url = 'https://www.reddit.com/r/memes/hot/.json'

module.exports = {
    name: 'meme',
    description: 'sends meme',
    execute(message, args) {

        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(subRedditName)
                        .setColor(4388341)
                        .setDescription(`[${title}](${link})\n\n${text}`)
                        .setURL(`https://reddit.com/${subRedditName}`)

                    message.channel.send(textembed)
                }

                var image = index.preview.images[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(subRedditName)
                        .setColor(4388341)
                        .setDescription(`[${title}](${link})\n\n${text}`)
                        .setURL(`https://reddit.com/${subRedditName}`)

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

这是因为您设置了一个硬编码数字 ( 99 ) 来从 response.data.children 数组中获取随机元素。我刚刚检查了该数组的长度,它是 26。如果您的随机数大于该值(并且您生成的是 1 到 100 之间的随机数), response.data.children[randomNumber] 将为 undefined

尝试使用数组的长度作为最大数字,这样它就永远不会超过元素的数量:

let index =
  response.data.children[
    Math.floor(Math.random() * response.data.children.length)
  ].data;

完整代码:

module.exports = {
  name: 'meme',
  description: 'sends meme',
  execute(message, args) {
    https.get(url, (result) => {
      let body = '';

      result.on('data', (chunk) => {
        body += chunk;
      });

      result
        .on('end', () => {
          const response = JSON.parse(body);
          const index =
            response.data.children[
              Math.floor(Math.random() * response.data.children.length)
            ].data;

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

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

            message.channel.send(textembed);
          }

          const imageembed = new Discord.MessageEmbed()
            .setTitle(subRedditName)
            .setImage(image)
            .setColor(4388341)
            .setDescription(`[${title}](${link})`)
            .setURL(`https://reddit.com/${subRedditName}`);

          message.channel.send(imageembed);
        })
        .on('error', function (e) {
          console.log('Got an error: ', e);
        });
    });
  },
};
Zsolt Meszaros
2021-02-22