postprefix
5/27/2016 - 11:19 AM

reddit_comments.rb

# Dump comments user has made on reddit to a file
# Usage: ./reddit_comments.rb User [Filename]

#!/usr/bin/env ruby
User = ARGV[0]
OutputFile = ARGV[1] || "#{User}.json"

require "rubygems"
require "json"
require "open-uri"

def parse_page(url)
  puts url
  JSON.parse(open(url).read)["data"]["children"].map{|x| x["data"]}
end

BaseUrl = "http://reddit.com/user/#{User}/comments/.json"

@page = parse_page(BaseUrl)

@comments = @page 

while !@page.empty?
  @page = parse_page(BaseUrl + "?after=#{@comments.last["name"]}")
  @comments += @page
end

File.open(OutputFile, "w"){|o| o.puts JSON.pretty_generate(@comments)}