diff --git a/bot.js b/bot.js index 277d6b4..28f3509 100644 --- a/bot.js +++ b/bot.js @@ -101,7 +101,7 @@ function noQuestion() { // 3. RedditBooru function bestEffortRequest(subpage, page_max) { - let reddit_response = asyncRedditRequest(subpage); + let reddit_response = asyncSiteRequest("https://www.reddit.com/r/" + subpage + "/.json?show=all&count=25&limit=100", handleRedditJson); if(reddit_response) { return reddit_response; } let imgur_response; @@ -147,22 +147,23 @@ function imgurRequest(subreddit, page_max) { return returnText; } -// Dalton async reddit? -function asyncRedditRequest(requested_item) { +// Abstracted Reddit Json media grab. +function handleRedditJson(data) { + let json = data.json(); + for(i = 0; i < json.data.children.length; i++) { + let rand = getRandomInt(0, json.data.children.length - 1); - let url= "https://www.reddit.com/r/" + requested_item + "/.json?show=all&count=25&limit=100"; + if (json.data.children[rand].data.post_hint === "image" || json.data.children[rand].data.post_hint === "link" || json.data.children.data.post_hint === "rich:video") { + return json.data.children[rand].data.url; + } + } +} + +// Makes an async url request with the provided function: 'process'. +function asyncSiteRequest(url, process) { fetch(url) - .then(data => { - let json = data.json(); - for(i = 0; i < json.data.children.length; i++) { - let rand = getRandomInt(0, json.data.children.length - 1); - - if (json.data.children[rand].data.post_hint === "image" || json.data.children[rand].data.post_hint === "link" || json.data.children.data.post_hint === "rich:video") { - return json.data.children[rand].data.url; - } - } - }) + .then(data => {return process(data);}) .catch(error => { client.channels.get('357365312620068874').send(error.message); return ""; })