(REDDIT) Error trying to subscribe to subreddits via API

I know that Snoo doesn't seem to be supported, but I wanted to use the ruby ​​framework since I'm trying to improve my Ruby skill.

I am trying to add some functionality, starting with subscribing and unsubscribing to subreddits. API Document Link

My first attempt was with the built-in post method which returned a 404 error

def subscribe(subreddit)
    logged_in?
    post('/api/subscribe.json',body:{uh: @modhash, action:'sub', sr: subreddit, api_type: 'json'})
end

      

Since the built-in post method was giving me 404, I decided to try the HTTParty post method:

def subscribe(subreddit)
    logged_in?
    HTTParty.post('http://www.reddit.com/api/subscribe.json',body:{uh: @modhash, action:'sub', sr: subreddit, api_type: 'json'})
end

      

This returns this:

pry(main)> reddit.subscribe('/r/nba')
=> {"json"=>{"errors"=>[["USER_REQUIRED", "please login to do that", nil]]}}

      

Does anyone know if I need to pass more information in the body or if I'm just submitting a poorly formed request? Thank!

Also, before running "reddit.subscribe", I confirmed that I was logged in with cookie, modhash, can access my account, etc.

+3


source to share


1 answer


Solution found:

def subscribe(subreddit)
  #query the subreddit for it 'about' info and get json back
  subreddit_json = self.subreddit_info(subreddit)

  #build the coded unique identifier for the targeted subreddit
  subreddit_id = subreddit_json['kind'] + "_" + subreddit_json['data']['id']

  #send post request to server
  server_response = self.class.post('/api/subscribe.json',
    body:{uh:@modhash, action:'sub', sr: subreddit_id, api_type:'json'})
end

      



The Reddit API does not accept a subtask name as the value passed in with 'sr' (e.g. sr: '/ r / funny'). This requires a subreddit "type" (which is always "t5" for subreddits) and a unique forum ID. The passed parameter will look something like this: sr: "t5_2qo4s". This information is available if you go to your target subreddit and add about.json like www.reddit.com/r/funny/about.json

+2


source







All Articles