generated from retr0-init/Discord-Bot-Framework-Module-Template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
4121 lines (3576 loc) · 153 KB
/
main.py
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 asyncio
import itertools
import logging
import math
import os
import re
import time
import traceback
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from enum import Enum, auto
from functools import lru_cache, partial, wraps
from itertools import islice
from logging.handlers import RotatingFileHandler
from multiprocessing import cpu_count
from operator import attrgetter
from pathlib import Path
from typing import (
Any,
AsyncGenerator,
Callable,
Concatenate,
Coroutine,
DefaultDict,
Dict,
FrozenSet,
Generic,
Iterable,
List,
Literal,
Optional,
ParamSpec,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
import aiofiles
import aiofiles.os
import aiofiles.ospath
import aiohttp
import aioshutil
import cysimdjson
import interactions
import numpy as np
import orjson
from cachetools import TTLCache
from interactions.api.events import (
ExtensionLoad,
ExtensionUnload,
MemberAdd,
MemberRemove,
MemberUpdate,
MessageCreate,
MessageReactionAdd,
MessageReactionRemove,
NewThreadCreate,
)
from interactions.client.errors import HTTPException, NotFound
from interactions.ext.paginators import Paginator
from pydantic import BaseModel
from yarl import URL
BASE_DIR: str = os.path.dirname(os.path.abspath(__file__))
LOG_FILE: str = os.path.join(BASE_DIR, "roles.log")
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(
"%(asctime)s | %(process)d:%(thread)d | %(levelname)-8s | %(name)s:%(funcName)s:%(lineno)d - %(message)s",
"%Y-%m-%d %H:%M:%S.%f %z",
)
file_handler = RotatingFileHandler(
LOG_FILE, maxBytes=1024 * 1024, backupCount=1, encoding="utf-8"
)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# Model
T = TypeVar("T", bound=Union[BaseModel, Counter, Dict[str, Any]])
P = ParamSpec("P")
class Status(Enum):
APPROVED = auto()
REJECTED = auto()
class EmbedColor(Enum):
OFF = 0x5D5A58
FATAL = 0xFF4343
ERROR = 0xE81123
WARN = 0xFFB900
INFO = 0x0078D7
DEBUG = 0x00B7C3
TRACE = 0x8E8CD8
ALL = 0x0063B1
class Action(Enum):
ADD = "add"
REMOVE = "remove"
INCARCERATE = "incarcerate"
RELEASE = "release"
class Data(BaseModel):
assigned_roles: Dict[str, Dict[str, int]] = field(default_factory=dict)
authorized_roles: Dict[str, int] = field(default_factory=dict)
assignable_roles: Dict[str, List[str]] = field(default_factory=dict)
incarcerated_members: Dict[str, Dict[str, Any]] = field(default_factory=dict)
class Config:
json_encoders = {
set: list,
}
@dataclass
class Config:
ELECT_VETTING_FORUM_ID: int = 1164834982737489930
APPR_VETTING_FORUM_ID: int = 1307001955230552075
VETTING_ROLE_IDS: List[int] = field(default_factory=lambda: [1200066469300551782])
ELECTORAL_ROLE_ID: int = 1200043628899356702
APPROVED_ROLE_ID: int = 1282944839679344721
TEMPORARY_ROLE_ID: int = 1164761892015833129
MINISTER_ROLE_ID: int = 1297556675473182720
MISSING_ROLE_ID: int = 1289949397362409472
INCARCERATED_ROLE_ID: int = 1247284720044085370
AUTHORIZED_CUSTOM_ROLE_IDS: List[int] = field(
default_factory=lambda: [1213490790341279754]
)
AUTHORIZED_PENITENTIARY_ROLE_IDS: List[int] = field(
default_factory=lambda: [1200097748259717193, 1247144717083476051]
)
REQUIRED_APPROVALS: int = 3
REQUIRED_REJECTIONS: int = 3
REJECTION_WINDOW_DAYS: int = 7
LOG_CHANNEL_ID: int = 1166627731916734504
LOG_FORUM_ID: int = 1159097493875871784
LOG_POST_ID: int = 1325394043177275445
GUILD_ID: int = 1150630510696075404
@dataclass
class Servant:
role_name: str
members: List[str]
member_count: int
@dataclass
class Approval:
approval_count: int = 0
rejection_count: int = 0
reviewers: Set[int] = field(default_factory=set)
last_approval_time: Optional[datetime] = None
class StickyRoles:
def __init__(self) -> None:
self.base_path: Path = Path(__file__).parent
self.db_path = self.base_path / "sticky_roles.json"
self._data_cache: Optional[dict] = None
self._last_read: float = 0
self._cache_ttl: float = 1.0
self._lock = asyncio.Lock()
self._cleanup_task: Optional[asyncio.Task] = None
async def read_data(self) -> Dict[str, Any]:
async with self._lock:
if (
not self._data_cache
or (time.monotonic() - self._last_read) > self._cache_ttl
):
try:
self._data_cache = orjson.loads(
await (await aiofiles.open(self.db_path, mode="rb")).read()
)
self._last_read = time.monotonic()
except (IOError, orjson.JSONDecodeError):
self._data_cache = {"members": {}}
return self._data_cache or {"members": {}}
async def write_data(self, data: Dict[str, Any]) -> None:
async with self._lock:
serialized = orjson.dumps(
data, option=orjson.OPT_INDENT_2 | orjson.OPT_SORT_KEYS
)
async with aiofiles.open(self.db_path, mode="wb") as f:
await f.write(serialized)
self._data_cache, self._last_read = data, time.monotonic()
async def get_sticky_roles(self, member_id: int) -> list[int]:
try:
data = await self.read_data()
return data.get("members", {}).get(str(member_id), {}).get("role_ids", [])
except Exception as e:
logger.error(
f"Error getting sticky roles for member {member_id}: {e}",
exc_info=True,
)
return []
async def update_sticky_roles(self, member_id: int, role_ids: list[int]) -> None:
try:
role_ids = [*{int(rid) for rid in role_ids}]
data = await self.read_data()
ts = datetime.now(timezone.utc).isoformat()
data["members"][str(member_id)] = {"role_ids": role_ids, "updated_at": ts}
await self.write_data(data)
except ValueError as e:
logger.error(
f"Invalid role ID format for member {member_id}: {e}",
exc_info=True,
)
raise
except Exception as e:
logger.error(
f"Error updating sticky roles for member {member_id}: {e}",
exc_info=True,
)
raise
async def cleanup_inactive_roles(self, days: int = 30) -> None:
try:
data = await self.read_data()
cutoff_ts = (datetime.now(timezone.utc) - timedelta(days=days)).timestamp()
data["members"] = {
mid: mdata
for mid, mdata in data["members"].items()
if datetime.fromisoformat(mdata["updated_at"]).timestamp() >= cutoff_ts
}
await self.write_data(data)
except Exception as e:
logger.error(f"Error during sticky roles cleanup: {e}", exc_info=True)
raise
class Model(Generic[T]):
def __init__(self) -> None:
self.base_path: URL = URL(str(Path(__file__).parent))
self._data_cache: Dict[str, Any] = {}
self.parser: cysimdjson.JSONParser = cysimdjson.JSONParser()
self._file_locks: Dict[str, asyncio.Lock] = {}
self._executor: ThreadPoolExecutor = ThreadPoolExecutor(
max_workers=min(cpu_count(), 4)
)
@staticmethod
def async_retry(max_retries: int = 3, delay: float = 1.0) -> Callable:
def decorator(func: Callable[..., Coroutine]) -> Callable[..., Coroutine]:
@wraps(func)
async def wrapper(*args: Any, **kwargs: Any) -> Any:
for attempt in range(max_retries):
try:
return await func(*args, **kwargs)
except Exception as e:
if attempt == max_retries - 1:
raise
logger.warning(
f"Attempt {attempt + 1} failed: {e}. Retrying..."
)
await asyncio.sleep(delay * (2**attempt))
return None
return wrapper
return decorator
async def get_file_lock(self, file_name: str) -> asyncio.Lock:
return self._file_locks.setdefault(file_name, asyncio.Lock())
@asynccontextmanager
async def file_operation(
self, file_path: Path, mode: str
) -> AsyncGenerator[Any, None]:
lock = await self.get_file_lock(str(file_path))
async with lock:
try:
async with aiofiles.open(str(file_path), mode=mode) as file:
yield file
except IOError as e:
logger.error(f"IO operation failed for {file_path}: {e}", exc_info=True)
raise
@async_retry()
async def load_data(self, file_name: str, model: Type[T]) -> T:
file_path = self.base_path / file_name
try:
async with self.file_operation(file_path, "rb") as file:
content = await file.read()
json_parsed = orjson.loads(content)
if issubclass(model, BaseModel):
instance = (
model.model_validate_json(content)
if content
else model.model_validate({})
)
else:
instance = cast(T, json_parsed if json_parsed else {})
if file_name == "custom.json":
instance = {
role: set(members) for role, members in instance.items()
}
self._data_cache[file_name] = instance
return instance
except FileNotFoundError:
instance = model.model_validate({}) if issubclass(model, BaseModel) else {}
await self.save_data(file_name, instance)
return cast(T, instance)
except Exception as e:
logger.error(f"Error loading {file_name}: {e}", exc_info=True)
raise ValueError(f"Failed to load {file_name}") from e
@async_retry()
async def save_data(self, file_name: str, data: T) -> None:
file_path = self.base_path / file_name
try:
json_data = orjson.dumps(
(data.model_dump(mode="json") if isinstance(data, BaseModel) else data),
option=orjson.OPT_INDENT_2
| orjson.OPT_SERIALIZE_NUMPY
| orjson.OPT_NON_STR_KEYS,
)
async with self.file_operation(file_path, "wb") as file:
await file.write(json_data)
self._data_cache[file_name] = data
logger.info(f"Successfully saved data to {file_name}")
except Exception as e:
logger.error(f"Error saving {file_name}: {e}", exc_info=True)
raise
def __del__(self) -> None:
self._executor.shutdown(wait=False, cancel_futures=True)
@dataclass
class Message:
message: str
user_stats: Dict[str, Any]
config: Dict[str, float]
validation_flags: Dict[str, bool]
_message_length: int = field(init=False, repr=False)
_char_frequencies: Counter = field(init=False, repr=False)
_is_chinese: bool = field(init=False, repr=False)
def __post_init__(self) -> None:
msg = self.message or ""
object.__setattr__(self, "_message_length", len(msg))
object.__setattr__(self, "_char_frequencies", Counter(msg))
object.__setattr__(
self,
"_is_chinese",
any(
ord(c) in range(0x4E00, 0x9FFF + 1)
or ord(c) in range(0x3400, 0x4DBF + 1)
for c in msg
),
)
def analyze(self) -> frozenset[str]:
violations: set[str] = set()
if self.validation_flags["repetition"]:
if self._check_repetition():
violations.add("message_repetition")
if self.validation_flags["digit_ratio"]:
if self._check_digit_ratio():
violations.add("excessive_digits")
if self.validation_flags["entropy"]:
if self._check_entropy():
violations.add("low_entropy")
if self.validation_flags["feedback"]:
self.user_stats["feedback_score"] = max(
-5, min(5, self.user_stats.get("feedback_score", 0) - len(violations))
)
return frozenset(violations)
def _check_repetition(self) -> bool:
last_msg = self.user_stats.get("last_message", "")
if self.message == last_msg:
rep_count = self.user_stats.get("repetition_count", 0) + 1
self.user_stats["repetition_count"] = rep_count
return rep_count >= self.config["MAX_REPEATED_MESSAGES"]
self.user_stats.update({"repetition_count": 0, "last_message": self.message})
return False
def _check_digit_ratio(self) -> bool:
if not self._message_length:
return False
threshold = self.config["DIGIT_RATIO_THRESHOLD"] * (
1.5 if self._is_chinese else 1.0
)
digit_count = sum(1 for c in self.message if c.isdigit())
return (digit_count / self._message_length) > threshold
def _check_entropy(self) -> bool:
if not self._message_length:
return False
freqs = np.array(list(self._char_frequencies.values()), dtype=np.float64)
probs = freqs / self._message_length
entropy = -np.sum(probs * np.log2(probs))
base_threshold = self.config["MIN_MESSAGE_ENTROPY"] * (
0.7 if self._is_chinese else 1.0
)
length_adjustment = (np.log2(max(self._message_length, 2)) / 10) * (
0.8 if self._is_chinese else 1.0
)
return entropy < max(base_threshold, 2.0 - length_adjustment)
# Controller
class ChannelHistoryIteractor:
def __init__(self, history: interactions.ChannelHistory) -> None:
self.history: interactions.ChannelHistory = history
self._retries = 0
self.MAX_RETRIES = 3
self.RETRY_DELAY = 1.0
def __aiter__(self):
return self
async def __anext__(self):
while self._retries < self.MAX_RETRIES:
try:
return await self.history.__anext__()
except StopAsyncIteration:
raise
except HTTPException as e:
try:
match e.code:
case 50083 | 10003 | 50001 | 50013:
logger.error(
f"Channel {self.history.channel.name} ({self.history.channel.id}): "
f"{'archived thread' if e.code == 50083 else 'unknown channel' if e.code == 10003 else 'no access' if e.code == 50001 else 'lacks permission'}"
)
raise StopAsyncIteration
case 10008:
logger.warning(
f"Unknown message in Channel {self.history.channel.name} ({self.history.channel.id})"
)
case 50021:
logger.warning(
f"System message in Channel {self.history.channel.name} ({self.history.channel.id})"
)
case 160005:
logger.warning(
f"Channel {self.history.channel.name} ({self.history.channel.id}) is a locked thread"
)
case _:
logger.warning(
f"Channel {self.history.channel.name} ({self.history.channel.id}) has unknown code {e.code}"
)
except ValueError:
logger.warning(
f"Unknown HTTP exception {e.code} {e.errors} {e.route} {e.response} {e.text}",
stack_info=True,
)
except aiohttp.ClientPayloadError as e:
self._retries += 1
if self._retries >= self.MAX_RETRIES:
logger.error(
f"Failed to fetch message history after {self.MAX_RETRIES} retries: {str(e)}"
)
raise StopAsyncIteration
logger.warning(
f"ClientPayloadError occurred (attempt {self._retries}/{self.MAX_RETRIES}): {str(e)}"
)
await asyncio.sleep(self.RETRY_DELAY * self._retries)
continue
except Exception as e:
logger.warning(
f"Unknown exception {e.__class__.__name__}: {str(e)}", exc_info=True
)
self._retries += 1
if self._retries >= self.MAX_RETRIES:
raise StopAsyncIteration
await asyncio.sleep(self.RETRY_DELAY * self._retries)
continue
class Roles(interactions.Extension):
def __init__(self, bot: interactions.Client):
self.bot: interactions.Client = bot
self.config: Config = Config()
self.sticky_roles: StickyRoles = StickyRoles()
self.vetting_roles: Data = Data()
self.custom_roles: Dict[str, Set[int]] = {}
self.incarcerated_members: Dict[str, Dict[str, Any]] = {}
self.stats: Dict[str, Dict[str, Any]] = {}
self.processed_thread_ids: Set[int] = set()
self.approval_counts: Dict[int, Approval] = {}
self.member_role_locks: Dict[int, Dict[str, Union[asyncio.Lock, datetime]]] = {}
self.stats_lock: asyncio.Lock = asyncio.Lock()
self.stats_save_task: asyncio.Task | None = None
self.reaction_roles: Dict[str, Dict[str, Any]] = {}
self.message_monitoring_enabled: bool = False
self.validation_flags: Dict[str, bool] = {
"repetition": True,
"digit_ratio": True,
"entropy": True,
"feedback": True,
}
self.limit_config: Dict[str, Union[float, int]] = {
"MESSAGE_WINDOW_SECONDS": 60.0,
"MAX_REPEATED_MESSAGES": 3,
"DIGIT_RATIO_THRESHOLD": 0.5,
"MIN_MESSAGE_ENTROPY": 1.5,
}
self.excluded_role_ids = {
self.config.ELECTORAL_ROLE_ID,
self.config.APPROVED_ROLE_ID,
self.config.TEMPORARY_ROLE_ID,
}
self.cache = TTLCache(maxsize=100, ttl=300)
self.base_path: Path = Path(__file__).parent
self.model: Model[Any] = Model()
self.load_tasks: List[Coroutine] = [
self.model.load_data("vetting.json", Data),
self.model.load_data("custom.json", dict),
self.model.load_data("incarcerated_members.json", dict),
self.model.load_data("stats.json", dict),
self.model.load_data("reaction_roles.json", dict),
]
asyncio.create_task(self.load_initial_data())
async def load_initial_data(self) -> None:
try:
results = await asyncio.gather(*self.load_tasks)
(
self.vetting_roles,
self.custom_roles,
self.incarcerated_members,
self.stats,
self.reaction_roles,
) = results
logger.info("Initial data loaded successfully")
data = await self.sticky_roles.read_data()
sticky_role_updates: List[Tuple[int, List[int]]] = []
after = None
while True:
members = await self.bot.http.list_members(
self.config.GUILD_ID, limit=1000, after=after
)
if not members:
break
for member in members:
member_id = int(member["user"]["id"])
role_ids = [int(role_id) for role_id in member["roles"]]
if role_ids:
sticky_role_updates.append((member_id, role_ids))
after = members[-1]["user"]["id"]
for member_id, roles in sticky_role_updates:
ts = datetime.now(timezone.utc).isoformat()
data["members"][str(member_id)] = {"role_ids": roles, "updated_at": ts}
await self.sticky_roles.write_data(data)
logger.info(
f"Sticky roles database initialized with {len(sticky_role_updates)} members"
)
except Exception as e:
logger.critical(f"Failed to load critical data: {e}", exc_info=True)
raise
# Decorator
ContextType = TypeVar("ContextType", bound=interactions.BaseContext)
@staticmethod
def error_handler(
func: Callable[Concatenate[Any, ContextType, P], Coroutine[Any, Any, T]]
) -> Callable[Concatenate[Any, ContextType, P], Coroutine[Any, Any, T]]:
@wraps(func)
async def wrapper(
self, ctx: interactions.BaseContext, *args: P.args, **kwargs: P.kwargs
) -> T:
try:
result = await asyncio.shield(func(self, ctx, *args, **kwargs))
logger.info(f"`{func.__name__}` completed successfully: {result}")
return result
except asyncio.CancelledError as ce:
logger.warning(
f"{func.__name__} was cancelled",
extra={"exc_info": True, "stack_info": True},
)
raise ce from None
except Exception as e:
error_msg = f"Error in {func.__name__}: {e!r}\n{traceback.format_exc()}"
logger.exception(error_msg)
raise e from None
return wrapper
# Validators
def get_assignable_role_ids(self) -> frozenset[int]:
return frozenset(
role_id
for roles in self.vetting_roles.assigned_roles.values()
for name, role_id in roles.items()
if any(
name in a_roles
for a_roles in self.vetting_roles.assignable_roles.values()
)
)
def has_required_roles(
self,
ctx: interactions.BaseContext,
required_role_ids: frozenset[int],
role_ids_to_check: frozenset[int] | None = None,
check_assignable: bool = False,
) -> bool:
has_permission = bool(
frozenset(map(attrgetter("id"), getattr(ctx, "author").roles))
& required_role_ids
)
return has_permission and (
not check_assignable
or (
role_ids_to_check is not None
and role_ids_to_check <= self.get_assignable_role_ids()
)
)
def validate_vetting_permissions(self, ctx: interactions.BaseContext) -> bool:
return self.has_required_roles(
ctx, frozenset(self.vetting_roles.authorized_roles.values())
)
def validate_vetting_permissions_with_roles(
self, ctx: interactions.BaseContext, role_ids_to_add: Iterable[int]
) -> bool:
return self.has_required_roles(
ctx,
frozenset(self.vetting_roles.authorized_roles.values()),
frozenset(role_ids_to_add),
check_assignable=True,
)
def validate_custom_permissions(self, ctx: interactions.BaseContext) -> bool:
return self.has_required_roles(
ctx, frozenset(self.config.AUTHORIZED_CUSTOM_ROLE_IDS)
)
def validate_penitentiary_permissions(self, ctx: interactions.BaseContext) -> bool:
return self.has_required_roles(
ctx, frozenset(self.config.AUTHORIZED_PENITENTIARY_ROLE_IDS)
)
@lru_cache()
def _get_category_role_ids(
self, category: str, *, _cache: dict[str, frozenset[int]] | None = None
) -> frozenset[int]:
key = f"category_role_ids_{category}"
if _cache is None:
return frozenset(
self.vetting_roles.assigned_roles.get(category, {}).values()
)
if key not in _cache:
_cache[key] = frozenset(
self.vetting_roles.assigned_roles.get(category, {}).values()
)
return _cache[key]
async def check_role_assignment_conflicts(
self,
ctx: interactions.SlashContext,
member: interactions.Member,
role_ids_to_add: Iterable[int],
) -> bool:
member_roles = frozenset(map(attrgetter("id"), member.roles))
roles_to_add = frozenset(role_ids_to_add)
others_role_ids = self._get_category_role_ids("others")
roles_to_check = roles_to_add - others_role_ids
if not roles_to_check:
return False
conflicts = [
(
member_roles & category_roles,
roles_to_add & category_roles,
)
for category, category_roles in (
(cat, self._get_category_role_ids(cat))
for cat in self.vetting_roles.assigned_roles
if cat != "others"
)
if bool(member_roles & category_roles)
and bool(roles_to_add & category_roles)
and len((member_roles & category_roles) | (roles_to_add & category_roles))
> 1
]
if conflicts:
existing, adding = conflicts[0]
await self.send_error(
ctx,
f"Conflicting roles detected in the category. "
f"Member already has {len(existing)} role(s) "
f"and is attempting to add {len(adding)} role(s).",
)
return True
return False
# View methods
async def create_embed(
self,
title: str,
description: str = "",
color: Union[EmbedColor, int] = EmbedColor.INFO,
fields: Optional[List[Dict[str, str]]] = None,
) -> interactions.Embed:
color_value: int = color.value if isinstance(color, EmbedColor) else color
embed: interactions.Embed = interactions.Embed(
title=title, description=description, color=color_value
)
if fields:
for field in fields:
embed.add_field(
name=field.get("name", ""),
value=field.get("value", ""),
inline=field.get("inline", True),
)
guild: Optional[interactions.Guild] = await self.bot.fetch_guild(
self.config.GUILD_ID
)
if guild and guild.icon:
embed.set_footer(text=guild.name, icon_url=guild.icon.url)
embed.timestamp = datetime.now(timezone.utc)
embed.set_footer(text="鍵政大舞台")
return embed
async def notify_vetting_reviewers(
self,
reviewer_role_ids: List[int],
thread: interactions.GuildPublicThread,
timestamp: str,
) -> None:
if not (guild := await self.bot.fetch_guild(thread.guild.id)):
error_msg = f"Could not fetch the guild with ID {thread.guild.id}."
logger.error(error_msg)
raise ValueError(error_msg)
is_appr_forum = thread.parent_id == self.config.APPR_VETTING_FORUM_ID
title = (
f"Quick Identity Verification #{timestamp}"
if is_appr_forum
else f"Voter Identity Verification #{timestamp}"
)
embed = await self.create_embed(
title=title,
description=f"[Click here to jump: {thread.name}](https://discord.com/channels/{thread.guild.id}/{thread.id})",
)
async def process_role(role_id: int) -> None:
try:
if not (role := await guild.fetch_role(role_id)):
logger.error(f"Reviewer role with ID {role_id} not found.")
return
for member in role.members:
await self.send_direct_message(member, embed)
logger.info(
f"Notifications sent to role ID {role_id} in thread {thread.id}"
)
except Exception as e:
logger.error(f"Error processing role {role_id}: {e}", exc_info=True)
for role_id in reviewer_role_ids:
await process_role(role_id)
logger.info(f"All reviewer notifications sent for thread {thread.id}")
@staticmethod
async def send_direct_message(
member: interactions.Member, embed: interactions.Embed
) -> None:
try:
await member.send(embed=embed)
logger.debug(f"Sent notification to member {member.id}")
except Exception as e:
logger.error(f"Failed to send embed to {member.id}: {e}", exc_info=True)
@lru_cache(maxsize=1)
def get_log_channels(self) -> tuple[int, int, int]:
return (
self.config.LOG_CHANNEL_ID,
self.config.LOG_POST_ID,
self.config.LOG_FORUM_ID,
)
async def send_response(
self,
ctx: Optional[
Union[
interactions.SlashContext,
interactions.InteractionContext,
interactions.ComponentContext,
]
],
title: str,
message: str,
color: EmbedColor,
log_to_channel: bool = True,
ephemeral: bool = True,
) -> None:
embed: interactions.Embed = await self.create_embed(title, message, color)
if ctx:
await ctx.send(embed=embed, ephemeral=ephemeral)
if log_to_channel:
LOG_CHANNEL_ID, LOG_POST_ID, LOG_FORUM_ID = self.get_log_channels()
await self.send_to_channel(LOG_CHANNEL_ID, embed)
await self.send_to_forum_post(LOG_FORUM_ID, LOG_POST_ID, embed)
async def send_to_channel(self, channel_id: int, embed: interactions.Embed) -> None:
try:
channel = await self.bot.fetch_channel(channel_id)
if not isinstance(
channel := (
channel if isinstance(channel, interactions.GuildText) else None
),
interactions.GuildText,
):
logger.error(f"Channel ID {channel_id} is not a valid text channel.")
return
await channel.send(embed=embed)
except NotFound as nf:
logger.error(f"Channel with ID {channel_id} not found: {nf!r}")
except Exception as e:
logger.error(f"Error sending message to channel {channel_id}: {e!r}")
async def send_to_forum_post(
self, forum_id: int, post_id: int, embed: interactions.Embed
) -> None:
try:
if not isinstance(
forum := await self.bot.fetch_channel(forum_id), interactions.GuildForum
):
logger.error(f"Channel ID {forum_id} is not a valid forum channel.")
return
if not isinstance(
thread := await forum.fetch_post(post_id),
interactions.GuildPublicThread,
):
logger.error(f"Post with ID {post_id} is not a valid thread.")
return
await thread.send(embed=embed)
except NotFound:
logger.error(f"{forum_id=}, {post_id=} - Forum or post not found")
except Exception as e:
logger.error(f"Forum post error [{forum_id=}, {post_id=}]: {e!r}")
async def send_error(
self,
ctx: Optional[
Union[
interactions.SlashContext,
interactions.InteractionContext,
interactions.ComponentContext,
]
],
message: str,
log_to_channel: bool = False,
ephemeral: bool = True,
) -> None:
await self.send_response(
ctx, "Error", message, EmbedColor.ERROR, log_to_channel, ephemeral
)
async def send_success(
self,
ctx: Optional[
Union[
interactions.SlashContext,
interactions.InteractionContext,
interactions.ComponentContext,
]
],
message: str,
log_to_channel: bool = True,
ephemeral: bool = True,
) -> None:
await self.send_response(
ctx, "Success", message, EmbedColor.INFO, log_to_channel, ephemeral
)
async def create_review_components(
self,
thread: interactions.GuildPublicThread,
) -> Tuple[interactions.Embed, List[interactions.Button]]:
approval_info: Approval = self.approval_counts.get(thread.id, Approval())
approval_count: int = approval_info.approval_count
is_appr_forum = thread.parent_id == self.config.APPR_VETTING_FORUM_ID
required_approvals = 1 if is_appr_forum else self.config.REQUIRED_APPROVALS
title = (
"Quick Identity Verification"
if is_appr_forum
else "Voter Identity Verification"
)
reviewers_text: str = (
",".join(f"<@{rid}>" for rid in sorted(approval_info.reviewers, key=int))
if approval_info.reviewers
else "No review records available"
)
embed: interactions.Embed = await self.create_embed(
title=title,
description=(
f"- Current status: {approval_count}/{required_approvals} votes\n"
f"- Review records: {reviewers_text}"
),
)
return embed, [
interactions.Button(style=s, label=l, custom_id=c)
for s, l, c in (
(interactions.ButtonStyle.SUCCESS, "Approve", "approve"),
(interactions.ButtonStyle.DANGER, "Reject", "reject"),
)
]
# Sticky roles
@interactions.listen("MemberRemove")
async def on_member_remove(self, event: MemberRemove) -> None:
try:
member_roles = [role.id for role in event.member.roles]
if member_roles:
await self.sticky_roles.update_sticky_roles(
event.member.id, member_roles
)
logger.info(
f"Saved {len(member_roles)} sticky roles for leaving member {event.member.id}"
)