-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdilbert.rb
51 lines (38 loc) · 965 Bytes
/
dilbert.rb
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
41
42
43
44
45
46
47
48
49
50
51
require 'open-uri'
require 'hpricot'
require 'tempfile'
class Dilbert < CampfireBot::Plugin
BASE_URL = 'http://dilbert.com/'
START_DATE = Date.parse('1996-01-01')
on_command 'dilbert', :dilbert
def dilbert(msg)
comic = case msg[:message].split(/\s+/)[0]
when 'latest'
fetch_latest
when 'random'
fetch_random
when /d+/
fetch_comic(msg[:message].split(/\s+/)[1])
else
fetch_random
end
msg.speak(BASE_URL + comic['src'])
end
private
def fetch_latest
fetch_comic
end
def fetch_random
fetch_comic(rand(number_of_comics))
end
def fetch_comic(id = nil)
# Rely on the comic being the last image on the page not nested
(Hpricot(open("#{BASE_URL}fast#{'/' + id_to_date(id) + '/' if id}"))/'//img').last
end
def id_to_date(id)
(START_DATE + id.days).to_date.to_s(:db)
end
def number_of_comics
(Date.today - START_DATE).to_i
end
end