Question

I've been trying to build a little bot which will be using Reddit's API. I can break down and read all the info I'm receiving without problem, but I haven't been able to send anything yet.

What I want to do is: Send a prepared JSON string to http://www.reddit.com/api/login and get some kind of response if I succeeded or failed.

If you need more info about Reddit's API: https://github.com/reddit/reddit/wiki/API

This is what I have so far:

require 'rubygems'
require 'httparty'
require 'json'
require 'pp'

class Login
  include HTTParty
  base_uri 'reddit.com/'
  default_params :output => 'json'
  format :json
  def post(message)
    options = {:body => JSON.generate(message)}
    self.class.post('api/login', options)
  end
end

login = Login.new()
pp login.post({'username' => 'USERNAME', 'passwd' => 'PW'})

This code gives me the following error:

/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/net/http.rb:1060:in `request': undefined method `closed?' for nil:NilClass (NoMethodError)

Even though a very similar chunk of code would post to Twitter. Also, I'm not sure if my code actually gets some kind of response from the site or not.

To me it doesn't matter if I use HTTParty or not, so if you know a much better way of doing this, feel free to share!

Thanks in advance!

Was it helpful?

Solution

You can rewrite it like this

class Login
  include HTTParty
  base_uri 'http://www.reddit.com'

  def post(username, password)
    options = {:body => {:user => username, :passwd => password, :api_type => 'json'}}
    self.class.post("/api/login/#{username}", options)
  end
end

Login.new.post('user', 'pass')

Just remember that API url for a login must be: http://www.reddit.com/api/login/USERNAME (with www) and you should pass api_type param in request.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top