2023-05-30 13:47:06 +03:00
|
|
|
#!/usr/bin/env python3
|
2023-11-22 22:18:23 +03:00
|
|
|
import aiohttp.client_exceptions
|
|
|
|
from pydantic.v1 import BaseSettings
|
|
|
|
from typing import List, Any, Dict, Optional
|
2023-05-30 13:33:41 +03:00
|
|
|
import logging
|
2023-03-08 13:31:45 +03:00
|
|
|
|
2023-11-22 22:18:23 +03:00
|
|
|
from aiogram import Dispatcher, types, Bot
|
2023-03-08 13:31:45 +03:00
|
|
|
|
2023-11-22 22:18:23 +03:00
|
|
|
import requests
|
|
|
|
import json
|
2023-03-08 13:31:45 +03:00
|
|
|
|
2023-11-22 22:18:23 +03:00
|
|
|
import hashlib
|
2023-03-08 13:31:45 +03:00
|
|
|
|
2023-09-29 21:12:44 +03:00
|
|
|
import asyncio
|
2023-03-08 13:31:45 +03:00
|
|
|
|
2023-11-22 22:18:23 +03:00
|
|
|
import re
|
|
|
|
import string
|
2023-05-30 11:51:20 +03:00
|
|
|
|
2023-05-30 13:47:06 +03:00
|
|
|
|
2023-05-30 13:33:41 +03:00
|
|
|
class Settings(BaseSettings):
|
|
|
|
debug: bool
|
2023-06-01 16:39:46 +03:00
|
|
|
coinapi_keys: List[str]
|
2023-05-30 13:33:41 +03:00
|
|
|
telegram_token: str
|
2023-05-30 11:51:20 +03:00
|
|
|
|
2023-05-30 13:33:41 +03:00
|
|
|
class Config:
|
|
|
|
env_file = '.env'
|
|
|
|
env_file_encoding = 'utf-8'
|
2023-05-30 11:51:20 +03:00
|
|
|
|
2023-05-30 13:47:06 +03:00
|
|
|
|
2023-11-22 22:18:23 +03:00
|
|
|
settings = Settings()
|
2023-05-30 13:47:06 +03:00
|
|
|
|
2023-05-30 13:33:41 +03:00
|
|
|
log = logging.getLogger('shirino')
|
|
|
|
handler = logging.StreamHandler()
|
|
|
|
fmt = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
|
2023-03-08 13:31:45 +03:00
|
|
|
|
2023-05-30 13:33:41 +03:00
|
|
|
handler.setFormatter(fmt)
|
|
|
|
log.addHandler(handler)
|
2023-03-08 13:31:45 +03:00
|
|
|
|
2023-05-30 13:33:41 +03:00
|
|
|
if settings.debug:
|
|
|
|
handler.setLevel(logging.DEBUG)
|
|
|
|
log.setLevel(logging.DEBUG)
|
2023-05-30 13:47:06 +03:00
|
|
|
|
2023-06-01 16:39:46 +03:00
|
|
|
coinapi_len = len(settings.coinapi_keys)
|
2023-11-22 22:18:23 +03:00
|
|
|
coinapi_active = [0]
|
|
|
|
|
2023-09-29 21:12:44 +03:00
|
|
|
dp = Dispatcher()
|
2023-03-08 13:31:45 +03:00
|
|
|
|
2023-11-22 22:18:23 +03:00
|
|
|
DDG_URL = 'https://duckduckgo.com/js/spice/currency'
|
|
|
|
COINAPI_URL = 'https://rest.coinapi.io/v1/exchangerate'
|
2023-03-08 13:31:45 +03:00
|
|
|
|
2023-05-30 13:47:06 +03:00
|
|
|
|
2023-11-22 22:18:23 +03:00
|
|
|
class Currency:
|
2023-05-30 13:33:41 +03:00
|
|
|
def __init__(self) -> None:
|
2023-06-01 15:58:33 +03:00
|
|
|
self.amount: float = 1.0
|
2023-11-22 22:18:23 +03:00
|
|
|
self.conv_amount: float = 1.0
|
2023-05-30 13:33:41 +03:00
|
|
|
self.from_currency = ''
|
|
|
|
self.conv_currency = ''
|
2023-05-30 13:47:06 +03:00
|
|
|
|
2023-05-30 13:33:41 +03:00
|
|
|
def convert(self) -> None:
|
2023-11-22 22:18:23 +03:00
|
|
|
if not self.ddg():
|
2023-05-30 13:33:41 +03:00
|
|
|
self.coinapi()
|
2023-05-30 13:47:06 +03:00
|
|
|
|
2023-06-01 15:58:33 +03:00
|
|
|
str_amount = f'{self.conv_amount}'
|
2023-09-29 21:12:44 +03:00
|
|
|
point = str_amount.find('.')
|
2023-06-01 15:58:33 +03:00
|
|
|
after_point = str_amount[point + 1:]
|
|
|
|
|
2023-11-22 22:18:23 +03:00
|
|
|
fnz = min(
|
2023-06-01 15:58:33 +03:00
|
|
|
(
|
|
|
|
after_point.index(i)
|
|
|
|
for i in string.digits[1:]
|
|
|
|
if i in after_point
|
|
|
|
),
|
|
|
|
default=-1,
|
|
|
|
)
|
2023-06-01 15:16:37 +03:00
|
|
|
|
|
|
|
if fnz == -1:
|
2023-06-01 15:58:33 +03:00
|
|
|
# it is an integer like 81.0
|
|
|
|
return
|
|
|
|
|
2023-06-01 16:07:20 +03:00
|
|
|
# how many digits should be after the point:
|
|
|
|
# ndigits (3 by default) after first non-zero
|
2023-11-22 22:18:23 +03:00
|
|
|
ndigits = fnz + 3
|
2023-06-01 15:16:37 +03:00
|
|
|
|
2023-06-01 16:07:20 +03:00
|
|
|
self.conv_amount = round(self.conv_amount, ndigits)
|
2023-06-01 15:16:37 +03:00
|
|
|
|
2023-11-22 22:18:23 +03:00
|
|
|
def ddg(self) -> float:
|
|
|
|
"""Получение данных фиатной валюты через DuckDuckGo
|
2023-05-30 13:47:06 +03:00
|
|
|
|
2023-11-22 22:18:23 +03:00
|
|
|
e.g: https://duckduckgo.com/js/spice/currency/1/USD/RUB
|
2023-05-30 13:33:41 +03:00
|
|
|
"""
|
|
|
|
|
2023-11-22 22:18:23 +03:00
|
|
|
res = requests.get(f'{DDG_URL}/{self.amount}/{self.from_currency}/{self.conv_currency}')
|
|
|
|
data: Dict[str, Any] = json.loads(re.findall(r'(.+)\);', res.text)[0])
|
2023-05-30 13:33:41 +03:00
|
|
|
|
|
|
|
log.debug(data)
|
|
|
|
|
2023-11-22 22:18:23 +03:00
|
|
|
if len(data.get('to')) == 0:
|
2023-05-30 13:33:41 +03:00
|
|
|
return False
|
|
|
|
|
2023-09-29 21:12:44 +03:00
|
|
|
conv: Dict[str, str] = data.get('to')[0]
|
2023-11-22 22:18:23 +03:00
|
|
|
conv_amount = conv.get("mid")
|
2023-09-29 21:12:44 +03:00
|
|
|
|
2023-11-22 22:18:23 +03:00
|
|
|
if conv_amount is None:
|
|
|
|
print("FUCK")
|
|
|
|
raise RuntimeError('Ошибка при конвертации валюты через DuckDuckGo')
|
2023-05-30 13:33:41 +03:00
|
|
|
|
|
|
|
log.debug(conv)
|
2023-11-22 22:18:23 +03:00
|
|
|
log.debug(conv_amount)
|
|
|
|
|
|
|
|
self.conv_amount = float(conv_amount)
|
2023-05-30 13:33:41 +03:00
|
|
|
|
|
|
|
return True
|
2023-05-30 13:47:06 +03:00
|
|
|
|
2023-06-01 16:39:46 +03:00
|
|
|
def coinapi(self, depth: int = coinapi_len) -> None:
|
2023-11-22 22:18:23 +03:00
|
|
|
"""Получение данных с CoinAPI для получения курса криптовалюты
|
|
|
|
|
2023-06-01 16:39:46 +03:00
|
|
|
Args:
|
2023-11-22 22:18:23 +03:00
|
|
|
depth (int, optional): Счетчик, защищающий от бесконечной рекурсии
|
2023-06-01 16:39:46 +03:00
|
|
|
"""
|
|
|
|
|
|
|
|
if depth <= 0:
|
|
|
|
raise RecursionError('Рейтлимит на всех токенах')
|
2023-05-30 13:33:41 +03:00
|
|
|
|
|
|
|
resp = requests.get(
|
|
|
|
(
|
|
|
|
f'{COINAPI_URL}/{self.from_currency}'
|
|
|
|
f'/{self.conv_currency}'
|
|
|
|
),
|
|
|
|
headers={
|
2023-06-01 16:39:46 +03:00
|
|
|
'X-CoinAPI-Key': settings.coinapi_keys[coinapi_active[0]],
|
2023-05-30 13:33:41 +03:00
|
|
|
},
|
2023-11-22 22:18:23 +03:00
|
|
|
timeout=3,
|
2023-05-30 13:33:41 +03:00
|
|
|
)
|
|
|
|
|
2023-06-01 16:39:46 +03:00
|
|
|
if resp.status_code == 429:
|
|
|
|
log.warning('CoinAPI ratelimited, rotating token')
|
|
|
|
rotate_token(settings.coinapi_keys, coinapi_active)
|
|
|
|
self.coinapi(depth - 1)
|
|
|
|
|
2023-05-30 13:33:41 +03:00
|
|
|
data: Dict[str, Any] = resp.json()
|
2023-06-01 15:58:33 +03:00
|
|
|
rate = data.get('rate')
|
|
|
|
if rate is None:
|
|
|
|
raise RuntimeError('Не удалось получить курс валюты от CoinAPI')
|
|
|
|
self.conv_amount = float(rate * self.amount)
|
2023-03-08 13:31:45 +03:00
|
|
|
|
|
|
|
|
2023-06-01 16:39:46 +03:00
|
|
|
def rotate_token(lst: List[str], active: List[int]) -> None:
|
2023-11-22 22:18:23 +03:00
|
|
|
"""Смена API-ключей CoinAPI при ratelimits
|
|
|
|
|
2023-06-01 16:39:46 +03:00
|
|
|
Args:
|
2023-11-22 22:18:23 +03:00
|
|
|
lst (List[str]): Список ключей
|
|
|
|
active (List[str]): Изменяемый объект с текущим ключевым индексом
|
2023-06-01 16:39:46 +03:00
|
|
|
"""
|
|
|
|
|
|
|
|
active[0] = (active[0] + 1) % len(lst)
|
|
|
|
|
|
|
|
|
2023-09-29 21:12:44 +03:00
|
|
|
@dp.inline_query()
|
|
|
|
async def currency(inline_query: types.InlineQuery) -> None:
|
2023-05-30 13:33:41 +03:00
|
|
|
query = inline_query.query
|
2023-09-29 21:12:44 +03:00
|
|
|
article: List[Optional[types.InlineQueryResultArticle]] = [None]
|
2023-03-08 13:31:45 +03:00
|
|
|
|
2023-11-22 22:18:23 +03:00
|
|
|
args = query.split()
|
2023-03-08 13:31:45 +03:00
|
|
|
|
2023-05-30 13:33:41 +03:00
|
|
|
result_id = hashlib.md5(query.encode()).hexdigest()
|
2023-11-22 22:18:23 +03:00
|
|
|
conv = Currency()
|
2023-03-08 13:31:45 +03:00
|
|
|
|
|
|
|
try:
|
2023-11-22 22:18:23 +03:00
|
|
|
if len(args) == 0:
|
|
|
|
article[0] = types.InlineQueryResultArticle(
|
|
|
|
id=result_id,
|
|
|
|
title="Требуется 2, либо 3 аргумента",
|
|
|
|
description=f"@shirino_bot USD RUB \n@shirino_bot 12 USD RUB",
|
|
|
|
input_message_content=types.InputTextMessageContent(
|
|
|
|
message_text="Требуется 2, либо 3 аргумента"
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
elif args[0].isdigit() or re.match(r'^-?\d+(?:\.\d+)$', args[0]) is not None:
|
|
|
|
conv.from_currency = args[1].upper()
|
|
|
|
conv.conv_currency = args[2].upper()
|
2023-05-30 13:33:41 +03:00
|
|
|
conv.convert()
|
2023-11-22 22:18:23 +03:00
|
|
|
elif type(args[0]) is str:
|
|
|
|
conv.from_currency = args[0].upper()
|
|
|
|
conv.conv_currency = args[1].upper()
|
2023-05-30 13:33:41 +03:00
|
|
|
conv.convert()
|
2023-05-30 11:51:20 +03:00
|
|
|
|
2023-11-22 22:18:23 +03:00
|
|
|
result_title = f'{conv.amount} {conv.from_currency} = {conv.conv_amount} {conv.conv_currency}'
|
|
|
|
result_desc = None
|
|
|
|
|
2023-05-30 11:51:20 +03:00
|
|
|
|
2023-10-28 22:02:29 +03:00
|
|
|
except aiohttp.client_exceptions.ClientError:
|
2023-11-22 22:18:23 +03:00
|
|
|
result_title = 'Произошла ошибка'
|
|
|
|
result_desc = 'Рейт-лимит от api telegram, попробуйте позже'
|
|
|
|
await asyncio.sleep(1)
|
2023-10-28 22:02:29 +03:00
|
|
|
|
2023-05-30 13:33:41 +03:00
|
|
|
except Exception as ex:
|
2023-11-22 22:18:23 +03:00
|
|
|
log.debug(ex)
|
|
|
|
result_title = 'Произошла ошибка'
|
|
|
|
result_desc = f'{type(ex).__name__}: {ex}'
|
2023-05-30 11:51:20 +03:00
|
|
|
|
2023-09-29 21:12:44 +03:00
|
|
|
article[0] = types.InlineQueryResultArticle(
|
2023-03-08 13:31:45 +03:00
|
|
|
id=result_id,
|
2023-11-22 22:18:23 +03:00
|
|
|
title=result_title,
|
|
|
|
description=result_desc,
|
2023-09-29 21:12:44 +03:00
|
|
|
input_message_content=types.InputTextMessageContent(
|
2023-11-22 22:18:23 +03:00
|
|
|
message_text=f"{result_title} \n{result_desc}",
|
2023-05-30 13:33:41 +03:00
|
|
|
),
|
|
|
|
)
|
|
|
|
|
|
|
|
await inline_query.answer(
|
2023-11-22 22:18:23 +03:00
|
|
|
article,
|
2023-05-30 13:33:41 +03:00
|
|
|
cache_time=1,
|
|
|
|
is_personal=True,
|
|
|
|
)
|
2023-03-08 13:31:45 +03:00
|
|
|
|
|
|
|
|
2023-09-29 21:12:44 +03:00
|
|
|
async def main() -> None:
|
|
|
|
bot = Bot(settings.telegram_token)
|
|
|
|
await dp.start_polling(bot)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
asyncio.run(main())
|