【问题标题】:Discord.js Display Reddit Post's TitleDiscord.js 显示 Reddit 帖子的标题
【发布时间】:2021-10-18 18:35:41
【问题描述】:

我有这段代码从 r/memes 顶部获取随机帖子,我希望它显示它选择的随机帖子的标题。

if(msg.content === '-meme')
  {
    var Channel = msg.channel.name
        if(Channel != "chill-bot-log" && Channel != "chill-shitpost") {
            msg.channel.send(msg.author + ' ezt a parancsot nem használhatod ebben a csatornában');
            console.info(msg.author + " megpróbálta loggolni a botot egy rossz csatornában.");
        } else {
    loadMemes(message);
  }
    function loadMemes() {
    fetch('https://www.reddit.com/r/memes.json?limit=800&?sort=hot&t=all')
    .then(res => res.json())
    //.then(res => console.log(res))
    .then(json => json.data.children.map(v => v.data.url))
    .then(urls => postRandomMeme(urls));
    }

    function postRandomMeme(urls) {
    const randomURL = urls[Math.floor(Math.random() * urls.length) + 1];
    const redditUrl = `https://www.reddit.com${randomURL.reddit}`;
    const embed = new Discord.RichEmbed({
    image: {
    url: randomURL
    }
    });
    embed.setFooter('Subreddit : r/memes')
    embed.setTitle(redditUrl)
    msg.channel.send(embed);
    }
  }

【问题讨论】:

  • 我知道每个人都会告诉我使用randompuppy,但我只想使用我已经拥有的这段代码。

标签: javascript discord.js reddit


【解决方案1】:
function loadMemes() {
  // Fetch JSON
  return fetch('https://www.reddit.com/r/memes.json?limit=800&?sort=hot&t=all')
    .then(res => res.json())
    // Return the actual posts
    .then(json => json.data.children);
}

function postRandomMeme(message) {
  return loadMemes().then(posts => {
    // Get a random post's title and URL
    const {title, url} = posts[Math.floor(Math.random() * posts.length)].data;
    // Create the embed
    // For Discord.js v11 replace MessageEmbed with RichEmbed
    const embed = new Discord.MessageEmbed({
      title,
      image: {url},
      footer: {text: 'Subreddit : r/memes'}
    });
    // Send the embed
    // For Discord.js v11/v12 use .send(embed)
    return message.channel.send({embeds: [embed]});
  })
}

// Usage:
postRandomMeme(msg)
  // Log all errors
  .catch(console.error);

【讨论】:

  • const {title, url} = posts[Math.floor(Math.random() * posts.length)]; ^^^^^ SyntaxError: Unexpected token 'const'
  • 我修好了,现在不行了,等我醒来再贴错误
  • 哦,是的,它不会使用 loadmemes
  • @VasDávidValentin 抱歉,忘记了{)。我已经编辑了我的答案。
  • loadMemes().then(posts => { ^ TypeError: Cannot read property 'then' of undefined
猜你喜欢
  • 1970-01-01
  • 2020-11-08
  • 2023-03-05
  • 2019-11-28
  • 2014-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多