Skip to content

Commit 8595d1b

Browse files
authored
Merge pull request CloudBotIRC#113 from linuxdaemon/gonzobot+crypto-fix
Cleanup + error handling for cryptocurrency.py
2 parents 62d114b + 8c01e4e commit 8595d1b

1 file changed

Lines changed: 63 additions & 44 deletions

File tree

plugins/cryptocurrency.py

Lines changed: 63 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -15,30 +15,53 @@
1515
import requests
1616

1717
from cloudbot import hook
18+
from cloudbot.util import colors
1819

19-
API_URL = "https://api.coinmarketcap.com/v1/ticker/{}?convert={}"
20+
API_URL = "https://api.coinmarketcap.com/v1/ticker/{}"
2021

22+
CURRENCY_SYMBOLS = {
23+
'USD': '$',
24+
'GBP': '£',
25+
'EUR': '€',
26+
}
2127

22-
# aliases
23-
@hook.command("bitcoin", "btc", autohelp=False)
24-
def bitcoin(text, reply):
25-
""" -- Returns current bitcoin value """
26-
# alias
27-
return crypto_command(" ".join(["bitcoin", text]), reply)
2828

29+
class Alias:
30+
__slots__ = ("name", "cmds")
2931

30-
@hook.command("litecoin", "ltc", autohelp=False)
31-
def litecoin(text, reply):
32-
""" -- Returns current litecoin value """
33-
# alias
34-
return crypto_command(" ".join(["litecoin", text]), reply)
32+
def __init__(self, name, *cmds):
33+
self.name = name
34+
if name not in cmds:
35+
cmds = (name,) + cmds
3536

37+
self.cmds = cmds
3638

37-
@hook.command("dogecoin", "doge", autohelp=False)
38-
def dogecoin(text, reply):
39-
""" -- Returns current dogecoin value """
40-
# alias
41-
return crypto_command(" ".join(["dogecoin", text]), reply)
39+
40+
ALIASES = (
41+
Alias('bitcoin', 'btc'),
42+
Alias('litecoin', 'ltc'),
43+
Alias('dogecoin', 'doge'),
44+
)
45+
46+
47+
def get_request(ticker, currency):
48+
return requests.get(API_URL.format(quote_plus(ticker)), params={'convert': currency})
49+
50+
51+
def alias_wrapper(alias):
52+
def func(text):
53+
return crypto_command(" ".join((alias.name, text)))
54+
55+
func.__doc__ = """- Returns the current {} value""".format(alias.name)
56+
func.__name__ = alias.name + "_alias"
57+
58+
return func
59+
60+
61+
def init_aliases():
62+
for alias in ALIASES:
63+
_hook = alias_wrapper(alias)
64+
globals()[_hook.__name__] = hook.command(*alias.cmds, autohelp=False)(_hook)
4265

4366

4467
# main command
@@ -48,15 +71,13 @@ def crypto_command(text, reply):
4871
args = text.split()
4972
ticker = args.pop(0)
5073

74+
if not args:
75+
currency = 'USD'
76+
else:
77+
currency = args.pop(0).upper()
78+
5179
try:
52-
if not args:
53-
currency = 'USD'
54-
else:
55-
currency = args.pop(0).upper()
56-
57-
encoded_ticker = quote_plus(ticker)
58-
encoded_currency = quote_plus(currency)
59-
request = requests.get(API_URL.format(encoded_ticker, encoded_currency))
80+
request = get_request(ticker, currency)
6081
request.raise_for_status()
6182
except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e:
6283
reply("Could not get value: {}".format(e))
@@ -67,32 +88,30 @@ def crypto_command(text, reply):
6788
if "error" in data:
6889
return "{}.".format(data['error'])
6990

70-
updated_time = datetime.fromtimestamp(float(data[0]['last_updated']))
91+
data = data[0]
92+
93+
updated_time = datetime.fromtimestamp(float(data['last_updated']))
7194
if (datetime.today() - updated_time).days > 2:
7295
# the API retains data for old ticker names that are no longer updated
7396
# in these cases we just return a "not found" message
7497
return "Currency not found."
7598

76-
change = float(data[0]['percent_change_24h'])
99+
change = float(data['percent_change_24h'])
77100
if change > 0:
78-
change_str = "\x033 {}%\x0f".format(change)
101+
change_str = "$(dark_green) {}%$(clear)".format(change)
79102
elif change < 0:
80-
change_str = "\x035 {}%\x0f".format(change)
103+
change_str = "$(dark_red) {}%$(clear)".format(change)
81104
else:
82105
change_str = "{}%".format(change)
83106

84-
if currency == 'GBP':
85-
currency_sign = '£'
86-
elif currency == 'EUR':
87-
currency_sign = '€'
88-
elif currency == 'USD':
89-
currency_sign = '$'
90-
else:
91-
currency_sign = ''
92-
93-
return "{} // \x0307{}{:,.2f}\x0f {} - {:,.7f} BTC // {} change".format(data[0]['symbol'],
94-
currency_sign,
95-
float(data[0]['price_' + currency.lower()]),
96-
currency.upper(),
97-
float(data[0]['price_btc']),
98-
change_str)
107+
currency_sign = CURRENCY_SYMBOLS.get(currency, '')
108+
109+
try:
110+
converted_value = data['price_' + currency.lower()]
111+
except LookupError:
112+
return "Unable to convert to currency '{}'".format(currency)
113+
114+
return colors.parse("{} // $(orange){}{:,.2f}$(clear) {} - {:,.7f} BTC // {} change".format(
115+
data['symbol'], currency_sign, float(converted_value), currency.upper(),
116+
float(data['price_btc']), change_str
117+
))

0 commit comments

Comments
 (0)