Created
October 11, 2020 18:30
-
-
Save jtmolon/5c1668ba02f466aaeb84b4875b97ef71 to your computer and use it in GitHub Desktop.
Get currency exchange updates from apilayer.net and generate a Unity notification on Ubuntu Desktop
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
import argparse | |
import os | |
import requests | |
import subprocess | |
import time | |
API_URL = 'http://apilayer.net/api' | |
class CheckAndNotify(object): | |
def __init__(self, from_, to, interval, always): | |
self.from_ = from_.upper() | |
self.to = to.upper() | |
self.interval = interval * 60 # minutes to seconds | |
self.always = always | |
self.access_key = os.environ.get('API_LAYER_KEY') | |
self.last_rate = None | |
self.currencies = [] | |
def get_default_params(self): | |
return {'access_key': self.access_key} | |
def validate_currencies(self): | |
params = self.get_default_params() | |
response = requests.get(f'{API_URL}/list', params=params) | |
self.currencies = response.json()['currencies'].keys() | |
return self.from_ in self.currencies and self.to in self.currencies | |
def check_and_notify(self): | |
params = self.get_default_params() | |
params['currencies'] = ','.join([self.from_, self.to]) | |
while True: | |
response = requests.get(f'{API_URL}/live', params=params) | |
quotes = response.json()['quotes'] | |
rate = quotes[f'USD{self.to}'] / quotes[f'USD{self.from_}'] | |
message = f'1 {self.from_} = {round(rate, 4)} {self.to}' | |
if not self.last_rate or self.always or self.last_rate != rate: | |
self.last_rate = rate | |
subprocess.run(['notify-send', message]) | |
time.sleep(self.interval) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser(description='Verify exchange rates and notify when target rates change.') | |
parser.add_argument('from_', metavar='from', type=str, help='convert from this currency') | |
parser.add_argument('to', metavar='to', type=str, help='convert to this currency') | |
parser.add_argument('--interval', type=int, dest='interval', default=15, | |
help='how often to check for updates (default 15 min)') | |
parser.add_argument('--always-notify', dest='always', action='store_true', | |
help='notify even if rate does not change (default False)') | |
args = parser.parse_args() | |
checker = CheckAndNotify(args.from_, args.to, args.interval, args.always) | |
if checker.validate_currencies(): | |
checker.check_and_notify() | |
else: | |
print(f'{checker.from_} or {checker.to} is not a valid currency.' | |
f' Please choose any of the following {list(checker.currencies)}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment