Skip to content

Commit 4e41b10

Browse files
committed
Moved HODL to its own lego per review in #17
1 parent 1c26870 commit 4e41b10

File tree

3 files changed

+204
-158
lines changed

3 files changed

+204
-158
lines changed

legos/cryptocurrency.py

+27-158
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,15 @@
22
import requests
33
import logging
44
import json
5-
import configparser
65

76
logger = logging.getLogger(__name__)
87

98

109
class Cryptocurrency(Lego):
11-
def __init__(self, baseplate, lock):
12-
super().__init__(baseplate, lock)
13-
self.crypto_index = configparser.ConfigParser()
14-
self.crypto_index.read('crypto_index.ini')
15-
if 'crypto_index' not in self.crypto_index.sections():
16-
self.crypto_index['crypto_index'] = {}
17-
self.crypto_index['crypto_index']['fsyms'] = 'BTC'
18-
self.crypto_index['crypto_index']['tsyms'] = 'USD,BTC'
19-
with open('crypto_index.ini', 'w') as configfile:
20-
self.crypto_index.write(configfile)
21-
2210
def listening_for(self, message):
2311
if message['text'] is not None:
2412
try:
25-
command = message['text'].split()[0]
26-
return command == '!crypto' or command == '!hodl'
13+
return message['text'].split()[0] == '!crypto'
2714
except Exception as e:
2815
logger.error('''Stocks lego failed to check message text:
2916
{}'''.format(e))
@@ -37,125 +24,12 @@ def handle(self, message):
3724
logger.error('''Could not identify message source in message:
3825
{}'''.format(message))
3926

40-
message_list = message['text'].split()
41-
if message_list[0] == '!hodl':
42-
self.reply(message, self._parse_multi_commands(message_list), opts)
43-
else:
44-
try:
45-
query = message['text'].split()[1]
46-
except:
47-
self.reply(message, "Invalid query", opts)
48-
self.reply(message, self._lookup_symbol(query), opts)
49-
50-
def _parse_multi_commands(self, message_list):
51-
if len(message_list) == 1:
52-
return self._lookup_multi()
53-
elif len(message_list) > 1:
54-
case_dict = {}
55-
case_dict['list'] = self._list_hodl_symbols
56-
case_dict['add'] = self._add_symbols
57-
case_dict['drop'] = self._drop_symbols
58-
return case_dict[message_list[1]](message_list)
59-
60-
def _list_hodl_symbols(self, message_list):
61-
fsyms = self.crypto_index['crypto_index']['fsyms']
62-
tsyms = self.crypto_index['crypto_index']['tsyms']
63-
return_val = ''
64-
return_val += 'Convert From: ' + fsyms + '\n'
65-
return_val += 'Convert To: ' + tsyms + '\n'
66-
return return_val
67-
68-
def _add_symbols(self, message_list):
69-
if len(message_list) < 3:
70-
return ('Please supply additional arguments, e.g.:\n'
71-
'!hodl add from BTC,LTC')
72-
elif message_list[2] == 'from':
73-
return self._add_from_symbols(message_list)
74-
elif message_list[2] == 'to':
75-
return self._add_to_symbols(message_list)
76-
else:
77-
return 'There was an issue processing your request.'
78-
79-
def _add_from_symbols(self, message_list):
80-
try:
81-
add_fsyms = message_list[3].split(',')
82-
old_fsyms = self.crypto_index['crypto_index']['fsyms'].split(',')
83-
new_fsyms = list(set(old_fsyms + add_fsyms))
84-
self.crypto_index['crypto_index']['fsyms'] = ','.join(new_fsyms)
85-
with open('crypto_index.ini', 'w') as configfile:
86-
self.crypto_index.write(configfile)
87-
return self._list_hodl_symbols(message_list)
88-
except:
89-
return ('Please supply additional arguments, e.g.:\n'
90-
'!hodl add from BTC,LTC')
91-
92-
def _add_to_symbols(self, message_list):
93-
try:
94-
add_tsyms = message_list[3].split(',')
95-
old_tsyms = self.crypto_index['crypto_index']['tsyms'].split(',')
96-
new_tsyms = list(set(old_tsyms + add_tsyms))
97-
self.crypto_index['crypto_index']['tsyms'] = ','.join(new_tsyms)
98-
with open('crypto_index.ini', 'w') as configfile:
99-
self.crypto_index.write(configfile)
100-
return self._list_hodl_symbols(message_list)
101-
except:
102-
return ('Please supply additional arguments, e.g.:\n'
103-
'!hodl add to BTC,LTC')
104-
105-
def _drop_symbols(self, message_list):
106-
if len(message_list) < 3:
107-
return ('Please supply additional arguments, e.g.:\n'
108-
'!hodl drop from BTC')
109-
elif message_list[2] == 'from':
110-
return self._drop_from_symbols(message_list)
111-
elif message_list[2] == 'to':
112-
return self._drop_to_symbols(message_list)
113-
else:
114-
return 'There was an issue processing your request.'
115-
116-
def _drop_from_symbols(self, message_list):
117-
try:
118-
drop_fsyms = message_list[3].split(',')
119-
old_fsyms = self.crypto_index['crypto_index']['fsyms'].split(',')
120-
new_fsyms = set(old_fsyms).symmetric_difference(set(drop_fsyms))
121-
self.crypto_index['crypto_index']['fsyms'] = ','.join(new_fsyms)
122-
with open('crypto_index.ini', 'w') as configfile:
123-
self.crypto_index.write(configfile)
124-
return self._list_hodl_symbols(message_list)
125-
except:
126-
return ('Please supply additional arguments, e.g.:\n'
127-
'!hodl drop from BTC,LTC')
128-
129-
def _drop_to_symbols(self, message_list):
13027
try:
131-
drop_tsyms = message_list[3].split(',')
132-
old_tsyms = self.crypto_index['crypto_index']['tsyms'].split(',')
133-
new_tsyms = set(old_tsyms).symmetric_difference(set(drop_tsyms))
134-
self.crypto_index['crypto_index']['tsyms'] = ','.join(new_tsyms)
135-
with open('crypto_index.ini', 'w') as configfile:
136-
self.crypto_index.write(configfile)
137-
return self._list_hodl_symbols(message_list)
28+
query = message['text'].split()[1]
13829
except:
139-
return ('Please supply additional arguments, e.g.:\n'
140-
'!hodl drop to BTC,LTC')
30+
self.reply(message, "Invalid query", opts)
14131

142-
def _lookup_multi(self):
143-
multi_url = self._build_index_url()
144-
get_multi = requests.get(multi_url)
145-
if get_multi.status_code == requests.codes.ok:
146-
api_response = json.loads(get_multi.text)
147-
return self._parse_multi_price_response(api_response)
148-
else:
149-
return 'There was an error getting the data: ' + get_multi.text
150-
151-
def _parse_multi_price_response(self, api_response):
152-
return_val = ''
153-
for key, value in api_response.items():
154-
return_val += key + ': | '
155-
for key, value in value.items():
156-
return_val += '{} {} | '.format(value, key)
157-
return_val += '\n'
158-
return return_val
32+
self.reply(message, self._lookup_symbol(query), opts)
15933

16034
def _lookup_symbol(self, query):
16135
query = query.upper()
@@ -166,21 +40,26 @@ def _lookup_symbol(self, query):
16640
params['tsyms'] = 'USD' # tsyms, the SYMbolS to convert To
16741
else:
16842
params['tsyms'] = 'USD,BTC' # tsyms, the SYMbolS to convert To
169-
request_url = self._build_index_url()
17043
api_response = requests.get(request_url, params=params)
17144
if api_response.status_code == requests.codes.ok:
172-
if 'There is no data for the symbol' in api_response['Message']:
45+
api_response = json.loads(api_response.text)
46+
if 'Message' in api_response and \
47+
'There is no data for the symbol' in api_response['Message']:
17348
matched_items = self._search_symbol(query)
174-
params['fsym'] = matched_items[0]['symbol']
175-
api_response = requests.get(request_url, params=params)
176-
if api_response.status_code == requests.codes.ok:
177-
api_response = json.loads(api_response.text)
178-
query = matched_items[0]['symbol']
179-
meta = 'Did you mean {}?'.format(matched_items[0]['name'])
180-
return self._parse_api_response(
181-
api_response, query, meta=meta)
49+
if len(matched_items) > 0:
50+
params['fsym'] = matched_items[0]['symbol']
51+
api_response = requests.get(request_url, params=params)
52+
if api_response.status_code == requests.codes.ok:
53+
api_response = json.loads(api_response.text)
54+
query = matched_items[0]['symbol']
55+
meta = 'Did you mean {}?'.format(
56+
matched_items[0]['name'])
57+
return self._parse_api_response(
58+
api_response, query, meta=meta)
59+
else:
60+
return 'We had trouble getting that ticker price.'
18261
else:
183-
return 'We had trouble getting that ticker price.'
62+
return 'Could not match "{}" to a symbol.'.format(query)
18463
else:
18564
return self._parse_api_response(api_response, query)
18665
else:
@@ -197,7 +76,8 @@ def _search_symbol(self, query):
19776
matched_items = []
19877
for coin in api_list['Data']:
19978
full_name = api_list['Data'][coin]['FullName']
200-
if query in full_name.lower():
79+
logger.debug('FULL NAME: ' + full_name)
80+
if query.lower() in full_name.lower():
20181
matched_items.append({"symbol": coin, "name": full_name})
20282

20383
return matched_items
@@ -206,31 +86,20 @@ def _search_symbol(self, query):
20686
return 'There was an error fetching the list'
20787

20888
def _parse_api_response(self, api_response, query, **kwargs):
89+
return_val = ''
20990
if 'meta' in kwargs:
210-
return_val = kwargs['meta'] + '\n'
211-
return_val = return_val + query + ': | '
91+
return_val += kwargs['meta'] + '\n'
92+
return_val += query + ': | '
21293
for key, value in api_response.items():
21394
return_val += '{} {} | '.format(value, key)
21495
if query == 'DOGE':
21596
return_val = 'WOW! {} TO THE MOON!!!'.format(return_val)
21697
return return_val
21798

218-
def _build_index_url(self):
219-
baseurl = 'https://min-api.cryptocompare.com/data/pricemulti'
220-
fsyms = self.crypto_index['crypto_index']['fsyms']
221-
tsyms = self.crypto_index['crypto_index']['tsyms']
222-
return baseurl + '?fsyms=' + fsyms + '&tsyms=' + tsyms
223-
22499
def get_name(self):
225100
return 'crypto'
226101

227102
def get_help(self):
228103
return ('Lookup a crypto symbol\'s value. Usage: !crypto <symbol>.\n'
229-
'List of symbols here: '
230-
'https://min-api.cryptocompare.com/data/all/coinlist.\n'
231-
'Usage for !hodl:\n'
232-
'!hodl -- returns prices for multiple coins at once.\n'
233-
'!hodl list -- returns the list of coins to convert from/to.\n'
234-
'!hodl <add/drop> <to/from> <comma separated symbols list>'
235-
' -- adds or drop list of symbols to the convert to or convert'
236-
' from list.')
104+
'List of symbols here:\n'
105+
'https://min-api.cryptocompare.com/data/all/coinlist.')

0 commit comments

Comments
 (0)