fulvia/modules/currency.py

71 lines
2.0 KiB
Python
Raw Normal View History

2018-03-16 03:13:43 -04:00
#!/usr/bin/env python3
"""
Currency conversions. BTC is handled separately from country currencies.
Other crypto coins to be added someday.
"""
import requests
from module import commands, example
CUR_URI = "https://v3.exchangerate-api.com/bulk/{API_KEY}/{CUR_FROM}"
BTC_URI = "https://api.coindesk.com/v1/bpi/currentprice/{CUR_TO}.json"
@commands('cur', 'currency', 'exchange')
@example('.cur 20 EUR to USD')
def exchange(bot, trigger):
"""Show the exchange rate between two currencies"""
amount = trigger.group(3)
cur_from = trigger.group(4)
cur_to = trigger.group(5)
if cur_to == "to":
cur_to = trigger.group(6)
if not all((amount, cur_to, cur_from)):
return bot.reply("I didn't understand that. Try: .cur 20 EUR to USD")
try:
amount = float(amount)
except ValueError:
return bot.reply("Invalid amount. Must be number.")
cur_to = cur_to.upper()
cur_from = cur_from.upper()
api_key = bot.config["currency"].get("api_key")
url = URI.format(**{"API_KEY": api_key, "CUR_FROM": cur_from})
res = requests.get(url, verify=True)
res.raise_for_status()
data = res.json()
if data["result"] == "failed":
return bot.reply("Invalid input currency. Must be ISO 4217 compliant.")
rate = data["rates"].get(cur_to)
if not rate:
return bot.reply("Invalid output currency. Must be ISO 4217 compliant.")
new_amount = round(rate*amount, 2)
msg = f"\x0310{amount} {cur_from}\x03 = \x0312{new_amount} {cur_to}"
bot.msg(msg)
@commands('btc', 'bitcoin')
@example('.btc EUR')
def bitcoin(bot, trigger):
"""
Show the current bitcoin value in USD. Optional parameter allows non-USD
conversion.
"""
cur_to = trigger.group(3)
if not cur_to:
cur_to = "USD"
cur_to = cur_to.upper()
url = BTC_URI.format(**{"CUR_TO": cur_to})
res = requests.get(url, verify=True)
if res.text.startswith("Sorry"):
return bot.reply("Invalid currency type. Must be ISO 4217 compliant.")
data = res.json()
rate = data["bpi"][cur_to]["rate_float"]
msg = f"\x03101 BTC\x03 = \x0312{rate} {cur_to}"
bot.msg(msg)