27 lines
853 B
Crystal
27 lines
853 B
Crystal
require "http/client"
|
|
require "json"
|
|
|
|
def get_reddit_json(subreddit)
|
|
request_url = "https://www.reddit.com/r/#{subreddit}/hot.json?limit=30"
|
|
response = HTTP::Client.get(request_url, headers: HTTP::Headers {
|
|
"User-agent" => "Joann-Pupper-Bot"
|
|
})
|
|
response.body?.try { |body| JSON.parse(body) }
|
|
end
|
|
|
|
def filter_reddit_json(json, completed)
|
|
json["data"]["children"]
|
|
.map(&.["data"])
|
|
.select do |it|
|
|
url = it["url"].as_s
|
|
name = it["name"].as_s
|
|
!completed.includes?(name) && (url.ends_with?(".png") || url.ends_with?(".jpg"))
|
|
end
|
|
end
|
|
|
|
def get_reddit_post(subreddit, completed)
|
|
json = get_reddit_json(subreddit)
|
|
post = json.try { |json| filter_reddit_json(json, completed).first? }
|
|
post.try { |post| completed.push(post["name"].as_s); post["url"].as_s }
|
|
end
|