简体   繁体   中英

TypeError: undefined is not a function in discord.js

I keep having this error and it always keeps referring to 14:19 (the [list] part):

TypeError: undefined is not a function

Here's my meme command:

const got = require('got');
const Discord  = require('discord.js');

module.exports = {
    name: "meme",
    description: "Shows a random meme.",
    async execute(message, args) {
        const subReddits = ["memes", "dankmemes", "comedyheaven", "historymemes", "Fauxcyrillic"];
        const random = subReddits[Math.floor(Math.random() * subReddits.length)];

        const embed = new Discord.MessageEmbed();
        got(`https://www.reddit.com/r/${random}/random/.json`)
        .then(response => {
            const [list] = JSON.parse(response.body);
            const [post] = list.data.children;

            const permalink = post.data.permalink;
            const memeUrl = `https://reddit.com${permalink}`;
            const memeImage = post.data.url;
            const memeTitle = post.data.title;
            const memeUpvotes = post.data.ups;
            const memeNumComments = post.data.num_comments;

            embed.setTitle(`${memeTitle}`);
            embed.setURL(`${memeUrl}`);
            embed.setColor(26763);
            embed.setImage(memeImage);
            embed.setFooter(`👍 ${memeUpvotes} 💬 ${memeNumComments}`);

            message.channel.send(embed);
        })
        .catch(console.error);
    },
};

The problem is that the returned value is not always an array, sometimes it's a single object. When it's not an array, you cant destructure list ( const [list] =... ). You need to check if the response.body is an array. If it's an array, grab the first element, otherwise leave it as is. Check the update code below:

const embed = new MessageEmbed();
const subReddits = [
  'memes',
  'dankmemes',
  'comedyheaven',
  'historymemes',
  'Fauxcyrillic',
];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];

try {
  const response = await got(`https://www.reddit.com/r/${random}/random/.json`);
  const body = JSON.parse(response.body);
  const posts = Array.isArray(body) ? body[0] : body;
  const post = posts.data.children[0].data;

  const memeUrl = `https://reddit.com${post.permalink}`;
  const memeImage = post.url;
  const memeTitle = post.title;
  const memeUpvotes = post.ups;
  const memeNumComments = post.num_comments;

  embed.setTitle(`${memeTitle}`);
  embed.setURL(`${memeUrl}`);
  embed.setColor(26763);
  embed.setImage(memeImage);
  embed.setFooter(`👍 ${memeUpvotes} 💬 ${memeNumComments}`);

  message.channel.send(embed);
} catch (err) {
  console.log(err);
}

I used async/await to get the response as you've already got an async execute method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM