←︎ irccex :: 55d5438


1
commit 55d54389c46a8fbf76666a48f558fbea185e21e7
2
Author: acidvegas <acid.vegas@acid.vegas>
3
Date:   Sat Mar 21 03:14:11 2020 -0400
4
5
    Added double fees loop, removed all 3rd party library requirements, cleaned up
6
---
7
 README.md                                |  3 ++-
8
 irccex/core/{cmc.py => coinmarketcap.py} | 29 ++++++++++----------
9
 irccex/core/config.py                    |  1 -
10
 irccex/core/irc.py                       | 45 +++++++++++++++++++++++---------
11
 irccex/data/cert/.gitignore              |  4 ---
12
 irccex/data/dbx.py                       | 12 ---------
13
 irccex/data/logs/.gitignore              |  4 ---
14
 7 files changed, 48 insertions(+), 50 deletions(-)
15
16
diff --git a/README.md b/README.md
17
index 49e4cc3..788783c 100644
18
--- a/README.md
19
+++ b/README.md
20
@@ -83,15 +83,16 @@ Support the project development if you like it: [Patreon.com/irccex](https://pat
21
 The IRCCEX project is completely open source & non-profit, though any support/pledges will help in motivation towards more development and adding new features!
22
 
23
 ###### Future Concepts & Ideas
24
+* Use multiple API keys to prevent rate limiting.
25
 * IRCCEX BlockChain - Keep an on-going ledger of every single transaction ever made in the channel. *(No idea what use it would have. Maybe a `!trades` command for recent history. The idea makes me laugh)*
26
 * Buying options - Spend a large sum of money on features like locking someone from trading for X amount of time (Charge Y per hour and max it to 24 hours), wallet spying, wallet bombing (sending a bunch of shitcoins), hindsight where you get private message alerts on a coins price changing (can be used whenever only once).
27
-* Double fees for 1-3 days randomly in round!
28
 * Post reward pool bangs will make you lose money to fuck with people spamming hard with bots to rack up the pool
29
 * Crate Drops - A "crate" will drop randomly in the channel that requires multiple `!break`'s to open it. Once opened, there will be 4 items you can get by typing the ! command under it. Items will include money, extra privlegges like holding more coins, and other items you can win.
30
 * **Suicide Round** - There is no bank in this mode, and if you lose your nick through a NICK or QUIT, you lose your wallet. Round can last 3-7 days and the top 10 wallets will score.
31
 * **Bank Round** - Round lasts a week and the top 10 players in the bank will score.
32
 * **Flash Match** - Round lasts a day and the top 10 players in the bank will score.
33
 
34
+###### Try it out
35
 We are running IRCCEX actively in **#exchange** on **EFNet** & **SuperNETs**, come chat with us, make some money, and share ideas!
36
 
37
 ###### Mirrors
38
diff --git a/irccex/core/cmc.py b/irccex/core/coinmarketcap.py
39
similarity index 63%
40
rename from irccex/core/cmc.py
41
rename to irccex/core/coinmarketcap.py
42
index 7a2a2d9..3d2cfe3 100644
43
--- a/irccex/core/cmc.py
44
+++ b/irccex/core/coinmarketcap.py
45
@@ -1,24 +1,23 @@
46
 #!/usr/bin/env python
47
-# IRC Cryptocurrency Exchange (IRCCEX) - Developed by acidvegas in Python (https://acid.vegas/irccex)
48
-# cmc.py
49
+# CoinMarketCap API Class - Developed by acidvegas in Python (https://acid.vegas/coinmarketcap)
50
 
51
+import http.client
52
 import json
53
 import time
54
-
55
-import requests
56
-
57
-import config
58
+import zlib
59
 
60
 class CoinMarketCap(object):
61
-	def __init__(self):
62
-		self.cache = {'global':dict(), 'ticker':dict()}
63
-		self.last  = {'global':0     , 'ticker':0     }
64
+	def __init__(self, api_key):
65
+		self.api_key = api_key
66
+		self.cache   = {'global':dict(), 'ticker':dict()}
67
+		self.last    = {'global':0     , 'ticker':0     }
68
 
69
-	def _api(self, _endpoint, _params={}):
70
-		session = requests.Session()
71
-		session.headers.update({'Accept':'application/json', 'Accept-Encoding':'deflate, gzip', 'X-CMC_PRO_API_KEY':config.CMC_API_KEY})
72
-		response = session.get('https://pro-api.coinmarketcap.com/v1/' + _endpoint, params=_params, timeout=15)
73
-		return json.loads(response.text.replace(': null', ': "0"'))['data']
74
+	def _api(self, _endpoint):
75
+		conn = http.client.HTTPSConnection('pro-api.coinmarketcap.com', timeout=15)
76
+		conn.request('GET', '/v1/' + _endpoint, headers={'Accept':'application/json', 'Accept-Encoding':'deflate, gzip', 'X-CMC_PRO_API_KEY':self.api_key})
77
+		response = zlib.decompress(conn.getresponse().read(), 16+zlib.MAX_WBITS).decode('utf-8').replace(': null', ': "0"')
78
+		conn.close()
79
+		return json.loads(response)['data']
80
 
81
 	def _global(self):
82
 		if time.time() - self.last['global'] < 300:
83
@@ -40,7 +39,7 @@ class CoinMarketCap(object):
84
 		if time.time() - self.last['ticker'] < 300:
85
 			return self.cache['ticker']
86
 		else:
87
-			data = self._api('cryptocurrency/listings/latest', {'limit':'5000'})
88
+			data = self._api('cryptocurrency/listings/latest?limit=5000')
89
 			self.cache['ticker'] = dict()
90
 			for item in data:
91
 				self.cache['ticker'][item['symbol']] = {
92
diff --git a/irccex/core/config.py b/irccex/core/config.py
93
index 81e4b3c..f1c56e3 100644
94
--- a/irccex/core/config.py
95
+++ b/irccex/core/config.py
96
@@ -15,7 +15,6 @@ class connection:
97
 
98
 class cert:
99
 	key      = None
100
-	file     = None
101
 	password = None
102
 
103
 class ident:
104
diff --git a/irccex/core/irc.py b/irccex/core/irc.py
105
index 09d5ea8..c5b3491 100644
106
--- a/irccex/core/irc.py
107
+++ b/irccex/core/irc.py
108
@@ -20,7 +20,7 @@ import time
109
 import config
110
 import constants
111
 import functions
112
-from cmc import CoinMarketCap
113
+from coinmarketcap import CoinMarketCap
114
 
115
 if config.connection.ssl:
116
 	import ssl
117
@@ -43,8 +43,8 @@ class IRC(object):
118
 		self.start       = time.time()
119
 
120
 	def run(self):
121
-		if os.path.isfile('data/db.pkl'):
122
-			with open('data/db.pkl', 'rb') as db_file:
123
+		if os.path.isfile('db.pkl'):
124
+			with open('db.pkl', 'rb') as db_file:
125
 				self.db = pickle.load(db_file)
126
 			print('[+] - Restored database!')
127
 		Loops.start_loops()
128
@@ -62,21 +62,19 @@ class IRC(object):
129
 			self.listen()
130
 
131
 	def create_socket(self):
132
-		family = socket.AF_INET6 if config.connection.ipv6 else socket.AF_INET
133
-		self.sock = socket.socket(family, socket.SOCK_STREAM)
134
+		self.sock = socket.socket(AF_INET6) if config.connection.ipv6 else socket.socket()
135
 		if config.connection.vhost:
136
 			self.sock.bind((config.connection.vhost, 0))
137
 		if config.connection.ssl:
138
 			ctx = ssl.SSLContext()
139
 			if config.cert.file:
140
-				ctx.load_cert_chain(config.cert.file, config.cert.key, config.cert.password)
141
+				ctx.load_cert_chain(config.cert.file, password=config.cert.password)
142
 			if config.connection.ssl_verify:
143
-				ctx.verify_mode = ssl.CERT_REQUIRED
144
+				ctx.check_hostname = True
145
 				ctx.load_default_certs()
146
+				self.sock = ctx.wrap_socket(self.sock, server_hostname=config.connection.server)
147
 			else:
148
-				ctx.check_hostname = False
149
-				ctx.verify_mode = ssl.CERT_NONE
150
-			self.sock = ctx.wrap_socket(self.sock)
151
+				self.sock = ctx.wrap_socket(self.sock)
152
 
153
 	def listen(self):
154
 		while True:
155
@@ -204,7 +202,7 @@ class Events:
156
 										Commands.sendmsg(chan, 'Cashed out {0} to your bank account! {1}'.format(color('${:,}'.format(int(amount)), constants.green), color('(current balance: ${:,})'.format(int(Bot.db['bank'][nick][0])), constants.grey)))
157
 							elif len(args) == 1:
158
 								if msg == '@irccex':
159
-									Commands.sendmsg(chan, constants.bold + 'IRC Cryptocurrency Exchange (IRCCEX) - Developed by acidvegas in Python - https://acid.vegas/irccex')
160
+									Commands.sendmsg(chan, constants.bold + 'IRC Cryptocurrency Exchange (IRCCEX) - Developed by acidvegas in Python - https://github.com/acidvegas/irccex')
161
 								elif msg == '@stats':
162
 									bank_total = 0
163
 									global_data = CMC._global()
164
@@ -501,6 +499,7 @@ class Events:
165
 class Loops:
166
 	def start_loops():
167
 		threading.Thread(target=Loops.backup).start()
168
+		threading.Thread(target=Loops.double_fees).start()
169
 		threading.Thread(target=Loops.maintenance).start()
170
 		threading.Thread(target=Loops.remind).start()
171
 		threading.Thread(target=Loops.reward).start()
172
@@ -510,11 +509,31 @@ class Loops:
173
 	def backup():
174
 		while True:
175
 			time.sleep(3600) # 1H
176
-			with open('data/db.pkl', 'wb') as db_file:
177
+			with open('db.pkl', 'wb') as db_file:
178
 				pickle.dump(Bot.db, db_file, pickle.HIGHEST_PROTOCOL)
179
 			Bot.last_backup = time.strftime('%I:%M')
180
 			print('[+] - Database backed up!')
181
 
182
+	def double_fees():
183
+		original_fees = {'cashout':config.fees.cashout,'send':config.fees.send,'trade':config.fees.trade}
184
+		while True:
185
+			try:
186
+				time.sleep(functions.random_int(604800,864000)) # 7D - 10D
187
+				config.fees.cashout = original_fees['cashout']*2
188
+				config.fees.send    = original_fees['send']*2
189
+				config.fees.trade   = original_fees['trade']*2
190
+				Commands.action(config.connection.channel, color('Double fees have been activated!', constants.red))
191
+				time.sleep(functions.random_int(86400, 259200)) # 1D - 3D
192
+				config.fees.cashout = original_fees['cashout']/2
193
+				config.fees.send    = original_fees['send']/2
194
+				config.fees.trade   = original_fees['trade']/2
195
+				Commands.notice(config.connection.channel, color('Double fees have been deactivated!', constants.red))
196
+			except Exception as ex:
197
+				config.fees.cashout = original_fees['cashout']
198
+				config.fees.send    = original_fees['send']
199
+				config.fees.trade   = original_fees['trade']
200
+				print('[!] - Error occured in the double fees loop! (' + str(ex) + ')')
201
+
202
 	def maintenance():
203
 		while True:
204
 			try:
205
@@ -596,5 +615,5 @@ class Loops:
206
 			finally:
207
 				time.sleep(3600) # 1H
208
 
209
-CMC = CoinMarketCap()
210
 Bot = IRC()
211
+CMC = CoinMarketCap(config.CMC_API_KEY)
212
diff --git a/irccex/data/cert/.gitignore b/irccex/data/cert/.gitignore
213
deleted file mode 100644
214
index 86d0cb2..0000000
215
--- a/irccex/data/cert/.gitignore
216
+++ /dev/null
217
@@ -1,4 +0,0 @@
218
-# Ignore everything in this directory
219
-*
220
-# Except this file
221
-!.gitignore
222
diff --git a/irccex/data/dbx.py b/irccex/data/dbx.py
223
deleted file mode 100644
224
index 066067b..0000000
225
--- a/irccex/data/dbx.py
226
+++ /dev/null
227
@@ -1,12 +0,0 @@
228
-import pickle, coinmarketcap
229
-CMC = coinmarketcap.CoinMarketCap()
230
-DB = pickle.load(open('db.pkl' 'rb'))
231
-wallets = dict()
232
-for nick in DB['wallet']:
233
-	total = 0
234
-	for symbol in DB['wallet'][nick]:
235
-		total += DB['wallet'][nick][symbol] if symbol == 'USD' else CMC.get()[symbol]['price_usd']*DB['wallet'][nick][symbol]
236
-	wallets[nick] = total
237
-data = sorted(wallets, key=wallets.get, reverse=True)
238
-for item in data:
239
-	print('[{0:02}] {1} ${2:,}'.format(data.index(item)+1, item.ljust(9), wallets[item]))
240
diff --git a/irccex/data/logs/.gitignore b/irccex/data/logs/.gitignore
241
deleted file mode 100644
242
index 86d0cb2..0000000
243
--- a/irccex/data/logs/.gitignore
244
+++ /dev/null
245
@@ -1,4 +0,0 @@
246
-# Ignore everything in this directory
247
-*
248
-# Except this file
249
-!.gitignore