-
Notifications
You must be signed in to change notification settings - Fork 15
/
btc.py
69 lines (51 loc) · 1.95 KB
/
btc.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
'''Get the latest Bitcoin price (in USD, EUR and GBP)'''
import requests
__author__ = ('CianLR', 'byxor', 'itsdoddsy')
COMMAND = 'btc'
API_URL = 'https://api.coindesk.com/v1/bpi/currentprice.json'
RESP_TEMPLATE = """€{}
${}
£{}
difference since last time: {}"""
LAST_EUROS = 100
class BitcoinException(Exception):
pass
class BadHTTPResponse(BitcoinException):
pass
class MissingFields(BitcoinException):
pass
def get_bitcoin_rates():
response = requests.get(API_URL)
if not response.ok:
message = "Error getting price. Response (code {}) {}".format(
response.status_code, response.text)
raise BadHTTPResponse(message)
response_json = response.json()
if not _is_valid_response(response_json):
message = "Response is missing fields: {}".format(str(response_json))
raise MissingFields(message)
euros = response_json['bpi']['EUR']['rate_float']
dollars = response_json['bpi']['USD']['rate_float']
sterling = response_json['bpi']['GBP']['rate_float']
return euros, dollars, sterling
def _is_valid_response(resp):
return ('bpi' in resp and
'EUR' in resp['bpi'] and 'rate' in resp['bpi']['EUR'] and
'USD' in resp['bpi'] and 'rate' in resp['bpi']['USD'] and
'GBP' in resp['bpi'] and 'rate' in resp['bpi']['GBP'])
def percentage_increase(before, after):
delta = after - before
return (delta * 100) / before
def percentage_string(n):
return "{:.3f}%".format(n)
def main(bot, author_id, message, thread_id, thread_type, **kwargs):
try:
global LAST_EUROS
euros, dollars, sterling = get_bitcoin_rates()
increase = percentage_increase(LAST_EUROS, euros)
message = RESP_TEMPLATE.format(
euros, dollars, sterling, percentage_string(increase))
LAST_EUROS = euros
except BitcoinException as e:
message = str(e)
bot.sendMessage(message, thread_id=thread_id, thread_type=thread_type)