Compare commits

..

No commits in common. "45b19fbdcf708ec80943472c0bbe78bfc20b7a1c" and "5e1b60558f8cfe3ca6f75227bd0de9032e6ede14" have entirely different histories.

2 changed files with 33 additions and 26 deletions

55
main.py
View file

@ -9,16 +9,21 @@ from typing import Any, Dict, List, Optional
import requests
from pydantic.v1 import BaseSettings
from pydantic import BaseSettings
from aiogram import Bot, Dispatcher, types # type: ignore
import asyncio
from aiogram import Bot, types # type: ignore
from aiogram.dispatcher import Dispatcher # type: ignore
from aiogram.utils import executor # type: ignore
from aiogram.types import InlineQuery # type: ignore
from aiogram.types import InlineQueryResultArticle
from aiogram.types import InputTextMessageContent
# Constants
DDG_URL = 'https://duckduckgo.com/js/spice/currency'
COINAPI_URL = 'https://rest.coinapi.io/v1/exchangerate'
# ---
@ -55,7 +60,8 @@ if settings.debug:
coinapi_len = len(settings.coinapi_keys)
coinapi_active = [0] # API key index
dp = Dispatcher()
bot = Bot(token=settings.telegram_token)
dp = Dispatcher(bot)
class CurrencyConverter:
@ -74,7 +80,7 @@ class CurrencyConverter:
self.coinapi()
str_amount = f'{self.conv_amount}'
point = str_amount.find('.')
point = str_amount.find(".")
after_point = str_amount[point + 1:]
fnz = min( # index of first non-zero digit
@ -118,23 +124,22 @@ class CurrencyConverter:
# Parsing JSON data
data: Dict[str, Any] = json.loads(
resp.text
.replace('ddg_spice_currency(', '')
.replace(');', '')
.replace('ddg_spice_currency(', '')
.replace(');', '')
)
log.debug(data)
# If the currency does not exist
error = data.get('to')[0].get('quotecurrency')
if error is None:
descr = data.get('headers', {}).get('description', '')
if descr.find('ERROR') != -1:
return False
# Otherwise
conv: Dict[str, str] = data.get('to')[0]
conv_amount = conv.get('mid')
conv: Dict[str, str] = data.get('conversion', {})
conv_amount = conv.get('converted-amount')
if conv_amount is None:
raise RuntimeError('Ошибка при конвертации через DDG')
self.conv_amount = float(conv_amount)
log.debug(conv)
@ -185,11 +190,10 @@ def rotate_token(lst: List[str], active: List[int]) -> None:
active[0] = (active[0] + 1) % len(lst)
@dp.inline_query()
async def currency(inline_query: types.InlineQuery) -> None:
@dp.inline_handler()
async def currency(inline_query: InlineQuery) -> None:
query = inline_query.query
article: List[Optional[types.InlineQueryResultArticle]] = [None]
article: List[Optional[InlineQueryResultArticle]] = [None]
text = query.split()
len_ = len(text)
@ -218,10 +222,10 @@ async def currency(inline_query: types.InlineQuery) -> None:
except Exception as ex:
result = f'{type(ex).__name__}: {ex}'
article[0] = types.InlineQueryResultArticle(
article[0] = InlineQueryResultArticle(
id=result_id,
title=result,
input_message_content=types.InputTextMessageContent(
input_message_content=InputTextMessageContent(
message_text=result,
),
)
@ -233,10 +237,13 @@ async def currency(inline_query: types.InlineQuery) -> None:
)
async def main() -> None:
bot = Bot(settings.telegram_token)
await dp.start_polling(bot)
@dp.message_handler(commands=['start'])
async def start(message: types.Message):
await message.answer("Hi! Bot can show the exchange rate of crypto and fiat currency. "
"The bot is used through the inline commands "
"`@shirino_bot 12 usd rub` or `@shirino_bot usd rub`"
"\n\nThe bot is open source on [Github](https://github.com/redume/shirino)",
parse_mode="markdown")
if __name__ == '__main__':
asyncio.run(main())
executor.start_polling(dp, skip_updates=True)

View file

@ -1,3 +1,3 @@
requests==2.31.0
pydantic[dotenv]==2.4.2
aiogram==3.1.1
aiogram==2.25.1
pydantic[dotenv]==1.10.8