fulvia/modules/currency.py

75 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
2019-11-05 07:58:20 -05:00
import config
2018-03-16 03:13:43 -04:00
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):
2018-09-19 13:01:52 -04:00
"""
Show the exchange rate between two currencies.
Supported currencies: https://www.exchangerate-api.com/supported-currencies
"""
2020-01-07 18:58:19 -05:00
if len(trigger.args) < 5:
return bot.reply("Insuffcient arguments.")
amount = trigger.args[1]
cur_from = trigger.args[2]
cur_to = trigger.args[4]
2018-03-16 03:13:43 -04:00
try:
amount = float(amount)
except ValueError:
return bot.reply("Invalid amount. Must be number.")
cur_to = cur_to.upper()
cur_from = cur_from.upper()
2019-10-08 12:39:13 -04:00
api_key = config.exchangerate_api_key
2018-05-17 23:06:45 -04:00
url = CUR_URI.format(**{"API_KEY": api_key, "CUR_FROM": cur_from})
2018-03-16 03:13:43 -04:00
res = requests.get(url, verify=True)
res.raise_for_status()
data = res.json()
2018-05-17 23:06:45 -04:00
if data["result"] == "error":
return bot.msg("Error: " + data["error"])
2018-03-16 03:13:43 -04:00
rate = data["rates"].get(cur_to)
if not rate:
2018-05-17 23:06:45 -04:00
return bot.msg("Invalid output currency. Must be ISO 4217 compliant.")
2018-03-16 03:13:43 -04:00
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.
"""
2020-01-07 18:58:19 -05:00
if len(trigger.args) < 2:
2018-03-16 03:13:43 -04:00
cur_to = "USD"
2020-01-07 18:58:19 -05:00
else:
cur_to = trigger.args[1]
cur_to = cur_to.upper()
2018-03-16 03:13:43 -04:00
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)