(REDDIT)尝试通过API订阅subreddits时出错

时间:2014-10-07 19:23:23

标签: ruby reddit

我知道Snoo似乎没有维护,但我想使用ruby框架,因为我试图提高我的Ruby技能。

我尝试添加一些功能,从订阅和取消订阅subreddits开始。 Link to API doc.

我的第一次尝试是使用内置的post方法返回404错误

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

由于内置post方法给了我404,我决定尝试HTTParty post方法:

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

返回:

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

有没有人知道我是否需要在正文中传递更多信息,或者我是否只是发送了一个格式错误的请求?谢谢!

此外,在运行之前" reddit.subscribe"我已经确认我已使用Cookie,modhash登录,可以访问我的帐户信息等。

1 个答案:

答案 0 :(得分:2)

找到解决方案:

def subscribe(subreddit)
  #query the subreddit for it's '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

Reddit API不接受subreddit名称作为传递给' sr'的值(例如sr:' / r / funny')。它需要subreddit" type" (对于subreddits总是' t5')和唯一的论坛ID。传递的参数类似于:sr:" t5_2qo4s"。如果您转到目标subreddit并添加about.json,则可以获得此信息,例如www.reddit.com/r/funny/about.json

相关问题