From b7396d4634f95573f5a2f15f2de52369aa97730f Mon Sep 17 00:00:00 2001 From: Redume Date: Tue, 7 Jan 2025 13:57:48 +0300 Subject: [PATCH 1/3] fix: replace , to . --- main.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index 0b92670..4889b47 100644 --- a/main.py +++ b/main.py @@ -15,7 +15,7 @@ config = yaml.safe_load(open('config.yaml')) @dp.inline_query() async def currency(query: types.InlineQuery) -> None: - global result, from_currency, conv_currency + global from_currency, conv_currency try: text = query.query.lower() @@ -33,7 +33,7 @@ async def currency(query: types.InlineQuery) -> None: query) if len(args) == 3: - conv.amount = float(args[0]) + conv.amount = float(args[0].replace(',', '.')) from_currency = args[1] conv_currency = args[2] elif len(args) == 2: From f103970be282215a74fe8555c0826ba5a025e316 Mon Sep 17 00:00:00 2001 From: Redume Date: Tue, 7 Jan 2025 13:58:08 +0300 Subject: [PATCH 2/3] chore: add print in execpt --- function/get_chart.py | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/function/get_chart.py b/function/get_chart.py index a29a36e..5c24938 100644 --- a/function/get_chart.py +++ b/function/get_chart.py @@ -1,22 +1,27 @@ -from http import HTTPStatus - import yaml import requests -from urllib3 import HTTPSConnectionPool +from http import HTTPStatus config = yaml.safe_load(open('config.yaml')) def get_chart(from_currency: str, conv_currency: str) -> (dict, None): try: - res = requests.get(f'{config['kekkai_instance']}/api/getChart/week/', { - 'from_currency': from_currency, - 'conv_currency': conv_currency - }, timeout=3) + response = requests.get(f'{config["kekkai_instance"]}/api/getChart/week/', params={ + 'from_currency': from_currency, + 'conv_currency': conv_currency + }, timeout=3) + + if not HTTPStatus(response.status_code).is_success: + return None + + try: + data = response.json() + return data.get('message', None) + except ValueError: + return None except requests.exceptions.ConnectionError: + print("API connection error.") return None - - if not HTTPStatus(res.status_code).is_success: + except requests.exceptions.RequestException as e: + print(f"There was an error: {e}") return None - - - return res.json().get('message', None) \ No newline at end of file From 24507c261993b56e6f2eb24330ef5fa056683d07 Mon Sep 17 00:00:00 2001 From: Redume Date: Tue, 7 Jan 2025 13:58:35 +0300 Subject: [PATCH 3/3] refactor --- utils/convert.py | 73 ++++++++++++++++++++++++------------------------ 1 file changed, 37 insertions(+), 36 deletions(-) diff --git a/utils/convert.py b/utils/convert.py index a956efa..c7cee9e 100644 --- a/utils/convert.py +++ b/utils/convert.py @@ -12,6 +12,7 @@ from utils.format_number import format_number config = yaml.safe_load(open('config.yaml')) + class Converter: def __init__(self): self.amount: float = 1.0 @@ -19,59 +20,59 @@ class Converter: self.from_currency: str = '' self.conv_currency: str = '' + def convert(self) -> None: - if not self.kekkai(): - self.ddg() + if not self.kekkai() and not self.ddg(): + raise RuntimeError('Failed to convert via Kekkai or DDG') number = Decimal(str(self.conv_amount)) - self.conv_amount = format_number(number.quantize(Decimal('1.00'), rounding=ROUND_DOWN)) - def ddg(self) -> None: - 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]) + def ddg(self) -> bool: + try: + res = requests.get( + f'https://duckduckgo.com/js/spice/currency/' + f'{self.amount}/{self.from_currency}/{self.conv_currency}', + timeout=3 + ) - del data['terms'] - del data['privacy'] - del data['timestamp'] + data = json.loads(re.findall(r'\(\s*(.*)\s*\);$', res.text)[0]) - if len(data.get('to')) == 0: - raise RuntimeError('Failed to get the exchange rate from DDG') + for key in ['terms', 'privacy', 'timestamp']: + data.pop(key, None) - conv = data.get('to')[0] - conv_amount = conv.get('mid') + if not data.get('to'): + return False - if conv_amount is None: - raise RuntimeError('Error when converting currency via DuckDuckGo') - - self.conv_amount = float(conv_amount) + self.conv_amount = float(data['to'][0].get('mid', 0.0)) + return True + except (requests.exceptions.RequestException, json.JSONDecodeError, IndexError) as e: + print(f"Error when requesting DDG: {e}") + return False def kekkai(self) -> bool: date = datetime.today().strftime('%Y-%m-%d') - try: - res = requests.get(f'{config['kekkai_instance']}/api/getRate/', { - 'from_currency': self.from_currency, - 'conv_currency': self.conv_currency, - 'date': date, - 'conv_amount': self.amount - }, timeout=3) + res = requests.get( + f"{config['kekkai_instance']}/api/getRate/", + params={ + 'from_currency': self.from_currency, + 'conv_currency': self.conv_currency, + 'date': date, + 'conv_amount': self.amount + }, + timeout=3 + ) - data = res.json() - - if not HTTPStatus(res.status_code).is_success: + if res.status_code != HTTPStatus.OK: return False - - self.conv_amount = data.get('conv_amount') - + data = res.json() + self.conv_amount = data.get('conv_amount', 0.0) return True - except requests.exceptions.ConnectionError: + + except (requests.exceptions.ConnectionError, json.JSONDecodeError) as e: + print(f"Error when querying Kekkai: {e}") return False - -