Compare commits

..

No commits in common. "e3f5396d1a2e8d4885a7165662b312aad167c938" and "9a2b16aefbb1201247e6f91b9d2db60e054370b7" have entirely different histories.

2 changed files with 115 additions and 70 deletions

148
main.py
View file

@ -4,8 +4,12 @@ import asyncio
import yaml import yaml
import hashlib import hashlib
import aiohttp
import json import json
import re
from word2number import w2n
from function.convert import Converter from function.convert import Converter
from function.format_number import format_number from function.format_number import format_number
@ -14,84 +18,124 @@ dp = Dispatcher()
@dp.message() @dp.message()
@dp.inline_query() async def message_conv(message: types.Message):
async def currency(query: types.Message | types.InlineQuery) -> None: with open('currency.json', 'r', encoding='utf-8') as f:
global result currency_json = json.load(f)
text = message.text.lower()
args = text.split()
number_match = re.match(r'\d+\.?\d*|\w+', args[0])
if number_match:
number_text = number_match.group(0)
try: try:
currency_json = json.load(open('currency.json', 'r', encoding='utf-8')) amount = float(number_text)
text = query.query if isinstance(query, types.InlineQuery) else query.text except ValueError:
args = text.split() try:
result_id = hashlib.md5(text.encode()).hexdigest() amount = float(w2n.word_to_num(number_text))
conv = Converter() except ValueError:
await message.reply("Не удалось распознать числовое значение.")
if len(args) <= 1: return
return await reply(result_id,
"2 or 3 arguments are required.",
"@shirino_bot USD RUB "
"\n@shirino_bot 12 USD RUB",
query)
if len(args) == 4:
conv.amount = float(args[0])
from_currency_alias = args[1].lower()
conv_currency_alias = args[3].lower()
elif len(args) == 3:
conv.amount = float(args[0])
from_currency_alias = args[1].lower()
conv_currency_alias = args[2].lower()
elif len(args) == 2:
from_currency_alias = args[0].lower()
conv_currency_alias = args[1].lower()
else: else:
return await reply(result_id, 'The source and target currency could not be determined.', None, query) await message.reply("Не удалось найти числовое значение.")
return
from_currency, conv_currency = None, None if len(args) == 4:
source_currency_alias = args[1]
target_currency_alias = args[3]
elif len(args) == 3:
source_currency_alias = args[0]
target_currency_alias = args[2]
else:
await message.reply("Не удалось определить исходную и целевую валюту.")
return
source_currency_code = None
target_currency_code = None
for currency_code, aliases in currency_json.items(): for currency_code, aliases in currency_json.items():
if from_currency_alias in aliases: if source_currency_alias in aliases:
from_currency = currency_code source_currency_code = currency_code
if conv_currency_alias in aliases: if target_currency_alias in aliases:
conv_currency = currency_code target_currency_code = currency_code
if from_currency and conv_currency: if not source_currency_code or not target_currency_code or amount is None:
break await message.reply("Не удалось найти сумму или валюты по указанным данным.")
return
if not from_currency or not conv_currency: conv = Converter()
return await reply(result_id, conv.amount = amount
'The currency exchange rate could not be found.', conv.from_currency = source_currency_code.upper()
None, conv.conv_currency = target_currency_code.upper()
query)
conv.from_currency = from_currency.upper()
conv.conv_currency = conv_currency.upper()
conv.convert() conv.convert()
result = f'{format_number(conv.amount)} {conv.from_currency} = {conv.conv_amount} {conv.conv_currency}' result = f'{format_number(conv.amount)} {conv.from_currency} = {conv.conv_amount} {conv.conv_currency}'
return await reply(result_id, result, None, query) await message.reply(result)
except Exception as e:
print(e)
async def reply(result_id: str | None, title: str | None, desc, query: types.InlineQuery | types.Message) -> None: async def inline_reply(result_id: str, title: str, description: str or None, inline_query: types.InlineQuery) -> None:
if isinstance(query, types.InlineQuery):
article = [None] article = [None]
article[0] = types.InlineQueryResultArticle( article[0] = types.InlineQueryResultArticle(
id=result_id, id=result_id,
title=title, title=title,
description=desc, description=description,
input_message_content=types.InputTextMessageContent( input_message_content=types.InputTextMessageContent(
message_text=title message_text=title
) )
) )
await query.answer( await inline_query.answer(
article, article,
cache_time=1, cache_time=1,
is_personal=True, is_personal=True,
) )
else:
await query.answer(title)
@dp.inline_query()
async def currency(inline_query: types.InlineQuery) -> None:
global result
query = inline_query.query
args = query.split()
result_id = hashlib.md5(query.encode()).hexdigest()
conv = Converter()
try:
if len(args) <= 1:
await inline_reply(result_id,
"2 or 3 arguments are required",
f"@shirino_bot USD RUB \n@shirino_bot 12 USD RUB", inline_query)
if len(args) == 3:
conv.amount = float(args[0].replace(',', '.'))
conv.from_currency = args[1].upper()
conv.conv_currency = args[2].upper()
conv.convert()
elif len(args) == 2:
conv.from_currency = args[0].upper()
conv.conv_currency = args[1].upper()
conv.convert()
result = (
f'{format_number(conv.amount)} {conv.from_currency} = '
f'{conv.conv_amount} {conv.conv_currency}'
)
except aiohttp.client_exceptions.ClientError:
await inline_reply(result_id,
"Rate-limit from the Telegram API, repeat the request later",
None,
inline_query)
await asyncio.sleep(1)
except Exception:
await inline_reply(result_id, "Invalid data format",
"@shirino_bot USD RUB \n@shirino_bot 12 USD RUB",
inline_query)
await inline_reply(result_id, result, None, inline_query)
async def main() -> None: async def main() -> None:

View file

@ -2,3 +2,4 @@ aiohttp~=3.9.5
requests~=2.32.3 requests~=2.32.3
PyYAML~=6.0.1 PyYAML~=6.0.1
aiogram~=3.7.0 aiogram~=3.7.0
word2number~=1.1