joann-pupper-bot/src/joann-pupper-bot/reddit.cr

48 lines
958 B
Crystal
Raw Normal View History

2018-03-20 16:31:49 -07:00
require "http/client"
require "json"
2019-04-14 14:39:38 -07:00
class RedditWrapper(T)
JSON.mapping(
kind: String,
data: T)
end
class RedditChild
JSON.mapping(
url: String,
name: String,
title: String)
end
class RedditResponse
JSON.mapping(
modhash: String,
dist: Int32,
children: Array(RedditWrapper(RedditChild)))
def self.from_subreddits(subreddits : Array(String))
request_url = URI.new scheme: "https", host: "www.reddit.com", path: "/r/#{subreddits.join "+"}/hot.json", query: "limit=30"
2018-03-20 16:31:49 -07:00
response = HTTP::Client.get(request_url, headers: HTTP::Headers {
2019-04-14 14:39:38 -07:00
"User-agent" => "Joann-Pupper-Bot"
2018-03-20 16:31:49 -07:00
})
2019-04-14 14:39:38 -07:00
return nil unless body = response.body?
begin
RedditWrapper(RedditResponse).from_json body
rescue e
2019-04-14 14:39:38 -07:00
nil
end
end
def self.from_subreddit(subreddit)
from_subreddits [subreddit]
end
def posts_matching(&block)
children
.map(&.data)
.select { |it| yield it }
end
2018-03-20 16:31:49 -07:00
end