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
from pydantic import BaseSettings
from pydantic.v1 import BaseSettings
from aiogram import Bot, types # type: ignore
from aiogram.dispatcher import Dispatcher # type: ignore
from aiogram.utils import executor # type: ignore
from aiogram import Bot, Dispatcher, types # type: ignore
import asyncio
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'
# ---
@ -60,8 +55,7 @@ if settings.debug:
coinapi_len = len(settings.coinapi_keys)
coinapi_active = [0] # API key index
bot = Bot(token=settings.telegram_token)
dp = Dispatcher(bot)
dp = Dispatcher()
class CurrencyConverter:
@ -80,7 +74,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
@ -131,15 +125,16 @@ class CurrencyConverter:
log.debug(data)
# If the currency does not exist
descr = data.get('headers', {}).get('description', '')
if descr.find('ERROR') != -1:
error = data.get('to')[0].get('quotecurrency')
if error is None:
return False
# Otherwise
conv: Dict[str, str] = data.get('conversion', {})
conv_amount = conv.get('converted-amount')
conv: Dict[str, str] = data.get('to')[0]
conv_amount = conv.get('mid')
if conv_amount is None:
raise RuntimeError('Ошибка при конвертации через DDG')
self.conv_amount = float(conv_amount)
log.debug(conv)
@ -190,10 +185,11 @@ def rotate_token(lst: List[str], active: List[int]) -> None:
active[0] = (active[0] + 1) % len(lst)
@dp.inline_handler()
async def currency(inline_query: InlineQuery) -> None:
@dp.inline_query()
async def currency(inline_query: types.InlineQuery) -> None:
query = inline_query.query
article: List[Optional[InlineQueryResultArticle]] = [None]
article: List[Optional[types.InlineQueryResultArticle]] = [None]
text = query.split()
len_ = len(text)
@ -222,10 +218,10 @@ async def currency(inline_query: InlineQuery) -> None:
except Exception as ex:
result = f'{type(ex).__name__}: {ex}'
article[0] = InlineQueryResultArticle(
article[0] = types.InlineQueryResultArticle(
id=result_id,
title=result,
input_message_content=InputTextMessageContent(
input_message_content=types.InputTextMessageContent(
message_text=result,
),
)
@ -237,13 +233,10 @@ async def currency(inline_query: InlineQuery) -> None:
)
@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")
async def main() -> None:
bot = Bot(settings.telegram_token)
await dp.start_polling(bot)
executor.start_polling(dp, skip_updates=True)
if __name__ == '__main__':
asyncio.run(main())

View file

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