2022-10-02 15:14:06 +00:00
|
|
|
from init import request
|
|
|
|
|
|
|
|
|
|
|
|
class Exchange:
|
2024-07-17 12:16:19 +00:00
|
|
|
API = "https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/"
|
2022-10-02 15:14:06 +00:00
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self.inited = False
|
|
|
|
self.data = {}
|
|
|
|
self.currencies = []
|
|
|
|
|
|
|
|
async def refresh(self):
|
|
|
|
try:
|
2024-03-02 12:18:09 +00:00
|
|
|
req = await request.get(self.API + "currencies.json")
|
2022-10-02 15:14:06 +00:00
|
|
|
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
|
|
|
|
|
2024-11-26 14:04:09 +00:00
|
|
|
async def check_ex(self, text: str):
|
|
|
|
tlist = text.split()
|
2022-10-02 15:14:06 +00:00
|
|
|
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"
|
2024-03-02 12:18:09 +00:00
|
|
|
endpoint = self.API + f"currencies/{FROM.lower()}.json"
|
2022-10-02 15:14:06 +00:00
|
|
|
try:
|
|
|
|
req = await request.get(endpoint)
|
|
|
|
rate_data = req.json()
|
2024-03-02 12:18:09 +00:00
|
|
|
rate = rate_data[FROM.lower()][TO.lower()]
|
2023-01-12 13:19:54 +00:00
|
|
|
return (
|
2024-03-02 12:18:09 +00:00
|
|
|
f"{num} {FROM} = <b>{round(num * rate, 2)} {TO}</b>\n"
|
|
|
|
f"Rate: <b>{round(1.0 * rate, 6)}</b>"
|
2023-01-12 13:19:54 +00:00
|
|
|
)
|
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()
|