-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
1467 lines (1370 loc) · 54.9 KB
/
Copy pathdb.py
File metadata and controls
1467 lines (1370 loc) · 54.9 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
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",
"security_enabled",
"antinuke_enabled",
"antinuke_threshold",
"antinuke_window_seconds",
"antinuke_timeout_minutes",
"audit_message_logs_enabled",
"audit_server_logs_enabled",
}
ROLE_LIST_COLUMNS = {"mod_role_ids", "admin_role_ids"}
SENTINEL_DAILY_DECAY = 0.88
def utcnow_iso() -> str:
return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
def decayed_sentinel_score(score: float, last_event_at: str | None, *, now_iso: str | None = None) -> float:
if not last_event_at:
return max(0.0, min(100.0, score))
try:
then = datetime.fromisoformat(last_event_at)
now = datetime.fromisoformat(now_iso or utcnow_iso())
except ValueError:
return max(0.0, min(100.0, score))
age_days = max(0.0, (now - then).total_seconds() / 86400)
return max(0.0, min(100.0, score * (SENTINEL_DAILY_DECAY ** age_days)))
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 24,
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,
security_enabled INTEGER NOT NULL DEFAULT 1,
antinuke_enabled INTEGER NOT NULL DEFAULT 1,
antinuke_threshold INTEGER NOT NULL DEFAULT 4,
antinuke_window_seconds INTEGER NOT NULL DEFAULT 120,
antinuke_timeout_minutes INTEGER NOT NULL DEFAULT 60,
audit_message_logs_enabled INTEGER NOT NULL DEFAULT 1,
audit_server_logs_enabled INTEGER NOT NULL DEFAULT 1,
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)
);
CREATE TABLE IF NOT EXISTS bluesky_feeds (
guild_id INTEGER PRIMARY KEY,
handle TEXT NOT NULL,
channel_id INTEGER NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
last_post_uri TEXT,
last_post_created_at TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS security_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
actor_id INTEGER NOT NULL,
action TEXT NOT NULL,
target_id INTEGER,
details TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS sentinel_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
channel_id INTEGER,
message_id INTEGER,
category TEXT NOT NULL,
action TEXT NOT NULL DEFAULT 'observe',
actor_kind TEXT NOT NULL DEFAULT 'human',
channel_scope TEXT NOT NULL DEFAULT 'public',
deleted INTEGER NOT NULL DEFAULT 0,
severity INTEGER NOT NULL,
confidence REAL NOT NULL,
summary TEXT NOT NULL,
content_hash TEXT NOT NULL,
excerpt TEXT,
signals_json TEXT NOT NULL DEFAULT '[]',
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS sentinel_profiles (
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
risk_score REAL NOT NULL DEFAULT 0,
event_count INTEGER NOT NULL DEFAULT 0,
last_event_at TEXT,
updated_at TEXT NOT NULL,
PRIMARY KEY (guild_id, user_id)
);
"""
)
for column_name, column_sql in (
("action", "TEXT NOT NULL DEFAULT 'observe'"),
("actor_kind", "TEXT NOT NULL DEFAULT 'human'"),
("channel_scope", "TEXT NOT NULL DEFAULT 'public'"),
("deleted", "INTEGER NOT NULL DEFAULT 0"),
):
self._ensure_column_locked("sentinel_events", column_name, column_sql)
for column_name, column_sql in (
("security_enabled", "INTEGER NOT NULL DEFAULT 1"),
("antinuke_enabled", "INTEGER NOT NULL DEFAULT 1"),
("antinuke_threshold", "INTEGER NOT NULL DEFAULT 4"),
("antinuke_window_seconds", "INTEGER NOT NULL DEFAULT 120"),
("antinuke_timeout_minutes", "INTEGER NOT NULL DEFAULT 60"),
("audit_message_logs_enabled", "INTEGER NOT NULL DEFAULT 1"),
("audit_server_logs_enabled", "INTEGER NOT NULL DEFAULT 1"),
):
self._ensure_column_locked("guild_config", column_name, column_sql)
self._ensure_column_locked("bluesky_feeds", "last_post_created_at", "TEXT")
self.connection.commit()
def _ensure_column_locked(self, table_name: str, column_name: str, column_sql: str) -> None:
rows = self.connection.execute(f"PRAGMA table_info({table_name})").fetchall()
existing = {str(row["name"]) for row in rows}
if column_name in existing:
return
self.connection.execute(f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_sql}")
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),
)
else:
for index, (title, description, points) in enumerate(DEFAULT_RULES, start=1):
cursor = self.connection.execute(
"""
UPDATE rules
SET title = ?, description = ?, points = ?
WHERE guild_id = ? AND position = ?
""",
(title, description, points, guild_id, index),
)
if cursor.rowcount == 0:
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",
"security_enabled",
"antinuke_enabled",
"audit_message_logs_enabled",
"audit_server_logs_enabled",
):
data[key] = bool(data[key])
return data
def create_backup(self, destination_path: str) -> str:
destination = Path(destination_path).expanduser()
destination.parent.mkdir(parents=True, exist_ok=True)
with self._lock:
backup_connection = sqlite3.connect(str(destination))
try:
self.connection.backup(backup_connection)
finally:
backup_connection.close()
return str(destination)
def add_security_event(
self,
guild_id: int,
actor_id: int,
action: str,
*,
target_id: int | None = None,
details: dict[str, Any] | None = None,
) -> int:
self.ensure_guild(guild_id)
with self._lock:
cursor = self.connection.execute(
"""
INSERT INTO security_events (guild_id, actor_id, action, target_id, details, created_at)
VALUES (?, ?, ?, ?, ?, ?)
""",
(
guild_id,
actor_id,
action,
target_id,
json.dumps(details or {}),
utcnow_iso(),
),
)
self.connection.commit()
return int(cursor.lastrowid)
def count_recent_security_events(
self,
guild_id: int,
actor_id: int,
*,
actions: list[str],
since_iso: str,
) -> int:
if not actions:
return 0
placeholders = ",".join("?" for _ in actions)
with self._lock:
row = self.connection.execute(
f"""
SELECT COUNT(*) AS count
FROM security_events
WHERE guild_id = ?
AND actor_id = ?
AND action IN ({placeholders})
AND created_at >= ?
""",
(guild_id, actor_id, *actions, since_iso),
).fetchone()
return int(row["count"] if row is not None else 0)
def list_recent_security_events(self, guild_id: int, limit: int = 10) -> list[dict[str, Any]]:
self.ensure_guild(guild_id)
with self._lock:
rows = self.connection.execute(
"""
SELECT *
FROM security_events
WHERE guild_id = ?
ORDER BY created_at DESC
LIMIT ?
""",
(guild_id, limit),
).fetchall()
events: list[dict[str, Any]] = []
for row in rows:
event = dict(row)
event["details"] = json.loads(event["details"] or "{}")
events.append(event)
return events
def add_sentinel_event(
self,
guild_id: int,
user_id: int,
*,
channel_id: int | None,
message_id: int | None,
category: str,
severity: int,
confidence: float,
summary: str,
content_hash: str,
excerpt: str | None,
signals: list[dict[str, Any]],
action: str = "observe",
actor_kind: str = "human",
channel_scope: str = "public",
deleted: bool = False,
) -> int:
self.ensure_guild(guild_id)
now = utcnow_iso()
bounded_severity = max(1, min(5, int(severity)))
bounded_confidence = max(0.0, min(1.0, float(confidence)))
with self._lock:
cursor = self.connection.execute(
"""
INSERT INTO sentinel_events (
guild_id, user_id, channel_id, message_id, category, action,
actor_kind, channel_scope, deleted, severity, confidence,
summary, content_hash, excerpt, signals_json, created_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
guild_id,
user_id,
channel_id,
message_id,
category,
action,
actor_kind,
channel_scope,
1 if deleted else 0,
bounded_severity,
bounded_confidence,
summary,
content_hash,
excerpt,
json.dumps(signals),
now,
),
)
profile = self.connection.execute(
"SELECT * FROM sentinel_profiles WHERE guild_id = ? AND user_id = ?",
(guild_id, user_id),
).fetchone()
increment = bounded_severity * bounded_confidence * 8
if profile is None:
risk_score = min(100.0, increment)
self.connection.execute(
"""
INSERT INTO sentinel_profiles (
guild_id, user_id, risk_score, event_count, last_event_at, updated_at
)
VALUES (?, ?, ?, 1, ?, ?)
""",
(guild_id, user_id, risk_score, now, now),
)
else:
current_score = decayed_sentinel_score(
float(profile["risk_score"]),
profile["last_event_at"],
now_iso=now,
)
risk_score = min(100.0, current_score + increment)
self.connection.execute(
"""
UPDATE sentinel_profiles
SET risk_score = ?,
event_count = event_count + 1,
last_event_at = ?,
updated_at = ?
WHERE guild_id = ? AND user_id = ?
""",
(risk_score, now, now, guild_id, user_id),
)
self.connection.commit()
return int(cursor.lastrowid)
def list_recent_sentinel_events(
self,
guild_id: int,
*,
limit: int = 10,
user_id: int | None = None,
min_severity: int | None = None,
) -> list[dict[str, Any]]:
self.ensure_guild(guild_id)
query = ["SELECT * FROM sentinel_events WHERE guild_id = ?"]
values: list[Any] = [guild_id]
if user_id is not None:
query.append("AND user_id = ?")
values.append(user_id)
if min_severity is not None:
query.append("AND severity >= ?")
values.append(min_severity)
query.append("ORDER BY id DESC LIMIT ?")
values.append(max(1, min(50, int(limit))))
with self._lock:
rows = self.connection.execute(" ".join(query), tuple(values)).fetchall()
events: list[dict[str, Any]] = []
for row in rows:
event = dict(row)
event["signals"] = json.loads(event.pop("signals_json") or "[]")
events.append(event)
return events
def get_sentinel_profile(self, guild_id: int, user_id: int) -> dict[str, Any] | None:
self.ensure_guild(guild_id)
with self._lock:
row = self.connection.execute(
"SELECT * FROM sentinel_profiles WHERE guild_id = ? AND user_id = ?",
(guild_id, user_id),
).fetchone()
if row is None:
return None
profile = dict(row)
profile["risk_score"] = decayed_sentinel_score(
float(profile["risk_score"]),
profile["last_event_at"],
)
return profile
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 save_bluesky_feed(
self,
guild_id: int,
*,
handle: str,
channel_id: int,
enabled: bool = True,
last_post_uri: str | None = None,
last_post_created_at: str | None = None,
) -> None:
self.ensure_guild(guild_id)
normalized_handle = handle.strip().lstrip("@").lower()
if not normalized_handle:
raise ValueError("Bluesky handle cannot be empty.")
now = utcnow_iso()
with self._lock:
self.connection.execute(
"""
INSERT INTO bluesky_feeds (
guild_id, handle, channel_id, enabled, last_post_uri, last_post_created_at, created_at, updated_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(guild_id) DO UPDATE SET
handle = excluded.handle,
channel_id = excluded.channel_id,
enabled = excluded.enabled,
last_post_uri = excluded.last_post_uri,
last_post_created_at = excluded.last_post_created_at,
updated_at = excluded.updated_at
""",
(
guild_id,
normalized_handle,
channel_id,
1 if enabled else 0,
last_post_uri,
last_post_created_at,
now,
now,
),
)
self.connection.commit()
def get_bluesky_feed(self, guild_id: int) -> dict[str, Any] | None:
self.ensure_guild(guild_id)
with self._lock:
row = self.connection.execute(
"SELECT * FROM bluesky_feeds WHERE guild_id = ?",
(guild_id,),
).fetchone()
if row is None:
return None
data = dict(row)
data["enabled"] = bool(data["enabled"])
return data
def list_enabled_bluesky_feeds(self) -> list[dict[str, Any]]:
with self._lock:
rows = self.connection.execute(
"SELECT * FROM bluesky_feeds WHERE enabled = 1 ORDER BY guild_id ASC",
).fetchall()
feeds: list[dict[str, Any]] = []
for row in rows:
data = dict(row)
data["enabled"] = bool(data["enabled"])
feeds.append(data)
return feeds
def set_bluesky_feed_enabled(self, guild_id: int, enabled: bool) -> bool:
self.ensure_guild(guild_id)
with self._lock:
cursor = self.connection.execute(
"UPDATE bluesky_feeds SET enabled = ?, updated_at = ? WHERE guild_id = ?",
(1 if enabled else 0, utcnow_iso(), guild_id),
)
self.connection.commit()
return cursor.rowcount > 0
def update_bluesky_feed_cursor(
self,
guild_id: int,
*,
last_post_uri: str | None,
last_post_created_at: str | None,
) -> bool:
self.ensure_guild(guild_id)
with self._lock:
cursor = self.connection.execute(
"""
UPDATE bluesky_feeds
SET last_post_uri = ?, last_post_created_at = ?, updated_at = ?
WHERE guild_id = ?
""",
(last_post_uri, last_post_created_at, utcnow_iso(), guild_id),
)
self.connection.commit()
return cursor.rowcount > 0
def delete_bluesky_feed(self, guild_id: int) -> bool:
self.ensure_guild(guild_id)
with self._lock:
cursor = self.connection.execute(
"DELETE FROM bluesky_feeds WHERE guild_id = ?",
(guild_id,),
)
self.connection.commit()
return cursor.rowcount > 0
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,
)