-
Notifications
You must be signed in to change notification settings - Fork 986
/
Copy pathcurrency.py
27 lines (24 loc) · 1.12 KB
/
currency.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import requests
from templates.text import TextTemplate
from error_msg import CONVERT_ERROR, EXAMPLE_CONVERSIONS
def process(input, entities):
output = {}
try:
from_currency = entities['from_currency'][0]['value'].upper()
to_currency = entities['to_currency'][0]['value'].upper()
r = requests.get('http://api.fixer.io/latest?base=' + from_currency)
data = r.json()
conversion_rate = data['rates'][to_currency]
conversion_details = '1 %s = %.4f %s' % (from_currency, conversion_rate, to_currency)
if 'number' in entities:
amount = entities['number'][0]['value']
if amount != 1:
conversion_details += '\n%s %s = %.4f %s' % (amount, from_currency, amount * conversion_rate, to_currency)
output['input'] = input
output['output'] = TextTemplate(conversion_details).get_message()
output['success'] = True
except:
error_message = CONVERT_ERROR.format('currencies') + EXAMPLE_CONVERSIONS
output['error_msg'] = TextTemplate(error_message).get_message()
output['success'] = False
return output