-
Notifications
You must be signed in to change notification settings - Fork 7
/
TableBot.py
534 lines (436 loc) · 19.9 KB
/
TableBot.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
'''
Created on Jul 30, 2020
@author: willg
'''
from collections import defaultdict
import WiimmfiSiteFunctions
import SmartTypes
import Room
import War
from datetime import datetime
import humanize
import common
from typing import TYPE_CHECKING, Dict, Tuple, Union, List
import ServerFunctions
import asyncio
from data_tracking import DataTracker
import TimerDebuggers
import copy
import re
if TYPE_CHECKING:
from Components import PictureView
lorenzi_style_key = "#style"
#The key and first item of the tuple are sent when the list of options is requested, the second value is the code Lorenzi's site uses
styles = {"1":("Default", "default style"),
"2":("Dark Theme", "dark"),
"3":("Color by Ranking", "rank"),
"4":("Mario Kart Universal", "mku"),
"5":("200 League", "200l"),
"6":("America's Cup", "americas"),
"7":("Euro League", "euro"),
"8":("マリオカートチームリーグ戦", "japan"),
"9":("Clan War League", "cwl"),
"10":("Runners Assemble", "runners"),
"11":("Mario Kart Worlds", "mkworlds")
}
lorenzi_graph_key = "#graph"
#The key and first item of the tuple are sent when the list of options is requested, the second value is the code Lorenzi's site uses
graphs = {"1":("None", "default graph"),
"2":("Absolute", "abs"),
"3":("Difference (Two Teams Only)", "diff")
}
DEFAULT_DC_POINTS = 3
last_wp_button: Dict[int, 'PictureView'] = {}
last_sug_view = {}
active_components = defaultdict(list)
class ChannelBot(object):
'''
classdocs
'''
def __init__(self, prev_command_sw=False, room=None, war=None, manualWarSetup=False, server_id=None, channel_id=None):
self.room:Room.Room = room
self.war:War.War = war
self.prev_command_sw = prev_command_sw
self.manualWarSetUp = manualWarSetup
self.last_used = datetime.now()
self.loungeFinishTime = None
self.lastWPTime = None
self.roomLoadTime = None
self.save_states = []
self.state_pointer = -1
self.resolved_errors = set() # this one isn't part of the save state
self.semi_resolved_errors = set() # this one is
self.should_send_mii_notification = True
self.set_style_and_graph(server_id)
self.set_dc_points(server_id)
self.server_id = server_id
self.channel_id = channel_id
self.race_size = 4
self.has_been_lounge_submitted = False
def is_table_loaded(self) -> bool:
return self.room is not None and self.war is not None
def get_race_size(self):
return self.race_size
def get_room(self):
return self.room
def get_war(self):
return self.war
def get_prev_command_sw(self):
return self.prev_command_sw
def get_manual_war_set_up(self):
return self.manualWarSetUp
def get_last_used(self):
return self.last_used
def get_lounge_finish_time(self):
return self.loungeFinishTime
def get_last_wptime(self):
return self.lastWPTime
def get_room_load_time(self):
return self.roomLoadTime
def get_save_states(self):
return self.save_states
def get_redo_states(self):
return self.redo_save_states
def get_should_send_mii_notification(self):
return self.should_send_mii_notification
def get_server_id(self):
return self.server_id
def get_channel_id(self):
return self.channel_id
def get_graph(self):
return self.graph
def get_style(self):
return self.style
def get_dc_points(self):
return self.dc_points
def get_resolved_errors(self):
return self.resolved_errors
def get_semi_resolved_errors(self):
return self.semi_resolved_errors
def get_all_resolved_errors(self):
return self.resolved_errors | self.semi_resolved_errors
def player_to_dc_num(self, race, player):
GPs = self.getWar().getNumberOfGPS()
dc_list = self.getRoom().get_dc_list_players(GPs)
return dc_list.index((race, player))+1
def player_to_num(self, player):
players = self.getRoom().get_sorted_player_list()
players = [player[0] for player in players]
return players.index(player)+1
def get_room_started_message(self):
started_war_str = "FFA started" if self.getWar().isFFA() else "Table started"
if self.getWar().ignoreLargeTimes:
started_war_str += " (ignoring errors for large finish times)"
started_war_str += f". {self.getRoom().getRXXText()}"
started_war_str += F"\n{self.getRoom().get_table_id_text()}"
return started_war_str
def set_race_size(self, new_race_size:int):
self.race_size = new_race_size
def set_style_and_graph(self, server_id):
self.graph = ServerFunctions.get_server_graph(server_id)
self.style = ServerFunctions.get_server_table_theme(server_id)
def set_dc_points(self, server_id):
#self.dc_points = ServerFunctions.get_dc_points(server_id)
self.dc_points = DEFAULT_DC_POINTS
def get_lorenzi_style_and_graph(self, prepend_newline=True):
result = '\n' if prepend_newline else ''
result += self.get_lorenzi_style_str() + "\n"
result += self.get_lorenzi_graph_str()
return result
def get_lorenzi_style_str(self) -> str:
if self.style not in styles:
return f"{lorenzi_style_key} {styles['1'][1]}"
else:
return f"{lorenzi_style_key} {styles[self.style][1]}"
def get_lorenzi_graph_str(self) -> str:
if self.graph not in graphs:
return f"{lorenzi_graph_key} {graphs['1'][1]}"
else:
return f"{lorenzi_graph_key} {graphs[self.graph][1]}"
def set_style(self, new_style):
if new_style not in styles:
return False
self.style = new_style
return True
def set_graph(self, new_graph):
if new_graph not in graphs:
return False
self.graph = new_graph
return True
def get_style_name(self, style=None):
if style is None:
return styles[self.style][0]
if style in styles:
return styles[style][0]
else:
"Error"
def get_graph_name(self, graph=None):
if graph is None:
return graphs[self.graph][0]
if graph in graphs:
return graphs[graph][0]
else:
"Error"
def is_valid_style(self, style):
return style in styles
def is_valid_graph(self, graph):
return graph in graphs
#Caller must ensure the dict is in the format key=str, value=tuple(str, str)
def __get_list_text__(self, dict_list:Dict[str, Tuple[str, str]]):
final_text = ""
for key, (display_text, _) in dict_list.items():
final_text += f"`{key}.` {display_text}\n"
return final_text.strip('\n')
def get_style_list_text(self):
return self.__get_list_text__(styles)
def get_graph_list_text(self):
return self.__get_list_text__(graphs)
def getBotunlockedInStr(self):
if self.is_table_loaded() or self.room.is_freed or len(self.room.races) < 12:
return None
time_passed_since_lounge_finish = datetime.now() - self.loungeFinishTime
cooldown_time = time_passed_since_lounge_finish - common.lounge_inactivity_time_period
return "Bot will become unlocked " + humanize.naturaltime(cooldown_time)
def updateLoungeFinishTime(self):
if self.loungeFinishTime is None and self.is_table_loaded() and len(self.room.races) >= self.war.numberOfGPs*4:
self.loungeFinishTime = datetime.now()
@TimerDebuggers.timer_coroutine
async def update_table(self) -> WiimmfiSiteFunctions.RoomLoadStatus:
'''RETURNS NO_ROOM_LOADED, HAS_NO_RACES, FAILED_REQUEST, SUCCESS'''
if not self.is_table_loaded():
return WiimmfiSiteFunctions.RoomLoadStatus(WiimmfiSiteFunctions.RoomLoadStatus.NO_ROOM_LOADED)
status = await self.room.update()
if status:
await DataTracker.RoomTracker.add_data(self) # Must come before adjustments are applied
self.room.apply_tabler_adjustments()
self.updateLoungeFinishTime()
asyncio.create_task(self.room.populate_miis()) # Must come after adjustments are applied
return status
async def verify_room_smart(self, smart_type: SmartTypes.SmartLookupTypes) -> Tuple[WiimmfiSiteFunctions.RoomLoadStatus, Union[None, Room.Race.Race]]:
'''RETURNS NOT_ON_FRONT_PAGE, NO_KNOWN_FCS, FAILED_REQUEST, SUCCESS'''
status_code, front_race = await WiimmfiSiteFunctions.get_front_race_smart(smart_type, hit_lounge_api=True)
return status_code, front_race
@TimerDebuggers.timer_coroutine
async def load_table_smart(self, smart_type: SmartTypes.SmartLookupTypes, war, message_id=None, setup_discord_id=0, setup_display_name="") -> WiimmfiSiteFunctions.RoomLoadStatus:
status, rxx, room_races = await WiimmfiSiteFunctions.get_races_smart(smart_type, hit_lounge_api=True)
if not status:
return status
self.reset()
room = Room.Room(self, rxx, room_races, message_id, setup_discord_id, setup_display_name)
self.setWar(war)
self.setRoom(room)
asyncio.create_task(self.room.populate_miis()) # We can create this task before adjustments are applied since calling this load_room_smart function loads a new room (with no real tabler adjustments)
# Make call to database to add data
await DataTracker.RoomTracker.add_data(self)
if self.getWar() is None: # The caller should have ensured that a war is set - dangerous game to play!
return WiimmfiSiteFunctions.RoomLoadStatus(WiimmfiSiteFunctions.RoomLoadStatus.SUCCESS_BUT_NO_WAR)
return WiimmfiSiteFunctions.RoomLoadStatus(WiimmfiSiteFunctions.RoomLoadStatus.SUCCESS)
async def add_room_races(self, rxx: str):
if not self.is_table_loaded():
return WiimmfiSiteFunctions.RoomLoadStatus(WiimmfiSiteFunctions.RoomLoadStatus.NO_ROOM_LOADED)
self.room.add_rxx(rxx)
# Important: We do NOT want to add data to database when this is called. The previous races are MODIFIED, we should NOT add modified races to the database - the new races will be added to the database when they call room.update()
# await DataTracker.RoomTracker.add_data(self)
return await self.update_table()
# self.room.apply_tabler_adjustments()
# asyncio.create_task(self.room.populate_miis()) # We must create this task after adjustments are applied since the adjustments applied to the new races may affect which miis we pull
# if self.getWar() is None: # The caller should have ensured that a war is set - dangerous game to play!
# return WiimmfiSiteFunctions.RoomLoadStatus(WiimmfiSiteFunctions.RoomLoadStatus.SUCCESS_BUT_NO_WAR)
# return WiimmfiSiteFunctions.RoomLoadStatus(WiimmfiSiteFunctions.RoomLoadStatus.SUCCESS)
def setRoom(self, room):
self.room = room
self.updateLoungeFinishTime()
def getRoom(self) -> Room.Room:
return self.room
def setWar(self, war):
self.war = war
def getWar(self) -> War.War:
return self.war
def updatedLastUsed(self):
self.last_used = datetime.now()
self.updateLoungeFinishTime()
def updateWPCoolDown(self):
self.lastWPTime = datetime.now()
def shouldSendNotificiation(self) -> bool:
if self.is_table_loaded():
return self.should_send_mii_notification
return False
def setShouldSendNotification(self, should_send_mii_notification):
self.should_send_mii_notification = should_send_mii_notification
def getWPCooldownSeconds(self) -> int:
if self.should_send_mii_notification:
self.should_send_mii_notification = False
if common.is_dev:
return 0
if self.lastWPTime is None:
return 0
curTime = datetime.now()
time_passed = curTime - self.lastWPTime
return max(0, common.wp_cooldown_seconds - int(time_passed.total_seconds()))
def updateRLCoolDown(self):
self.roomLoadTime = datetime.now()
def getRLCooldownSeconds(self) -> int:
if common.is_dev:
return 0
if self.roomLoadTime is None:
return 0
curTime = datetime.now()
time_passed = curTime - self.roomLoadTime
return max(0, common.mkwx_page_cooldown_seconds - int(time_passed.total_seconds()))
def isFinishedLounge(self) -> bool:
if self.getRoom() is None or not self.getRoom().is_initialized():
return True
if self.room.is_freed:
return True
if self.lastWPTime is not None:
time_passed_since_last_wp = datetime.now() - self.lastWPTime
if time_passed_since_last_wp > common.inactivity_unlock:
return True
time_passed_since_last_used = datetime.now() - self.last_used
if time_passed_since_last_used > common.inactivity_unlock:
return True
if self.loungeFinishTime is None:
return False
time_passed_since_lounge_finish = datetime.now() - self.loungeFinishTime
return time_passed_since_lounge_finish > common.lounge_inactivity_time_period
def freeLock(self):
if self.is_table_loaded():
self.room.is_freed = True
#self.room.set_up_user = None
#self.room.set_up_user_display_name = ""
#self.loungeFinishTime = None
def isInactive(self):
curTime = datetime.now()
time_passed_since_last_used = curTime - self.last_used
return time_passed_since_last_used > common.inactivity_time_period
def get_save_state(self, command="Unknown Command"):
save_state = {}
save_state["War"] = self.getWar().get_recoverable_save_state()
save_state["Room"] = self.getRoom().get_recoverable_save_state()
save_state["graph"] = self.graph
save_state["race_size"] = self.race_size
save_state["style"] = self.style
save_state['semi_resolved_errors'] = copy.copy(self.semi_resolved_errors)
return (command, save_state)
def add_save_state(self, command="Unknown Command", save_state=None):
if save_state is None:
command, save_state = self.get_save_state(command)
self.save_states = self.save_states[:self.state_pointer+1] #clear all "redo" states
self.save_states.append((command, save_state)) #append new state
self.state_pointer += 1 #increment state pointer (state pointer always points to previous save state)
#Function that removes the last save state - does not restore it
def remove_last_save_state(self):
if len(self.save_states) < 1 or self.state_pointer < 0:
return False
command, _ = self.save_states.pop(self.state_pointer)
return command
#removes last "redo"
def remove_last_redo_state(self):
if len(self.save_states) <1 or self.state_pointer+1 >= len(self.save_states):
return False
return self.save_states.pop(self.state_pointer+1)[0]
def get_undo_list(self):
ret = "Undoable commands:"
undos = self.save_states[:self.state_pointer+1]
if len(undos)==0:
return "No commands to undo."
for i, (command, _) in enumerate(undos[::-1]):
command = re.sub(r"<@!?(\d{15,20})>\s*", "/", command)
ret+=f'\n {i+1}. `{command}`'
return ret
def get_redo_list(self):
ret = "Redoable commands:"
redos = self.save_states[self.state_pointer+1:-1]
if len(redos)==0:
return "No commands to redo."
for i, (command, _) in enumerate(redos):
command = re.sub(r"<@!?(\d{15,20})>\s*", "/", command)
ret+=f'\n {i+1}. `{command}`'
return ret
#restores previous state (?undo)
def restore_last_save_state(self, do_all=False):
if len(self.save_states) < 1 or self.state_pointer < 0:
return False
if self.state_pointer+1 == len(self.save_states):
self.add_save_state(command=None) #save the current state before reverting to the previous state if it hasn't been saved yet
self.state_pointer-=1
if do_all:
self.state_pointer = 0
command, save_state = self.save_states[self.state_pointer]
self.state_pointer-=1
self.getRoom().restore_save_state(save_state["Room"])
self.getWar().restore_save_state(save_state["War"])
self.graph = save_state["graph"]
self.style = save_state["style"]
self.race_size = save_state["race_size"]
self.semi_resolved_errors = copy.copy(save_state['semi_resolved_errors'])
return command
#restores to the following state (?redo)
def restore_last_redo_state(self, do_all=False):
if len(self.save_states) <1 or self.state_pointer+2 >= len(self.save_states):
return False
if do_all:
self.state_pointer=len(self.save_states)-2
else:
if self.state_pointer+2 < len(self.save_states):
self.state_pointer+=1
command, save_state = self.save_states[self.state_pointer][0], self.save_states[self.state_pointer+1][1]
self.getRoom().restore_save_state(save_state["Room"])
self.getWar().restore_save_state(save_state["War"])
self.graph = save_state["graph"]
self.style = save_state["style"]
self.race_size = save_state["race_size"]
self.semi_resolved_errors = copy.copy(save_state['semi_resolved_errors'])
return command
async def clear_last_wp_button(self):
try:
await last_wp_button[self.channel_id].on_timeout()
last_wp_button.pop(self.channel_id, None)
except Exception:
pass
def add_sug_view(self, view):
# self.clear_last_sug_view()
last_sug_view[self.channel_id] = view
def clear_last_sug_view(self):
try:
view = last_sug_view.pop(self.channel_id, None)
if view:
asyncio.create_task(view.on_timeout())
except Exception:
pass
def add_component(self, component):
active_components[self.channel_id].append(component)
def clear_all_components(self):
components = active_components.pop(self.channel_id, [])
for c in components:
try:
asyncio.create_task(c.on_timeout())
except Exception:
pass
def unload_table(self):
if self.is_table_loaded():
self.room.destroy()
self.setRoom(None)
self.setWar(None)
def destroy(self):
asyncio.create_task(self.clear_last_wp_button())
self.clear_last_sug_view()
self.clear_all_components()
self.unload_table()
def reset(self):
self.destroy()
self.prev_command_sw = False
self.manualWarSetUp = False
self.last_used = datetime.now()
self.loungeFinishTime = None
#Don't reset these, these are needed to prevent abuse to Wiimmfi and Lorenzi's site
#self.lastWPTime = None
#self.roomLoadTime = None
self.save_states = []
self.state_pointer = -1
self.resolved_errors = set()
self.semi_resolved_errors = set()
self.should_send_mii_notification = True
self.set_style_and_graph(self.server_id)
self.race_size = 4
self.has_been_lounge_submitted = False