mirror of
https://github.com/Redume/Shirino.git
synced 2024-11-22 00:06:22 +03:00
Compare commits
No commits in common. "45b19fbdcf708ec80943472c0bbe78bfc20b7a1c" and "5e1b60558f8cfe3ca6f75227bd0de9032e6ede14" have entirely different histories.
45b19fbdcf
...
5e1b60558f
2 changed files with 33 additions and 26 deletions
55
main.py
55
main.py
|
@ -9,16 +9,21 @@ from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
from pydantic.v1 import BaseSettings
|
from pydantic import BaseSettings
|
||||||
|
|
||||||
from aiogram import Bot, Dispatcher, types # type: ignore
|
from aiogram import Bot, types # type: ignore
|
||||||
|
from aiogram.dispatcher import Dispatcher # type: ignore
|
||||||
import asyncio
|
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
|
# 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'
|
||||||
|
|
||||||
|
|
||||||
# ---
|
# ---
|
||||||
|
|
||||||
|
|
||||||
|
@ -55,7 +60,8 @@ 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
|
||||||
dp = Dispatcher()
|
bot = Bot(token=settings.telegram_token)
|
||||||
|
dp = Dispatcher(bot)
|
||||||
|
|
||||||
|
|
||||||
class CurrencyConverter:
|
class CurrencyConverter:
|
||||||
|
@ -74,7 +80,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
|
||||||
|
@ -118,23 +124,22 @@ class CurrencyConverter:
|
||||||
# Parsing JSON data
|
# Parsing JSON data
|
||||||
data: Dict[str, Any] = json.loads(
|
data: Dict[str, Any] = json.loads(
|
||||||
resp.text
|
resp.text
|
||||||
.replace('ddg_spice_currency(', '')
|
.replace('ddg_spice_currency(', '')
|
||||||
.replace(');', '')
|
.replace(');', '')
|
||||||
)
|
)
|
||||||
|
|
||||||
log.debug(data)
|
log.debug(data)
|
||||||
|
|
||||||
# If the currency does not exist
|
# If the currency does not exist
|
||||||
error = data.get('to')[0].get('quotecurrency')
|
descr = data.get('headers', {}).get('description', '')
|
||||||
if error is None:
|
if descr.find('ERROR') != -1:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# Otherwise
|
# Otherwise
|
||||||
conv: Dict[str, str] = data.get('to')[0]
|
conv: Dict[str, str] = data.get('conversion', {})
|
||||||
conv_amount = conv.get('mid')
|
conv_amount = conv.get('converted-amount')
|
||||||
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)
|
||||||
|
@ -185,11 +190,10 @@ 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_query()
|
@dp.inline_handler()
|
||||||
async def currency(inline_query: types.InlineQuery) -> None:
|
async def currency(inline_query: InlineQuery) -> None:
|
||||||
|
|
||||||
query = inline_query.query
|
query = inline_query.query
|
||||||
article: List[Optional[types.InlineQueryResultArticle]] = [None]
|
article: List[Optional[InlineQueryResultArticle]] = [None]
|
||||||
|
|
||||||
text = query.split()
|
text = query.split()
|
||||||
len_ = len(text)
|
len_ = len(text)
|
||||||
|
@ -218,10 +222,10 @@ async def currency(inline_query: types.InlineQuery) -> None:
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
result = f'{type(ex).__name__}: {ex}'
|
result = f'{type(ex).__name__}: {ex}'
|
||||||
|
|
||||||
article[0] = types.InlineQueryResultArticle(
|
article[0] = InlineQueryResultArticle(
|
||||||
id=result_id,
|
id=result_id,
|
||||||
title=result,
|
title=result,
|
||||||
input_message_content=types.InputTextMessageContent(
|
input_message_content=InputTextMessageContent(
|
||||||
message_text=result,
|
message_text=result,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
@ -233,10 +237,13 @@ async def currency(inline_query: types.InlineQuery) -> None:
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
async def main() -> None:
|
@dp.message_handler(commands=['start'])
|
||||||
bot = Bot(settings.telegram_token)
|
async def start(message: types.Message):
|
||||||
await dp.start_polling(bot)
|
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__':
|
executor.start_polling(dp, skip_updates=True)
|
||||||
asyncio.run(main())
|
|
||||||
|
|
|
@ -1,3 +1,3 @@
|
||||||
requests==2.31.0
|
requests==2.31.0
|
||||||
pydantic[dotenv]==2.4.2
|
aiogram==2.25.1
|
||||||
aiogram==3.1.1
|
pydantic[dotenv]==1.10.8
|
||||||
|
|
Loading…
Add table
Reference in a new issue