#!/usr/bin/env ruby # frozen_string_literal: true require 'webrick' require 'redd' require 'pry' # The REPL session to initialize Pry in. module Reddit class << self attr_accessor :reddit end end server = WEBrick::HTTPServer.new( Port: 8000, BindAddress: '0.0.0.0', Logger: WEBrick::Log.new(File.open(File::NULL, 'w')), AccessLog: [] ) server.mount_proc '/' do |_, res| res.body = <<-EOS Redd Quickstart

redd // quickstart

Start a new session in your terminal?
EOS end server.mount_proc '/authenticate' do |_, res| res.set_redirect( WEBrick::HTTPStatus[302], Redd.url( client_id: 'P4txR-D6TzF8cg', response_type: 'code', state: '0', redirect_uri: 'http://localhost:8000/redirect', duration: 'permanent', scope: %w(account creddits edit flair history identity livemanage modconfig modcontributors modflair modlog modmail modothers modposts modself modwiki mysubreddits privatemessages read report save submit subscribe vote wikiedit wikiread) ) ) end server.mount_proc '/redirect' do |req, res| err = req.query['error'] should_exit = err.nil? || err == 'access_denied' res.body = <<-EOS Done! #{should_exit ? '' : "

Uh oh, there was an error: #{err}

"} EOS unless err Reddit.reddit = Redd.it( user_agent: "Ruby:Redd-Quickstart:v#{Redd::VERSION} (by unknown)", client_id: 'P4txR-D6TzF8cg', redirect_uri: 'http://localhost:8000/redirect', code: req.query['code'], auto_refresh: true ) server.stop end end # Get the server going and shut it all down if user hits Ctrl-C begin puts "Listening at \e[34mhttp://localhost:8000\e[0m..." server.start rescue Interrupt server.shutdown exit end Reddit.instance_exec do # Post a colourful welcome message suggestions = [ # Session#me 'reddit.me.link_karma', # Subreddit listings "reddit.subreddit('pics').hot.first.title", # User listings 'puts reddit.me.comments(sort: :top).first.body', # Sending messages "reddit.user('Mustermind').send_message(subject: 'Hi!', text: 'How are you?')", # Subscribing to subreddits "reddit.subreddit('EarthPorn').subscribe", # Upvoting 'reddit.front_page.hot(time: :month).first.upvote', # Add friend "reddit.user('Mustermind').friend", # List friends 'reddit.friends.each { |friend| puts friend.name };', # Hiding / Duplicates 'reddit.front_page.hot.each { |l| l.hide if l.duplicates.count > 2 }' ] puts "Hi \e[35m/u/#{reddit.me.name}\e[0m! Try `\e[34m#{suggestions.sample}\e[0m`." # Load Pry Pry.start(self) end