iShotaBot/defs/exchange.py

66 lines
2.0 KiB
Python
Raw Normal View History

2022-10-02 15:14:06 +00:00
from init import request
class Exchange:
2023-01-12 13:19:54 +00:00
API = (
"https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies.json"
)
2022-10-02 15:14:06 +00:00
def __init__(self):
self.inited = False
self.data = {}
self.currencies = []
async def refresh(self):
try:
req = await request.get(self.API)
data = req.json()
self.currencies.clear()
for key in list(enumerate(data)):
self.currencies.append(key[1].upper())
self.currencies.sort()
self.inited = True
except Exception:
pass
async def check_ex(self, message):
tlist = message.text.split()
if not 2 < len(tlist) < 5:
2023-01-12 13:19:54 +00:00
return "help"
2022-10-02 15:14:06 +00:00
elif len(tlist) == 3:
num = 1.0
FROM = tlist[1].upper().strip()
TO = tlist[2].upper().strip()
else:
try:
num = float(tlist[1])
if len(str(int(num))) > 10:
2023-01-12 13:19:54 +00:00
return "ValueBig"
2022-10-02 15:14:06 +00:00
if len(str(num)) > 15:
2023-01-12 13:19:54 +00:00
return "ValueSmall"
2022-10-02 15:14:06 +00:00
except ValueError:
2023-01-12 13:19:54 +00:00
return "ValueError"
2022-10-02 15:14:06 +00:00
FROM = tlist[2].upper().strip()
TO = tlist[3].upper().strip()
if self.currencies.count(FROM) == 0:
2023-01-12 13:19:54 +00:00
return "FromError"
2022-10-02 15:14:06 +00:00
if self.currencies.count(TO) == 0:
2023-01-12 13:19:54 +00:00
return "ToError"
endpoint = (
f"https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/"
f"{FROM.lower()}/{TO.lower()}.json"
)
2022-10-02 15:14:06 +00:00
try:
req = await request.get(endpoint)
rate_data = req.json()
2023-01-12 13:19:54 +00:00
return (
f"{num} {FROM} = <b>{round(num * rate_data[TO.lower()], 2)} {TO}</b>\n"
f"Rate: <b>{round(1.0 * rate_data[TO.lower()], 6)}</b>"
)
2022-10-02 15:14:06 +00:00
except Exception as e:
print(e)
2023-01-12 13:19:54 +00:00
return "请求 API 发送错误。"
2022-10-02 15:14:06 +00:00
exchange_client = Exchange()