refactor: Fixed the code, removed the problematic characters, and made indents

This commit is contained in:
Данил 2025-03-26 14:13:20 +03:00
parent 7a246c8b92
commit ae039e2310
5 changed files with 80 additions and 41 deletions

View file

@ -9,7 +9,7 @@ import yaml
from utils.format_number import format_number
config = yaml.safe_load(open('config.yaml'))
config = yaml.safe_load(open('config.yaml', 'r', encoding='utf-8'))
class Converter:
def __init__(self):
@ -17,7 +17,7 @@ class Converter:
self.conv_amount: float = 0.0
self.from_currency: str = ''
self.conv_currency: str = ''
async def convert(self) -> None:
if not await self.kekkai():
await self.ddg()
@ -45,26 +45,32 @@ class Converter:
async def ddg(self) -> None:
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=3)) as session:
async with aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=3)
) as session:
async with session.get(
'https://duckduckgo.com/js/spice/currency/'
f'{self.amount}/{self.from_currency}/{self.conv_currency}'
) as res:
data_text = await res.text()
data = json.loads(re.findall(r'\(\s*(.*)\s*\);$', data_text)[0])
for key in ['terms', 'privacy', 'timestamp']:
data.pop(key, None)
if not data.get('to'):
raise RuntimeError('Failed to get the exchange rate from DuckDuckGo')
raise RuntimeError(
'Failed to get the exchange rate from DuckDuckGo'
)
conv = data.get('to')[0]
conv_amount = conv.get('mid')
if conv_amount is None:
raise RuntimeError('Error when converting currency via DuckDuckGo')
raise RuntimeError(
'Error when converting currency via DuckDuckGo'
)
self.conv_amount = float(conv_amount)

View file

@ -1,19 +1,20 @@
from http import HTTPStatus
import yaml
import aiohttp
from http import HTTPStatus
config = yaml.safe_load(open('config.yaml'))
config = yaml.safe_load(open('config.yaml', 'r', encoding='utf-9'))
async def create_chart(from_currency: str, conv_currency: str) -> (dict, None):
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=3)) as session:
async with session.get(f'{config["kekkai_instance"]}/api/getChart/month/', params={
'from_currency': from_currency,
'conv_currency': conv_currency
}) as res:
async with session.get(
f'{config["kekkai_instance"]}/api/getChart/month/', params={
'from_currency': from_currency,
'conv_currency': conv_currency
}) as res:
if not HTTPStatus(res.status).is_success:
return None
data = await res.json()
return data.get('message', None)

75
main.py
View file

@ -1,8 +1,4 @@
from functions.convert import Converter
from utils.format_number import format_number
from utils.inline_query import reply
from functions.create_chart import create_chart
import hashlib
import yaml
from aiohttp import web
@ -13,10 +9,16 @@ from aiogram.enums import ParseMode
from aiogram.webhook.aiohttp_server import SimpleRequestHandler, setup_application
from aiogram.filters import CommandStart
import hashlib
from functions.convert import Converter
from functions.create_chart import create_chart
from utils.format_number import format_number
from utils.inline_query import reply
config = yaml.safe_load(open('config.yaml'))
bot = Bot(token=config['telegram_token'], default=DefaultBotProperties(parse_mode=ParseMode.HTML))
config = yaml.safe_load(open('config.yaml', 'r', encoding='utf-8'))
bot = Bot(
token=config['telegram_token'],
default=DefaultBotProperties(parse_mode=ParseMode.HTML)
)
router = Router()
@ -57,13 +59,26 @@ async def currency(query: types.InlineQuery) -> None:
try:
conv.amount = float(args[0].replace(',', '.'))
if conv.amount < 0:
return await reply(result_id, [("Negative amounts are not supported.", None, None)], query)
return await reply(
result_id,
[
("Negative amounts are not supported.", None, None)
],
query
)
except ValueError:
return await reply(result_id, [("Please enter a valid number for the amount.",
f'@{get_bot.username} USD RUB \n'
f'@{get_bot.username} 12 USD RUB',
None, None)], query)
return await reply(
result_id,
[
(
"Please enter a valid number for the amount.",
f'@{get_bot.username} USD RUB \n'
f'@{get_bot.username} 12 USD RUB',
None, None
)
],
query)
from_currency = args[1]
conv_currency = args[2]
@ -71,23 +86,37 @@ async def currency(query: types.InlineQuery) -> None:
from_currency = args[0]
conv_currency = args[1]
else:
return await reply(result_id,
[(
'The source and target currency could not be determined.',
None, None
)],
query)
return await reply(
result_id,
[
(
'The source and target currency could not be determined.',
None, None
)
],
query
)
conv.from_currency = from_currency.upper()
conv.conv_currency = conv_currency.upper()
try:
await conv.convert()
except RuntimeError as e:
return await reply(result_id, [('The currency exchange rate could not be determined', None, None)], query)
except RuntimeError:
return await reply(
result_id,
[
(
'The currency exchange rate could not be determined',
None, None
)
],
query
)
chart = await create_chart(from_currency, conv_currency)
message = f'{format_number(conv.amount)} {conv.from_currency} = {conv.conv_amount} {conv.conv_currency}'
message = f'{format_number(conv.amount)} {conv.from_currency} ' \
f'= {conv.conv_amount} {conv.conv_currency}'
results = [(message, None, None)]
@ -99,7 +128,7 @@ async def currency(query: types.InlineQuery) -> None:
async def on_startup(bot: Bot) -> None:
await bot.set_webhook(
f"{config['webhook']['base_url']}{config['webhook']['path']}",
f"{config['webhook']['base_url']}{config['webhook']['path']}",
secret_token=config['webhook']['secret_token'],
allowed_updates=['inline_query', 'message']
)

View file

@ -11,7 +11,10 @@ def format_number(number):
return formatted_integer
fractional_str = f"{fractional_part:.30f}".split('.')[1]
first_non_zero = next((i for i, char in enumerate(fractional_str) if char != '0'), len(fractional_str))
first_non_zero = next(
(i for i, char in enumerate(fractional_str) if char != '0'),
len(fractional_str)
)
result_fractional = fractional_str[:first_non_zero + 3]
result_fractional = result_fractional.rstrip('0')

View file

@ -1,7 +1,7 @@
from aiogram import types
import re
from aiogram import types
async def reply(result_id: str, args: list, query: types.InlineQuery) -> None:
if not args:
return
@ -32,4 +32,4 @@ async def reply(result_id: str, args: list, query: types.InlineQuery) -> None:
parse_mode='markdown',
cache_time=0,
is_personal=True
)
)