#!/usr/bin/env python3 """ Currency conversions. BTC is handled separately from country currencies. Other crypto coins to be added someday. """ import requests import config from module import commands, example CUR_URI = "https://v6.exchangerate-api.com/v6/{API_KEY}/latest/{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. Supported currencies: https://www.exchangerate-api.com/supported-currencies """ if len(trigger.args) < 5: return bot.reply("Insuffcient arguments.") amount = trigger.args[1] cur_from = trigger.args[2] cur_to = trigger.args[4] 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 = config.exchangerate_api_key url = CUR_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"] == "error": return bot.msg("Error: " + data["error"]) rate = data["conversion_rates"].get(cur_to) if not rate: return bot.msg("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. """ if len(trigger.args) < 2: cur_to = "USD" else: cur_to = trigger.args[1] 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)