Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Python-Chatbot/exchange.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
32 lines (26 sloc)
1.24 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################################################## | |
# Benjamin Grant | |
""" | |
requests (http://docs.python-requests.org/en/master/) by Kenneth Reitz used for retrieving data from the web | |
The idea for this module is from Codio Week 1. The use of XML ElementTree also derived from there, however the logic was entirely created myself with help from https://docs.python.org/2/library/xml.etree.elementtree.html | |
""" | |
import requests | |
import xml.etree.ElementTree as ET | |
# Returns a dictionary of currencies and rates | |
async def getCurrencyDictionary(): | |
# Use of a context manager taken from http://docs.python-requests.org/en/master/api/#request-sessions | |
with requests.Session() as r: | |
response = r.get("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml").text | |
root = ET.fromstring(response) | |
curr={} | |
for child in root[2][0]: | |
curr[child.attrib["currency"]] = float(child.attrib["rate"]) | |
curr["EUR"] = 1 | |
curr["XDR"] = 1/(0.423 + 12.1*(1/curr["JPY"]) + 0.111*(1/curr["GBP"]) + 0.66*(1/curr["USD"])) | |
return curr | |
async def convertCurrency(to, base, amount): | |
if amount <= 0: | |
return amount | |
currencies = await getCurrencyDictionary() | |
return amount*currencies[to]/currencies[base] | |
################################################## |