-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsubs.py
More file actions
1547 lines (1351 loc) · 69.5 KB
/
Copy pathsubs.py
File metadata and controls
1547 lines (1351 loc) · 69.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
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.
One pinned message per channel acts as a live board. Members interact entirely
through buttons:
➕ Need a sub — opens a modal (date, time, position, spots, notes) and posts
a request onto the board.
Sub for … — one button per open request; click to take an open spot,
click again to drop it. The requester is notified on change.
🙋 I can sub — toggle yourself onto the "available subs" list.
🛠 Manage — requester-only panel to add a specific person to a spot,
remove someone, or close a request early.
Requests auto-expire a few hours after their game time, so played-out games drop
off the board on their own. State lives in a small JSON file (see sub_store).
Notifications try a DM first and fall back to an @-mention in the board channel.
discord.py >= 2.4 is required for DynamicItem (persistent per-request 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
from datetime import datetime, date, timedelta, timezone
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)))
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_MANAGE = "sub:manage"
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)
# ── Date/time parsing for the modal ─────────────────────────────────────────
_DATE_FORMATS = ("%Y-%m-%d", "%m/%d/%Y", "%m/%d", "%b %d", "%B %d", "%m-%d")
_TIME_FORMATS = ("%I:%M %p", "%I %p", "%I:%M%p", "%I%p", "%H:%M")
def parse_when(date_str: str, time_str: str, *, ref: datetime | None = None) -> datetime:
"""
Parse a date + time the way a member would type it. Accepts e.g.
date "2026-06-20", "6/20", "Jun 20"; time "7:30 PM", "7pm", "19:30".
Formats without a year assume the year that keeps the game in the future.
Raises ValueError if neither field parses.
"""
ref = ref or club_now()
date_str = date_str.strip()
time_str = time_str.strip().upper().replace(".", "")
d = None
for fmt in _DATE_FORMATS:
try:
parsed = datetime.strptime(date_str, fmt)
except ValueError:
continue
d = parsed
if "%Y" not in fmt: # no year supplied — assume current, roll forward if past
d = d.replace(year=ref.year)
break
if d is None:
raise ValueError(f"Couldn't read the date “{date_str}”. Try e.g. 2026-06-20 or Jun 20.")
t = None
for fmt in _TIME_FORMATS:
try:
t = datetime.strptime(time_str, fmt)
break
except ValueError:
continue
if t is None:
raise ValueError(f"Couldn't read the time “{time_str}”. Try e.g. 7:30 PM or 19:30.")
when = d.replace(hour=t.hour, minute=t.minute, second=0, microsecond=0)
# If a year-less date landed clearly in the past, it's next year's game.
if when < ref - timedelta(days=1):
when = when.replace(year=when.year + 1)
return when
def fmt_when(game_ts: str) -> str:
try:
dt = datetime.fromisoformat(game_ts)
except (ValueError, TypeError):
return game_ts or "TBD"
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"
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(" –—-·,")
def _truncate(s: str, n: int) -> str:
s = s or ""
return s if len(s) <= n else s[: n - 1] + "…"
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) or datetime.combine(dd, datetime.min.time())
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"])
uniq.append(g)
return uniq
# ── Board rendering ─────────────────────────────────────────────────────────
BOARD_TITLE = f"🥌 Subs Board — {CLUB_NAME}"
def _looks_like_board(msg) -> bool:
"""True if a message is one of our pinned subs boards (by embed title)."""
return any("Subs Board" in (e.title or "") for e in msg.embeds)
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 build_embed(state: dict) -> discord.Embed:
reqs = store.requests_sorted(state)
e = discord.Embed(title=BOARD_TITLE, color=0x1a6bb5)
if not reqs:
e.description = "No open sub requests right now.\n\nPress **➕ Need a sub** to post one."
else:
lines = []
for i, r in enumerate(reqs[:MAX_BUTTON_REQUESTS], start=1):
opn = store.open_spots(r)
icon = "🟢" if opn > 0 else "✅"
# League name is intentionally omitted — it's redundant with the
# date/time (and the league title itself embeds the season/date).
bits = []
if r.get("team"):
bits.append(f"Team {r['team']}")
status = f"{len(r.get('filled', []))}/{r['spots_needed']} filled"
# Name the subs so you can see who you're playing with (pending = invited
# but not yet confirmed).
names = [f["name"] for f in r.get("filled", [])]
names += [f"{p['name']} (pending)" for p in r.get("pending", [])]
if names:
status += " — " + ", ".join(names)
bits.append(status)
lines.append(f"`{i}.` {icon} **{fmt_when(r['game_ts'])}** · " + " · ".join(bits))
e.description = "\n\n".join(lines)
if len(reqs) > MAX_BUTTON_REQUESTS:
e.description += f"\n\n…and {len(reqs) - MAX_BUTTON_REQUESTS} more (older ones fill first)."
avail = state.get("availability", [])
if avail:
# Anyone already filled/pending on a request is no longer "available" for that
# game — hide them from the list (keyed by user + league + game-minute). When a
# requester later removes them they're un-committed again and reappear here;
# only a self-drop deletes their availability outright.
committed = set()
for r in state.get("requests", []):
lid_r = str(r.get("league_id") or "")
gk = _game_key(r.get("game_ts", ""))
for m in r.get("filled", []) + r.get("pending", []):
committed.add((m["user_id"], lid_r, gk))
# Grouped by league → game so the board answers "who can sub THIS game?" at a
# glance, instead of a per-person list you have to scan for dates. Subs who
# listed no specific games are shown on an "any game" line for that league.
groups: dict[str, dict] = {}
order: list[str] = []
for a in avail:
lkey = str(a.get("league_id") or "")
if lkey not in groups:
groups[lkey] = {"title": clean_title(a.get("league", "")) or "Other league",
"games": {}, "any": []}
order.append(lkey)
g = groups[lkey]
games = a.get("games") or []
if games:
for iso in games:
if (a["user_id"], lkey, _game_key(iso)) in committed:
continue # already subbing this game — not available for it
g["games"].setdefault(iso, []).append(a["name"])
else:
g["any"].append(a["name"])
rows = []
for lkey in order:
g = groups[lkey]
if not g["games"] and not g["any"]:
continue # everyone offered here is already committed — nothing to show
rows.append(f"**{_truncate(g['title'], 40)}**")
for iso in sorted(g["games"]):
rows.append(f"{fmt_when(iso)} — {', '.join(sorted(g['games'][iso]))}")
if g["any"]:
rows.append(f"any game — {', '.join(sorted(g['any']))}")
if rows:
e.add_field(name="🙋 Available to sub", value="\n".join(rows)[:1024], inline=False)
e.set_footer(text="➕ post a request · 🙋 offer to sub")
return e
def build_view(state: dict) -> discord.ui.View:
# Just the three control buttons. Claiming an open spot is done from the
# "I can sub" flow (multi-select of open requests), not per-request buttons.
view = discord.ui.View(timeout=None)
view.add_item(NewRequestButton())
view.add_item(AvailableButton())
view.add_item(ManageButton())
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 can sub", 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 ManageButton(discord.ui.DynamicItem[discord.ui.Button], template=r"sub:manage"):
def __init__(self):
super().__init__(discord.ui.Button(
label="Manage", emoji="🛠️",
style=discord.ButtonStyle.secondary, custom_id=CID_MANAGE, 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")
uid = interaction.user.id
has_avail = any(a.get("user_id") == uid for a in cog.state.get("availability", []))
if not (_my_requests(cog.state, uid) or _my_spots(cog.state, uid) or has_avail):
await interaction.response.send_message(
"Nothing to manage yet — you have no open requests, sub spots, or availability listed.",
ephemeral=True)
return
await interaction.response.send_message(
"**Manage** — your requests, the spots you're subbing, and your availability:",
view=ManageHomeView(cog.state, uid), ephemeral=True)
# ── 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):
opts = [
discord.SelectOption(
label=_truncate(clean_title(l.get("title", "")), 100),
value=str(l["id"]),
description=(l.get("day") or None),
default=(str(l["id"]) == str(selected)),
)
for l in leagues[: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)
class TeamSelect(discord.ui.Select):
def __init__(self, names: list[str], selected, row: int = 1):
opts = _unique_options([
discord.SelectOption(label=_truncate(n, 100), value=_truncate(n, 100), default=(n == selected))
for n in names[:24]
])
# Always allow a typed team — some leagues expose no team list, and the
# requester may want a name that isn't in it.
opts.append(discord.SelectOption(label="⌨️ Enter team manually…", value="__manual__"))
placeholder = "Your team…" if names else "Enter your team…"
super().__init__(placeholder=placeholder, min_values=1, max_values=1, options=opts, row=row)
async def callback(self, interaction: discord.Interaction):
if self.values[0] == "__manual__":
await interaction.response.send_modal(TeamModal(self.view))
return
self.view.team = self.values[0]
await self.view.refresh(interaction)
class TeamModal(discord.ui.Modal, title="Enter your team"):
team_in = discord.ui.TextInput(label="Team name", placeholder="e.g. Simpson", required=True, max_length=60)
def __init__(self, flow):
super().__init__()
self.flow = flow
async def on_submit(self, interaction: discord.Interaction):
self.flow.team = str(self.team_in).strip()
await interaction.response.defer()
try:
await self.flow.message.edit(content=self.flow.prompt(), view=self.flow.build())
except discord.HTTPException:
pass
class GameSelect(discord.ui.Select):
def __init__(self, games: list[dict], selected_isos, *, multi: bool, allow_manual: bool, row: int = 2):
self.multi = multi
# Two draws can share a start time; dedupe so the iso values stay unique.
opts = _unique_options([
discord.SelectOption(label=_truncate(g["label"], 100), value=g["iso"], default=(g["iso"] in (selected_isos or [])))
for g in games[:23]
])
if allow_manual:
opts.append(discord.SelectOption(label="⌨️ Enter date manually…", value="__manual__"))
if not opts:
opts = [discord.SelectOption(label="No games in the next 2 weeks", value="__none__")]
super().__init__(
placeholder=("Games you can cover…" if multi else "Which game…"),
min_values=1, max_values=(len(opts) if multi else 1), options=opts, row=row,
)
async def callback(self, interaction: discord.Interaction):
vals = self.values
if "__none__" in vals:
await interaction.response.defer()
return
if "__manual__" in vals:
await interaction.response.send_modal(ManualDateModal(self.view))
return
if self.multi:
self.view.game_isos = list(vals)
else:
self.view.game_iso = vals[0]
await self.view.refresh(interaction)
class SpotsSelect(discord.ui.Select):
def __init__(self, selected: int, row: int = 3):
opts = [
discord.SelectOption(label=f"{n} spot{'s' if n > 1 else ''} needed", value=str(n), default=(n == selected))
for n in range(1, 5)
]
super().__init__(placeholder="How many subs needed…", min_values=1, max_values=1, options=opts, row=row)
async def callback(self, interaction: discord.Interaction):
self.view.spots = int(self.values[0])
await self.view.refresh(interaction)
class ManualDateModal(discord.ui.Modal, title="Enter game date & time"):
date_in = discord.ui.TextInput(label="Game date", placeholder="2026-06-20 or Jun 20", required=True, max_length=20)
time_in = discord.ui.TextInput(label="Game time", placeholder="7:30 PM or 19:30", required=True, max_length=12)
def __init__(self, flow):
super().__init__()
self.flow = flow
async def on_submit(self, interaction: discord.Interaction):
try:
when = parse_when(str(self.date_in), str(self.time_in))
except ValueError as ex:
await interaction.response.send_message(f"⚠️ {ex}", ephemeral=True)
return
self.flow.game_iso = when.replace(second=0, microsecond=0).isoformat()
await interaction.response.defer()
try:
await self.flow.message.edit(content=self.flow.prompt(), view=self.flow.build())
except discord.HTTPException:
pass
# ── Need-a-sub flow (ephemeral, league → team → game → spots → details) ──────
class NeedSubFlowView(discord.ui.View):
def __init__(self, leagues: list[dict]):
super().__init__(timeout=300)
self.leagues = leagues
self.league_id = None
self.team = None
self.game_iso = None
self.spots = 1
self.message = None
self.posted = False # one-shot guard: a posted flow can't post again
self.build()
def league(self) -> dict | None:
return next((l for l in self.leagues if str(l["id"]) == str(self.league_id)), None)
def on_league_change(self):
self.team = None
self.game_iso = None
def build(self) -> "NeedSubFlowView":
self.clear_items()
self.add_item(LeagueSelect(self.leagues, self.league_id, row=0))
lg = self.league()
if lg:
names = lg.get("team_names") or []
# Always offer the team step (dropdown when the league lists teams, plus
# a manual-entry option) — team is required info for a sub request.
self.add_item(TeamSelect(names, self.team, row=1))
self.add_item(GameSelect(
league_games(lg, club_now()),
[self.game_iso] if self.game_iso else [],
multi=False, allow_manual=True, row=2,
))
self.add_item(SpotsSelect(self.spots, row=3))
self.add_item(PostNeedButton(disabled=not self.ready(), row=4))
return self
def ready(self) -> bool:
lg = self.league()
if not lg:
return False
return bool(self.team) and bool(self.game_iso)
def prompt(self) -> str:
lg = self.league()
if not lg:
return "**Need a sub** — pick the league:"
parts = [f"League: **{clean_title(lg.get('title', ''))}**"]
if self.team:
parts.append(f"Team: **{self.team}**")
if self.game_iso:
parts.append(f"Game: **{fmt_when(self.game_iso)}**")
parts.append(f"Spots: **{self.spots}**")
tail = "Press **Post request**." if self.ready() else "Pick team, game, and spots."
return "**Need a sub** — " + " · ".join(parts) + f"\n{tail}"
async def refresh(self, interaction: discord.Interaction):
await interaction.response.edit_message(content=self.prompt(), view=self.build())
class PostNeedButton(discord.ui.Button):
def __init__(self, *, disabled: bool, row: int = 4):
super().__init__(label="Post request", emoji="✅", style=discord.ButtonStyle.success, row=row, disabled=disabled)
async def callback(self, interaction: discord.Interaction):
f: NeedSubFlowView = self.view
# One-shot guard: posting isn't idempotent (each call appends a new
# request), so an impatient double-tap would post twice. Set the flag
# synchronously — before any await — so a second callback (which can only
# run once this one yields) sees it and bails. Belt-and-braces with the
# button being removed from the view on success below.
if f.posted:
try:
await interaction.response.defer()
except discord.HTTPException:
pass
return
f.posted = True
try:
await interaction.response.defer()
except discord.HTTPException:
pass
lg = f.league()
title = clean_title(lg.get("title", "")) if lg else ""
cog: "Subs" = interaction.client.get_cog("Subs")
status, req = await cog.add_request(
requester=interaction.user,
league_id=f.league_id or "",
league=title,
team=f.team or "",
game_ts=f.game_iso,
spots=f.spots,
channel=interaction.channel,
)
if status == "duplicate":
# Don't stack an identical request on the board. Keep the flow open so
# they can tweak the team/game and re-post if it really is different.
f.posted = False
await interaction.edit_original_response(
content=(f"⚠️ There's already an open request for **{f.team}** · "
f"{fmt_when(f.game_iso)}. Claim or **Manage** that one instead — "
"or change the team/game below and re-post.\n\n" + f.prompt()),
view=f.build(),
)
return
# Offer to invite an available sub straight away (optional).
view = InviteView(req["id"], cog.state)
await interaction.edit_original_response(
content=(f"✅ Posted: **{title}** · {f.team or '—'} · {fmt_when(f.game_iso)} · needs {f.spots}.\n"
"Invite an available sub now (optional), or just leave it on the board:"),
view=view,
)
# ── Available-to-sub flow (ephemeral, league → games) ───────────────────────
class AvailFlowView(discord.ui.View):
def __init__(self, leagues: list[dict], user_id: int, state: dict | None = None):
super().__init__(timeout=300)
self.leagues = leagues
self.user_id = user_id
self.state = state or {}
self.league_id = None
self.game_isos: list[str] = []
self.message = None
self.build()
def league(self) -> dict | None:
return next((l for l in self.leagues if str(l["id"]) == str(self.league_id)), None)
def on_league_change(self):
self.game_isos = []
def open_requests(self) -> list[dict]:
"""All open requests (any league) the user could claim — shown first so they
can grab a spot without first having to pick a league."""
return _open_requests_for_fill(self.state, None, [], self.user_id)
def build(self) -> "AvailFlowView":
self.clear_items()
row = 0
# Claim open spots FIRST — always shown (a disabled placeholder when nothing
# is open), any league, no league pick needed.
self.add_item(FillOpenRequestSelect(self.open_requests(), row=row))
row += 1
# Then the optional general-availability path: pick a league → games → post.
self.add_item(LeagueSelect(self.leagues, self.league_id, row=row))
row += 1
lg = self.league()
if lg:
games = league_games(lg, club_now())
if games:
self.add_item(GameSelect(games, self.game_isos, multi=True, allow_manual=False, row=row))
row += 1
self.add_item(PostAvailButton(row=row))
return self
def prompt(self) -> str:
lines = ["**I can sub**"]
has_open = bool(self.open_requests())
if has_open:
lines.append("🔔 **Claim open spots** — pick any games that need a sub (any league) "
"from the top menu.")
prefix = "Or list " if has_open else "List "
lg = self.league()
if lg:
s = f"**general availability** · {clean_title(lg.get('title', ''))}"
if self.game_isos:
s += " · " + ", ".join(fmt_when(g) for g in self.game_isos)
lines.append(f"{prefix}{s} — choose games (or none for any), then **Post availability**.")
else:
lines.append(f"{prefix}**general availability** for other times — pick a league below.")
return "\n".join(lines)
async def refresh(self, interaction: discord.Interaction):
await interaction.response.edit_message(content=self.prompt(), view=self.build())
class PostAvailButton(discord.ui.Button):
def __init__(self, row: int = 2):
super().__init__(label="Post availability", emoji="🙋", style=discord.ButtonStyle.success, row=row)
async def callback(self, interaction: discord.Interaction):
# Ack immediately (feedback + dodge the 3s deadline before the board sync).
await interaction.response.defer()
view: AvailFlowView = self.view
lg = view.league()
if not lg:
return # leave the flow open so they can pick a league
title = clean_title(lg.get("title", ""))
cog: "Subs" = interaction.client.get_cog("Subs")
await cog.add_availability(user=interaction.user, league_id=view.league_id, league=title, games=view.game_isos)
gtxt = ", ".join(fmt_when(g) for g in view.game_isos) if view.game_isos else "any game"
await interaction.edit_original_response(
content=f"✅ Listed you as available for **{title}** · {gtxt}.", view=None)
def _open_requests_for_fill(state: dict, league_id, game_isos, user_id: int) -> list[dict]:
"""Open requests the user could fill from the 'I can sub' flow: in the chosen
league, matching the chosen game(s) (or any game in the league if none chosen),
with an open spot, excluding the user's own requests and ones they're already in."""
lid = str(league_id or "")
out = []
for r in store.requests_sorted(state):
if lid and str(r.get("league_id") or "") != lid:
continue
if store.open_spots(r) <= 0:
continue
if r.get("requester_id") == user_id or store.is_involved(r, user_id):
continue
if game_isos and not any(_same_game(r.get("game_ts", ""), g) for g in game_isos):
continue
out.append(r)
return out
class FillOpenRequestSelect(discord.ui.Select):
"""Surfaced in the 'I can sub' flow: pick one or more open requests (any league)
to claim their spots directly (each requester is notified). Renders as a disabled
placeholder when nothing is open, so the option stays visible instead of vanishing."""
def __init__(self, reqs: list[dict], row: int = 1):
opts = _unique_options([
discord.SelectOption(
label=_truncate(f"{fmt_when_short(r['game_ts'])}"
+ (f" · Team {r['team']}" if r.get("team") else ""), 100),
value=r["id"],
description=_truncate(f"{store.open_spots(r)} of {r['spots_needed']} spots open", 100),
)
for r in reqs[:25]
])
disabled = not opts
if disabled:
opts = [discord.SelectOption(label="No open requests to claim right now", value="__none__")]
super().__init__(
placeholder=("No open requests right now" if disabled else "Claim open spot(s) that need a sub…"),
min_values=1, max_values=(1 if disabled else max(1, len(opts))),
options=opts, disabled=disabled, row=row)
async def callback(self, interaction: discord.Interaction):
await interaction.response.defer()
if self.values and self.values[0] == "__none__":
return # disabled placeholder — nothing to claim
cog: "Subs" = interaction.client.get_cog("Subs")
filled, already, unavailable = [], [], []
for rid in self.values:
result, req = await cog.fill_request_spot(interaction.user, rid)
when = fmt_when(req["game_ts"]) if req else "that game"
if result == "added":
filled.append(when)
elif result == "already":
already.append(when)
else: # full / closed
unavailable.append(when)
parts = []
if filled:
parts.append("✅ You're in for: " + ", ".join(filled) + " — requester(s) notified.")
if already:
parts.append("Already in for: " + ", ".join(already) + ".")
if unavailable:
parts.append("Couldn't claim (filled up or closed): " + ", ".join(unavailable) + ".")
await interaction.edit_original_response(content="\n".join(parts) or "Nothing to claim.", view=None)
# ── Invite an available sub (requester picks → DM confirmation) ─────────────
def _same_game(a_iso: str, b_iso: str) -> bool:
"""True if two game timestamps refer to the same draw, compared to the minute
and tolerant of minor ISO formatting differences."""
if a_iso == b_iso:
return True
try:
return (datetime.fromisoformat(a_iso).replace(second=0, microsecond=0)
== datetime.fromisoformat(b_iso).replace(second=0, microsecond=0))
except (ValueError, TypeError):
return False
def _find_open_duplicate(state: dict, league_id, game_ts: str, team: str) -> dict | None:
"""An existing open request for the same league + game + team (case/space
tolerant), or None. All requests on the board are open, so a match is a dup."""
lid = str(league_id or "")
team_norm = (team or "").strip().casefold()
for r in state.get("requests", []):
if str(r.get("league_id") or "") != lid:
continue
if (r.get("team") or "").strip().casefold() != team_norm:
continue
if _same_game(r.get("game_ts", ""), game_ts or ""):
return r
return None
def _availability_for_request(state: dict, req: dict | None) -> list[dict]:
"""Subs who can cover THIS request: available in its league AND for its game
time. An availability with no specific games listed covers any game in that
league. Deduped by user; the requester-side filtering (anyone already filled or
pending) is applied so they don't show up as invitable."""
if not req:
return []
lid = str(req.get("league_id") or "")
game = req.get("game_ts") or ""
out, seen = [], set()
for a in state.get("availability", []):
uid = a["user_id"]
# Skip the requester themselves (you can't sub your own request) and anyone
# already filled/pending on it.
if uid in seen or uid == req.get("requester_id") or store.is_involved(req, uid):
continue
if lid and str(a.get("league_id") or "") != lid:
continue # different league
games = a.get("games") or []
if games and game and not any(_same_game(game, g) for g in games):
continue # available in this league, but not for this game time
seen.add(uid)
out.append(a)
return out
class InviteView(discord.ui.View):
"""Ephemeral picker shown after posting or via Manage."""
def __init__(self, rid: str, state: dict):
super().__init__(timeout=300)
req = store.find_request(state, rid)
self.add_item(InviteSelect(rid, _availability_for_request(state, req)))
class InviteSelect(discord.ui.Select):
def __init__(self, rid: str, entries: list[dict], row: int | None = None):
self.rid = rid
self.names = {int(a["user_id"]): a["name"] for a in entries}
opts = []
for a in entries[:25]:
games = a.get("games") or []
desc = ", ".join(fmt_when_short(g) for g in games) if games else "any game"
opts.append(discord.SelectOption(
label=_truncate(a["name"], 100), value=str(a["user_id"]), description=_truncate(desc, 100)))
opts = _unique_options(opts) # belt-and-braces: never emit a duplicate user value
disabled = not opts
if not opts:
opts = [discord.SelectOption(label="No available subs to invite", value="__none__")]
super().__init__(placeholder="Invite an available sub…", min_values=1, max_values=1,
options=opts, disabled=disabled, row=row)
async def callback(self, interaction: discord.Interaction):
# Ack immediately (the invite does a DM + board sync that can be slow).
await interaction.response.defer()
if self.values[0] == "__none__":
return
uid = int(self.values[0])
name = self.names.get(uid, "a sub")
cog: "Subs" = interaction.client.get_cog("Subs")
# invite_sub is idempotent (returns "already" if they're already pending/
# filled), so a repeated pick can't double-book or double-DM.
result = await cog.invite(self.rid, uid, name, inviter=interaction.user)
msgs = {
"invited": f"📨 Invited **{name}** — they'll get a DM to confirm. Pending until they accept.",
"already": f"**{name}** is already on this request.",
"full": "No open spots left to invite into.",
"closed": "That request is no longer available.",
}
view = InviteView(self.rid, cog.state) if result in ("invited", "already") else None
await interaction.edit_original_response(content=msgs.get(result, "Done."), view=view)
def confirm_view(rid: str, uid) -> discord.ui.View:
v = discord.ui.View(timeout=None)
v.add_item(ConfirmButton(rid, uid))
v.add_item(DeclineButton(rid, uid))
return v
class ConfirmButton(discord.ui.DynamicItem[discord.ui.Button],
template=r"sub:confirm:(?P<rid>[0-9a-f]+):(?P<uid>\d+)"):
def __init__(self, rid: str, uid):
self.rid = rid
self.uid = str(uid)
super().__init__(discord.ui.Button(
label="Confirm", emoji="✅", style=discord.ButtonStyle.success,
custom_id=f"sub:confirm:{rid}:{uid}"))
@classmethod
async def from_custom_id(cls, interaction, item, match):
return cls(match["rid"], match["uid"])
async def callback(self, interaction: discord.Interaction):
cog: "Subs" = interaction.client.get_cog("Subs")
await cog.handle_invite_response(interaction, self.rid, int(self.uid), confirm=True)
class DeclineButton(discord.ui.DynamicItem[discord.ui.Button],
template=r"sub:decline:(?P<rid>[0-9a-f]+):(?P<uid>\d+)"):
def __init__(self, rid: str, uid):
self.rid = rid
self.uid = str(uid)
super().__init__(discord.ui.Button(
label="Can't", emoji="❌", style=discord.ButtonStyle.danger,
custom_id=f"sub:decline:{rid}:{uid}"))
@classmethod
async def from_custom_id(cls, interaction, item, match):
return cls(match["rid"], match["uid"])
async def callback(self, interaction: discord.Interaction):
cog: "Subs" = interaction.client.get_cog("Subs")
await cog.handle_invite_response(interaction, self.rid, int(self.uid), confirm=False)
# ── Manage flow (ephemeral) ─────────────────────────────────────────────────
# Manages both sides of the board for the caller: requests they opened, the spots
# they're subbing (drop), and the availability they've listed (remove).
def _my_requests(state: dict, uid: int) -> list[dict]:
return [r for r in store.requests_sorted(state) if r.get("requester_id") == uid]
def _my_spots(state: dict, uid: int) -> list[dict]:
"""Requests where the caller is a sub (filled or pending)."""
return [r for r in store.requests_sorted(state)
if store.is_filled_by(r, uid) or store.is_pending_by(r, uid)]
class ManageHomeView(discord.ui.View):
"""One ephemeral panel with a select per category the caller has anything in."""
def __init__(self, state: dict, uid: int):
super().__init__(timeout=180)
row = 0
my_requests = _my_requests(state, uid)
if my_requests:
self.add_item(ManagePickSelect(my_requests, row=row))
row += 1
my_spots = _my_spots(state, uid)
if my_spots:
self.add_item(DropSpotSelect(my_spots, uid, 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 ManagePickSelect(discord.ui.Select):
def __init__(self, requests: list[dict], row: int | None = None):
options = [
discord.SelectOption(
label=fmt_when(r["game_ts"])[:100],
value=r["id"],
description=(f"{store.open_spots(r)} open · filled: " +
(", ".join(f["name"] for f in r["filled"]) or "nobody"))[:100],
)
for r in requests[:25]
]
super().__init__(placeholder="Manage a request you opened…",
options=options, min_values=1, max_values=1, 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 available.", view=None)
return
await interaction.response.edit_message(
content=f"Managing **{fmt_when(req['game_ts'])}** ({store.open_spots(req)} open):",
view=ManageActionView(req["id"], cog.state),
)
class DropSpotSelect(discord.ui.Select):
"""Drop a spot the caller is subbing (filled or pending). Requester is notified."""
def __init__(self, spots: list[dict], uid: int, row: int | None = None):
opts = _unique_options([
discord.SelectOption(
label=_truncate(f"{fmt_when_short(r['game_ts'])}"
+ (f" · Team {r['team']}" if r.get("team") else ""), 100),
value=r["id"],
description=_truncate(
"awaiting your confirmation" if store.is_pending_by(r, uid) else "you're in", 100),