【问题标题】:How do I get if a subreddit that the bot is trying to fetch doesn't exist?如果机器人试图获取的 subreddit 不存在,我该如何获取?
【发布时间】:2020-12-24 08:09:09
【问题描述】:

我在这个社区的帮助下收集了一些代码,如果机器人因为不存在而无法从 subreddit 发送随机帖子,我不知道如何获取?这是代码:

if (msg.content.startsWith('-reddit ')) {
 const subname = msg.content.slice(8);
 const mxlenght = 30;
 if (subname.length >= mxlenght) {
  msg.reply('Ez a subreddit név meghaladja a 30 karakteres maximumot.');
 } else {
  function loadMemes() {
   // Fetch JSON
   return (
    fetch(
     'https://www.reddit.com/r/' + subname + '.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
     const embed = new Discord.RichEmbed({
      title,
      image: { url },
      footer: { text: 'Subreddit : r/' + subname },
     });
     // Send the embed
     return message.channel.send(embed);
    })
    .catch(console.error);
  }

  // Usage:
  postRandomMeme(msg).catch(console.error);
 }
}

【问题讨论】:

    标签: javascript node.js discord discord.js


    【解决方案1】:

    经过一番研究,我认为问题出在URL。首先,您正在从www.reddit.com 获取数据,此时您应该查看api.reddit.com。其次,subreddit 名称后面需要有一个斜杠。

    这是完成后的URL 的样子:

    `https://api.reddit.com/r/${subname}/.json?limit=800&?sort=hot&t=all`
    

    【讨论】:

    • 它可以正常工作并且发送它没有问题,我的问题是我想这样做,以便如果用户使用 -reddit(子名称)请求的 subreddit 不存在,它会回复与“那不存在”或类似内容的聊天。
    猜你喜欢
    • 2018-09-27
    • 2019-03-11
    • 2017-09-24
    • 2020-12-12
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    相关资源
    最近更新 更多