-
Notifications
You must be signed in to change notification settings - Fork 1
/
xkcd.rb
45 lines (37 loc) · 1.38 KB
/
xkcd.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
require 'rest-client'
class Xkcd < AbsPlugin
def command
/^\/xkcd\s?([0-9]*?)?$/
end
def show_usage
bot.api.send_message(chat_id: message.chat.id, text: "get xkcd comics with\n/xkcd to get the last comic\n/xkcd *comic number*")
end
def examples
[
{ command: '/xkcd', description: 'return a random issue of xkcd web comic' },
{ command: '/xkcd 6', description: 'return issue number 6 of xkcd comic' }
]
end
def do_stuff(match_results)
number = match_results[1]
begin
if number.empty?
# get the last comic published number
response = RestClient.get('https://xkcd.com/info.0.json')
decoded = JSON.parse(response)
# generate random comic from 1 to the last comic published
random_comic = Random.rand(1..decoded["num"])
response = RestClient.get("https://xkcd.com/#{random_comic}/info.0.json")
else
# or get the one with specified number
response = RestClient.get("https://xkcd.com/#{number}/info.0.json")
end
decoded = JSON.parse(response)
system("wget \"#{decoded["img"]}\" -O xkcd.png")
bot.api.send_photo(chat_id: message.chat.id, photo: Faraday::UploadIO.new('xkcd.png', 'image/png'))
File.delete('xkcd.png')
rescue
bot.api.send_message(chat_id: message.chat.id, text: "xkcd comic number you entered does not exist!")
end
end
end