diff --git a/commands.py b/commands.py index cc9e2f0..4a2907b 100644 --- a/commands.py +++ b/commands.py @@ -6,6 +6,7 @@ import requests from services.cheesecom import CheeseCom, CheeseComError from services.converter import Converter, ConverterError +from services.exchangerates import ExchangeRates, ExchangeRatesError from services.roll20 import Roll20, Roll20Error from services.youtube import Youtube, YoutubeError @@ -23,6 +24,7 @@ class Commands(object): self.config = config self.logger = logger self.last_roll_formula = None + self.rates = ExchangeRates() def add_quote(self, id, text, game, date): try: @@ -213,6 +215,7 @@ class Commands(object): def convert(self, expression, unit=None): c = Converter() + c.update_currencies(*self.rates.query()) try: return c.convert(expression, unit) except ConverterError as e: diff --git a/services/converter.py b/services/converter.py index 82a5cab..c87aaac 100644 --- a/services/converter.py +++ b/services/converter.py @@ -31,6 +31,11 @@ class Converter(object): self.ureg.floz: self.ureg.milliliter, } + def update_currencies(self, base, rates): + self.ureg.define('{0} = [currency]'.format(base)) + for currency, rate in rates.items(): + self.ureg.define('{0} = {1} / {2}'.format(currency, base, rate)) + def convert(self, expression, unit=None): try: q = self.ureg.parse_expression(expression) diff --git a/services/exchangerates.py b/services/exchangerates.py new file mode 100644 index 0000000..e5d672c --- /dev/null +++ b/services/exchangerates.py @@ -0,0 +1,28 @@ +import datetime + +import requests + + +API_URL = 'https://api.exchangeratesapi.io/latest' + + +class ExchangeRatesError(Exception): + pass + + +class ExchangeRates(object): + def __init__(self): + self.cache = {} + + def query(self): + today = datetime.datetime.utcnow().date().isoformat() + try: + base, rates = self.cache[today] + except KeyError: + try: + data = requests.get(API_URL).json() + base, rates = data['base'], data['rates'] + self.cache[data['date']] = base, rates + except Exception as e: + raise ExchangeRatesError(str(e)) + return base, rates