Archived
1
0
Fork 0
This repository has been archived on 2024-04-26. You can view files and clone it, but cannot push or open issues or pull requests.
akari-bot/modules/exchange_rate/__init__.py

52 lines
2.2 KiB
Python
Raw Normal View History

2023-04-18 01:49:11 +00:00
import datetime
2023-04-19 15:00:21 +00:00
import json
2023-04-17 16:25:06 +00:00
2023-04-19 07:45:29 +00:00
from config import Config
2023-04-17 16:25:06 +00:00
from core.builtins import Bot
from core.component import module
2023-04-19 07:45:29 +00:00
from core.utils.http import get_url
2023-04-17 16:25:06 +00:00
2023-04-19 08:29:46 +00:00
exchange_rate = module('exchange_rate',
desc='{exchange_rate.help.desc}',
alias={'exchangerate': 'exchange_rate',
2023-04-18 09:34:41 +00:00
'excr': 'exchange_rate'},
2023-04-18 10:20:54 +00:00
developers=['DoroWolf'])
2023-04-17 16:25:06 +00:00
2023-04-18 13:59:07 +00:00
api_key = Config('exchange_rate_api_key')
2023-04-17 16:25:06 +00:00
2023-04-19 08:29:46 +00:00
2023-04-19 15:04:40 +00:00
@exchange_rate.command('<base> <target> <amount> {{exchange_rate.help}}')
2023-04-17 16:25:06 +00:00
async def _(msg: Bot.MessageSession):
2023-04-18 01:56:31 +00:00
base_currency = msg.parsed_msg['<base>'].upper()
target_currency = msg.parsed_msg['<target>'].upper()
2023-04-18 06:16:01 +00:00
# url = f'https://v6.exchangerate-api.com/v6/{api_key}/codes'
# response = await get_url(url, fmt='read', status_code=200)
# response_str = response.decode('utf-8')
# data = json.loads(response_str)
# supported_currencies = data['supported_codes']
# unsupported_currencies = []
# if base_currency not in supported_currencies:
# unsupported_currencies.append(base_currency)
# if target_currency not in supported_currencies:
# unsupported_currencies.append(target_currency)
# if unsupported_currencies:
# await msg.finish(f"{msg.locale.t('exchange_rate.message.error.invalid')}{', '.join(unsupported_currencies)}")
2023-04-19 11:50:05 +00:00
amount = msg.parsed_msg['<amount>']
try:
amount = float(amount)
if amount <= 0:
await msg.finish(msg.locale.t('exchange_rate.message.error.non_positive'))
except ValueError:
await msg.finish(msg.locale.t('exchange_rate.message.error.non_digital'))
2023-04-17 16:25:06 +00:00
url = f'https://v6.exchangerate-api.com/v6/{api_key}/pair/{base_currency}/{target_currency}/{amount}'
2023-04-19 11:50:05 +00:00
response = await get_url(url, fmt='read', status_code=200)
2023-04-19 14:56:50 +00:00
response_str = response.decode('utf-8')
data = json.loads(response_str)
2023-04-19 11:50:05 +00:00
exchange_rate = data['conversion_result']
current_time = datetime.datetime.now().strftime("%Y-%m-%d")
await msg.finish(
msg.locale.t('exchange_rate.message', amount=amount, base=base_currency, exchange_rate=exchange_rate,
target=target_currency, time=current_time))