-
Notifications
You must be signed in to change notification settings - Fork 249
/
cryptocurrency.py
94 lines (70 loc) · 2.62 KB
/
cryptocurrency.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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
"""
cryptocurrency.py
A plugin that uses the CoinMarketCap JSON API to get values for cryptocurrencies.
Created By:
- Luke Rogers <https://github.com/lukeroge>
Special Thanks:
- https://coinmarketcap-nexuist.rhcloud.com/
License:
GPL v3
"""
from urllib.parse import quote_plus
from datetime import datetime
import requests
from cloudbot import hook
API_URL = "https://coinmarketcap-nexuist.rhcloud.com/api/{}"
# aliases
@hook.command("bitcoin", "btc", autohelp=False)
def bitcoin():
""" -- Returns current bitcoin value """
# alias
return crypto_command("btc")
@hook.command("litecoin", "ltc", autohelp=False)
def litecoin():
""" -- Returns current litecoin value """
# alias
return crypto_command("ltc")
@hook.command("dogecoin", "doge", autohelp=False)
def dogecoin():
""" -- Returns current dogecoin value """
# alias
return crypto_command("doge")
@hook.command("dash", "darkcoin", autohelp=False)
def dash():
""" -- Returns current darkcoin/dash value """
# alias
return crypto_command("dash")
@hook.command("zetacoin", "zet", autohelp=False)
def zet():
""" -- Returns current Zetacoin value """
# alias
return crypto_command("zet")
# main command
@hook.command("crypto", "cryptocurrency")
def crypto_command(text):
""" <ticker> -- Returns current value of a cryptocurrency """
try:
encoded = quote_plus(text)
request = requests.get(API_URL.format(encoded))
request.raise_for_status()
except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e:
return "Could not get value: {}".format(e)
data = request.json()
if "error" in data:
return "{}.".format(data['error'])
updated_time = datetime.fromtimestamp(data['timestamp'])
if (datetime.today() - updated_time).days > 2:
# the API retains data for old ticker names that are no longer updated
# in these cases we just return a "not found" message
return "Currency not found."
change = float(data['change'])
if change > 0:
change_str = "\x033 {}%\x0f".format(change)
elif change < 0:
change_str = "\x035 {}%\x0f".format(change)
else:
change_str = "{}%".format(change)
return "{} // \x0307${:,.2f}\x0f USD - {:,.7f} BTC // {} change".format(data['symbol'].upper(),
float(data['price']['usd']),
float(data['price']['btc']),
change_str)