Skip to content
This repository has been archived by the owner on Jun 8, 2023. It is now read-only.

Commit

Permalink
Merge pull request #300 from artfuldodger/master
Browse files Browse the repository at this point in the history
Handle 403 response from reddit
  • Loading branch information
tombell committed Feb 16, 2012
2 parents 13c2f78 + f4cba00 commit a5149ea
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
46 changes: 46 additions & 0 deletions src/scripts/reddit-random-top.coffee
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# a reddit <subreddit> - A random top (today) post from the specified subreddit. Tries to find a picture if possible.
module.exports = (robot) ->
robot.respond /a reddit( .+)*/i, (msg) ->
reddit msg, msg.match[1]?.trim()

reddit = (msg, subreddit) ->
url = if subreddit? then "http://www.reddit.com/r/#{subreddit}/top.json" else "http://www.reddit.com/top.json"
msg
.http(url)
.get() (err, res, body) ->

# Sometimes when a subreddit doesn't exist, it wants to redirect you to the search page.
# Oh, and it doesn't send back 302s as JSON
if body?.match(/^302/)?[0] == '302'
msg.send "That subreddit does not seem to exist."
return

posts = JSON.parse(body)

# If the response has an error attribute, let's get out of here.
if posts.error?
msg.send "That doesn't seem to be a valid subreddit. [http response #{posts.error}]"
return

unless posts.data?.children? && posts.data.children.length > 0
msg.send "While that subreddit exists, there does not seem to be anything there."
return

post = getPost(posts)

tries_to_find_picture = 0

while post?.domain != "i.imgur.com" && tries_to_find_picture < 30
post = getPost(posts)
tries_to_find_picture++

# Send pictures with the url on one line so Campfire displays it as an image
if post.domain == 'i.imgur.com'
msg.send "#{post.title} - http://www.reddit.com#{post.permalink}"
msg.send post.url
else
msg.send "#{post.title} - #{post.url} - http://www.reddit.com#{post.permalink}"

getPost = (posts) ->
random = Math.round(Math.random() * posts.data.children.length)
posts.data.children[random]?.data
5 changes: 3 additions & 2 deletions src/scripts/reddit.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ module.exports = (robot)->
location = lookup_site + reddit

message.http( location ).get() (error, response, body)->
return response_handler "Sorry, something went wrong" if error
return response_handler "Reddit doesn't know what you're talking about" if response.statusCode == 404
return response_handler "Sorry, something went wrong" if error
return response_handler "Reddit doesn't know what you're talking about" if response.statusCode == 404
return response_handler "Reddit doesn't want anyone to go there any more." if response.statusCode == 403

list = JSON.parse( body ).data.children
count = 0
Expand Down

0 comments on commit a5149ea

Please sign in to comment.