comp-tg/src/cmds/rub.lua

71 lines
1.9 KiB
Lua
Raw Normal View History

2021-07-20 06:56:14 +00:00
-- It uses data from central bank of Russia
--- and external service to get json from xml
-- Privacy and security is unknown
local rub = {
2021-04-14 06:03:25 +00:00
url = 'https://api.factmaven.com/xml-to-json/?xml='
.. 'https://www.cbr.ru/scripts/XML_daily.asp',
2021-07-26 13:12:03 +00:00
tools = require 'etc.api.tools',
2021-04-14 06:03:25 +00:00
}
2021-07-26 13:12:03 +00:00
function rub:course(wants)
local resp, succ = self.tools._req(self.url, 'GET')
2021-07-26 13:12:03 +00:00
if not succ then return 'err' end
resp = self.tools.json.decode(resp or '{}')
2021-04-14 06:03:25 +00:00
resp = resp.ValCurs
2021-07-26 13:12:03 +00:00
table.insert(resp.Valute, {
ID = 'R01000',
NumCode = '001',
CharCode = 'RUB',
Nominal = 1,
Name = 'Российский рубль',
Value = '1'
})
2022-02-13 11:06:46 +00:00
local uah = table.findV(resp.Valute, {CharCode = 'UAH'})
table.insert(resp.Valute, {
ID = 'R02000',
NumCode = '200',
CharCode = 'SHT',
Nominal = 1,
Name = 'Штаны',
Value = ('%f'):format(tonumber(uah.Value:gsub(',', '.'), nil) / uah.Nominal * 40)
})
2021-04-14 06:03:25 +00:00
wants = type(wants) == 'table' and wants or {}
local r, founds = {}, {}
2021-07-26 13:12:03 +00:00
2021-04-14 06:03:25 +00:00
for i = 1, #resp.Valute do
local v = resp.Valute[i]
if table.find(wants, v.CharCode) then
table.insert(founds, v.CharCode)
2021-07-26 13:12:03 +00:00
table.insert(r, ('%d %s (%s) - %f ₽'):format(v.Nominal, v.Name, v.CharCode, v.Value:gsub(',', '.')))
2021-04-14 06:03:25 +00:00
end
end
return r, resp.Date, founds
end
2021-07-26 13:12:03 +00:00
return {
run = function(C, msg)
local wants = {'USD', 'EUR', table.unpack(msg.args)}
for i = 1, #wants do wants[i] = wants[i]:upper() end -- uppercase
2021-04-14 06:03:25 +00:00
2021-07-26 13:12:03 +00:00
local v, d, f = rub:course(wants)
if v == 'error' then
2021-07-27 08:15:28 +00:00
return C.api:reply(msg, C.locale:get('error', 'req_err', msg.l))
2021-04-14 06:03:25 +00:00
end
2021-07-26 13:12:03 +00:00
local nf = {}
for _, i in pairs(wants) do
if not table.find(f, i) then table.insert(nf, i) end
end
2021-04-14 06:03:25 +00:00
2021-07-26 13:12:03 +00:00
local s = msg.loc.cur:format(d, table.concat(v, '\n'))
if #nf > 0 then s = s .. msg.loc.notf .. table.concat(nf, ',') end
2021-04-14 06:03:25 +00:00
2021-07-26 13:12:03 +00:00
C.api:reply(msg, s .. msg.loc.prov)
end
2021-07-19 07:55:01 +00:00
}