-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
438 lines (364 loc) · 15.5 KB
/
utils.py
File metadata and controls
438 lines (364 loc) · 15.5 KB
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
import asyncio
import random
from typing import TYPE_CHECKING
import zoneinfo
import datetime
import datetime
import logging
import hikari
from services.avianart import AvianResponsePayload
import app_context as ac
if TYPE_CHECKING:
from services.racetime import LadderRaceHandler
ladder_kwargs = {
"goal": "Beat the game (Group)",
"start_delay": 15,
"time_limit": 6,
"auto_start": False,
"allow_midrace_chat": False,
"allow_non_entrant_chat": True,
"allow_comments": True,
"hide_comments": True,
"streaming_required": True,
"unlisted": False,
"chat_message_delay": 0,
"partitionable": False,
"hide_entrants": False,
}
logger = logging.getLogger("pyladderchicken")
utc = zoneinfo.ZoneInfo("UTC")
est = zoneinfo.ZoneInfo("US/Eastern")
random_post_race_messages = [
"LOL PED SEED",
"Nice flute.",
"Why does StoolChicken hate me?",
"Anyone else finish without pearl?",
"15bb...",
"169, nice.",
"Always a sword in swamp",
"LITERAL LAST LOCATION MITTS",
"Pearl on pyramid, what a surprise.",
"Hard required fireless IP, finally!",
"Hover seed smh",
"Oh course I did X when I should have done Y.",
"What a rude seed.",
"Sword go mode sucks.",
"I should learn glitches...",
]
async def open_race_room(race_id: int):
"""
Opens a room and notifies the Discord channel.
"""
race = ac.database_service.get_scheduled_race_by_id(race_id)
race_utc_datetime = race.time.replace(tzinfo=est).astimezone(utc)
# Convert from EST to UTC
delta_ts = (
datetime.datetime.now(utc) + (race_utc_datetime - datetime.datetime.now(utc))
).timestamp()
ping_roles = ac.database_service.get_default_plus_mode_pingable_roles(
race.mode_obj.id
)
roles_str = ""
for role in ping_roles:
roles_str += f"<@&{role.roleId}> "
race_kwargs = ladder_kwargs.copy()
if race.mode_obj.archetype_obj.ladder:
race_kwargs["goal"] = f"Beat The Game (1v1)"
race_kwargs["partitionable"] = True
# race_kwargs['hide_entrants'] = True
room_name = await ac.racetime_service.start_race(
# We use info_user because it will be concatenated with info_bot later
info_user=f"Step Ladder Series - [{race.mode_obj.archetype_obj.name}] - {race.mode_obj.name}",
**race_kwargs,
)
races_channel_id = ac.database_service.get_setting("races_channel_id")
message = f"{roles_str}\n**[{race.mode_obj.archetype_obj.name}] {race.mode_obj.name}** -- {ac.racetime_service.get_raceroom_url(room_name)} -- <t:{int(delta_ts)}:R>"
if race.mode_obj.archetype_obj.ladder:
message += (
f"\n**This is a 1v1 ladder race using the partitioning system in rt.gg**"
)
if races_channel_id:
await ac.discord_service.send_message(
content=message, channel_id=races_channel_id
)
await ac.discord_service.send_message(content=message)
ac.database_service.add_fired_race(room_name, race)
await update_schedule_message()
return room_name
async def roll_seed(race_id: int):
"""
Rolls a seed for the given slug and namespace.
"""
race = ac.database_service.get_scheduled_race_by_id(race_id)
if not race.raceId:
logger.error(f"Cannot roll seed! Race {race.id} does not have a race room.")
return
room_name = ac.database_service.get_race_by_id(race.raceId).raceRoom.lstrip("/")
namespace = race.mode_obj.slug.split("/")[0] if "/" in race.mode_obj.slug else None
slug = (
race.mode_obj.slug.split("/")[1]
if "/" in race.mode_obj.slug
else race.mode_obj.slug
)
seed_info = await ac.avianart_service.generate_seed(slug, True, namespace=namespace)
retry_count = 0
while retry_count < 10:
if room_name not in ac.racetime_service.handlers:
logger.error(f"Room {room_name} not found in handlers, retrying...")
await asyncio.sleep(5)
retry_count += 1
continue
break
race_handler: LadderRaceHandler = ac.racetime_service.handler_objects.get(
room_name, None
)
if race_handler:
hash_str = seed_response_to_hash(seed_info.response)
await race_handler.send_message(
f"Here is your seed: https://alttpr.racing/getseed.php?race={race.raceId} - ({hash_str})"
)
await race_handler.set_bot_raceinfo(
f"{race.mode_obj.slug} - https://alttpr.racing/getseed.php?race={race.raceId} - ({hash_str})"
)
else:
logger.error(f"No handler found for room: {room_name}")
updated_race = ac.database_service.update_race_seed(
race.raceId, seed_info.response.hash
)
if not updated_race:
logger.error(
f"Failed to update race {race.raceId} with seed ID {seed_info.response.hash}."
)
admin_role = ac.database_service.get_setting("admin_role_id")
admin_ping = f"<@&{admin_role}> " if admin_role else ""
await ac.discord_service.send_message(
content=f"{admin_ping}Failed to update race {race.raceId} with seed ID {seed_info.response.hash}.",
force_mention=True
)
await ac.discord_service.send_message(
content=f"Seed for race {race.raceId}: https://avianart.games/perm/{seed_info.response.hash} (https://alttpr.racing/getseed.php?race={race.raceId})",
suppress_embeds=True
)
# TODO: Supress embeds
racers = race_handler.data.get("entrants", [])
savior_message = None
if (not race.mode_obj.archetype_obj.ladder and len(racers) == 1) or (
race.mode_obj.archetype_obj.ladder and len(racers) % 2 == 1
):
savior_roles = ac.database_service.get_savior_roles(
race.mode_obj.archetype_obj.id
)
logger.debug(f"Only one racer found, pinging savior role(s).")
if savior_roles:
roles_str = " ".join([f"<@&{role.roleId}>" for role in savior_roles])
savior_message = f"{roles_str} - There is only one racer for the following race!\n**{race.mode_obj.name}** -- {ac.racetime_service.get_raceroom_url(room_name)}"
if race.mode_obj.archetype_obj.ladder and len(racers) % 2 == 1:
savior_message = f"{roles_str} - This is a ladder race and there are an odd number of entrants!\n**{race.mode_obj.name}** -- {ac.racetime_service.get_raceroom_url(room_name)}"
races_channel_id = ac.database_service.get_setting("races_channel_id")
if races_channel_id and savior_message:
await ac.discord_service.send_message(
content=savior_message, channel_id=races_channel_id
)
async def ping_unready(race_id: int):
"""
Pings @unready in the Discord channel and racetime.
"""
race = ac.database_service.get_scheduled_race_by_id(race_id)
if not race.raceId:
logger.error(f"Cannot ping unready! Race {race.id} does not have a race room.")
return
room_name = ac.database_service.get_race_by_id(race.raceId).raceRoom.lstrip("/")
retry_count = 0
while retry_count < 10:
if room_name not in ac.racetime_service.handlers:
logger.error(f"Room {room_name} not found in handlers, retrying...")
await asyncio.sleep(5)
retry_count += 1
continue
break
race_handler: LadderRaceHandler = ac.racetime_service.handler_objects.get(
room_name, None
)
await race_handler.send_message(
"@unready Race starting in less than a minute! Ready up or you will be removed!"
)
async def warn_partitioned_race(race_id: int):
"""
Warn users that the race is about to be partitioned.
"""
race = ac.database_service.get_scheduled_race_by_id(race_id)
if not race.raceId:
logger.error(
f"Cannot warn partitioned race! Race {race.id} does not have a race room."
)
return
room_name = ac.database_service.get_race_by_id(race.raceId).raceRoom.lstrip("/")
retry_count = 0
while retry_count < 10:
if room_name not in ac.racetime_service.handlers:
logger.error(f"Room {room_name} not found in handlers, retrying...")
await asyncio.sleep(5)
retry_count += 1
continue
break
race_handler: LadderRaceHandler = ac.racetime_service.handler_objects.get(
room_name, None
)
await race_handler.send_message(
"@entrants Race is about to be partitioned! You will have ~2 minutes to ready up in the partitioned room or you will be disqualified!"
)
await race_handler.send_message(
"If there are an odd number of entrants at the time of partitioning, the last entrant to join will be removed automatically."
)
async def force_start_race(
race_id: int = None, race_room: str = None, ladder: bool = False, suppress_post_race_message: bool = False
):
"""
Forces the start of the race in the Discord channel and racetime.
"""
if not race_room and not ladder:
race = ac.database_service.get_scheduled_race_by_id(race_id)
if not race.raceId:
logger.error(
f"Cannot force start race! Race {race.raceId} does not have a race room."
)
return
room_name = ac.database_service.get_race_by_id(race.raceId).raceRoom.lstrip("/")
elif race_room and ladder:
room_name = race_room.lstrip("/")
race = ac.database_service.get_partitioned_race_by_room_name(
room_name
).parentRace.scheduledRace
retry_count = 0
while retry_count < 10:
if room_name not in ac.racetime_service.handlers:
logger.error(f"Room {room_name} not found in handlers, retrying...")
await asyncio.sleep(5)
retry_count += 1
continue
break
race_handler: LadderRaceHandler = ac.racetime_service.handler_objects.get(
room_name, None
)
ready = 0
for entrant in race_handler.data.get("entrants", []):
if entrant["status"]["value"] == "ready":
ready += 1
if (ready < 2 and not race.mode_obj.archetype_obj.ladder) or (
(len(race_handler.data.get("entrants", [])) < 2)
and race.mode_obj.archetype_obj.ladder
):
logger.error(
f"Not enough ready players to force start race {race.raceId}. Cancelling."
)
await ac.discord_service.send_message(
content=f"Not enough ready players to force start race {race.raceId}. Cancelling."
)
await race_handler.send_message(
"Not enough ready players to start the race! Race cancelled."
)
await race_handler.cancel_race()
return
await race_handler.send_message("Force starting race! Get ready!")
try:
await race_handler.force_start()
except Exception as e:
logger.error(f"Failed to force start race {race.raceId}: {e}")
admin_role = ac.database_service.get_setting("admin_role_id")
admin_ping = f"<@&{admin_role}> " if admin_role else ""
await ac.discord_service.send_message(
content=f"{admin_ping}Failed to force start race {race.raceId}: {e}",
force_mention=True
)
post_race_channel_id = ac.database_service.get_setting("post_race_channel_id")
if post_race_channel_id and not suppress_post_race_message:
thread: hikari.GuildThreadChannel = await ac.discord_service.bot.rest.create_thread(
post_race_channel_id,
hikari.ChannelType.GUILD_PUBLIC_THREAD,
f"[{race.mode_obj.archetype_obj.name}] {race.mode_obj.name} - {room_name.split('/')[-1]} "
)
await thread.send(f'_{random.choice(random_post_race_messages)}_')
def get_schedule_message(num_races: int = 10) -> str:
"""
Generates a message with the current schedule
"""
content = "**Step Ladder Schedule** (Times are local)\n"
upcoming_races = ac.database_service.get_future_scheduled_races(limit=num_races)
previous_race = ac.database_service.get_previous_race()
schedule = [previous_race] + upcoming_races
for n, entry in enumerate(schedule):
content += f"<t:{int(entry.time.replace(tzinfo=est).timestamp())}:f> (<t:{int(entry.time.replace(tzinfo=est).timestamp())}:R>) - **{entry.mode_obj.name}**"
if entry.mode_obj.archetype_obj.ladder:
content += " (1v1)"
if entry.raceId != -1 and entry.raceId is not None:
race = ac.database_service.get_race_by_id(entry.raceId)
content += f" - {ac.racetime_service.get_raceroom_url(race.raceRoom)}"
if n < len(schedule) - 1:
content += "\n"
return content
async def update_schedule_message() -> None:
"""
Updates the schedule message in the specified channel.
"""
schedule_message_id = ac.database_service.get_setting("schedule_message_id")
schedule_channel_id = ac.database_service.get_setting("schedule_channel_id")
schedule_num_races = ac.database_service.get_setting("schedule_num_races")
if not schedule_message_id or not schedule_channel_id or not schedule_num_races:
return
content = get_schedule_message(schedule_num_races)
await ac.discord_service.bot.rest.edit_message(
channel=schedule_channel_id,
message=schedule_message_id,
content=content,
)
async def schedule_future_races() -> None:
future_races = ac.database_service.get_future_scheduled_races()
scheduled_jobs = set([x.id for x in ac.scheduler_service.scheduler.get_jobs()])
_race_jobs = [
"open_race_",
"roll_seed_",
"force_start_",
]
# For each job, check that all scheduled components exist, if one missing, schedule the whole race
logger.info("Scheduling future races...")
for race in future_races:
if race.mode_obj.archetype_obj.ladder:
race_jobs = _race_jobs.copy() + ['warn_partitioned_']
else:
race_jobs = _race_jobs.copy() + ['ping_unready_']
for job in race_jobs:
if f"{job}{race.id}" not in scheduled_jobs:
ac.scheduler_service.schedule_race(race.id)
logger.info("All future races have been scheduled.")
await update_schedule_message()
def estnow() -> datetime.datetime:
"""
Returns the current time in EST.
"""
return datetime.datetime.now(est)
def seed_response_to_hash(response: AvianResponsePayload) -> str:
if response.fshash:
return convert_hash(response.fshash)
elif response.spoiler["meta"]["hash"]:
return convert_hash(response.spoiler["meta"]["hash"])
else:
return "No hash available"
def convert_hash(hash_str: str) -> str:
"""
Converts a hash string to a format suitable for use in URLs.
"""
hash_conversions = {
"Bomb": "Bombs",
"Powder": "Magic Powder",
"Rod": "Ice Rod",
"Ocarina": "Flute",
"Bug Net": "Bugnet",
"Bottle": "Empty Bottle",
"Potion": "Green Potion",
"Cane": "Somaria",
"Pearl": "Moon Pearl",
"Key": "Big Key",
}
hash_list = hash_str.split(", ")
hash_str = "/".join([f'Hash{hash_conversions.get(item, item).replace(" ", "")}' for item in hash_list])
return hash_str