This repository has been archived on 2021-04-24. You can view files and clone it, but cannot push or open issues or pull requests.
Mikubot-2/plugins/xkcd.lua

60 lines
1.3 KiB
Lua
Raw Normal View History

local command = 'xkcd [query]'
local doc = [[```
/xkcd [query]
Returns an xkcd strip and its alt text. If there is no query, it will be randomized.
```]]
2015-07-03 00:15:52 +02:00
local triggers = {
'^/xkcd[@'..bot.username..']*'
2015-07-03 00:15:52 +02:00
}
local action = function(msg)
local input = msg.text:input()
2015-07-03 00:15:52 +02:00
local jstr, res = HTTP.request('http://xkcd.com/info.0.json')
2015-07-03 00:15:52 +02:00
if res ~= 200 then
sendReply(msg, config.errors.connection)
return
2015-07-03 00:15:52 +02:00
end
2015-07-03 00:15:52 +02:00
local latest = JSON.decode(jstr).num
local res_url
2015-07-03 00:15:52 +02:00
if input then
local url = 'https://ajax.googleapis.com/ajax/services/search/web?v=1.0&safe=active&q=site%3axkcd%2ecom%20' .. URL.escape(input)
local jstr, res = HTTPS.request(url)
2015-07-03 00:15:52 +02:00
if res ~= 200 then
sendReply(msg, config.errors.connection)
return
2015-07-03 00:15:52 +02:00
end
local jdat = JSON.decode(jstr)
if #jdat.responseData.results == 0 then
sendReply(msg, config.errors.results)
return
end
res_url = jdat.responseData.results[1].url .. 'info.0.json'
2015-07-03 00:15:52 +02:00
else
res_url = 'http://xkcd.com/' .. math.random(latest) .. '/info.0.json'
2015-07-03 00:15:52 +02:00
end
local jstr, res = HTTP.request(res_url)
2015-07-03 00:15:52 +02:00
if res ~= 200 then
sendReply(msg, config.errors.connection)
return
2015-07-03 00:15:52 +02:00
end
local jdat = JSON.decode(jstr)
2015-07-03 00:15:52 +02:00
local output = '[' .. jdat.num .. '](' .. jdat.img .. ')\n' .. jdat.alt
sendMessage(msg.chat.id, output, false, nil, true)
2015-07-03 00:15:52 +02:00
end
return {
action = action,
triggers = triggers,
doc = doc,
command = command
}