PagerMaid_Plugins/rate.py

61 lines
1.9 KiB
Python
Raw Normal View History

2020-08-11 17:05:21 +00:00
""" Pagermaid currency exchange rates plugin. Plugin by @fruitymelon """
import asyncio, json
from json.decoder import JSONDecodeError
import urllib.request
from pagermaid.listener import listener
API = "https://api.exchangeratesapi.io/latest"
currencies = []
data = {}
inited = False
2020-08-14 11:58:26 +00:00
2020-08-11 17:05:21 +00:00
def init():
2020-08-14 11:58:26 +00:00
with urllib.request.urlopen(API) as response:
result = response.read()
try:
global data
data = json.loads(result)
data["rates"][data["base"]] = 1.0
for key in list(enumerate(data["rates"])):
currencies.append(key[1])
currencies.sort()
except JSONDecodeError as e:
raise e
global inited
inited = True
2020-08-11 17:05:21 +00:00
init()
2020-08-14 11:58:26 +00:00
2020-08-11 17:05:21 +00:00
@listener(is_plugin=True, outgoing=True, command="rate",
2020-11-22 02:15:14 +00:00
description="货币汇率插件",
parameters="<FROM> <TO> <NB>")
2020-08-11 17:05:21 +00:00
async def rate(context):
2020-08-14 11:58:26 +00:00
while not inited:
await asyncio.sleep(1)
if not context.parameter:
await context.edit(
2020-11-22 02:15:14 +00:00
f"这是货币汇率插件\n\n使用方法: `-rate <FROM> <TO> <NB>`\n\n支持货币: \n{', '.join(currencies)}")
2020-08-14 11:58:26 +00:00
return
2020-11-22 02:15:14 +00:00
if len(context.parameter) != 3:
await context.edit(f"使用方法: `-rate <FROM> <TO> <NB>`\n\n支持货币: \n{', '.join(currencies)}")
2020-08-14 11:58:26 +00:00
return
FROM = context.parameter[0].upper().strip()
TO = context.parameter[1].upper().strip()
2020-11-22 02:15:14 +00:00
try:
NB = float(context.parameter[2].strip())
except:
NB = 1.0
2020-08-14 11:58:26 +00:00
if currencies.count(FROM) == 0:
await context.edit(
2020-11-22 02:15:14 +00:00
f"{FROM}不是支持的货币. \n\n支持货币: \n{', '.join(currencies)}")
2020-08-14 11:58:26 +00:00
return
if currencies.count(TO) == 0:
2020-11-22 02:15:14 +00:00
await context.edit(f"{TO}不是支持的货币. \n\n支持货币: \n{', '.join(currencies)}")
2020-08-14 11:58:26 +00:00
return
2020-11-22 02:15:14 +00:00
await context.edit(f'{FROM} : {TO} = {NB} : {round(data["rates"][TO]/data["rates"][FROM]*NB,2)}')