-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2703 lines (2318 loc) · 101 KB
/
main.py
File metadata and controls
2703 lines (2318 loc) · 101 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
import os
import asyncio
import random
import json
import shutil
import datetime
import typing
from collections import Counter
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Set, Tuple
from dotenv import load_dotenv; load_dotenv()
import aiosqlite
import discord
from discord import app_commands
from discord.ext import commands
# -----------------------------
# Configi :3
# -----------------------------
QUEUE_SIZE = 10
READYCHECK_SECONDS = 120
GUILD_SCOPED = True
PICK_TIMEOUT_SECONDS = 45
AUTO_VOICE_CHANNELS = True
TEAM1_VOICE_CHANNEL_ID = 1442861436542910494
TEAM2_VOICE_CHANNEL_ID = 1442861481564831785
VOICE_LOBBY_CHANNEL_ID = 364497233061871628
# ---- UI: värit ja footer ----
EMBED_COLOR_PRIMARY = 0x29377e
EMBED_FOOTER_TEXT = "CSDraft by Alex"
PICK_ORDER = [
"team1", "team2", "team1", "team2", "team1", "team2", "team2"
]
# ---- Elo settings ----
INITIAL_RATING = 1000.0
BASE_MATCH_DELTA = 25.0
MAX_MATCH_DELTA = 30.0
MAX_DRAW_DELTA = 5.0
def build_stats_embed(
bot_name: str,
display_name: str,
games: int, wins: int, winrate: float,
captain: int, first_picked: int, last_picked: int,
r_games: int, r_wins: int, r_captain: int, r_first: int, r_last: int,
total_players: int,
elo_rating: float,
r_elo: int,
avg_pick_round: Optional[float],
) -> discord.Embed:
emb = discord.Embed(
title=f"Pelaajatilastot",
color=EMBED_COLOR_PRIMARY
)
emb.add_field(
name="Pelatut pelit",
value=f"**{display_name}** on pelannut **{games}** peliä "
f"({r_games}/{total_players})",
inline=False
)
emb.add_field(
name="Voitot",
value=f"**{display_name}** on voittanut **{wins}** peliä (**{winrate:.1f}%** WR) "
f"({r_wins}/{total_players})",
inline=False
)
emb.add_field(
name="Elo",
value=f"**{display_name}** elo: **{int(round(elo_rating))}** "
f"({r_elo}/{total_players})",
inline=False
)
emb.add_field(
name="Kapteeni",
value=f"**{display_name}** on toiminut kapteenina **{captain}** kertaa "
f"({r_captain}/{total_players})",
inline=False
)
emb.add_field(
name="Valittu ensimmäisenä",
value=f"**{display_name}** on valittu ensimmäisenä **{first_picked}** kertaa "
f"({r_first}/{total_players})",
inline=False
)
emb.add_field(
name="Valittu viimeisenä",
value=f"**{display_name}** on valittu viimeisenä **{last_picked}** kertaa "
f"({r_last}/{total_players})",
inline=False
)
avg_text = f"{avg_pick_round:.2f}" if avg_pick_round is not None else "—"
emb.add_field(
name="Valinnan keskiarvo",
value=f"**{display_name}** on valittu keskimäärin vuorolla **{avg_text}**",
inline=False,
)
emb.set_footer(text="CSDraft by Alex")
return emb
def format_winrate(winrate: float, show_label: bool) -> str:
label = " WR" if show_label else ""
return f"{winrate:.1f}%{label}"
# -----------------------------
@dataclass
class DraftState:
queue: List[int] = field(default_factory=list)
queue_joined_at: Dict[int, datetime.datetime] = field(default_factory=dict)
readycheck_active: bool = False
ready_users: Set[int] = field(default_factory=set)
fake_users: Set[int] = field(default_factory=set)
ready_task: Optional[asyncio.Task] = None
draft_active: bool = False
captains: Tuple[int, int] | None = None
team1: List[int] = field(default_factory=list)
team2: List[int] = field(default_factory=list)
number_by_uid: Dict[int, int] = field(default_factory=dict)
pick_pool: List[int] = field(default_factory=list)
pick_order: List[str] = field(default_factory=lambda: PICK_ORDER.copy())
pick_index: int = 0
pick_msg: Optional[discord.Message] = None
pick_timer_task: Optional[asyncio.Task] = None
pick_deadline_ts: Optional[float] = None
timer_msg: Optional[discord.Message] = None
last_pick_prefix: Optional[str] = None
rc_timer_task: Optional[asyncio.Task] = None
rc_timer_msg: Optional[discord.Message] = None
rc_deadline_ts: Optional[float] = None
pick_timer_seq: int = 0
game_id: Optional[int] = None
# -----------------------------
# Database tsydeemi :3
# -----------------------------
SCHEMA_SQL = """
PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS players (
user_id INTEGER PRIMARY KEY,
games_played INTEGER NOT NULL DEFAULT 0,
wins INTEGER NOT NULL DEFAULT 0,
captain_wins INTEGER NOT NULL DEFAULT 0,
captain_count INTEGER NOT NULL DEFAULT 0,
first_pick_count INTEGER NOT NULL DEFAULT 0,
last_pick_count INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS games (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
team1 TEXT NOT NULL, -- JSON array of user_ids
team2 TEXT NOT NULL, -- JSON array of user_ids
winner INTEGER, -- 1 or 2, NULL if unset
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS ratings (
user_id TEXT PRIMARY KEY,
rating REAL NOT NULL,
elo_games INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS rating_history (
game_id TEXT NOT NULL,
user_id TEXT NOT NULL,
pre_rating REAL NOT NULL,
post_rating REAL NOT NULL,
delta REAL NOT NULL,
created_at TEXT NOT NULL,
UNIQUE(game_id, user_id)
);
CREATE TABLE IF NOT EXISTS captain_opt_out (
user_id INTEGER PRIMARY KEY
);
"""
class DB:
def __init__(self, path: str = "draftbot.sqlite3") -> None:
self.path = path
self._lock = asyncio.Lock()
async def init(self):
async with aiosqlite.connect(self.path) as db:
await db.executescript(SCHEMA_SQL)
await db.execute("BEGIN")
async def column_exists(table: str, column: str) -> bool:
cur = await db.execute(f"PRAGMA table_info({table})")
rows = await cur.fetchall()
return any(row[1] == column for row in rows)
ratings_has_rd = await column_exists("ratings", "rd")
history_has_pre_rd = await column_exists("rating_history", "pre_rd")
history_has_post_rd = await column_exists("rating_history", "post_rd")
if ratings_has_rd:
await db.execute(
"""
CREATE TABLE IF NOT EXISTS ratings_new (
user_id TEXT PRIMARY KEY,
rating REAL NOT NULL,
elo_games INTEGER NOT NULL
)
"""
)
await db.execute(
"INSERT INTO ratings_new (user_id, rating, elo_games) SELECT user_id, rating, elo_games FROM ratings"
)
await db.execute("DROP TABLE ratings")
await db.execute("ALTER TABLE ratings_new RENAME TO ratings")
if history_has_pre_rd or history_has_post_rd:
await db.execute(
"""
CREATE TABLE IF NOT EXISTS rating_history_new (
game_id TEXT NOT NULL,
user_id TEXT NOT NULL,
pre_rating REAL NOT NULL,
post_rating REAL NOT NULL,
delta REAL NOT NULL,
created_at TEXT NOT NULL,
UNIQUE(game_id, user_id)
)
"""
)
await db.execute(
"""
INSERT INTO rating_history_new
(game_id, user_id, pre_rating, post_rating, delta, created_at)
SELECT game_id, user_id, pre_rating, post_rating, delta, created_at
FROM rating_history
"""
)
await db.execute("DROP TABLE rating_history")
await db.execute("ALTER TABLE rating_history_new RENAME TO rating_history")
try:
await db.execute("ALTER TABLE players ADD COLUMN captain_wins INTEGER NOT NULL DEFAULT 0")
except aiosqlite.OperationalError:
pass
await db.commit()
async def ensure_player(self, user_id: int):
async with self._lock:
async with aiosqlite.connect(self.path) as db:
await db.execute(
"INSERT OR IGNORE INTO players (user_id) VALUES (?)",
(user_id,),
)
await db.commit()
async def ensure_rating(self, user_id: int):
async with self._lock:
async with aiosqlite.connect(self.path) as db:
await db.execute(
"INSERT OR IGNORE INTO ratings (user_id, rating, elo_games) VALUES (?, ?, ?)",
(user_id, INITIAL_RATING, 0),
)
await db.commit()
async def get_rating_rows(self, user_ids: List[int]) -> Dict[int, Tuple[float, int]]:
if not user_ids:
return {}
placeholders = ",".join("?" for _ in user_ids)
async with aiosqlite.connect(self.path) as db:
cur = await db.execute(
f"SELECT user_id, rating, elo_games FROM ratings WHERE user_id IN ({placeholders})",
tuple(user_ids),
)
rows = await cur.fetchall()
return {int(uid): (float(rating), int(games)) for uid, rating, games in rows}
async def get_top_ratings(self, limit: int = 10) -> List[Tuple[int, float, int]]:
async with aiosqlite.connect(self.path) as db:
cur = await db.execute(
"SELECT user_id, rating, elo_games FROM ratings ORDER BY rating DESC, elo_games DESC, user_id ASC LIMIT ?",
(limit,),
)
rows = await cur.fetchall()
return [(int(uid), float(rating), int(games)) for uid, rating, games in rows]
async def get_games_played(self, user_ids: List[int]) -> Dict[int, int]:
if not user_ids:
return {}
placeholders = ",".join("?" for _ in user_ids)
async with aiosqlite.connect(self.path) as db:
cur = await db.execute(
f"SELECT user_id, games_played FROM players WHERE user_id IN ({placeholders})",
tuple(user_ids),
)
rows = await cur.fetchall()
return {int(uid): int(games) for uid, games in rows}
async def get_captain_opt_outs(self, user_ids: List[int]) -> Set[int]:
if not user_ids:
return set()
placeholders = ",".join("?" for _ in user_ids)
async with aiosqlite.connect(self.path) as db:
cur = await db.execute(
f"SELECT user_id FROM captain_opt_out WHERE user_id IN ({placeholders})",
tuple(user_ids),
)
rows = await cur.fetchall()
return {int(uid) for (uid,) in rows}
async def set_captain_opt_out(self, user_id: int, opted_out: bool) -> None:
async with self._lock:
async with aiosqlite.connect(self.path) as db:
if opted_out:
await db.execute(
"INSERT OR IGNORE INTO captain_opt_out (user_id) VALUES (?)",
(user_id,),
)
else:
await db.execute(
"DELETE FROM captain_opt_out WHERE user_id = ?",
(user_id,),
)
await db.commit()
async def get_rating_changes_for_game(self, game_id: int) -> Dict[int, float]:
async with aiosqlite.connect(self.path) as db:
cur = await db.execute(
"SELECT user_id, delta FROM rating_history WHERE game_id = ?",
(str(game_id),),
)
rows = await cur.fetchall()
return {int(uid): float(delta) for uid, delta in rows}
async def get_rating_history_for_game(self, game_id: int) -> Dict[int, Tuple[float, float, float]]:
async with aiosqlite.connect(self.path) as db:
cur = await db.execute(
"SELECT user_id, pre_rating, post_rating, delta FROM rating_history WHERE game_id = ?",
(str(game_id),),
)
rows = await cur.fetchall()
return {
int(uid): (float(pre_rating), float(post_rating), float(delta))
for uid, pre_rating, post_rating, delta in rows
}
async def _rollback_ratings_for_game_tx(self, db: aiosqlite.Connection, game_id: int) -> None:
cur = await db.execute(
"SELECT user_id, pre_rating FROM rating_history WHERE game_id = ?",
(str(game_id),),
)
rows = await cur.fetchall()
if not rows:
return
for user_id, pre_rating in rows:
await db.execute(
"INSERT OR IGNORE INTO ratings (user_id, rating, elo_games) VALUES (?, ?, ?)",
(user_id, pre_rating, 0),
)
await db.execute(
"UPDATE ratings SET rating = ?, elo_games = CASE WHEN elo_games > 0 THEN elo_games - 1 ELSE 0 END WHERE user_id = ?",
(pre_rating, user_id),
)
await db.execute("DELETE FROM rating_history WHERE game_id = ?", (str(game_id),))
async def rollback_ratings_for_game(self, game_id: int) -> None:
async with self._lock:
async with aiosqlite.connect(self.path) as db:
await db.execute("BEGIN")
await self._rollback_ratings_for_game_tx(db, game_id)
await db.commit()
def _expected_score(self, rating_a: float, rating_b: float) -> float:
return 1.0 / (1.0 + 10 ** ((rating_b - rating_a) / 400.0))
async def _apply_ratings_for_game_tx(
self,
db: aiosqlite.Connection,
game_id: int,
team1_ids: List[int],
team2_ids: List[int],
result: str,
) -> None:
if result not in {"team1_win", "team2_win", "draw"}:
raise ValueError("Tuntematon ottelutulos.")
for uid in team1_ids + team2_ids:
await db.execute(
"INSERT OR IGNORE INTO ratings (user_id, rating, elo_games) VALUES (?, ?, ?)",
(uid, INITIAL_RATING, 0),
)
all_ids = team1_ids + team2_ids
placeholders = ",".join("?" for _ in all_ids)
cur = await db.execute(
f"SELECT user_id, rating, elo_games FROM ratings WHERE user_id IN ({placeholders})",
tuple(all_ids),
)
rows = await cur.fetchall()
ratings_map = {int(uid): (float(rating), int(games)) for uid, rating, games in rows}
team1_ratings = [ratings_map[uid][0] for uid in team1_ids]
team2_ratings = [ratings_map[uid][0] for uid in team2_ids]
team1_rating = average(team1_ratings)
team2_rating = average(team2_ratings)
exp_team1 = self._expected_score(team1_rating, team2_rating)
exp_team2 = 1.0 - exp_team1
if result == "team1_win":
score_team1, score_team2 = 1.0, 0.0
elif result == "team2_win":
score_team1, score_team2 = 0.0, 1.0
else:
score_team1 = score_team2 = 0.5
timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat()
async def apply_for_team(team_ids: List[int], score_team: float, expected_team: float) -> None:
for uid in team_ids:
rating, elo_games = ratings_map[uid]
delta = BASE_MATCH_DELTA * (score_team - expected_team)
if score_team == 0.5:
delta = _clip(delta, -MAX_DRAW_DELTA, MAX_DRAW_DELTA)
else:
delta = _clip(delta, -MAX_MATCH_DELTA, MAX_MATCH_DELTA)
new_rating = rating + delta
await db.execute(
"UPDATE ratings SET rating = ?, elo_games = elo_games + 1 WHERE user_id = ?",
(new_rating, uid),
)
await db.execute(
"""
INSERT INTO rating_history
(game_id, user_id, pre_rating, post_rating, delta, created_at)
VALUES (?, ?, ?, ?, ?, ?)
""",
(
str(game_id),
uid,
rating,
new_rating,
delta,
timestamp,
),
)
await apply_for_team(team1_ids, score_team1, exp_team1)
await apply_for_team(team2_ids, score_team2, exp_team2)
async def apply_ratings_for_game(
self,
game_id: int,
team1_ids: List[int],
team2_ids: List[int],
result: str,
) -> None:
async with self._lock:
async with aiosqlite.connect(self.path) as db:
await db.execute("BEGIN")
await self._apply_ratings_for_game_tx(db, game_id, team1_ids, team2_ids, result)
await db.commit()
async def recalc_all_ratings_from_history(self) -> int:
async with self._lock:
async with aiosqlite.connect(self.path) as db:
await db.execute("BEGIN")
await db.execute("DELETE FROM rating_history")
await db.execute("DELETE FROM ratings")
cur = await db.execute(
"SELECT id, team1, team2, winner FROM games WHERE winner IS NOT NULL ORDER BY created_at ASC, id ASC"
)
games = await cur.fetchall()
for game_id, team1_raw, team2_raw, winner in games:
team1 = json.loads(team1_raw)
team2 = json.loads(team2_raw)
if winner == 1:
result = "team1_win"
elif winner == 2:
result = "team2_win"
else:
result = "draw"
await self._apply_ratings_for_game_tx(db, game_id, team1, team2, result)
await db.commit()
return len(games)
async def bump_captain(self, user_id: int, delta: int = 1):
await self.ensure_player(user_id)
async with self._lock:
async with aiosqlite.connect(self.path) as db:
await db.execute(
"UPDATE players SET captain_count = captain_count + ? WHERE user_id = ?",
(delta, user_id),
)
await db.commit()
async def bump_first_last(self, user_id: int, first: bool = False, last: bool = False):
if not (first or last):
return
await self.ensure_player(user_id)
column = "first_pick_count" if first else "last_pick_count"
async with self._lock:
async with aiosqlite.connect(self.path) as db:
await db.execute(
f"UPDATE players SET {column} = {column} + 1 WHERE user_id = ?",
(user_id,),
)
await db.commit()
async def record_game(
self,
guild_id: int,
team1: List[int],
team2: List[int],
captain1: Optional[int] = None,
captain2: Optional[int] = None,
) -> int:
if captain1 in team1:
team1 = [captain1] + [uid for uid in team1 if uid != captain1]
if captain2 in team2:
team2 = [captain2] + [uid for uid in team2 if uid != captain2]
async with self._lock:
async with aiosqlite.connect(self.path) as db:
for uid in team1 + team2:
await db.execute("INSERT OR IGNORE INTO players (user_id) VALUES (?)", (uid,))
await db.execute(
"UPDATE players SET games_played = games_played + 1 WHERE user_id = ?",
(uid,),
)
cur = await db.execute(
"INSERT INTO games (guild_id, team1, team2) VALUES (?,?,?)",
(guild_id, json.dumps(team1), json.dumps(team2)),
)
await db.commit()
return cur.lastrowid
async def set_winner(self, game_id: int, winner_team: int, overwrite: bool = False) -> Tuple[List[int], List[int]]:
if winner_team not in (1, 2):
raise ValueError("Voittajan tulee olla 1 tai 2.")
async with self._lock:
async with aiosqlite.connect(self.path) as db:
cur = await db.execute("SELECT team1, team2, winner FROM games WHERE id=?", (game_id,))
row = await cur.fetchone()
if not row:
raise ValueError("Peliä ei löytynyt tällä ID:llä.")
team1 = json.loads(row[0])
team2 = json.loads(row[1])
previous_winner = row[2]
captain1 = team1[0] if team1 else None
captain2 = team2[0] if team2 else None
if previous_winner is None:
await db.execute("UPDATE games SET winner=? WHERE id=?", (winner_team, game_id))
winners = team1 if winner_team == 1 else team2
for uid in winners:
await db.execute("UPDATE players SET wins = wins + 1 WHERE user_id = ?", (uid,))
winning_captain = captain1 if winner_team == 1 else captain2
if winning_captain is not None:
await db.execute(
"UPDATE players SET captain_wins = captain_wins + 1 WHERE user_id = ?",
(winning_captain,),
)
result = "team1_win" if winner_team == 1 else "team2_win"
await self._apply_ratings_for_game_tx(db, game_id, team1, team2, result)
await db.commit()
return team1, team2
if not overwrite:
raise ValueError("Tälle pelille on jo asetettu voittaja.")
if previous_winner == winner_team:
await db.commit()
return team1, team2
prev_winners = team1 if previous_winner == 1 else team2
new_winners = team1 if winner_team == 1 else team2
if previous_winner in (1, 2):
for uid in prev_winners:
await db.execute("UPDATE players SET wins = wins - 1 WHERE user_id = ?", (uid,))
prev_captain = captain1 if previous_winner == 1 else captain2
if prev_captain is not None:
await db.execute(
"UPDATE players SET captain_wins = captain_wins - 1 WHERE user_id = ?",
(prev_captain,),
)
for uid in new_winners:
await db.execute("UPDATE players SET wins = wins + 1 WHERE user_id = ?", (uid,))
new_captain = captain1 if winner_team == 1 else captain2
if new_captain is not None:
await db.execute(
"UPDATE players SET captain_wins = captain_wins + 1 WHERE user_id = ?",
(new_captain,),
)
await db.execute("UPDATE games SET winner=? WHERE id=?", (winner_team, game_id))
await self._rollback_ratings_for_game_tx(db, game_id)
result = "team1_win" if winner_team == 1 else "team2_win"
await self._apply_ratings_for_game_tx(db, game_id, team1, team2, result)
await db.commit()
return team1, team2
async def set_draw(self, game_id: int, overwrite: bool = False) -> Tuple[List[int], List[int]]:
async with self._lock:
async with aiosqlite.connect(self.path) as db:
cur = await db.execute("SELECT team1, team2, winner FROM games WHERE id=?", (game_id,))
row = await cur.fetchone()
if not row:
raise ValueError("Peliä ei löytynyt tällä ID:llä.")
team1 = json.loads(row[0])
team2 = json.loads(row[1])
previous_winner = row[2]
captain1 = team1[0] if team1 else None
captain2 = team2[0] if team2 else None
if previous_winner is None:
await db.execute("UPDATE games SET winner=0 WHERE id=?", (game_id,))
await self._apply_ratings_for_game_tx(db, game_id, team1, team2, "draw")
await db.commit()
return team1, team2
if previous_winner in (1, 2):
if not overwrite:
raise ValueError("Tälle pelille on jo asetettu voittaja.")
prev_winners = team1 if previous_winner == 1 else team2
for uid in prev_winners:
await db.execute("UPDATE players SET wins = wins - 1 WHERE user_id = ?", (uid,))
prev_captain = captain1 if previous_winner == 1 else captain2
if prev_captain is not None:
await db.execute(
"UPDATE players SET captain_wins = captain_wins - 1 WHERE user_id = ?",
(prev_captain,),
)
await db.execute("UPDATE games SET winner=0 WHERE id=?", (game_id,))
await self._rollback_ratings_for_game_tx(db, game_id)
await self._apply_ratings_for_game_tx(db, game_id, team1, team2, "draw")
await db.commit()
return team1, team2
# Oli jo tasapeli (winner=0)
await db.commit()
return team1, team2
async def get_player(self, user_id: int) -> Optional[dict]:
async with aiosqlite.connect(self.path) as db:
cur = await db.execute(
"SELECT games_played,wins,captain_count,first_pick_count,last_pick_count FROM players WHERE user_id=?",
(user_id,),
)
row = await cur.fetchone()
if not row:
return None
return {
"games_played": row[0],
"wins": row[1],
"captain_count": row[2],
"first_pick_count": row[3],
"last_pick_count": row[4],
}
async def leaderboard(self, column: str, limit: int = 10) -> List[Tuple[int, int, int]]:
valid = {
"games_played": "games_played",
"wins": "wins",
"captain_count": "captain_count",
"first_pick_count": "first_pick_count",
"last_pick_count": "last_pick_count",
}
if column not in valid:
raise ValueError("Tuntematon sarake leaderbordiin")
async with aiosqlite.connect(self.path) as db:
cur = await db.execute(
f"SELECT user_id, {valid[column]}, games_played, wins FROM players ORDER BY {valid[column]} DESC, wins DESC, user_id ASC LIMIT ?",
(limit,),
)
return await cur.fetchall()
async def get_game(self, game_id: int) -> Optional[dict]:
async with aiosqlite.connect(self.path) as db:
cur = await db.execute(
"SELECT id, guild_id, team1, team2, winner FROM games WHERE id=?",
(game_id,)
)
row = await cur.fetchone()
if not row:
return None
return {
"id": row[0],
"guild_id": row[1],
"team1": json.loads(row[2]),
"team2": json.loads(row[3]),
"winner": row[4], # 1 tai 2 tai None
}
async def get_rank(self, field: str, user_id: int) -> int:
valid = {"games_played", "wins", "captain_count", "first_pick_count", "last_pick_count"}
if field not in valid:
raise ValueError("Tuntematon kenttä rankille")
async with self._lock:
async with aiosqlite.connect(self.path) as db:
# Pelaajan arvo
cur = await db.execute(f"SELECT {field} FROM players WHERE user_id = ?", (user_id,))
row = await cur.fetchone()
target = int(row[0]) if row and row[0] is not None else 0
# Pelaajien kokonaismäärä
cur = await db.execute("SELECT COUNT(*) FROM players")
(total_players,) = await cur.fetchone()
total_players = int(total_players or 0)
# Nollissa: kaikille viimeinen sijoitus (== total_players)
if target <= 0:
return total_players
# Muissa arvoissa: dense ranking
cur = await db.execute(f"SELECT COUNT(*) FROM players WHERE {field} > ?", (target,))
(higher_count,) = await cur.fetchone()
return int(higher_count) + 1
async def get_elo_rank(self, user_id: int) -> int:
async with self._lock:
async with aiosqlite.connect(self.path) as db:
cur = await db.execute("SELECT rating FROM ratings WHERE user_id = ?", (user_id,))
row = await cur.fetchone()
target = float(row[0]) if row and row[0] is not None else 0.0
cur = await db.execute("SELECT COUNT(*) FROM ratings")
(total_players,) = await cur.fetchone()
total_players = int(total_players or 0)
if target <= 0:
return total_players
cur = await db.execute("SELECT COUNT(*) FROM ratings WHERE rating > ?", (target,))
(higher_count,) = await cur.fetchone()
return int(higher_count) + 1
async def count_players(self) -> int:
async with aiosqlite.connect(self.path) as db:
cur = await db.execute("SELECT COUNT(*) FROM players")
(n,) = await cur.fetchone()
return int(n or 0)
async def get_recent_game_ids(self, limit: int = 10) -> List[int]:
async with aiosqlite.connect(self.path) as db:
cur = await db.execute("SELECT id FROM games ORDER BY id DESC LIMIT ?", (limit,))
rows = await cur.fetchall()
return [r[0] for r in rows]
async def get_head_to_head(self, user_id: int, opponent_id: int) -> dict:
if user_id == opponent_id:
return {"games": 0, "wins": 0, "losses": 0, "draws": 0}
games = wins = losses = draws = 0
async with aiosqlite.connect(self.path) as db:
cur = await db.execute(
"SELECT team1, team2, winner FROM games WHERE team1 LIKE ? OR team2 LIKE ?",
(f"%{user_id}%", f"%{user_id}%"),
)
rows = await cur.fetchall()
for team1_raw, team2_raw, winner in rows:
team1 = json.loads(team1_raw)
team2 = json.loads(team2_raw)
if user_id in team1 and opponent_id in team2:
user_team = 1
elif user_id in team2 and opponent_id in team1:
user_team = 2
else:
continue
if winner is None:
continue
games += 1
if winner == 0:
draws += 1
elif winner == user_team:
wins += 1
else:
losses += 1
return {"games": games, "wins": wins, "losses": losses, "draws": draws}
async def get_head_to_head_summary(self, user_id: int) -> Dict[int, dict]:
stats: Dict[int, dict] = {}
async with aiosqlite.connect(self.path) as db:
cur = await db.execute(
"SELECT team1, team2, winner FROM games WHERE team1 LIKE ? OR team2 LIKE ?",
(f"%{user_id}%", f"%{user_id}%"),
)
rows = await cur.fetchall()
for team1_raw, team2_raw, winner in rows:
team1 = json.loads(team1_raw)
team2 = json.loads(team2_raw)
if user_id in team1:
user_team = 1
opponents = team2
elif user_id in team2:
user_team = 2
opponents = team1
else:
continue
if winner is None:
continue
for opponent_id in opponents:
entry = stats.setdefault(
opponent_id,
{"games": 0, "wins": 0, "losses": 0, "draws": 0},
)
entry["games"] += 1
if winner == 0:
entry["draws"] += 1
elif winner == user_team:
entry["wins"] += 1
else:
entry["losses"] += 1
return stats
async def get_draws_for_users(self, user_ids: List[int]) -> Dict[int, int]:
if not user_ids:
return {}
target_ids = set(user_ids)
draws_by_user = {uid: 0 for uid in target_ids}
async with aiosqlite.connect(self.path) as db:
cur = await db.execute(
"SELECT team1, team2 FROM games WHERE winner = 0"
)
rows = await cur.fetchall()
for team1_raw, team2_raw in rows:
team1 = json.loads(team1_raw)
team2 = json.loads(team2_raw)
for uid in team1 + team2:
if uid in target_ids:
draws_by_user[uid] += 1
return draws_by_user
async def get_pick_winrates(
self,
user_ids: List[int],
pick_index: int,
) -> Dict[int, Dict[str, int]]:
if not user_ids:
return {}
target_ids = set(user_ids)
stats = {uid: {"games": 0, "wins": 0, "draws": 0} for uid in target_ids}
async with aiosqlite.connect(self.path) as db:
cur = await db.execute(
"SELECT team1, winner FROM games WHERE winner IS NOT NULL"
)
rows = await cur.fetchall()
for team1_raw, winner in rows:
team1 = json.loads(team1_raw)
if not team1:
continue
if pick_index >= 0 and len(team1) <= pick_index:
continue
try:
picked_uid = team1[pick_index]
except IndexError:
continue
if picked_uid not in target_ids:
continue
entry = stats[picked_uid]
entry["games"] += 1
if winner == 0:
entry["draws"] += 1
elif winner == 1:
entry["wins"] += 1
return stats
async def get_pick_turns_for_user(
self,
user_id: int,
pick_order: List[str],
) -> List[int]:
turns: List[int] = []
async with aiosqlite.connect(self.path) as db:
cur = await db.execute(
"SELECT team1, team2 FROM games"
)
rows = await cur.fetchall()
for team1_raw, team2_raw in rows:
team1 = json.loads(team1_raw)
team2 = json.loads(team2_raw)
if not team1 and not team2:
continue
captain1 = team1[0] if team1 else None
captain2 = team2[0] if team2 else None
if user_id in {captain1, captain2}:
continue
if user_id not in team1 and user_id not in team2:
continue
team1_picks = team1[1:] if len(team1) > 1 else []
team2_picks = team2[1:] if len(team2) > 1 else []
idx1 = idx2 = 0
for pick_index, team in enumerate(pick_order, start=1):
if team == "team1":
if idx1 >= len(team1_picks):
continue
picked_uid = team1_picks[idx1]
idx1 += 1
else:
if idx2 >= len(team2_picks):
continue
picked_uid = team2_picks[idx2]
idx2 += 1
if picked_uid == user_id:
turns.append(pick_index)
leftover = team1_picks[idx1:] + team2_picks[idx2:]
for offset, picked_uid in enumerate(leftover, start=1):
if picked_uid == user_id:
turns.append(len(pick_order) + offset)
return turns
# -----------------------------
# Bot :3
# -----------------------------
class DraftBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
super().__init__(command_prefix="!", intents=intents, case_insensitive=True)
self.db = DB()
self.states: Dict[int, DraftState] = {} # key: guild_id
def get_state(self, guild_id: int) -> DraftState:
if guild_id not in self.states:
self.states[guild_id] = DraftState()
return self.states[guild_id]
async def setup_hook(self) -> None:
await self.db.init()
if GUILD_SCOPED and self.guilds:
for g in self.guilds:
self.tree.copy_global_to(guild=g)
await self.tree.sync(guild=g)
else:
await self.tree.sync()
bot = DraftBot()
# -----------------------------
# Utility hommelit :3
# -----------------------------
def mention(uid: int) -> str:
return f"<@{uid}>"
def format_elapsed(seconds: float) -> str:
total_seconds = max(0, int(seconds))
minutes, sec = divmod(total_seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
parts = []
if days:
parts.append(f"{days}d")
if hours:
parts.append(f"{hours}h")
if minutes:
parts.append(f"{minutes}m")
if sec or not parts:
parts.append(f"{sec}s")
return " ".join(parts)
def average(values: List[float]) -> float:
if not values:
raise ValueError("Average requires at least one value.")
return sum(values) / len(values)