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

60 lines
2.4 KiB
Python
Raw Normal View History

2023-04-18 01:49:11 +00:00
import datetime
2023-04-17 16:25:06 +00:00
import requests
from core.builtins import Bot
from core.component import module
2023-04-18 05:25:46 +00:00
from core.exceptions import NoReportException
2023-04-17 16:25:06 +00:00
2023-04-18 09:34:41 +00:00
exchange_rate = module('exchange_rate',
desc='汇率转换器。',
alias={'exchangerate': 'exchange_rate',
'excr': 'exchange_rate'},
developers=['DoroWolf'], required_superuser = True)
2023-04-17 16:25:06 +00:00
api_key = 'd31697e581d5c35b038c625c'
2023-04-18 10:07:36 +00:00
@exchange_rate.command('<amount> <base> <target> {根据当日汇率转换货币价格。}')
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
2023-04-18 10:10:37 +00:00
# url = f'https://v6.exchangerate-api.com/v6/{api_key}/codes'
# response = requests.get(url)
# if response.status_code == 200:
# data = response.json()
# 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"发生错误:无效的货币单位:{' '.join(unsupported_currencies)}")
# exit()
# else:
# data = response.json()
# error_type = data['error-type']
# raise NoReportException(f"{error_type}")
2023-04-18 06:16:01 +00:00
2023-04-18 01:49:11 +00:00
amount = None
while amount is None:
try:
amount = float(msg.parsed_msg['<amount>'])
if amount <= 0:
2023-04-18 01:56:31 +00:00
await msg.finish("发生错误:金额必须为正数。")
2023-04-18 01:49:11 +00:00
except ValueError:
2023-04-18 01:51:30 +00:00
await msg.finish("发生错误:无效的金额。")
2023-04-17 16:25:06 +00:00
url = f'https://v6.exchangerate-api.com/v6/{api_key}/pair/{base_currency}/{target_currency}/{amount}'
response = requests.get(url)
if response.status_code == 200:
data = response.json()
2023-04-18 04:39:17 +00:00
exchange_rate = data['conversion_result']
current_time = datetime.datetime.now().strftime("%Y-%m-%d")
await msg.finish(f'{amount} {base_currency} -> {exchange_rate} {target_currency}\n{current_time}')
2023-04-17 16:25:06 +00:00
else:
2023-04-18 07:16:35 +00:00
data = response.json()
2023-04-18 10:07:36 +00:00
error_type = data['error-type']
2023-04-18 07:08:32 +00:00
raise NoReportException(f"{error_type}")