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/otouto/plugins/xkcd.lua

59 lines
1.5 KiB
Lua
Raw Normal View History

local xkcd = {}
local HTTP = require('socket.http')
local JSON = require('dkjson')
2016-06-07 06:31:34 +02:00
local utilities = require('otouto.utilities')
xkcd.command = 'xkcd [i]'
function xkcd:init(config)
xkcd.triggers = utilities.triggers(self.info.username, config.cmd_pat):t('xkcd', true).table
xkcd.doc = [[```
]]..config.cmd_pat..[[xkcd [i]
Returns the latest xkcd strip and its alt text. If a number is given, returns that number strip. If "r" is passed in place of a number, returns a random strip.
```]]
end
2015-07-03 00:15:52 +02:00
2016-05-27 02:26:30 +02:00
function xkcd:action(msg, config)
local jstr, res = HTTP.request('http://xkcd.com/info.0.json')
2015-07-03 00:15:52 +02:00
if res ~= 200 then
2016-05-27 02:26:30 +02:00
utilities.send_reply(self, msg, config.errors.connection)
return
2015-07-03 00:15:52 +02:00
end
local latest = JSON.decode(jstr).num
local strip_num = latest
2015-07-03 00:15:52 +02:00
local input = utilities.input(msg.text)
2015-07-03 00:15:52 +02:00
if input then
if input == '404' then
utilities.send_message(self, msg.chat.id, '*404*\nNot found.', false, nil, true)
return
elseif tonumber(input) then
if tonumber(input) > latest then
strip_num = latest
else
strip_num = input
end
elseif input == 'r' then
strip_num = math.random(latest)
end
2015-07-03 00:15:52 +02:00
end
local res_url = 'http://xkcd.com/' .. strip_num .. '/info.0.json'
jstr, res = HTTP.request(res_url)
2015-07-03 00:15:52 +02:00
if res ~= 200 then
2016-05-27 02:26:30 +02:00
utilities.send_reply(self, 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.safe_title .. ' (*[' .. jdat.num .. '](' .. jdat.img .. ')*)*\n_' .. jdat.alt:gsub('_', '\\_') .. '_'
utilities.send_message(self, msg.chat.id, output, false, nil, true)
2015-07-03 00:15:52 +02:00
end
return xkcd