-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb_helpers.py
More file actions
871 lines (744 loc) · 22.3 KB
/
db_helpers.py
File metadata and controls
871 lines (744 loc) · 22.3 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
"""
Database helper functions for the minigame system.
This module provides atomic operations for user balances,
transaction logging, and safe database operations.
"""
import json
import math
import sqlite3
from contextlib import contextmanager
from datetime import datetime
from typing import Optional
from database import get_db_connection
# XP-to-level configuration
LEVEL_MULTIPLIER = 125
def calculate_level_from_xp(xp: float) -> int:
"""Calculate level from XP."""
if xp < 0:
xp = 0
return int(math.sqrt(xp / LEVEL_MULTIPLIER)) + 1
def calculate_xp_for_level(level: int) -> float:
"""Calculate XP required to reach a given level."""
return ((level - 1) ** 2) * LEVEL_MULTIPLIER
@contextmanager
def transaction(conn: sqlite3.Connection):
"""Context manager for database transactions."""
try:
yield conn
conn.commit()
except Exception:
conn.rollback()
raise
def ensure_user_exists(
guild_id: str,
user_id: str,
conn: Optional[sqlite3.Connection] = None
) -> dict:
"""
Ensure a user exists in the database.
Returns user data dictionary.
"""
should_close = conn is None
if conn is None:
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute(
"""
SELECT guildId, userId, xp, level, messages, coins
FROM users WHERE guildId = ? AND userId = ?
""",
(str(guild_id), str(user_id)),
)
result = cursor.fetchone()
if result:
return dict(result)
# Create new user
cursor.execute(
"""
INSERT INTO users (guildId, userId, xp, level, messages, coins)
VALUES (?, ?, 0, 1, 0, 0)
""",
(str(guild_id), str(user_id)),
)
conn.commit()
return {
"guildId": str(guild_id),
"userId": str(user_id),
"xp": 0,
"level": 1,
"messages": 0,
"coins": 0,
}
finally:
if should_close:
conn.close()
def get_user_balance(
guild_id: str,
user_id: str,
conn: Optional[sqlite3.Connection] = None
) -> dict:
"""Get user's current balance (coins and xp)."""
user = ensure_user_exists(guild_id, user_id, conn)
return {
"coins": user["coins"],
"xp": user["xp"],
"level": user["level"],
}
def add_coins(
guild_id: str,
user_id: str,
amount: float,
reason: str = "unknown",
related_id: Optional[int] = None,
related_type: Optional[str] = None,
conn: Optional[sqlite3.Connection] = None,
) -> dict:
"""
Add coins to a user's balance.
Returns updated balance info.
"""
should_close = conn is None
if conn is None:
conn = get_db_connection()
cursor = conn.cursor()
try:
user = ensure_user_exists(guild_id, user_id, conn)
new_balance = user["coins"] + amount
cursor.execute(
"UPDATE users SET coins = ? WHERE guildId = ? AND userId = ?",
(new_balance, str(guild_id), str(user_id)),
)
# Log transaction
log_transaction(
guild_id=guild_id,
user_id=user_id,
kind=reason,
amount=amount,
currency="coins",
balance_after=new_balance,
related_id=related_id,
related_type=related_type,
conn=conn,
)
conn.commit()
return {
"old_balance": user["coins"],
"new_balance": new_balance,
"amount_added": amount,
}
finally:
if should_close:
conn.close()
def spend_coins(
guild_id: str,
user_id: str,
amount: float,
reason: str = "unknown",
related_id: Optional[int] = None,
related_type: Optional[str] = None,
conn: Optional[sqlite3.Connection] = None,
) -> dict:
"""
Spend coins from a user's balance.
Raises ValueError if insufficient funds.
Returns updated balance info.
"""
should_close = conn is None
if conn is None:
conn = get_db_connection()
cursor = conn.cursor()
try:
user = ensure_user_exists(guild_id, user_id, conn)
if user["coins"] < amount:
raise ValueError(
f"Insufficient coins: have {user['coins']}, need {amount}"
)
new_balance = user["coins"] - amount
cursor.execute(
"UPDATE users SET coins = ? WHERE guildId = ? AND userId = ?",
(new_balance, str(guild_id), str(user_id)),
)
# Log transaction
log_transaction(
guild_id=guild_id,
user_id=user_id,
kind=reason,
amount=-amount,
currency="coins",
balance_after=new_balance,
related_id=related_id,
related_type=related_type,
conn=conn,
)
conn.commit()
return {
"old_balance": user["coins"],
"new_balance": new_balance,
"amount_spent": amount,
}
finally:
if should_close:
conn.close()
def add_xp(
guild_id: str,
user_id: str,
amount: float,
reason: str = "unknown",
related_id: Optional[int] = None,
related_type: Optional[str] = None,
conn: Optional[sqlite3.Connection] = None,
) -> dict:
"""
Add XP to a user's balance and update level.
Returns updated balance info and level change data.
"""
should_close = conn is None
if conn is None:
conn = get_db_connection()
cursor = conn.cursor()
try:
user = ensure_user_exists(guild_id, user_id, conn)
new_xp = user["xp"] + amount
old_level = user["level"]
new_level = calculate_level_from_xp(new_xp)
cursor.execute(
"UPDATE users SET xp = ?, level = ? WHERE guildId = ? AND userId = ?",
(new_xp, new_level, str(guild_id), str(user_id)),
)
# Log transaction
log_transaction(
guild_id=guild_id,
user_id=user_id,
kind=reason,
amount=amount,
currency="xp",
balance_after=new_xp,
related_id=related_id,
related_type=related_type,
conn=conn,
)
conn.commit()
return {
"old_xp": user["xp"],
"new_xp": new_xp,
"old_level": old_level,
"new_level": new_level,
"level_up": new_level > old_level,
"level_down": new_level < old_level,
"amount_added": amount,
}
finally:
if should_close:
conn.close()
def spend_xp(
guild_id: str,
user_id: str,
amount: float,
reason: str = "unknown",
related_id: Optional[int] = None,
related_type: Optional[str] = None,
conn: Optional[sqlite3.Connection] = None,
) -> dict:
"""
Spend XP from a user's balance and update level.
Raises ValueError if insufficient XP.
Returns updated balance info and level change data.
"""
should_close = conn is None
if conn is None:
conn = get_db_connection()
cursor = conn.cursor()
try:
user = ensure_user_exists(guild_id, user_id, conn)
if user["xp"] < amount:
raise ValueError(f"Insufficient XP: have {user['xp']}, need {amount}")
new_xp = user["xp"] - amount
old_level = user["level"]
new_level = calculate_level_from_xp(new_xp)
cursor.execute(
"UPDATE users SET xp = ?, level = ? WHERE guildId = ? AND userId = ?",
(new_xp, new_level, str(guild_id), str(user_id)),
)
# Log transaction
log_transaction(
guild_id=guild_id,
user_id=user_id,
kind=reason,
amount=-amount,
currency="xp",
balance_after=new_xp,
related_id=related_id,
related_type=related_type,
conn=conn,
)
conn.commit()
return {
"old_xp": user["xp"],
"new_xp": new_xp,
"old_level": old_level,
"new_level": new_level,
"level_up": new_level > old_level,
"level_down": new_level < old_level,
"amount_spent": amount,
}
finally:
if should_close:
conn.close()
def log_transaction(
guild_id: str,
user_id: str,
kind: str,
amount: float,
currency: str = "coins",
balance_after: Optional[float] = None,
metadata: Optional[dict] = None,
related_id: Optional[int] = None,
related_type: Optional[str] = None,
conn: Optional[sqlite3.Connection] = None,
) -> int:
"""Log a transaction to the ledger. Returns transaction ID."""
should_close = conn is None
if conn is None:
conn = get_db_connection()
cursor = conn.cursor()
try:
meta_json = json.dumps(metadata) if metadata else "{}"
cursor.execute(
"""
INSERT INTO transactions (
guildId, userId, kind, amount, currency, balance_after,
metadata, related_id, related_type, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
str(guild_id),
str(user_id),
kind,
amount,
currency,
balance_after,
meta_json,
related_id,
related_type,
datetime.utcnow().isoformat(),
),
)
conn.commit()
return cursor.lastrowid
finally:
if should_close:
conn.close()
def get_user_transactions(
guild_id: str,
user_id: str,
limit: int = 20,
kind: Optional[str] = None,
conn: Optional[sqlite3.Connection] = None,
) -> list:
"""Get recent transactions for a user."""
should_close = conn is None
if conn is None:
conn = get_db_connection()
cursor = conn.cursor()
try:
if kind:
cursor.execute(
"""
SELECT * FROM transactions
WHERE guildId = ? AND userId = ? AND kind = ?
ORDER BY created_at DESC LIMIT ?
""",
(str(guild_id), str(user_id), kind, limit),
)
else:
cursor.execute(
"""
SELECT * FROM transactions
WHERE guildId = ? AND userId = ?
ORDER BY created_at DESC LIMIT ?
""",
(str(guild_id), str(user_id), limit),
)
return [dict(row) for row in cursor.fetchall()]
finally:
if should_close:
conn.close()
# Guild settings helpers
def get_guild_settings(
guild_id: str,
conn: Optional[sqlite3.Connection] = None
) -> dict:
"""Get or create guild settings."""
should_close = conn is None
if conn is None:
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute(
"SELECT * FROM guild_settings WHERE guildId = ?",
(str(guild_id),),
)
result = cursor.fetchone()
if result:
return dict(result)
# Create default settings
cursor.execute(
"""
INSERT INTO guild_settings (guildId) VALUES (?)
""",
(str(guild_id),),
)
conn.commit()
return {
"guildId": str(guild_id),
"minigame_enabled": 1,
"minigame_channel_id": None,
"xp_trading_enabled": 1,
"trade_tax_percent": 10.0,
"duel_tax_percent": 10.0,
"daily_xp_transfer_cap_percent": 10.0,
"daily_xp_transfer_cap_max": 500,
"capture_cooldown_seconds": 60,
"duel_cooldown_seconds": 300,
}
finally:
if should_close:
conn.close()
def set_minigame_enabled(
guild_id: str,
enabled: bool,
conn: Optional[sqlite3.Connection] = None,
) -> bool:
"""Enable or disable the minigame system for a guild."""
should_close = conn is None
if conn is None:
conn = get_db_connection()
cursor = conn.cursor()
try:
# Ensure settings exist
get_guild_settings(guild_id, conn)
cursor.execute(
"""
UPDATE guild_settings SET minigame_enabled = ?, updated_at = ?
WHERE guildId = ?
""",
(1 if enabled else 0, datetime.utcnow().isoformat(), str(guild_id)),
)
conn.commit()
return True
finally:
if should_close:
conn.close()
def is_minigame_enabled(
guild_id: str,
conn: Optional[sqlite3.Connection] = None,
) -> bool:
"""Check if the minigame system is enabled for a guild."""
settings = get_guild_settings(guild_id, conn)
return bool(settings.get("minigame_enabled", 1))
def set_minigame_channel(
guild_id: str,
channel_id: Optional[str],
conn: Optional[sqlite3.Connection] = None,
) -> bool:
"""Set the minigame channel for a guild."""
should_close = conn is None
if conn is None:
conn = get_db_connection()
cursor = conn.cursor()
try:
# Ensure settings exist
get_guild_settings(guild_id, conn)
cursor.execute(
"""
UPDATE guild_settings SET minigame_channel_id = ?, updated_at = ?
WHERE guildId = ?
""",
(channel_id, datetime.utcnow().isoformat(), str(guild_id)),
)
conn.commit()
return True
finally:
if should_close:
conn.close()
def add_quest_exception_channel(
guild_id: str,
channel_id: str,
conn: Optional[sqlite3.Connection] = None,
) -> bool:
"""Add a channel to the quest exception list."""
should_close = conn is None
if conn is None:
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute(
"""
INSERT OR IGNORE INTO quest_exception_channels (guildId, channelId)
VALUES (?, ?)
""",
(str(guild_id), str(channel_id)),
)
conn.commit()
return cursor.rowcount > 0
finally:
if should_close:
conn.close()
def remove_quest_exception_channel(
guild_id: str,
channel_id: str,
conn: Optional[sqlite3.Connection] = None,
) -> bool:
"""Remove a channel from the quest exception list."""
should_close = conn is None
if conn is None:
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute(
"""
DELETE FROM quest_exception_channels
WHERE guildId = ? AND channelId = ?
""",
(str(guild_id), str(channel_id)),
)
conn.commit()
return cursor.rowcount > 0
finally:
if should_close:
conn.close()
def get_quest_exception_channels(
guild_id: str,
conn: Optional[sqlite3.Connection] = None,
) -> list:
"""Get all quest exception channels for a guild."""
should_close = conn is None
if conn is None:
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute(
"SELECT channelId FROM quest_exception_channels WHERE guildId = ?",
(str(guild_id),),
)
return [row[0] for row in cursor.fetchall()]
finally:
if should_close:
conn.close()
def is_minigame_channel(
guild_id: str,
channel_id: str,
conn: Optional[sqlite3.Connection] = None,
) -> bool:
"""Check if a channel is the designated minigame channel."""
settings = get_guild_settings(guild_id, conn)
return settings.get("minigame_channel_id") == str(channel_id)
def is_quest_exception_channel(
guild_id: str,
channel_id: str,
conn: Optional[sqlite3.Connection] = None,
) -> bool:
"""Check if a channel is a quest exception channel."""
exception_channels = get_quest_exception_channels(guild_id, conn)
return str(channel_id) in exception_channels
# Cooldown helpers
def check_cooldown(
guild_id: str,
user_id: str,
action_type: str,
cooldown_seconds: int,
conn: Optional[sqlite3.Connection] = None,
) -> tuple[bool, int]:
"""
Check if user is on cooldown for an action.
Returns (is_on_cooldown, seconds_remaining).
"""
should_close = conn is None
if conn is None:
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute(
"""
SELECT last_action_at FROM user_cooldowns
WHERE guildId = ? AND userId = ? AND action_type = ?
""",
(str(guild_id), str(user_id), action_type),
)
result = cursor.fetchone()
if not result:
return False, 0
last_action = datetime.fromisoformat(result[0])
now = datetime.utcnow()
elapsed = (now - last_action).total_seconds()
if elapsed >= cooldown_seconds:
return False, 0
remaining = int(cooldown_seconds - elapsed)
return True, remaining
finally:
if should_close:
conn.close()
def set_cooldown(
guild_id: str,
user_id: str,
action_type: str,
conn: Optional[sqlite3.Connection] = None,
) -> None:
"""Set/update cooldown for a user action."""
should_close = conn is None
if conn is None:
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute(
"""
INSERT INTO user_cooldowns (guildId, userId, action_type, last_action_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(guildId, userId, action_type)
DO UPDATE SET last_action_at = excluded.last_action_at
""",
(
str(guild_id),
str(user_id),
action_type,
datetime.utcnow().isoformat(),
),
)
conn.commit()
finally:
if should_close:
conn.close()
# Daily tracking helpers
def get_daily_tracking(
guild_id: str,
user_id: str,
conn: Optional[sqlite3.Connection] = None,
) -> dict:
"""Get or create daily tracking data for a user."""
should_close = conn is None
if conn is None:
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute(
"""
SELECT * FROM user_daily_tracking
WHERE guildId = ? AND userId = ?
""",
(str(guild_id), str(user_id)),
)
result = cursor.fetchone()
if result:
return dict(result)
# Create new tracking record
cursor.execute(
"""
INSERT INTO user_daily_tracking (guildId, userId)
VALUES (?, ?)
""",
(str(guild_id), str(user_id)),
)
conn.commit()
return {
"guildId": str(guild_id),
"userId": str(user_id),
"last_daily_claim": None,
"streak": 0,
"daily_xp_transferred": 0,
"last_xp_transfer_reset": None,
}
finally:
if should_close:
conn.close()
def update_daily_tracking(
guild_id: str,
user_id: str,
updates: dict,
conn: Optional[sqlite3.Connection] = None,
) -> None:
"""Update daily tracking data for a user."""
should_close = conn is None
if conn is None:
conn = get_db_connection()
# Ensure record exists
get_daily_tracking(guild_id, user_id, conn)
# Whitelist of allowed column names to prevent SQL injection
allowed_columns = {
"last_daily_claim",
"streak",
"daily_xp_transferred",
"last_xp_transfer_reset",
"last_capture_at",
"last_duel_at",
}
# Validate all column names
for key in updates.keys():
if key not in allowed_columns:
raise ValueError(f"Invalid column name: {key}")
cursor = conn.cursor()
try:
set_clause = ", ".join([f"{k} = ?" for k in updates.keys()])
values = list(updates.values()) + [str(guild_id), str(user_id)]
cursor.execute(
f"""
UPDATE user_daily_tracking SET {set_clause}
WHERE guildId = ? AND userId = ?
""",
values,
)
conn.commit()
finally:
if should_close:
conn.close()
def check_daily_xp_limit(
guild_id: str,
user_id: str,
xp_amount: int,
conn: Optional[sqlite3.Connection] = None,
) -> tuple[bool, int, int]:
"""
Check if user can transfer XP within daily limits.
Returns (can_transfer, current_transferred, limit).
"""
settings = get_guild_settings(guild_id, conn)
user = ensure_user_exists(guild_id, user_id, conn)
tracking = get_daily_tracking(guild_id, user_id, conn)
# Calculate daily limit (10% of XP or max cap, whichever is lower)
percent_cap = user["xp"] * (settings["daily_xp_transfer_cap_percent"] / 100)
max_cap = settings["daily_xp_transfer_cap_max"]
daily_limit = int(min(percent_cap, max_cap))
# Reset daily counter if needed
now = datetime.utcnow()
last_reset = tracking.get("last_xp_transfer_reset")
if last_reset:
last_reset_dt = datetime.fromisoformat(last_reset)
if (now - last_reset_dt).days >= 1:
# Reset counter
update_daily_tracking(
guild_id,
user_id,
{
"daily_xp_transferred": 0,
"last_xp_transfer_reset": now.isoformat(),
},
conn,
)
tracking["daily_xp_transferred"] = 0
current_transferred = tracking.get("daily_xp_transferred", 0)
remaining = daily_limit - current_transferred
can_transfer = remaining >= xp_amount
return can_transfer, current_transferred, daily_limit
def record_xp_transfer(
guild_id: str,
user_id: str,
xp_amount: int,
conn: Optional[sqlite3.Connection] = None,
) -> None:
"""Record XP transfer against daily limit."""
tracking = get_daily_tracking(guild_id, user_id, conn)
current = tracking.get("daily_xp_transferred", 0)
updates = {"daily_xp_transferred": current + xp_amount}
if not tracking.get("last_xp_transfer_reset"):
updates["last_xp_transfer_reset"] = datetime.utcnow().isoformat()
update_daily_tracking(guild_id, user_id, updates, conn)