2024-08-25 18:04:34 +03:00
|
|
|
import yaml
|
|
|
|
import requests
|
|
|
|
|
|
|
|
import json
|
|
|
|
import re
|
|
|
|
|
2024-12-21 23:32:25 +03:00
|
|
|
from datetime import datetime
|
|
|
|
from http import HTTPStatus
|
|
|
|
|
2024-08-25 18:04:34 +03:00
|
|
|
from decimal import Decimal, ROUND_DOWN
|
2024-11-28 21:50:03 +03:00
|
|
|
from utils.format_number import format_number
|
2024-08-25 18:04:34 +03:00
|
|
|
|
|
|
|
config = yaml.safe_load(open('config.yaml'))
|
|
|
|
|
|
|
|
coinapi_len = len(config['coinapi_keys'])
|
|
|
|
coinapi_active = [0]
|
|
|
|
|
|
|
|
|
|
|
|
class Converter:
|
|
|
|
def __init__(self):
|
|
|
|
self.amount: float = 1.0
|
|
|
|
self.conv_amount: float = 0.0
|
|
|
|
self.from_currency: str = ''
|
|
|
|
self.conv_currency: str = ''
|
|
|
|
|
|
|
|
def convert(self) -> None:
|
2024-12-21 23:32:25 +03:00
|
|
|
if not self.kekkai():
|
|
|
|
self.kekkai()
|
2024-08-25 18:04:34 +03:00
|
|
|
|
|
|
|
number = Decimal(str(self.conv_amount))
|
|
|
|
|
|
|
|
self.conv_amount = format_number(number.quantize(Decimal('1.00'), rounding=ROUND_DOWN))
|
|
|
|
|
2024-12-21 23:32:25 +03:00
|
|
|
def ddg(self) -> None:
|
2024-08-25 18:04:34 +03:00
|
|
|
res = requests.get('https://duckduckgo.com/js/spice/currency'
|
|
|
|
f'/{self.amount}'
|
|
|
|
f'/{self.from_currency}'
|
|
|
|
f'/{self.conv_currency}')
|
|
|
|
|
|
|
|
data = json.loads(re.findall(r'\(\s*(.*)\s*\);$', res.text)[0])
|
|
|
|
|
|
|
|
del data['terms']
|
|
|
|
del data['privacy']
|
|
|
|
del data['timestamp']
|
|
|
|
|
|
|
|
if len(data.get('to')) == 0:
|
2024-12-21 23:32:25 +03:00
|
|
|
raise RuntimeError('Failed to get the exchange rate from DDG')
|
2024-08-25 18:04:34 +03:00
|
|
|
|
|
|
|
conv = data.get('to')[0]
|
|
|
|
conv_amount = conv.get('mid')
|
|
|
|
|
|
|
|
if conv_amount is None:
|
2024-08-25 20:01:43 +03:00
|
|
|
raise RuntimeError('Error when converting currency via DuckDuckGo')
|
2024-08-25 18:04:34 +03:00
|
|
|
|
|
|
|
self.conv_amount = float(conv_amount)
|
|
|
|
|
2024-12-21 23:32:25 +03:00
|
|
|
def kekkai(self) -> bool:
|
|
|
|
date = datetime.today().strftime('%Y-%m-%d')
|
2024-08-25 18:04:34 +03:00
|
|
|
|
2024-12-21 23:32:25 +03:00
|
|
|
res = requests.get(f'{config['kekkai_instance']}/api/getRate/', {
|
|
|
|
'from_currency': self.from_currency,
|
|
|
|
'conv_currency': self.conv_currency,
|
|
|
|
'date': date
|
|
|
|
}, timeout=3)
|
2024-08-25 18:04:34 +03:00
|
|
|
|
2024-12-21 23:32:25 +03:00
|
|
|
data = res.json()
|
2024-08-25 18:04:34 +03:00
|
|
|
|
2024-12-21 23:32:25 +03:00
|
|
|
if not HTTPStatus(res.status_code).is_success:
|
|
|
|
return None
|
2024-08-25 18:04:34 +03:00
|
|
|
|
2024-12-21 23:32:25 +03:00
|
|
|
self.conv_amount = float(data.get('rate') * self.amount)
|
2024-08-25 18:04:34 +03:00
|
|
|
|
2024-12-21 23:32:25 +03:00
|
|
|
return True
|
2024-08-25 18:04:34 +03:00
|
|
|
|
|
|
|
|