1
+ # a reddit <subreddit> - A random top (today) post from the specified subreddit. Tries to find a picture if possible.
2
+ module .exports = (robot ) ->
3
+ robot .respond / a reddit( . + )* / i , (msg ) ->
4
+ reddit msg, msg .match [1 ]? .trim ()
5
+
6
+ reddit = (msg , subreddit ) ->
7
+ url = if subreddit? then " http://www.reddit.com/r/#{ subreddit} /top.json" else " http://www.reddit.com/top.json"
8
+ msg
9
+ .http (url)
10
+ .get () (err , res , body ) ->
11
+
12
+ # Sometimes when a subreddit doesn't exist, it wants to redirect you to the search page.
13
+ # Oh, and it doesn't send back 302s as JSON
14
+ if body ? .match (/ ^ 302/ )? [0 ] == ' 302'
15
+ msg .send " That subreddit does not seem to exist."
16
+ return
17
+
18
+ posts = JSON .parse (body)
19
+
20
+ # If the response has an error attribute, let's get out of here.
21
+ if posts .error ?
22
+ msg .send " That doesn't seem to be a valid subreddit. [http response #{ posts .error } ]"
23
+ return
24
+
25
+ unless posts .data ? .children ? && posts .data .children .length > 0
26
+ msg .send " While that subreddit exists, there does not seem to be anything there."
27
+ return
28
+
29
+ post = getPost (posts)
30
+
31
+ tries_to_find_picture = 0
32
+
33
+ while post ? .domain != " i.imgur.com" && tries_to_find_picture < 30
34
+ post = getPost (posts)
35
+ tries_to_find_picture++
36
+
37
+ # Send pictures with the url on one line so Campfire displays it as an image
38
+ if post .domain == ' i.imgur.com'
39
+ msg .send " #{ post .title } - http://www.reddit.com#{ post .permalink } "
40
+ msg .send post .url
41
+ else
42
+ msg .send " #{ post .title } - #{ post .url } - http://www.reddit.com#{ post .permalink } "
43
+
44
+ getPost = (posts ) ->
45
+ random = Math .round (Math .random () * posts .data .children .length )
46
+ posts .data .children [random]? .data
0 commit comments