简体   繁体   English

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

[英]TypeError: Cannot read property 'data' of undefined | discord.js

So I am making a Discord bot and I have a meme command that gets memes from r/memes, however sometimes it gives a meme and sometimes the code crashes and gives this error in console:所以我正在制作一个 Discord 机器人,我有一个从 r/memes 获取 meme 的 meme 命令,但有时它会给出 meme,有时代码会崩溃并在控制台中出现此错误:

TypeError: Cannot read property 'data' of undefined

I'm not too sure what it could be so if anyone could help me out that would help a lot.我不太确定它会是什么,所以如果有人可以帮助我,那将有很大帮助。

Here's my !meme command code:这是我的!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)
            })
        })
    },
}

It's because you're setting a hardcoded number ( 99 ) to get a random element from the response.data.children array.这是因为您设置了一个硬编码数字 ( 99 ) 以从response.data.children数组中获取一个随机元素。 I've just checked the length of that array and it was 26. If your random number will be larger than that (and there is as you're generating a random number between 1 and 100), response.data.children[randomNumber] will be undefined .我刚刚检查了该数组的长度,它是 26。如果你的随机数大于那个(并且你正在生成一个介于 1 和 100 之间的随机数), response.data.children[randomNumber]将是undefined的。

Try to use the array's length as the max number instead so it will never be more than the number of elements:尝试使用数组的长度作为最大数量,这样它就不会超过元素的数量:

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

The full code:完整代码:

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);
        });
    });
  },
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型错误:无法读取未定义 Discord.js javascript 的属性“添加” - TypeError: Cannot read property 'add' of undefined Discord.js javascript 类型错误:无法读取未定义的属性 'has' // Discord.js - TypeError: Cannot read property 'has' of undefined // Discord.js 遇到 TypeError:无法读取 Discord.JS 中未定义的属性“0” - Encountering TypeError: Cannot read property '0' of undefined in Discord.JS Discord.JS UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“startsWith” - Discord.JS UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startsWith' of undefined 类型错误:无法读取未定义的属性“角色”|| Discord.js - TypeError: Cannot read property 'roles' of undefined || Discord.js (Discord.js)TypeError:无法读取未定义的属性“添加” - (Discord.js) TypeError: Cannot read property 'add' of undefined Discord.js:类型错误:无法读取未定义的属性“删除” - Discord.js : TypeError: Cannot read property 'remove' of undefined Discord.js“类型错误:无法读取未定义的属性‘有’” - Discord.js "TypeError: Cannot read property 'has' of undefined" 类型错误:无法读取未定义的 discord.js 的属性“用户名” - TypeError: Cannot read property 'username' of undefined discord.js Discord.js | 类型错误:无法读取未定义的属性“声音” - Discord.js | TypeError: Cannot read property 'voice' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM