Compare commits

...

3 commits

2 changed files with 26 additions and 33 deletions

51
main.py
View file

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

View file

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