-
Notifications
You must be signed in to change notification settings - Fork 4
/
tricebot.py
313 lines (277 loc) · 10.5 KB
/
tricebot.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import zipfile
import urllib.parse
import tempfile
import requests
import re
class GameMade:
def __init__(self, success: bool, gameID: int, replayName: str):
self.success = success
self.gameID = gameID
self.replayName = replayName
class TriceBot:
# Set externURL to the domain address and apiURL to the loopback address in LAN configs
def __init__(
self, authToken: str, apiURL: str = "https://0.0.0.0:8000", externURL: str = ""
):
self.authToken = authToken
self.apiURL = apiURL
if externURL == "":
self.externURL = self.apiURL
else:
self.externURL = externURL
# verify = false as self signed ssl certificates will cause errors here
def req(self, urlpostfix: str, data: str, abs: bool = False) -> str:
print(data)
url = urlpostfix
if not abs:
url = f"{self.apiURL}/{url}"
resp = requests.get(url, timeout=7.0, data=data, verify=False).text
if not abs:
print(resp)
return resp
def reqBin(self, urlpostfix: str, data: str, abs: bool = False) -> str:
print(data)
url = urlpostfix
if not abs:
url = f"{self.apiURL}/{url}"
resp = requests.get(url, timeout=7.0, data=data, verify=False).content
if not abs:
print(resp)
return resp
def reqBin(self, urlpostfix: str, data: str, abs: bool = False) -> str:
print(data)
url = urlpostfix
if not abs:
url = f"{self.apiURL}/{url}"
resp = requests.get(url, timeout=7.0, data=data, verify=False).content
if not abs:
print(resp)
return resp
def checkauthkey(self):
return self.req("api/checkauthkey", self.authToken) == "1"
def getDownloadLink(self, replayName: str) -> str:
return f"{self.externURL}/{replayName}"
# Returns 1 if the game was ended and, 0 if there was an error
def endGame(self, gameid):
data = f"authtoken={self.authToken}\n"
data += f"gameid={gameid}"
res = self.req("api/endgame", data)
if res == "success":
return 1
return 0
# Returns the zip file which contains all of the downloaded files
# Returns none if the zip file would be empty or if there was an IOError
def downloadReplays(self, replayURLs, replaysNotFound=[]):
# Download all the replays
replayStrs = []
replayNames = []
# Iterate over each replay url
for replayURL in replayURLs:
try:
res = self.reqBin(
replayURL.replace(self.externURL, self.apiURL), "", abs=True
)
split = replayURL.split("/")
name = urllib.parse.unquote(split[len(split) - 1])
try:
if (
res.decode() == "error 404"
or re.match("Not found \[.*\]", res.decode())
or re.match("<!DOCTYPE html>.*", res.decode())
or re.match("<html>.*", res.decode())
):
# Error file not found
replaysNotFound.append(name)
# print(res == "error 404")
# print(re.match("Not found \[.*\]", res))
# print(re.match("<!DOCTYPE html>.*", res))
else:
# Create a temp file and write the data
replayStrs.append(res)
replayNames.append(name)
except UnicodeDecodeError as e:
print(e) # This means we got binary :)
# Create a temp file and write the data
replayStrs.append(res)
replayNames.append(name)
except OSError as exc:
# Network issues
print("[TRICEBOT ERROR]: Netty error")
replaysNotFound.append(replayURL)
# Create zip file then close the temp files
try:
if len(replayStrs) == 0:
return None
tmpFile = tempfile.TemporaryFile(
mode="wb+", suffix="tricebot.py", prefix="replaydownloads.zip"
)
# tmpFile = open("I hate python.zip", "wb+")
zipf = zipfile.ZipFile(tmpFile, "w", zipfile.ZIP_DEFLATED)
for i in range(0, len(replayStrs)):
replayStr = replayStrs[i]
name = replayNames[i]
zipf.writestr(name, replayStr)
zipf.close()
tmpFile.seek(0)
return tmpFile
except IOError as exc:
print(exc)
return None
# Returns:
# 1 if the operation was a success
# 2 if the slot was occupied (warns the admin that a player may need to be kicked)
# 0 if a network error occurred
# -1 if the game was not found
# -2 if the player slot was not found
def changePlayerInfo(self, gameID: int, oldPlayerName: str, newPlayerName: str):
body = f"authtoken={self.authToken}\n"
body += f"oldplayername={oldPlayerName}\n"
body += f"newplayername={newPlayerName}\n"
body += f"gameid={gameID}"
res = ""
try:
res = self.req("api/updateplayerinfo", body)
except OSError as exc:
# Network issues
print("[TRICEBOT ERROR]: Netty error")
res = "network error"
if res == "success":
return 1
elif res == "success but occupied":
return 2
elif res == "error game not found":
return -1
elif res == "error player not found":
return -2
else:
return 0
# 1 if success
# 0 auth token is bad, error 404 or network issue
# -1 game not found
def disablePlayerDeckVerificatoin(self, gameID: str) -> int:
body = f"authtoken={self.authToken}\n"
body += f"gameid={gameID}"
res = ""
try:
res = self.req("api/disableplayerdeckverification", body)
except OSError as exc:
# Network issues
print("[TRICEBOT ERROR]: Netty error")
res = "network error"
return 0
if res == "success":
return 1
elif res == "error 404" or "invalid auth token":
return 0
elif res == "game not found":
return -1
return 0
# 1 if success
# 0 auth token is bad or error404 or network issue
# -1 if player not found
# -2 if an unknown error occurred
def kickPlayer(self, gameID: int, name: str) -> int:
body = f"authtoken={self.authToken}\n"
body += f"gameid={gameID}\n"
body += f"target={name}"
try:
message = self.req("api/kickplayer", body)
except OSError as exc:
# Network issues
print("[TRICEBOT ERROR]: Netty error")
return 0
# Check for server error
if (
message == "timeout error"
or message == "error 404"
or message == "invalid auth token"
):
return 0
if message == "success":
return 1
elif message == "error not found":
return -1
return -2
def createGame(
self,
gamename: str,
password: str,
playercount: int,
spectatorsallowed: bool,
spectatorsneedpassword: bool,
spectatorscanchat: bool,
spectatorscanseehands: bool,
onlyregistered: bool,
playerdeckverification: bool,
playernames,
deckHashes,
):
if len(playernames) != len(deckHashes):
GameMade(False, -1, -1) # They must the same length dummy!
body = f"authtoken={self.authToken}\n"
body += f'gamename={gamename.replace(" ", "").replace("_", "")}\n'
body += f"password={password}\n"
body += f"playerCount={playercount}\n"
body += f"spectatorsAllowed={int(spectatorsallowed)}\n"
body += f"spectatorsNeedPassword={int(spectatorsneedpassword)}\n"
body += f"spectatorsCanChat={int(spectatorscanchat)}\n"
body += f"spectatorsCanSeeHands={int(spectatorscanseehands)}\n"
body += f"onlyRegistered={int(onlyregistered)}\n"
body += f"playerDeckVerification={int(playerdeckverification)}\n"
if playerdeckverification:
for i in range(0, len(playernames)):
if playernames[i] == "" or playernames[i] == None: # No name
body += f"playerName=*\n"
else:
body += f"playerName={playernames[i]}\n"
if len(deckHashes[i]) == 0:
body += f"deckHash=*\n"
else:
for deckHash in deckHashes[i]:
body += f"deckHash={deckHash}\n"
try:
message = self.req("api/creategame", body)
print(message)
except OSError as exc:
# Network issues
print("[TRICEBOT ERROR]: Netty error")
return GameMade(False, -1, "")
# Check for server error
if (
(message.lower() == "timeout error")
or (message.lower() == "error 404")
or (message.lower() == "invalid auth token")
):
# Server issues
print("[TRICEBOT ERROR]: " + message)
return GameMade(False, -1, "")
# Try to parse the message
lines = message.split("\n")
gameID: int = -1
replayName: str = ""
# Parse line for line
for line in lines:
parts = line.split("=")
# Check length
if len(parts) >= 2:
tag = parts[0]
value = ""
for i in range(1, len(parts)):
value += parts[i]
if i != len(parts) - 1:
value += "="
if tag == "gameid":
# There has to be a better way to do this
try:
gameID = int(value)
except:
# Error checked at end
pass
elif tag == "replayName":
replayName = urllib.parse.quote(value)
# Ignore other tags
# Ignores lines that have no equals in them
# Check if there was an error
success = (gameID != -1) and (replayName != "")
print(success)
return GameMade(success, gameID, replayName)