-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsubs.py
More file actions
1909 lines (1649 loc) · 85.8 KB
/
Copy pathsubs.py
File metadata and controls
1909 lines (1649 loc) · 85.8 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
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Subs board — an interactive, persistent Discord widget for "I need a sub" /
"I can sub" coordination.
Requests and availability are SHARED across every server the bot is in; each
server renders its own board of that same data. A change made anywhere updates the
shared data and reposts the board on the SERVER WHERE IT HAPPENED (so testing on
one server doesn't spam another) — other servers pick up the change the next time
someone acts there. `/subs` shows a private copy; `/subs show:True` (re)posts a
server's public board in the current channel. The board is never pinned — it
reposts fresh at the bottom on each change. It groups open games by date with a
🔴/🟡/🟢 status per spot and lists who's available for each. Interaction is on the
board:
➕ Need a sub — league → team → game → spots (picked from the system). The
TEAM is optional — chairs often don't set teams until a day
or two before the first draw. The GAME never is: when you
need a sub is the point. A league with no schedule posted
still offers real dates, projected weekly from its title's
start date onto its own night.
🙋 I'm free — list your availability so you get tagged for matching games.
➕ Fill for someone — mark another member into an open spot (offline sync).
➖ Remove — cancel a sub (click a name → confirm), cancel a request you
opened, or clear your availability.
🙋 <game> — one hand-raise button per open game; one tap takes the spot.
When a request is posted (and again ~24h before an unfilled game), the bot posts a
public alert that @-mentions the members available for that game, each carrying an
"I'll take it" button. The only DM the bot sends is to a request's owner, letting
them know their game just gained or lost a sub; everything else is in the channel.
Sub rosters freeze LOCK_MINUTES before game time. Requests auto-expire a few hours
after their game. (Requests can no longer be posted without a date, but ones made
while that was allowed still render and age out after SUBS_UNDATED_DAYS.)
State lives in a small JSON file (see sub_store).
discord.py >= 2.4 is required for DynamicItem (persistent buttons that survive a
bot restart without re-registering each message).
"""
from __future__ import annotations
import os
import re
import html
import time
import logging
# NB: `time` (the stdlib module, imported above) is used for monotonic clocks in
# the click debounce. Import datetime's time CLASS under another name — plain
# `from datetime import time` shadows the module and turns time.monotonic() into
# an AttributeError at the first button click.
from datetime import datetime, date, timedelta, timezone
from datetime import time as clock_time
import discord
from discord import app_commands
from discord.ext import commands, tasks
import sub_store as store
from league_client import get_cached_leagues, draw_to_datetime
log = logging.getLogger(__name__)
STORE_PATH = os.environ.get("SUBS_STORE_PATH", "subs_store.json")
CLUB_NAME = os.environ.get("CLUB_NAME", "Curling Club")
TIMEZONE_OFFSET = int(os.environ.get("TIMEZONE_OFFSET", "-5")) # America/Chicago default
GRACE_HOURS = int(os.environ.get("SUBS_GRACE_HOURS", str(store.DEFAULT_GRACE_HOURS)))
# A request with no game date has nothing to expire against — it ages out this
# many days after it was posted instead.
UNDATED_DAYS = int(os.environ.get("SUBS_UNDATED_DAYS", str(store.DEFAULT_UNDATED_DAYS)))
# How close to game time an unfilled request gets an automatic re-alert (once).
REMINDER_HOURS = int(os.environ.get("SUBS_REMINDER_HOURS", "24"))
# Sub rosters freeze this many minutes before tip-off — no more adds/removes/claims.
LOCK_MINUTES = int(os.environ.get("SUBS_LOCK_MINUTES", "30"))
MAX_BUTTON_REQUESTS = 20 # Discord caps a message at 25 components; reserve a row for controls.
# Several buttons act on shared state and can be impatiently double-tapped before
# the first click visibly resolves. We ignore a repeat click (same user, same
# target) within this window so a double-tap is idempotent: a "Take a spot" toggle
# can't take-then-drop, and a Confirm/Decline can't clobber its own result.
CLICK_DEBOUNCE_SECONDS = 3.0
CID_NEW = "sub:new"
CID_AVAIL = "sub:avail"
CID_FILLFOR = "sub:fillfor"
CID_REMOVE = "sub:remove"
# Per-request one-tap claim/hand-raise button (alert page + board): "sub:take:<rid>".
CID_TAKE_PREFIX = "sub:take:"
def club_now() -> datetime:
"""Current club-local time as a naive datetime (matches stored game_ts)."""
return datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(hours=TIMEZONE_OFFSET)
def is_locked(req: dict, *, now: datetime | None = None) -> bool:
"""True once a game is within LOCK_MINUTES of starting (or already underway) — its
sub roster is frozen and can no longer be changed. Unparseable times never lock."""
now = now or club_now()
try:
return datetime.fromisoformat(req["game_ts"]) <= now + timedelta(minutes=LOCK_MINUTES)
except (ValueError, KeyError, TypeError):
return False
# ── Date/time formatting ────────────────────────────────────────────────────
# A league night whose start time the club hasn't settled yet. Expiry, locking
# and sorting all key off a real timestamp, so we park these at the very end of
# their day: the request then lives through the whole draw day instead of dying
# at midnight, and never locks early. No draw starts at 23:59, so the value
# doubles as the marker that the time is still to be confirmed.
TIME_TBC = clock_time(23, 59)
def fmt_when(game_ts: str) -> str:
"""A game's date/time for display. Two non-obvious cases are normal, not
errors: an empty timestamp (a legacy request posted with no date at all) and
TIME_TBC (date known, start time not announced yet)."""
try:
dt = datetime.fromisoformat(game_ts)
except (ValueError, TypeError):
return game_ts or "date TBD"
if dt.time() == TIME_TBC:
return f"{dt.strftime('%a %b %-d')} · time TBC"
return f"{dt.strftime('%a %b %-d')} · {dt.strftime('%-I:%M %p')}"
def fmt_when_short(game_ts: str) -> str:
try:
dt = datetime.fromisoformat(game_ts)
except (ValueError, TypeError):
return "TBD"
if dt.time() == TIME_TBC:
return f"{dt.strftime('%a %-m/%-d')} TBC"
h = dt.strftime('%-I:%M%p').lower().replace(":00", "")
return f"{dt.strftime('%a %-m/%-d')} {h}"
def first_name(name: str) -> str:
return (name or "").split()[0] if name else name
# ── League / game helpers ───────────────────────────────────────────────────
# Admins embed scheduling noise in league titles (e.g. "– Summer 2026 League 2 –
# Begins July 5"). We strip the date/time-ish tokens so the name doesn't echo the
# game date/time we already display. Best-effort across formats — weekday names
# (Sunday/Tuesday/…) are deliberately NOT stripped since they're part of the name.
_MONTHS = (r"(?:January|February|March|April|May|June|July|August|September|October|"
r"November|December|Jan|Feb|Mar|Apr|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec)")
_TITLE_NOISE = [
re.compile(r"\bBegins\b.*$", re.I), # "Begins July 5" tail
re.compile(r"\b\d{1,2}:\d{2}\s*(?:[ap]\.?m\.?)?", re.I), # 9:00 AM, 19:30
re.compile(r"\b\d{1,2}\s*[ap]\.?m\.?\b", re.I), # 9am, 7 pm
re.compile(r"\b\d{4}-\d{2}-\d{2}\b"), # 2026-07-05
re.compile(r"\b\d{1,2}/\d{1,2}(?:/\d{2,4})?\b"), # 7/5, 07/05/26
re.compile(rf"\b{_MONTHS}\b\.?\s*\d{{0,2}}(?:st|nd|rd|th)?", re.I), # July 5, Jul
re.compile(r"\b(?:Spring|Summer|Fall|Autumn|Winter)\b", re.I), # season
re.compile(r"\b(?:19|20)\d{2}\b"), # 2026
]
def clean_title(title: str) -> str:
"""Decode HTML entities and strip admin-embedded date/time noise (seasons,
years, month-dates, clock times, "Begins …" tails) plus orphaned punctuation,
so the league name doesn't repeat the game date/time we already show."""
t = html.unescape(title or "")
for pat in _TITLE_NOISE:
t = pat.sub(" ", t)
t = re.sub(r"[(\[]\s*[)\]]", " ", t) # drop emptied ()/[] pairs
t = re.sub(r"\s+", " ", t) # collapse whitespace
t = re.sub(r"(?:\s*[–—\-·,]\s*){2,}", " – ", t) # collapse separator runs
return t.strip(" –—-·,")
# "Summer 2026 League 2" tells a sub nothing — after clean_title strips the season
# and year, the bare sequence number ("League 2", "League #3") is pure noise too.
_LEAGUE_SEQ = re.compile(r"[\s–—\-·,]*\bLeagues?\s*#?\s*\d+\s*$", re.I)
def league_name(title: str) -> str:
"""Human league name: clean_title minus a trailing sequence number
("Thursday League – Summer 2026 League 3 – Begins August 6" → "Thursday League").
Never returns empty — falls back to the cleaned title if stripping ate it all."""
base = clean_title(title)
stripped = _LEAGUE_SEQ.sub("", base).strip(" –—-·,")
return stripped or base
def _draw_dates(league: dict) -> list[date]:
out = []
for d in league.get("draws", []) or []:
try:
out.append(date.fromisoformat(d["date"]))
except (ValueError, KeyError, TypeError):
continue
return sorted(set(out))
# Every league title at this club ends "– Begins September 6" / "– Begins Sept 4".
# clean_title() strips that as noise for DISPLAY, but it's the only machine-readable
# start date a league has before its schedule is posted — which is exactly when we
# need one. Parsed off the RAW title, before clean_title eats it.
_BEGINS_RE = re.compile(rf"\bBegins\b\s*:?\s*({_MONTHS})\.?\s+(\d{{1,2}})", re.I)
_TITLE_YEAR_RE = re.compile(r"\b(20\d{2})\b")
_MONTH_NUM = {m: i for i, m in enumerate(
("jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec"), start=1)}
def title_start_date(title: str, *, today: date | None = None) -> date | None:
"""The date in a league title's "Begins …" tail, or None.
The year comes from the season in the same title ("Fall 2026") when it's
there; otherwise we take whichever year puts the date nearest to now, so a
January league read in December lands next year rather than eleven months
ago."""
raw = html.unescape(title or "")
m = _BEGINS_RE.search(raw)
if not m:
return None
month = _MONTH_NUM.get(m.group(1)[:3].casefold())
if not month:
return None
day = int(m.group(2))
ym = _TITLE_YEAR_RE.search(raw)
today = today or date.today()
years = [int(ym.group(1))] if ym else [today.year - 1, today.year, today.year + 1]
best = None
for y in years:
try:
cand = date(y, month, day)
except ValueError:
continue # e.g. "Begins February 30"
if best is None or abs((cand - today).days) < abs((best - today).days):
best = cand
return best
def league_start_date(league: dict, *, today: date | None = None) -> date | None:
"""When this league starts: its first scheduled draw, else the date in its
title. The title is all we have for a league whose schedule isn't posted."""
dates = _draw_dates(league)
if dates:
return dates[0]
return title_start_date(league.get("title", ""), today=today)
def league_date_range(league: dict) -> str:
""""8/2 – 8/30" across a league's scheduled draws. With no schedule posted,
falls back to "from 9/6" off the title, so a Fall league is still identifiable
in a picker that lists several leagues on the same night."""
dates = _draw_dates(league)
if not dates:
start = league_start_date(league)
return f"from {start.month}/{start.day}" if start else ""
first, last = dates[0], dates[-1]
a = f"{first.month}/{first.day}"
if first == last:
return a
return f"{a} – {last.month}/{last.day}"
def league_label(league: dict) -> str:
"""What a league is called everywhere a human reads it: name + run dates, e.g.
"Sunday Rise & Shine League 8/2 – 8/30". The dates are what tell someone on the
sub board WHICH Sunday league this is; the admin's "League 2" never did."""
name = league_name(league.get("title", ""))
rng = league_date_range(league)
return f"{name} {rng}".strip() if rng else name
_WEEKDAY_ORDER = {d: i for i, d in enumerate(
("sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"))}
def league_weekday_index(league: dict) -> int:
"""0 = Sunday … 6 = Saturday; 7 when the day can't be determined (sorts last).
Prefers the league's own `day`, then a draw's parsed weekday, then the first
draw's date."""
d = (league.get("day") or "").strip().casefold()
if d in _WEEKDAY_ORDER:
return _WEEKDAY_ORDER[d]
for dr in league.get("draws", []) or []:
wd = (dr.get("weekday") or "").strip().casefold()
if wd in _WEEKDAY_ORDER:
return _WEEKDAY_ORDER[wd]
start = league_start_date(league)
if start:
return (start.weekday() + 1) % 7 # date.weekday() is Mon=0; we want Sun=0
return 7
def league_sort_key(league: dict):
"""Sort order for every league list a member sees: day of week Sun→Sat, then
start date within that day, then name. Leagues on the same night land together,
earliest-starting first — so "which Sunday league is this?" is answered by
position as well as by the label."""
start = league_start_date(league)
return (league_weekday_index(league),
start or date.max,
league_name(league.get("title", "")).casefold())
def league_sub_label(league: dict) -> str:
"""Secondary line for a league picker: when it's played."""
bits = [x for x in ((league.get("day") or ""), (league.get("time") or "")) if x]
return " · ".join(bits)
def stored_league(text: str) -> str:
"""Display a league name that was already labelled when it was stored. Do NOT
run clean_title over these — it would strip the very dates league_label added."""
return html.unescape(text or "").strip()
def _truncate(s: str, n: int) -> str:
s = s or ""
return s if len(s) <= n else s[: n - 1] + "…"
_CLOCK_RE = re.compile(r"^\s*(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\s*$", re.I)
def _parse_clock(text: str) -> clock_time | None:
"""'7:45 pm' / '9am' / '9:00 a.m.' -> time. None if it isn't a clock time."""
m = _CLOCK_RE.match(text or "")
if not m:
return None
hour = int(m.group(1)) % 12
if m.group(3).lower() == "p":
hour += 12
return clock_time(hour, int(m.group(2) or 0))
def _league_time(league: dict) -> clock_time | None:
"""The league's start time, from its `time` field or, failing that, whatever
time its known draws are at. None if we can't tell."""
t = _parse_clock(league.get("time") or "")
if t is not None:
return t
for d in league.get("draws", []) or []:
t = _parse_clock(d.get("time") or "")
if t is not None:
return t
return None
def league_games(league: dict, now: datetime) -> list[dict]:
"""
All upcoming draws for a league (from today onward). Each item:
{iso, label, dt}. De-duped and sorted by time.
"""
today = now.date()
out: list[dict] = []
for d in league.get("draws", []):
try:
dd = date.fromisoformat(d["date"])
except (ValueError, KeyError, TypeError):
continue
if dd < today:
continue
dt = draw_to_datetime(d)
if dt is None or (dt.hour == 0 and dt.minute == 0):
# draw_to_datetime falls back to midnight when a row's time is
# missing or unparseable. No club draws at midnight, so read that as
# "time unknown" and use the league's start time instead — otherwise
# the picker offers "12:00 AM" and the request expires a day early.
dt = datetime.combine(dd, _league_time(league) or time(0, 0))
dt = dt.replace(second=0, microsecond=0)
out.append({"iso": dt.isoformat(), "label": fmt_when(dt.isoformat()), "dt": dt})
out.sort(key=lambda g: g["dt"])
seen, uniq = set(), []
for g in out:
if g["iso"] in seen:
continue
seen.add(g["iso"])
g["projected"] = False
uniq.append(g)
return uniq
# How many nights to offer when a league's schedule isn't published yet. Discord
# caps a select at 25 options; 8 weeks is a season and leaves room to spare.
PROJECTED_NIGHTS = 8
def projected_games(league: dict, now: datetime, *, start: date | None = None,
count: int = PROJECTED_NIGHTS) -> list[dict]:
"""Upcoming *league nights* worked out from the league's day and start date,
for the stretch before the chair posts a schedule. When you need a sub is the
whole point of a request, so an unscheduled league still has to offer real
dates: weekly on its own night, starting from the league's own start date, so
a date that isn't a league night can't be picked.
The START TIME may legitimately be unknown — the club itself sometimes hasn't
settled it ("either 6pm or 7pm", per the Fall over/under league page). We
don't guess it (a neighbouring league's time would be flat wrong: Sunday
morning is 9am, Sunday night is not) and we don't let it block the date,
which is the part people actually need. Those entries carry TIME_TBC."""
idx = league_weekday_index(league)
if idx > 6:
return [] # no idea what night this league plays
t = _league_time(league)
time_known = t is not None
target = (idx - 1) % 7 # our Sun=0…Sat=6 → date.weekday()'s Mon=0…Sun=6
begins = start if start is not None else league_start_date(league, today=now.date())
d = max(begins or now.date(), now.date())
d += timedelta(days=(target - d.weekday()) % 7)
out: list[dict] = []
while len(out) < count:
dt = datetime.combine(d, t or TIME_TBC)
d += timedelta(days=7)
if dt <= now:
continue # tonight's draw already started
out.append({"iso": dt.isoformat(), "label": fmt_when(dt.isoformat()),
"dt": dt, "projected": True, "time_known": time_known})
return out
def league_is_over(league: dict, now: datetime) -> bool:
"""True when every draw this league has is in the past. Finished seasons sit
in the cache for weeks without an `ended` flag; they're dead ends in a picker
(nothing left to sub for), so we hide them. A league with NO draws is not
over — that's a season whose schedule simply hasn't been posted."""
dates = _draw_dates(league)
return bool(dates) and dates[-1] < now.date()
def game_options(league: dict, now: datetime, *, cap: int = 25) -> list[dict]:
"""What the game picker offers.
A posted schedule always wins — we never invent dates that contradict one,
even to extend past its last draw. Projected nights are strictly the
no-schedule-yet case, which is the one that used to leave the picker empty
and the request unpostable. A league whose draws have ALL been played is a
finished season, not an unscheduled one: it gets nothing, so old leagues
lingering in the cache without an `ended` flag can't be picked."""
real = league_games(league, now)
if real:
return real[:cap]
if _draw_dates(league) or league.get("fetch_failed"):
# Either the schedule exists and it's all in the past, or we couldn't read
# the league's page at all. "No draws" only means "not scheduled yet" when
# we actually managed to look — otherwise a site outage would have us
# inventing league nights out of nothing.
return []
return projected_games(league, now)[:cap]
# ── Board rendering ─────────────────────────────────────────────────────────
BOARD_TITLE = f"Subs Board — {CLUB_NAME}"
def _game_key(iso: str) -> str:
"""Game timestamp normalized to the minute, for matching availability to requests."""
try:
return datetime.fromisoformat(iso).replace(second=0, microsecond=0).isoformat()
except (ValueError, TypeError):
return iso or ""
def _before(iso: str, floor: datetime) -> bool:
"""True if `iso` is a real timestamp earlier than `floor`. An empty or
unparseable value is NOT "before" — undated items are handled on their own
terms and unreadable ones are never silently dropped."""
if not iso:
return False
try:
return datetime.fromisoformat(iso) < floor
except (ValueError, TypeError):
return False
def _req_icon(req: dict) -> str:
"""Traffic light by urgency: 🔴 nobody yet, 🟡 partly covered, 🟢 fully covered."""
needed = int(req["spots_needed"])
covered = needed - store.open_spots(req) # filled + pending
if covered <= 0:
return "🔴"
if covered < needed:
return "🟡"
return "🟢"
def _embed_color(reqs: list[dict]) -> int:
"""Bar color reflects the most urgent open request (red beats yellow beats green)."""
icons = {_req_icon(r) for r in reqs}
if "🔴" in icons:
return 0xE03A3A
if "🟡" in icons:
return 0xE6A700
if reqs:
return 0x2FA84F
return 0x1A6BB5
INDENT = "\u00a0\u00a0\u00a0" # non-breaking spaces: Discord keeps these, so lines indent under the date
def _req_for(req: dict) -> str:
"""Who the spot is for: the team when one is named, otherwise the person who
asked (teams often aren't set until a day or two before the first draw)."""
if req.get("team"):
return f"Team {req['team']}"
who = first_name(req.get("requester_name", ""))
return f"{who}'s spot" if who else "Sub"
def _req_status_line(req: dict) -> str:
needed = int(req["spots_needed"])
covered = needed - store.open_spots(req)
names = [f["name"] for f in req.get("filled", [])]
names += [f"{p['name']} (pending)" for p in req.get("pending", [])]
who = ", ".join(names) if names else "nobody yet"
return f"{INDENT}{_req_icon(req)} {_req_for(req)} — {covered}/{needed} · {who}"
def _available_for_group(state: dict, grp: dict, key: str) -> list[str]:
"""Who's genuinely free for this time slot: anyone whose availability covers the
game and who isn't already tied up in it. Being tied up means subbing one of the
slot's requests (filled or pending) — or having opened one, since a requester
needs a sub precisely because they can't play. Assigned subs drop off this list
and show by name on their spot line instead."""
tied_up = set()
for r in grp["reqs"]:
tied_up.add(r.get("requester_id"))
for m in r.get("filled", []) + r.get("pending", []):
tied_up.add(m["user_id"])
names = []
for a in state.get("availability", []):
if a["user_id"] in tied_up:
continue
games = a.get("games") or []
lid = str(a.get("league_id") or "")
if grp["reqs"]:
# Covers the slot if it matches any request here: same league, and either
# this specific game or an "any game in this league" offer.
covers = any(
(not lid or str(r.get("league_id") or "") == lid)
and (not games or any(_same_game(r.get("game_ts", ""), g) for g in games))
for r in grp["reqs"]
)
else:
# No request opened for this game yet — only an explicit game listing counts.
covers = any(_game_key(g) == key for g in games)
if covers:
names.append(a["name"])
return sorted(set(names))
def build_embed(state: dict) -> discord.Embed:
"""One combined, date-ordered board. A game appears if it has a request OR if
anyone is available for it. Under each date: the sub spots (traffic-light status,
with the names of whoever is in), then the available subs not yet assigned.
General (any-time) availability is summarized at the bottom."""
reqs = store.requests_sorted(state)
e = discord.Embed(title=BOARD_TITLE, color=_embed_color(reqs))
# Date groups come from requests AND from game-specific availability, so a game
# with willing subs shows up even before anyone opens a request for it.
groups: dict[str, dict] = {}
for r in reqs:
ts = r.get("game_ts", "")
if ts:
k = _game_key(ts)
groups.setdefault(k, {"iso": ts, "label": fmt_when(ts), "reqs": []})["reqs"].append(r)
else:
# Undated requests group per league rather than into one anonymous
# "date TBD" pile — the league is the only context they carry, and
# it's what tells a would-be sub whether it's their night.
k = f"tbd:{r.get('league_id') or ''}"
lg = stored_league(r.get("league", ""))
groups.setdefault(k, {"iso": "", "reqs": [],
"label": "Date TBD" + (f" · {lg}" if lg else "")})["reqs"].append(r)
for a in state.get("availability", []):
for iso in (a.get("games") or []):
groups.setdefault(_game_key(iso), {"iso": iso, "label": fmt_when(iso), "reqs": []})
# Hard today-forward floor. store.expire() already prunes past dates, but it
# only runs every 15 minutes and only mutates what it can parse — this makes
# the board itself incapable of showing yesterday. Undated ("Date TBD") groups
# carry no date to be behind, so they're never floored out.
floor = store.day_floor(club_now())
for k in [k for k, g in groups.items() if _before(g.get("iso"), floor)]:
del groups[k]
def _sort_key(k: str):
try:
return (0, datetime.fromisoformat(groups[k]["iso"]), "")
except (ValueError, TypeError):
return (1, datetime.max, k) # undated sinks below every real date
order = sorted(groups, key=_sort_key)
blocks = []
for k in order[:MAX_BUTTON_REQUESTS]:
grp = groups[k]
lines = [f"**{grp['label']}**"]
for r in grp["reqs"]:
lines.append(_req_status_line(r))
free = _available_for_group(state, grp, k)
if free:
lines.append(f"{INDENT}available: {', '.join(free)}")
blocks.append("\n".join(lines))
if len(order) > MAX_BUTTON_REQUESTS:
blocks.append(f"…and {len(order) - MAX_BUTTON_REQUESTS} more game(s).")
if blocks:
e.description = "\n\n".join(blocks)
else:
# No dated games — but an any-time roster below may still have people on it.
e.description = ("No sub requests right now.\n\nUse **Need a sub** to post one, "
"or **I'm free** to list your availability.")
# Bottom: people available with no specific game (any time), grouped by league.
anytime: dict[str, dict] = {}
aorder: list[str] = []
for a in state.get("availability", []):
if a.get("games"):
continue # game-specific availability shows on the "available:" lines above
lkey = str(a.get("league_id") or "")
if lkey not in anytime:
anytime[lkey] = {"title": stored_league(a.get("league", "")) or "Any league", "names": []}
aorder.append(lkey)
anytime[lkey]["names"].append(a["name"])
if aorder:
rows = [f"**{_truncate(anytime[l]['title'], 40)}** — {', '.join(sorted(anytime[l]['names']))}"
for l in aorder]
e.add_field(name="Available any time", value="\n".join(rows)[:1024], inline=False)
e.set_footer(text="🔴 none · 🟡 partial · 🟢 filled — tap a game button below to take a spot")
return e
def build_view(state: dict) -> discord.ui.View:
"""Row 0 = the four verbs; below that, one 🙋 hand-raise button per open game so
claiming a spot is a single tap (no form)."""
view = discord.ui.View(timeout=None)
view.add_item(NewRequestButton()) # ➕ Need a sub
view.add_item(AvailableButton()) # 🙋 I'm free
view.add_item(FillForButton()) # ✍️ Fill for someone
view.add_item(RemoveButton()) # ✖️ Remove
# A game within LOCK_MINUTES of tip-off is frozen — no hand-raise button for it.
open_reqs = [r for r in store.requests_sorted(state)
if store.open_spots(r) > 0 and not is_locked(r)]
for i, r in enumerate(open_reqs[:20]): # rows 1–4, 5 buttons each
who = r["team"] if r.get("team") else first_name(r.get("requester_name", ""))
when = fmt_when_short(r["game_ts"]) if r.get("game_ts") else "TBD"
label = _truncate(f"{when} {who}", 80)
view.add_item(PageClaimButton(r["id"], label=label,
style=discord.ButtonStyle.success, row=1 + i // 5))
return view
# ── Persistent buttons (DynamicItem — survive restarts) ─────────────────────
class NewRequestButton(discord.ui.DynamicItem[discord.ui.Button], template=r"sub:new"):
def __init__(self):
super().__init__(discord.ui.Button(
label="Need a sub", emoji="➕",
style=discord.ButtonStyle.success, custom_id=CID_NEW, row=0,
))
@classmethod
async def from_custom_id(cls, interaction, item, match):
return cls()
async def callback(self, interaction: discord.Interaction):
cog: "Subs" = interaction.client.get_cog("Subs")
# thinking=True shows an ephemeral "curlbot is thinking…" right away while we
# load leagues, then we edit that placeholder into the flow.
await interaction.response.defer(thinking=True, ephemeral=True)
leagues = await cog.get_leagues()
if not leagues:
await interaction.edit_original_response(
content="Couldn't load the league list just now — try again in a moment.")
return
view = NeedSubFlowView(leagues)
view.message = await interaction.edit_original_response(content=view.prompt(), view=view)
class AvailableButton(discord.ui.DynamicItem[discord.ui.Button], template=r"sub:avail"):
def __init__(self):
super().__init__(discord.ui.Button(
label="I'm free", emoji="🙋",
style=discord.ButtonStyle.primary, custom_id=CID_AVAIL, row=0,
))
@classmethod
async def from_custom_id(cls, interaction, item, match):
return cls()
async def callback(self, interaction: discord.Interaction):
cog: "Subs" = interaction.client.get_cog("Subs")
# thinking=True shows an ephemeral "curlbot is thinking…" right away while we
# load leagues, then we edit that placeholder into the flow.
await interaction.response.defer(thinking=True, ephemeral=True)
leagues = await cog.get_leagues()
if not leagues:
await interaction.edit_original_response(
content="Couldn't load the league list just now — try again in a moment.")
return
view = AvailFlowView(leagues, interaction.user.id, cog.state)
view.message = await interaction.edit_original_response(content=view.prompt(), view=view)
class FillForButton(discord.ui.DynamicItem[discord.ui.Button], template=r"sub:fillfor"):
"""Mark someone ELSE into an open spot (offline sync) — they told you they'd cover
it, so you record it for them."""
def __init__(self):
super().__init__(discord.ui.Button(
label="Fill for someone", emoji="➕",
style=discord.ButtonStyle.success, custom_id=CID_FILLFOR, row=0))
@classmethod
async def from_custom_id(cls, interaction, item, match):
return cls()
async def callback(self, interaction: discord.Interaction):
cog: "Subs" = interaction.client.get_cog("Subs")
open_reqs = [r for r in store.requests_sorted(cog.state)
if store.open_spots(r) > 0 and not is_locked(r)]
if not open_reqs:
await interaction.response.send_message("No open spots to fill right now.", ephemeral=True)
return
await interaction.response.send_message(
"**Fill for someone** — pick the game, then choose the teammate to mark in:",
view=FillForView(cog.state), ephemeral=True)
class FillForView(discord.ui.View):
def __init__(self, state: dict):
super().__init__(timeout=300)
self.state = state
self.rid: str | None = None
self.build()
def build(self) -> "FillForView":
self.clear_items()
open_reqs = [r for r in store.requests_sorted(self.state)
if store.open_spots(r) > 0 and not is_locked(r)]
self.add_item(FillForPick(open_reqs, self.rid, row=0))
if self.rid and store.find_request(self.state, self.rid):
self.add_item(FillForMemberSelect(self.rid, row=1))
return self
def prompt(self) -> str:
if not self.rid:
return "**Fill for someone** — pick the game, then choose the teammate to mark in:"
req = store.find_request(self.state, self.rid)
when = fmt_when(req["game_ts"]) if req else "that game"
return f"**Fill for someone** · {when} — choose the teammate to mark in:"
class FillForPick(discord.ui.Select):
def __init__(self, reqs: list[dict], selected, row: int = 0):
opts = _unique_options([
discord.SelectOption(
label=_truncate(f"{fmt_when_short(r['game_ts'])} · {_req_for(r)}", 100),
value=r["id"],
description=_truncate(f"{store.open_spots(r)} open", 100),
default=(r["id"] == selected),
)
for r in reqs[:25]
])
if not opts:
opts = [discord.SelectOption(label="No open spots right now", value="__none__")]
super().__init__(placeholder="Which game…", min_values=1, max_values=1, options=opts, row=row)
async def callback(self, interaction: discord.Interaction):
if self.values[0] == "__none__":
await interaction.response.defer()
return
self.view.rid = self.values[0]
await interaction.response.edit_message(content=self.view.prompt(), view=self.view.build())
class FillForMemberSelect(discord.ui.UserSelect):
def __init__(self, rid: str, row: int = 1):
self.rid = rid
super().__init__(placeholder="Choose the teammate to mark in…", min_values=1, max_values=1, row=row)
async def callback(self, interaction: discord.Interaction):
await interaction.response.defer()
cog: "Subs" = interaction.client.get_cog("Subs")
member = self.values[0]
if cog._is_repeat_click(cog._click_cooldown, ("fillfor", interaction.user.id, self.rid, member.id)):
return
result, req = await cog.fill_spot_for(interaction.user, self.rid, member, interaction.channel)
when = fmt_when(req["game_ts"]) if req else "that game"
msgs = {
"added": f"✅ Marked **{member.display_name}** in for **{when}** — they and the requester were notified.",
"already": f"**{member.display_name}** is already on that request.",
"requester": "That's the requester — they can't sub their own request.",
"full": "No open spots left on that request.",
"locked": f"**{when}** starts too soon — the roster's locked.",
"closed": "That request is no longer on the board.",
}
await interaction.edit_original_response(content=msgs.get(result, "Done."), view=None)
# ── Remove (click a name → confirm; cancel a request; clear availability) ─────
def _all_committed_subs(state: dict) -> list[tuple]:
"""Every listed sub across all requests as (rid, req, member-dict). Skips games
whose roster has locked (within LOCK_MINUTES of start) — those can't be changed."""
out = []
for r in store.requests_sorted(state):
if is_locked(r):
continue
for m in r.get("filled", []) + r.get("pending", []):
out.append((r["id"], r, m))
return out
class RemoveButton(discord.ui.DynamicItem[discord.ui.Button], template=r"sub:remove"):
"""Remove a sub (click a name → confirm), cancel a request you opened, or clear
your own availability — all in one place."""
def __init__(self):
super().__init__(discord.ui.Button(
label="Remove", emoji="➖",
style=discord.ButtonStyle.danger, custom_id=CID_REMOVE, row=0))
@classmethod
async def from_custom_id(cls, interaction, item, match):
return cls()
async def callback(self, interaction: discord.Interaction):
cog: "Subs" = interaction.client.get_cog("Subs")
view = RemoveHomeView(cog.state, interaction.user.id)
if not view.children:
await interaction.response.send_message(
"Nothing to remove right now — no subs, requests, or availability listed.",
ephemeral=True)
return
await interaction.response.send_message(
"**Remove** — cancel a sub (you'll confirm), cancel a request you opened, "
"or clear your availability:", view=view, ephemeral=True)
class RemoveHomeView(discord.ui.View):
def __init__(self, state: dict, uid: int):
super().__init__(timeout=180)
row = 0
subs = _all_committed_subs(state)
if subs:
self.add_item(RemoveSubSelect(subs, row=row)); row += 1
my_reqs = _my_requests(state, uid)
if my_reqs:
self.add_item(CancelRequestSelect(my_reqs, row=row)); row += 1
my_avail = [a for a in state.get("availability", []) if a.get("user_id") == uid]
if my_avail:
self.add_item(RemoveAvailSelect(my_avail, row=row)); row += 1
class RemoveSubSelect(discord.ui.Select):
def __init__(self, subs: list[tuple], row: int = 0):
opts = _unique_options([
discord.SelectOption(
label=_truncate(m["name"], 100),
value=f"{rid}:{m['user_id']}",
description=_truncate(f"{fmt_when_short(r['game_ts'])} · {_req_for(r)}", 100),
)
for (rid, r, m) in sorted(subs, key=lambda t: (t[2]["name"] or "").casefold())[:25]
])
super().__init__(placeholder="Remove a sub (click a name)…",
min_values=1, max_values=1, options=opts, row=row)
async def callback(self, interaction: discord.Interaction):
rid, _, uid_s = self.values[0].partition(":")
cog: "Subs" = interaction.client.get_cog("Subs")
req = store.find_request(cog.state, rid)
if not req:
await interaction.response.edit_message(content="That request is no longer on the board.", view=None)
return
target = int(uid_s)
name = next((m["name"] for m in (req.get("filled", []) + req.get("pending", []))
if m["user_id"] == target), "this sub")
await interaction.response.edit_message(
content=f"Remove **{name}** from **{fmt_when(req['game_ts'])}**?",
view=ConfirmRemoveSubView(rid, target, name))
class ConfirmRemoveSubView(discord.ui.View):
def __init__(self, rid: str, target: int, name: str):
super().__init__(timeout=120)
self.rid = rid
self.target = target
self.name = name
@discord.ui.button(label="Remove", emoji="✖️", style=discord.ButtonStyle.danger)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.defer()
cog: "Subs" = interaction.client.get_cog("Subs")
if cog._is_repeat_click(cog._click_cooldown, ("rmsub", interaction.user.id, self.rid, self.target)):
return
result, req = await cog.remove_sub_by_anyone(interaction.user, self.rid, self.target, interaction.channel)
when = fmt_when(req["game_ts"]) if req else "that game"
if result == "removed":
msg = f"✖️ Removed **{self.name}** from **{when}** — they and the requester were notified."
elif result == "absent":
msg = "They were already off that spot."
elif result == "locked":
msg = f"**{when}** starts too soon — the roster's locked."
else:
msg = "That request is no longer on the board."
await interaction.edit_original_response(content=msg, view=None)
@discord.ui.button(label="Keep", style=discord.ButtonStyle.secondary)
async def keep(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.edit_message(content="Okay — left them on.", view=None)
class CancelRequestSelect(discord.ui.Select):
def __init__(self, reqs: list[dict], row: int = 1):
opts = _unique_options([
discord.SelectOption(
label=_truncate(f"{fmt_when_short(r['game_ts'])} · {_req_for(r)}", 100),
value=r["id"],
description=_truncate(f"{store.open_spots(r)} open · cancel this request", 100),
)
for r in reqs[:25]
])
super().__init__(placeholder="Cancel a request you opened…",
min_values=1, max_values=1, options=opts, row=row)
async def callback(self, interaction: discord.Interaction):
cog: "Subs" = interaction.client.get_cog("Subs")
req = store.find_request(cog.state, self.values[0])
if not req or req["requester_id"] != interaction.user.id:
await interaction.response.edit_message(content="That request is no longer yours to cancel.", view=None)
return
await interaction.response.edit_message(
content=f"Cancel your request for **{fmt_when(req['game_ts'])}**? Any subs on it will be told.",
view=ConfirmCancelView(req["id"]))
class ConfirmCancelView(discord.ui.View):
def __init__(self, rid: str):
super().__init__(timeout=120)
self.rid = rid
@discord.ui.button(label="Cancel request", emoji="✖️", style=discord.ButtonStyle.danger)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.defer()
cog: "Subs" = interaction.client.get_cog("Subs")
req = store.find_request(cog.state, self.rid)
if not req or req["requester_id"] != interaction.user.id:
await interaction.edit_original_response(content="That request is no longer yours to cancel.", view=None)
return
if cog._is_repeat_click(cog._click_cooldown, ("cancelreq", interaction.user.id, self.rid)):
return
await cog.close_request(self.rid, interaction.channel)
await interaction.edit_original_response(content="✖️ Request cancelled and removed from the board.", view=None)
@discord.ui.button(label="Keep", style=discord.ButtonStyle.secondary)
async def keep(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.edit_message(content="Okay — kept the request.", view=None)
# ── Shared selects for the league/game flows ────────────────────────────────
def _unique_options(opts: list[discord.SelectOption]) -> list[discord.SelectOption]:
"""Drop options whose value repeats, keeping the first. Discord rejects a
Select whose options share a value (error 50035: "option value is already
used"), which would otherwise fail the whole message render."""
seen, out = set(), []
for o in opts:
if o.value in seen:
continue
seen.add(o.value)
out.append(o)
return out
class LeagueSelect(discord.ui.Select):
def __init__(self, leagues: list[dict], selected, row: int = 0):
ordered = sorted(leagues, key=league_sort_key)
opts = [
discord.SelectOption(
label=_truncate(league_label(l), 100),
value=str(l["id"]),
description=(league_sub_label(l) or None),
default=(str(l["id"]) == str(selected)),
)
for l in ordered[:25]
] or [discord.SelectOption(label="No active leagues", value="__none__")]
super().__init__(placeholder="Choose a league…", min_values=1, max_values=1,
options=_unique_options(opts), row=row)
async def callback(self, interaction: discord.Interaction):
if self.values[0] == "__none__":
await interaction.response.defer()
return
self.view.league_id = self.values[0]
self.view.on_league_change()
await self.view.refresh(interaction)