fix: exchange api

This commit is contained in:
xtaodada 2024-03-02 20:18:09 +08:00
parent a89c56f6a9
commit 58379c3493
Signed by: xtaodada
GPG Key ID: 4CBB3F4FA8C85659

View File

@ -3,7 +3,7 @@ from init import request
class Exchange: class Exchange:
API = ( API = (
"https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies.json" "https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/"
) )
def __init__(self): def __init__(self):
@ -13,7 +13,7 @@ class Exchange:
async def refresh(self): async def refresh(self):
try: try:
req = await request.get(self.API) req = await request.get(self.API + "currencies.json")
data = req.json() data = req.json()
self.currencies.clear() self.currencies.clear()
for key in list(enumerate(data)): for key in list(enumerate(data)):
@ -46,16 +46,14 @@ class Exchange:
return "FromError" return "FromError"
if self.currencies.count(TO) == 0: if self.currencies.count(TO) == 0:
return "ToError" return "ToError"
endpoint = ( endpoint = self.API + f"currencies/{FROM.lower()}.json"
f"https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/"
f"{FROM.lower()}/{TO.lower()}.json"
)
try: try:
req = await request.get(endpoint) req = await request.get(endpoint)
rate_data = req.json() rate_data = req.json()
rate = rate_data[FROM.lower()][TO.lower()]
return ( return (
f"{num} {FROM} = <b>{round(num * rate_data[TO.lower()], 2)} {TO}</b>\n" f"{num} {FROM} = <b>{round(num * rate, 2)} {TO}</b>\n"
f"Rate: <b>{round(1.0 * rate_data[TO.lower()], 6)}</b>" f"Rate: <b>{round(1.0 * rate, 6)}</b>"
) )
except Exception as e: except Exception as e:
print(e) print(e)