Add possiblity to convert currencies

master
Nikola Forró 6 years ago
parent f52142fb06
commit b2f2bef029

@ -6,6 +6,7 @@ import requests
from services.cheesecom import CheeseCom, CheeseComError from services.cheesecom import CheeseCom, CheeseComError
from services.converter import Converter, ConverterError from services.converter import Converter, ConverterError
from services.exchangerates import ExchangeRates, ExchangeRatesError
from services.roll20 import Roll20, Roll20Error from services.roll20 import Roll20, Roll20Error
from services.youtube import Youtube, YoutubeError from services.youtube import Youtube, YoutubeError
@ -23,6 +24,7 @@ class Commands(object):
self.config = config self.config = config
self.logger = logger self.logger = logger
self.last_roll_formula = None self.last_roll_formula = None
self.rates = ExchangeRates()
def add_quote(self, id, text, game, date): def add_quote(self, id, text, game, date):
try: try:
@ -213,6 +215,7 @@ class Commands(object):
def convert(self, expression, unit=None): def convert(self, expression, unit=None):
c = Converter() c = Converter()
c.update_currencies(*self.rates.query())
try: try:
return c.convert(expression, unit) return c.convert(expression, unit)
except ConverterError as e: except ConverterError as e:

@ -31,6 +31,11 @@ class Converter(object):
self.ureg.floz: self.ureg.milliliter, 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): def convert(self, expression, unit=None):
try: try:
q = self.ureg.parse_expression(expression) q = self.ureg.parse_expression(expression)

@ -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
Loading…
Cancel
Save