comp-tg/src/cmds/rub.lua

92 lines
2.2 KiB
Lua

class 'Rub' {
url = 'https://api.factmaven.com/xml-to-json/?xml=https://www.cbr.ru/scripts/XML_daily.asp',
pat = '%d %s (%s) - %f ₽',
function(this)
this.tools = require 'api.tools'
end,
getPat = function(this, val)
return this.pat:format(val.Nominal, val.Name, val.CharCode, val.Value:gsub(',', '.'))
end,
course = function(this, wants)
local res, ok = this.tools._req(this.url, 'GET')
if not ok
then return 'err'
end
res = this.tools.json.decode(res or '{}')
res = res.ValCurs
if not res
then return 'err'
end
-- Pseudo-valutes
table.insert(res.Valute, {
ID = 'R01000',
NumCode = '001',
CharCode = 'RUB',
Nominal = 1,
Name = 'Российский рубль',
Value = '1',
})
local uah = table.findV(res.Valute, {CharCode = 'UAH'})
assert(uah, 'No UAH found')
table.insert(res.Valute, {
ID = 'R02000',
NumCode = '200',
CharCode = 'SHT',
Nominal = 1,
Name = 'Штаны',
Value = ('%f'):format(tonumber(uah.Value:gsub(',', '.'), nil) / uah.Nominal * 40), -- 40 UAH
})
local r, founds = {}, {}
if table.find(wants, 'ALL') then
for _, v in pairs(res.Valute)
do table.insert(r, this:getPat(v))
end
return r, res.Date, wants -- string, date, found
end
for _, v in pairs(res.Valute) do
if table.find(wants, v.CharCode) then
table.insert(founds, v.CharCode)
table.insert(r, this:getPat(v))
end
end
return r, res.Date, founds --
end,
}
local rub = new 'Rub' ()
return {
run = function(self, msg)
local wants = {
'USD',
'EUR',
table.unpack(msg.args)
}
for i = 1, #wants do
wants[i] = wants[i]:upper()
end
local v, d, f = rub:course(wants)
if v == 'err' then
return self.api:reply(msg, self.locale:get('error', 'req_err', msg.l))
end
local nf = { }
for _, i in pairs(wants) do
if not table.find(f, i) then
table.insert(nf, i)
end
end
local s = msg.loc.cur:format(d, table.concat(v, '\n'))
if #nf > 0 then
s = s .. msg.loc.notf .. table.concat(nf, ',')
end
self.api:reply(msg, s .. msg.loc.prov)
end
}