/
reddit.ex
40 lines (35 loc) · 921 Bytes
/
reddit.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
defmodule Alice.Handlers.Reddit do
@moduledoc """
Alice does Reddit
"""
use Alice.Router
route ~r<\breddit me (/?r/)?(.*)\z>, :random_image_from_subreddit
command ~r<\breddit( me)? (/?r/)?(.*)\z>, :random_image_from_subreddit
@doc "`reddit me ____` - gets a random image from your specified subreddit"
def random_image_from_subreddit(conn) do
conn
|> get_term
|> get_post
|> build_reply
|> reply(conn)
end
defp get_term(conn) do
conn
|> Alice.Conn.last_capture
|> String.downcase
|> String.replace(~r/[_\s]+/, "")
|> String.strip
end
defp get_post(name) do
name
|> Sub.new
|> Sub.recent_images
|> Enum.random
end
defp build_reply(post) do
["> *#{post.title} • /r/#{post.subreddit}*",
"> #{post.score} points and #{post.num_comments} comments so far on reddit",
"> #{post.url}"]
|> Enum.join("\n")
end
end