Search code examples
javascriptdiscord.jsreddit

Discord.js Display Reddit Post's Title


I have this code that gets a random post from the top of r/memes and I want it to display the random post's title that it picked.

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

Solution

  • 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);