-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
960 lines (886 loc) · 35.6 KB
/
db.py
File metadata and controls
960 lines (886 loc) · 35.6 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
from __future__ import annotations
from datetime import datetime, timezone
import json
from pathlib import Path
import sqlite3
import threading
from typing import Any
from config import DEFAULT_RULES
from utils.blocklist import normalize_blocked_terms
CONFIG_COLUMNS = {
"log_channel_id",
"rules_channel_id",
"report_channel_id",
"appeal_channel_id",
"automod_enabled",
"invite_filter_enabled",
"caps_filter_enabled",
"spam_filter_enabled",
"repeat_filter_enabled",
"mention_filter_enabled",
"min_account_age_hours",
"warn_timeout_threshold",
"warn_kick_threshold",
"warn_ban_threshold",
"warn_timeout_minutes",
"caps_ratio",
"caps_min_length",
"mention_threshold",
"spam_threshold",
"spam_window_seconds",
"repeat_threshold",
"repeat_window_seconds",
"raid_mode",
}
ROLE_LIST_COLUMNS = {"mod_role_ids", "admin_role_ids"}
def utcnow_iso() -> str:
return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
class Database:
def __init__(self, path: str) -> None:
database_path = Path(path).expanduser()
database_path.parent.mkdir(parents=True, exist_ok=True)
self.path = str(database_path)
self.connection = sqlite3.connect(self.path, check_same_thread=False)
self.connection.row_factory = sqlite3.Row
self._lock = threading.RLock()
self._initialize()
def close(self) -> None:
with self._lock:
self.connection.close()
def _initialize(self) -> None:
with self._lock:
self.connection.executescript(
"""
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS guild_config (
guild_id INTEGER PRIMARY KEY,
mod_role_ids TEXT NOT NULL DEFAULT '[]',
admin_role_ids TEXT NOT NULL DEFAULT '[]',
log_channel_id INTEGER,
rules_channel_id INTEGER,
report_channel_id INTEGER,
appeal_channel_id INTEGER,
automod_enabled INTEGER NOT NULL DEFAULT 1,
invite_filter_enabled INTEGER NOT NULL DEFAULT 1,
caps_filter_enabled INTEGER NOT NULL DEFAULT 1,
spam_filter_enabled INTEGER NOT NULL DEFAULT 1,
repeat_filter_enabled INTEGER NOT NULL DEFAULT 1,
mention_filter_enabled INTEGER NOT NULL DEFAULT 1,
min_account_age_hours INTEGER NOT NULL DEFAULT 0,
warn_timeout_threshold INTEGER NOT NULL DEFAULT 3,
warn_kick_threshold INTEGER NOT NULL DEFAULT 5,
warn_ban_threshold INTEGER NOT NULL DEFAULT 7,
warn_timeout_minutes INTEGER NOT NULL DEFAULT 1440,
caps_ratio REAL NOT NULL DEFAULT 0.75,
caps_min_length INTEGER NOT NULL DEFAULT 12,
mention_threshold INTEGER NOT NULL DEFAULT 5,
spam_threshold INTEGER NOT NULL DEFAULT 6,
spam_window_seconds INTEGER NOT NULL DEFAULT 12,
repeat_threshold INTEGER NOT NULL DEFAULT 3,
repeat_window_seconds INTEGER NOT NULL DEFAULT 90,
raid_mode INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS rules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
position INTEGER NOT NULL,
title TEXT NOT NULL,
description TEXT NOT NULL,
points INTEGER NOT NULL DEFAULT 1,
enabled INTEGER NOT NULL DEFAULT 1
);
CREATE TABLE IF NOT EXISTS blocked_words (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
term TEXT NOT NULL,
created_at TEXT NOT NULL,
UNIQUE(guild_id, term)
);
CREATE TABLE IF NOT EXISTS lenient_words (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
term TEXT NOT NULL,
created_at TEXT NOT NULL,
UNIQUE(guild_id, term)
);
CREATE TABLE IF NOT EXISTS promo_keywords (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
term TEXT NOT NULL,
created_at TEXT NOT NULL,
UNIQUE(guild_id, term)
);
CREATE TABLE IF NOT EXISTS cases (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
moderator_id INTEGER NOT NULL,
action TEXT NOT NULL,
reason TEXT NOT NULL,
points INTEGER NOT NULL DEFAULT 0,
active INTEGER NOT NULL DEFAULT 1,
expires_at TEXT,
created_at TEXT NOT NULL,
metadata TEXT NOT NULL DEFAULT '{}'
);
CREATE TABLE IF NOT EXISTS embed_templates (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
name TEXT NOT NULL,
title TEXT NOT NULL,
description TEXT NOT NULL,
footer TEXT,
image_url TEXT,
thumbnail_url TEXT,
fields_json TEXT NOT NULL DEFAULT '[]',
created_at TEXT NOT NULL,
UNIQUE(guild_id, name)
);
CREATE TABLE IF NOT EXISTS reports (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
kind TEXT NOT NULL,
author_id INTEGER NOT NULL,
target_id INTEGER,
case_id INTEGER,
reason TEXT NOT NULL,
evidence_url TEXT,
status TEXT NOT NULL DEFAULT 'open',
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS ticket_abuse_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
author_id INTEGER NOT NULL,
kind TEXT NOT NULL,
reason TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS scheduled_actions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
action TEXT NOT NULL,
execute_at TEXT NOT NULL,
payload TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS intro_acknowledgements (
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
message_id INTEGER,
created_at TEXT NOT NULL,
PRIMARY KEY (guild_id, user_id)
);
"""
)
self.connection.commit()
def ensure_guild(self, guild_id: int) -> None:
with self._lock:
now = utcnow_iso()
self.connection.execute(
"INSERT OR IGNORE INTO guild_config (guild_id, created_at, updated_at) VALUES (?, ?, ?)",
(guild_id, now, now),
)
existing_rules = self.connection.execute(
"SELECT COUNT(*) AS count FROM rules WHERE guild_id = ?",
(guild_id,),
).fetchone()["count"]
if existing_rules == 0:
for index, (title, description, points) in enumerate(DEFAULT_RULES, start=1):
self.connection.execute(
"INSERT INTO rules (guild_id, position, title, description, points, enabled) VALUES (?, ?, ?, ?, ?, 1)",
(guild_id, index, title, description, points),
)
self.connection.commit()
def _touch_guild(self, guild_id: int) -> None:
self.connection.execute(
"UPDATE guild_config SET updated_at = ? WHERE guild_id = ?",
(utcnow_iso(), guild_id),
)
def get_guild_config(self, guild_id: int) -> dict[str, Any]:
self.ensure_guild(guild_id)
with self._lock:
row = self.connection.execute(
"SELECT * FROM guild_config WHERE guild_id = ?",
(guild_id,),
).fetchone()
if row is None:
raise RuntimeError(f"Missing config row for guild {guild_id}.")
data = dict(row)
data["mod_role_ids"] = json.loads(data["mod_role_ids"])
data["admin_role_ids"] = json.loads(data["admin_role_ids"])
for key in (
"automod_enabled",
"invite_filter_enabled",
"caps_filter_enabled",
"spam_filter_enabled",
"repeat_filter_enabled",
"mention_filter_enabled",
"raid_mode",
):
data[key] = bool(data[key])
return data
def set_config_value(self, guild_id: int, column: str, value: Any) -> None:
if column not in CONFIG_COLUMNS:
raise ValueError(f"Unsupported config column: {column}")
self.ensure_guild(guild_id)
with self._lock:
self.connection.execute(
f"UPDATE guild_config SET {column} = ? WHERE guild_id = ?",
(value, guild_id),
)
self._touch_guild(guild_id)
self.connection.commit()
def add_role_id(self, guild_id: int, column: str, role_id: int) -> None:
if column not in ROLE_LIST_COLUMNS:
raise ValueError(f"Unsupported role list column: {column}")
config = self.get_guild_config(guild_id)
values = set(config[column])
values.add(role_id)
with self._lock:
self.connection.execute(
f"UPDATE guild_config SET {column} = ? WHERE guild_id = ?",
(json.dumps(sorted(values)), guild_id),
)
self._touch_guild(guild_id)
self.connection.commit()
def remove_role_id(self, guild_id: int, column: str, role_id: int) -> None:
if column not in ROLE_LIST_COLUMNS:
raise ValueError(f"Unsupported role list column: {column}")
config = self.get_guild_config(guild_id)
values = [value for value in config[column] if value != role_id]
with self._lock:
self.connection.execute(
f"UPDATE guild_config SET {column} = ? WHERE guild_id = ?",
(json.dumps(values), guild_id),
)
self._touch_guild(guild_id)
self.connection.commit()
def list_rules(self, guild_id: int) -> list[dict[str, Any]]:
self.ensure_guild(guild_id)
with self._lock:
rows = self.connection.execute(
"SELECT id, position, title, description, points, enabled FROM rules WHERE guild_id = ? ORDER BY position ASC, id ASC",
(guild_id,),
).fetchall()
return [dict(row) for row in rows]
def add_rule(self, guild_id: int, title: str, description: str, points: int) -> int:
self.ensure_guild(guild_id)
with self._lock:
max_position_row = self.connection.execute(
"SELECT COALESCE(MAX(position), 0) AS max_position FROM rules WHERE guild_id = ?",
(guild_id,),
).fetchone()
next_position = int(max_position_row["max_position"]) + 1
cursor = self.connection.execute(
"INSERT INTO rules (guild_id, position, title, description, points, enabled) VALUES (?, ?, ?, ?, ?, 1)",
(guild_id, next_position, title, description, points),
)
self.connection.commit()
return int(cursor.lastrowid)
def update_rule(
self,
guild_id: int,
rule_id: int,
*,
title: str | None = None,
description: str | None = None,
points: int | None = None,
enabled: bool | None = None,
) -> bool:
self.ensure_guild(guild_id)
updates: list[str] = []
values: list[Any] = []
if title is not None:
updates.append("title = ?")
values.append(title)
if description is not None:
updates.append("description = ?")
values.append(description)
if points is not None:
updates.append("points = ?")
values.append(points)
if enabled is not None:
updates.append("enabled = ?")
values.append(1 if enabled else 0)
if not updates:
return False
values.extend((guild_id, rule_id))
with self._lock:
cursor = self.connection.execute(
f"UPDATE rules SET {', '.join(updates)} WHERE guild_id = ? AND id = ?",
tuple(values),
)
self.connection.commit()
return cursor.rowcount > 0
def delete_rule(self, guild_id: int, rule_id: int) -> bool:
self.ensure_guild(guild_id)
with self._lock:
cursor = self.connection.execute(
"DELETE FROM rules WHERE guild_id = ? AND id = ?",
(guild_id, rule_id),
)
self.connection.commit()
return cursor.rowcount > 0
def reset_rules(self, guild_id: int) -> None:
self.ensure_guild(guild_id)
with self._lock:
self.connection.execute("DELETE FROM rules WHERE guild_id = ?", (guild_id,))
for index, (title, description, points) in enumerate(DEFAULT_RULES, start=1):
self.connection.execute(
"INSERT INTO rules (guild_id, position, title, description, points, enabled) VALUES (?, ?, ?, ?, ?, 1)",
(guild_id, index, title, description, points),
)
self.connection.commit()
def add_blocked_word(self, guild_id: int, term: str) -> bool:
self.ensure_guild(guild_id)
normalized = term.strip().lower()
if not normalized:
return False
with self._lock:
cursor = self.connection.execute(
"INSERT OR IGNORE INTO blocked_words (guild_id, term, created_at) VALUES (?, ?, ?)",
(guild_id, normalized, utcnow_iso()),
)
self.connection.commit()
return cursor.rowcount > 0
def remove_blocked_word(self, guild_id: int, term: str) -> bool:
self.ensure_guild(guild_id)
normalized = term.strip().lower()
with self._lock:
cursor = self.connection.execute(
"DELETE FROM blocked_words WHERE guild_id = ? AND term = ?",
(guild_id, normalized),
)
self.connection.commit()
return cursor.rowcount > 0
def list_blocked_words(self, guild_id: int) -> list[str]:
self.ensure_guild(guild_id)
with self._lock:
rows = self.connection.execute(
"SELECT term FROM blocked_words WHERE guild_id = ? ORDER BY term ASC",
(guild_id,),
).fetchall()
return [str(row["term"]) for row in rows]
def count_blocked_words(self, guild_id: int) -> int:
self.ensure_guild(guild_id)
with self._lock:
row = self.connection.execute(
"SELECT COUNT(*) AS count FROM blocked_words WHERE guild_id = ?",
(guild_id,),
).fetchone()
return int(row["count"])
def clear_blocked_words(self, guild_id: int) -> int:
self.ensure_guild(guild_id)
with self._lock:
cursor = self.connection.execute(
"DELETE FROM blocked_words WHERE guild_id = ?",
(guild_id,),
)
self.connection.commit()
return int(cursor.rowcount)
def bulk_add_blocked_words(self, guild_id: int, terms: list[str]) -> int:
self.ensure_guild(guild_id)
normalized_terms = normalize_blocked_terms(terms)
if not normalized_terms:
return 0
rows = [(guild_id, term, utcnow_iso()) for term in normalized_terms]
with self._lock:
before = self.connection.total_changes
self.connection.executemany(
"INSERT OR IGNORE INTO blocked_words (guild_id, term, created_at) VALUES (?, ?, ?)",
rows,
)
self.connection.commit()
return int(self.connection.total_changes - before)
def add_lenient_word(self, guild_id: int, term: str) -> bool:
self.ensure_guild(guild_id)
normalized = term.strip().lower()
if not normalized:
return False
with self._lock:
cursor = self.connection.execute(
"INSERT OR IGNORE INTO lenient_words (guild_id, term, created_at) VALUES (?, ?, ?)",
(guild_id, normalized, utcnow_iso()),
)
self.connection.commit()
return cursor.rowcount > 0
def remove_lenient_word(self, guild_id: int, term: str) -> bool:
self.ensure_guild(guild_id)
normalized = term.strip().lower()
with self._lock:
cursor = self.connection.execute(
"DELETE FROM lenient_words WHERE guild_id = ? AND term = ?",
(guild_id, normalized),
)
self.connection.commit()
return cursor.rowcount > 0
def list_lenient_words(self, guild_id: int) -> list[str]:
self.ensure_guild(guild_id)
with self._lock:
rows = self.connection.execute(
"SELECT term FROM lenient_words WHERE guild_id = ? ORDER BY term ASC",
(guild_id,),
).fetchall()
return [str(row["term"]) for row in rows]
def clear_lenient_words(self, guild_id: int) -> int:
self.ensure_guild(guild_id)
with self._lock:
cursor = self.connection.execute(
"DELETE FROM lenient_words WHERE guild_id = ?",
(guild_id,),
)
self.connection.commit()
return int(cursor.rowcount)
def bulk_add_lenient_words(self, guild_id: int, terms: list[str]) -> int:
self.ensure_guild(guild_id)
normalized_terms = normalize_blocked_terms(terms)
if not normalized_terms:
return 0
rows = [(guild_id, term, utcnow_iso()) for term in normalized_terms]
with self._lock:
before = self.connection.total_changes
self.connection.executemany(
"INSERT OR IGNORE INTO lenient_words (guild_id, term, created_at) VALUES (?, ?, ?)",
rows,
)
self.connection.commit()
return int(self.connection.total_changes - before)
def add_promo_keyword(self, guild_id: int, term: str) -> bool:
self.ensure_guild(guild_id)
normalized = term.strip().lower()
if not normalized:
return False
with self._lock:
cursor = self.connection.execute(
"INSERT OR IGNORE INTO promo_keywords (guild_id, term, created_at) VALUES (?, ?, ?)",
(guild_id, normalized, utcnow_iso()),
)
self.connection.commit()
return cursor.rowcount > 0
def remove_promo_keyword(self, guild_id: int, term: str) -> bool:
self.ensure_guild(guild_id)
normalized = term.strip().lower()
with self._lock:
cursor = self.connection.execute(
"DELETE FROM promo_keywords WHERE guild_id = ? AND term = ?",
(guild_id, normalized),
)
self.connection.commit()
return cursor.rowcount > 0
def list_promo_keywords(self, guild_id: int) -> list[str]:
self.ensure_guild(guild_id)
with self._lock:
rows = self.connection.execute(
"SELECT term FROM promo_keywords WHERE guild_id = ? ORDER BY term ASC",
(guild_id,),
).fetchall()
return [str(row["term"]) for row in rows]
def clear_promo_keywords(self, guild_id: int) -> int:
self.ensure_guild(guild_id)
with self._lock:
cursor = self.connection.execute(
"DELETE FROM promo_keywords WHERE guild_id = ?",
(guild_id,),
)
self.connection.commit()
return int(cursor.rowcount)
def bulk_add_promo_keywords(self, guild_id: int, terms: list[str]) -> int:
self.ensure_guild(guild_id)
normalized_terms = normalize_blocked_terms(terms)
if not normalized_terms:
return 0
rows = [(guild_id, term, utcnow_iso()) for term in normalized_terms]
with self._lock:
before = self.connection.total_changes
self.connection.executemany(
"INSERT OR IGNORE INTO promo_keywords (guild_id, term, created_at) VALUES (?, ?, ?)",
rows,
)
self.connection.commit()
return int(self.connection.total_changes - before)
def add_case(
self,
guild_id: int,
user_id: int,
moderator_id: int,
action: str,
reason: str,
*,
points: int = 0,
active: bool = True,
expires_at: str | None = None,
metadata: dict[str, Any] | None = None,
) -> int:
self.ensure_guild(guild_id)
with self._lock:
cursor = self.connection.execute(
"""
INSERT INTO cases (
guild_id, user_id, moderator_id, action, reason, points,
active, expires_at, created_at, metadata
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
guild_id,
user_id,
moderator_id,
action,
reason,
points,
1 if active else 0,
expires_at,
utcnow_iso(),
json.dumps(metadata or {}),
),
)
self.connection.commit()
return int(cursor.lastrowid)
def get_case(self, guild_id: int, case_id: int) -> dict[str, Any] | None:
self.ensure_guild(guild_id)
with self._lock:
row = self.connection.execute(
"SELECT * FROM cases WHERE guild_id = ? AND id = ?",
(guild_id, case_id),
).fetchone()
if row is None:
return None
data = dict(row)
data["metadata"] = json.loads(data["metadata"])
data["active"] = bool(data["active"])
return data
def list_member_cases(self, guild_id: int, user_id: int, limit: int = 10) -> list[dict[str, Any]]:
self.ensure_guild(guild_id)
with self._lock:
rows = self.connection.execute(
"SELECT * FROM cases WHERE guild_id = ? AND user_id = ? ORDER BY id DESC LIMIT ?",
(guild_id, user_id, limit),
).fetchall()
data = []
for row in rows:
item = dict(row)
item["metadata"] = json.loads(item["metadata"])
item["active"] = bool(item["active"])
data.append(item)
return data
def search_cases(
self,
guild_id: int,
*,
user_id: int | None = None,
action: str | None = None,
created_after: str | None = None,
limit: int = 10,
) -> list[dict[str, Any]]:
self.ensure_guild(guild_id)
query = ["SELECT * FROM cases WHERE guild_id = ?"]
values: list[Any] = [guild_id]
if user_id is not None:
query.append("AND user_id = ?")
values.append(user_id)
if action is not None:
query.append("AND action = ?")
values.append(action)
if created_after is not None:
query.append("AND created_at >= ?")
values.append(created_after)
query.append("ORDER BY id DESC LIMIT ?")
values.append(limit)
with self._lock:
rows = self.connection.execute(" ".join(query), tuple(values)).fetchall()
results: list[dict[str, Any]] = []
for row in rows:
item = dict(row)
item["metadata"] = json.loads(item["metadata"])
item["active"] = bool(item["active"])
results.append(item)
return results
def deactivate_case(self, guild_id: int, case_id: int) -> bool:
self.ensure_guild(guild_id)
with self._lock:
cursor = self.connection.execute(
"UPDATE cases SET active = 0 WHERE guild_id = ? AND id = ? AND active = 1",
(guild_id, case_id),
)
self.connection.commit()
return cursor.rowcount > 0
def clear_active_warnings_for_member(self, guild_id: int, user_id: int) -> int:
self.ensure_guild(guild_id)
with self._lock:
cursor = self.connection.execute(
"UPDATE cases SET active = 0 WHERE guild_id = ? AND user_id = ? AND action = 'warn' AND active = 1",
(guild_id, user_id),
)
self.connection.commit()
return int(cursor.rowcount)
def get_active_warning_points(self, guild_id: int, user_id: int) -> int:
self.ensure_guild(guild_id)
with self._lock:
row = self.connection.execute(
"SELECT COALESCE(SUM(points), 0) AS total FROM cases WHERE guild_id = ? AND user_id = ? AND action = 'warn' AND active = 1",
(guild_id, user_id),
).fetchone()
return int(row["total"])
def save_embed_template(
self,
guild_id: int,
name: str,
title: str,
description: str,
*,
footer: str | None = None,
image_url: str | None = None,
thumbnail_url: str | None = None,
fields: list[dict[str, Any]] | None = None,
) -> None:
self.ensure_guild(guild_id)
with self._lock:
self.connection.execute(
"""
INSERT INTO embed_templates (
guild_id, name, title, description, footer, image_url,
thumbnail_url, fields_json, created_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(guild_id, name) DO UPDATE SET
title = excluded.title,
description = excluded.description,
footer = excluded.footer,
image_url = excluded.image_url,
thumbnail_url = excluded.thumbnail_url,
fields_json = excluded.fields_json
""",
(
guild_id,
name.lower(),
title,
description,
footer,
image_url,
thumbnail_url,
json.dumps(fields or []),
utcnow_iso(),
),
)
self.connection.commit()
def get_embed_template(self, guild_id: int, name: str) -> dict[str, Any] | None:
self.ensure_guild(guild_id)
with self._lock:
row = self.connection.execute(
"SELECT * FROM embed_templates WHERE guild_id = ? AND name = ?",
(guild_id, name.lower()),
).fetchone()
if row is None:
return None
data = dict(row)
data["fields_json"] = json.loads(data["fields_json"])
return data
def list_embed_templates(self, guild_id: int) -> list[str]:
self.ensure_guild(guild_id)
with self._lock:
rows = self.connection.execute(
"SELECT name FROM embed_templates WHERE guild_id = ? ORDER BY name ASC",
(guild_id,),
).fetchall()
return [str(row["name"]) for row in rows]
def add_report(
self,
guild_id: int,
kind: str,
author_id: int,
target_id: int | None,
reason: str,
*,
case_id: int | None = None,
evidence_url: str | None = None,
) -> int:
self.ensure_guild(guild_id)
with self._lock:
cursor = self.connection.execute(
"""
INSERT INTO reports (
guild_id, kind, author_id, target_id, case_id,
reason, evidence_url, status, created_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, 'open', ?)
""",
(guild_id, kind, author_id, target_id, case_id, reason, evidence_url, utcnow_iso()),
)
self.connection.commit()
return int(cursor.lastrowid)
def get_report(self, guild_id: int, report_id: int) -> dict[str, Any] | None:
self.ensure_guild(guild_id)
with self._lock:
row = self.connection.execute(
"SELECT * FROM reports WHERE guild_id = ? AND id = ?",
(guild_id, report_id),
).fetchone()
return dict(row) if row is not None else None
def list_reports(
self,
guild_id: int,
*,
kind: str | None = None,
status: str | None = None,
limit: int = 10,
) -> list[dict[str, Any]]:
self.ensure_guild(guild_id)
query = ["SELECT * FROM reports WHERE guild_id = ?"]
values: list[Any] = [guild_id]
if kind is not None:
query.append("AND kind = ?")
values.append(kind)
if status is not None:
query.append("AND status = ?")
values.append(status)
query.append("ORDER BY id DESC LIMIT ?")
values.append(limit)
with self._lock:
rows = self.connection.execute(" ".join(query), tuple(values)).fetchall()
return [dict(row) for row in rows]
def get_latest_report_by_author(
self,
guild_id: int,
author_id: int,
*,
kind: str | None = None,
) -> dict[str, Any] | None:
self.ensure_guild(guild_id)
query = ["SELECT * FROM reports WHERE guild_id = ? AND author_id = ?"]
values: list[Any] = [guild_id, author_id]
if kind is not None:
query.append("AND kind = ?")
values.append(kind)
query.append("ORDER BY created_at DESC LIMIT 1")
with self._lock:
row = self.connection.execute(" ".join(query), tuple(values)).fetchone()
return dict(row) if row is not None else None
def list_recent_reports_by_author(
self,
guild_id: int,
author_id: int,
*,
kind: str | None = None,
since_iso: str | None = None,
limit: int = 25,
) -> list[dict[str, Any]]:
self.ensure_guild(guild_id)
query = ["SELECT * FROM reports WHERE guild_id = ? AND author_id = ?"]
values: list[Any] = [guild_id, author_id]
if kind is not None:
query.append("AND kind = ?")
values.append(kind)
if since_iso is not None:
query.append("AND created_at >= ?")
values.append(since_iso)
query.append("ORDER BY created_at DESC LIMIT ?")
values.append(limit)
with self._lock:
rows = self.connection.execute(" ".join(query), tuple(values)).fetchall()
return [dict(row) for row in rows]
def update_report_status(self, guild_id: int, report_id: int, status: str) -> bool:
self.ensure_guild(guild_id)
with self._lock:
cursor = self.connection.execute(
"UPDATE reports SET status = ? WHERE guild_id = ? AND id = ?",
(status, guild_id, report_id),
)
self.connection.commit()
return cursor.rowcount > 0
def add_ticket_abuse_event(
self,
guild_id: int,
author_id: int,
*,
kind: str,
reason: str,
) -> int:
self.ensure_guild(guild_id)
with self._lock:
cursor = self.connection.execute(
"""
INSERT INTO ticket_abuse_events (
guild_id, author_id, kind, reason, created_at
)
VALUES (?, ?, ?, ?, ?)
""",
(guild_id, author_id, kind, reason, utcnow_iso()),
)
self.connection.commit()
return int(cursor.lastrowid)
def count_recent_ticket_abuse_events(
self,
guild_id: int,
author_id: int,
*,
since_iso: str,
) -> int:
self.ensure_guild(guild_id)
with self._lock:
row = self.connection.execute(
"""
SELECT COUNT(*) AS count
FROM ticket_abuse_events
WHERE guild_id = ? AND author_id = ? AND created_at >= ?
""",
(guild_id, author_id, since_iso),
).fetchone()
return int(row["count"]) if row is not None else 0
def schedule_action(
self,
guild_id: int,
user_id: int,
action: str,
execute_at: str,
payload: dict[str, Any] | None = None,
) -> int:
self.ensure_guild(guild_id)
with self._lock:
cursor = self.connection.execute(
"INSERT INTO scheduled_actions (guild_id, user_id, action, execute_at, payload, created_at) VALUES (?, ?, ?, ?, ?, ?)",
(guild_id, user_id, action, execute_at, json.dumps(payload or {}), utcnow_iso()),
)
self.connection.commit()
return int(cursor.lastrowid)
def list_due_actions(self, before_iso: str) -> list[dict[str, Any]]:
with self._lock:
rows = self.connection.execute(
"SELECT * FROM scheduled_actions WHERE execute_at <= ? ORDER BY execute_at ASC, id ASC",
(before_iso,),
).fetchall()
actions: list[dict[str, Any]] = []
for row in rows:
item = dict(row)
item["payload"] = json.loads(item["payload"])
actions.append(item)
return actions
def delete_scheduled_action(self, action_id: int) -> None:
with self._lock:
self.connection.execute("DELETE FROM scheduled_actions WHERE id = ?", (action_id,))
self.connection.commit()
def has_intro_acknowledgement(self, guild_id: int, user_id: int) -> bool:
self.ensure_guild(guild_id)
with self._lock:
row = self.connection.execute(
"SELECT 1 FROM intro_acknowledgements WHERE guild_id = ? AND user_id = ?",
(guild_id, user_id),
).fetchone()
return row is not None
def mark_intro_acknowledgement(self, guild_id: int, user_id: int, *, message_id: int | None = None) -> bool:
self.ensure_guild(guild_id)
with self._lock:
cursor = self.connection.execute(
"""
INSERT OR IGNORE INTO intro_acknowledgements (
guild_id, user_id, message_id, created_at
)
VALUES (?, ?, ?, ?)
""",
(guild_id, user_id, message_id, utcnow_iso()),
)
self.connection.commit()
return cursor.rowcount > 0