-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
1551 lines (1304 loc) · 61.3 KB
/
bot.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 os
import sys
import logging
import asyncio
import aiosqlite
import yaml
import time
import discord
from discord.ext import commands, tasks
from typing import List, Dict, Any, Optional
from contextlib import asynccontextmanager
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
import io
from collections import defaultdict
# loggin
logging.basicConfig(
level=logging.DEBUG, # set to INFO for less sql spam
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("bot.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger('AGS')
# config
DEFAULT_CONFIG = {
'bot': {
'prefix': '~',
# 'token': 'YOUR_BOT_TOKEN_HERE' # this is just a BOT_TOKEN environment variable now
},
'database': {
'filename': 'member_activity_data.sqlite'
},
'guilds': {
'GUILD_ID_PLACEHOLDER': {
'channels_to_scan': [],
'authorized_ids': [],
'activity_check': {
'message': "React to this message within 48 hours to confirm your activity.",
'emoji': '✅',
'duration_hours': 48
},
'rate_limit': {
'rate': 1,
'per': 1
},
'members_per_page': 10,
'max_messages_per_channel': 10000,
'days_to_scan': 30, # new parameter for time-based scanning
'ignore_role_id': None
}
}
}
class ConfigManager:
_instance = None
_config = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(ConfigManager, cls).__new__(cls)
cls._instance._lock = asyncio.Lock()
# do not call asyncio.create_task here, u will regret it
return cls._instance
def _load_config(self) -> None:
create_default_config()
self._config = load_config()
@property
def config(self) -> Dict[str, Any]:
return self._config
def get_guild_config(self, guild_id: int) -> Dict[str, Any]:
return self._config.get('guilds', {}).get(str(guild_id), {})
def reload_config(self) -> None:
with self._lock:
self._load_config()
def create_default_config() -> None:
if not os.path.exists('config.yaml'):
try:
with open('config.yaml', 'w') as config_file:
yaml.dump(DEFAULT_CONFIG, config_file, default_flow_style=False)
logger.info("Default config.yaml created. Please update it with your settings.")
except Exception as e:
logger.error(f"Failed to create config.yaml: {e}", exc_info=True)
raise
def load_config() -> Dict[str, Any]:
try:
with open('config.yaml', 'r') as config_file:
config = yaml.safe_load(config_file)
# validation of configuration
if not config.get('bot', {}).get('prefix'):
raise ValueError("Bot prefix not set in config.yaml.")
# ensure required fields are present
if 'database' not in config or 'filename' not in config['database']:
raise ValueError("Database filename not set in config.yaml.")
return config
except Exception as e:
logger.error(f"Error loading config.yaml: {e}", exc_info=True)
raise
# db
class MemberData:
def __init__(self, db_path: str):
self.db_path = db_path
async def initialize(self):
async with aiosqlite.connect(self.db_path) as db:
await db.execute('''
CREATE TABLE IF NOT EXISTS members (
guild_id TEXT,
member_id TEXT,
message_count INTEGER,
join_date TEXT,
displayname TEXT,
username TEXT,
first_message_date TEXT,
last_message_date TEXT,
category TEXT,
left INTEGER DEFAULT 0,
PRIMARY KEY (guild_id, member_id)
)
''')
await db.execute('''
CREATE TABLE IF NOT EXISTS activity_checks (
guild_id TEXT PRIMARY KEY,
message_id TEXT,
channel_id TEXT,
end_time TEXT
)
''')
await db.execute('''
CREATE TABLE IF NOT EXISTS reactions (
guild_id TEXT,
user_id TEXT,
reacted INTEGER,
PRIMARY KEY (guild_id, user_id)
)
''')
# create indexes, could maybe do some more here but it should be quick as is
await db.execute('CREATE INDEX IF NOT EXISTS idx_members_guild_member ON members (guild_id, member_id)')
await db.execute('CREATE INDEX IF NOT EXISTS idx_members_category ON members (guild_id, category)')
await db.execute('CREATE INDEX IF NOT EXISTS idx_reactions_guild_user ON reactions (guild_id, user_id)')
await db.commit()
@asynccontextmanager
async def get_db(self):
try:
async with aiosqlite.connect(self.db_path) as db:
yield db
except Exception as e:
logger.error(f"Database error: {e}", exc_info=True)
raise
async def update_member(self, guild_id: str, member_id: str, data: Dict[str, Any]) -> None:
async with self.get_db() as conn:
await conn.execute('''
INSERT OR REPLACE INTO members
(guild_id, member_id, message_count, join_date, displayname, username,
first_message_date, last_message_date, category, left)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
guild_id, member_id, data['message_count'], data['join_date'],
data['displayname'], data['username'], data['first_message_date'],
data['last_message_date'], data['category'], data.get('left', 0)
))
await conn.commit()
async def get_member(self, guild_id: str, member_id: str) -> Optional[Dict[str, Any]]:
async with self.get_db() as conn:
async with conn.execute('''
SELECT * FROM members WHERE guild_id = ? AND member_id = ?
''', (guild_id, member_id)) as cursor:
row = await cursor.fetchone()
if row:
return dict(zip([col[0] for col in cursor.description], row))
return None
async def get_members_by_category(self, guild_id: str, category: str) -> List[Dict[str, Any]]:
async with self.get_db() as conn:
async with conn.execute('''
SELECT * FROM members
WHERE guild_id = ? AND category = ?
ORDER BY message_count DESC
''', (guild_id, category)) as cursor:
rows = await cursor.fetchall()
return [dict(zip([col[0] for col in cursor.description], row)) for row in rows]
async def get_all_members(self, guild_id: str) -> List[Dict[str, Any]]:
async with self.get_db() as conn:
async with conn.execute('''
SELECT * FROM members WHERE guild_id = ?
''', (guild_id,)) as cursor:
rows = await cursor.fetchall()
return [dict(zip([col[0] for col in cursor.description], row)) for row in rows]
async def batch_update_members(self, guild_id: str, member_data_list: List[Dict[str, Any]]) -> None:
async with self.get_db() as conn:
await conn.executemany('''
INSERT OR REPLACE INTO members
(guild_id, member_id, message_count, join_date, displayname, username,
first_message_date, last_message_date, category, left)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', [
(guild_id, data['member_id'], data['message_count'], data['join_date'],
data['displayname'], data['username'], data['first_message_date'],
data['last_message_date'], data['category'], data.get('left', 0))
for data in member_data_list
])
await conn.commit()
class ActivityCheckData:
def __init__(self, db_path: str):
self.db_path = db_path
@asynccontextmanager
async def get_db(self):
try:
async with aiosqlite.connect(self.db_path) as db:
yield db
except Exception as e:
logger.error(f"Database error: {e}", exc_info=True)
raise
async def save_activity_check(self, guild_id: str, message_id: str,
channel_id: str, end_time: str) -> None:
async with self.get_db() as conn:
await conn.execute('''
INSERT OR REPLACE INTO activity_checks
(guild_id, message_id, channel_id, end_time)
VALUES (?, ?, ?, ?)
''', (guild_id, message_id, channel_id, end_time))
await conn.commit()
async def get_activity_check(self, guild_id: str) -> Optional[Dict[str, Any]]:
async with self.get_db() as conn:
async with conn.execute('''
SELECT * FROM activity_checks WHERE guild_id = ?
''', (guild_id,)) as cursor:
row = await cursor.fetchone()
if row:
return dict(zip([col[0] for col in cursor.description], row))
return None
async def delete_activity_check(self, guild_id: str) -> None:
async with self.get_db() as conn:
await conn.execute('DELETE FROM activity_checks WHERE guild_id = ?', (guild_id,))
await conn.commit()
class ReactionData:
def __init__(self, db_path: str):
self.db_path = db_path
@asynccontextmanager
async def get_db(self):
try:
async with aiosqlite.connect(self.db_path) as db:
yield db
except Exception as e:
logger.error(f"Database error: {e}", exc_info=True)
raise
async def save_reaction(self, guild_id: str, user_id: str, reacted: int) -> None:
async with self.get_db() as conn:
await conn.execute('''
INSERT OR REPLACE INTO reactions (guild_id, user_id, reacted)
VALUES (?, ?, ?)
''', (guild_id, user_id, reacted))
await conn.commit()
async def get_reacted_users(self, guild_id: str) -> List[str]:
async with self.get_db() as conn:
async with conn.execute('''
SELECT user_id FROM reactions WHERE guild_id = ? AND reacted = 1
''', (guild_id,)) as cursor:
rows = await cursor.fetchall()
return [row[0] for row in rows]
async def delete_reactions(self, guild_id: str) -> None:
async with self.get_db() as conn:
await conn.execute('DELETE FROM reactions WHERE guild_id = ?', (guild_id,))
await conn.commit()
# util
class RateLimiter:
def __init__(self, rate: int, per: float):
self.rate = rate
self.per = per
self.tokens = rate
self.updated_at = time.monotonic()
self.lock = asyncio.Lock()
async def wait(self) -> None:
async with self.lock:
now = time.monotonic()
elapsed = now - self.updated_at
self.updated_at = now
self.tokens += elapsed * (self.rate / self.per)
if self.tokens > self.rate:
self.tokens = self.rate
if self.tokens < 1:
sleep_time = (1 - self.tokens) * (self.per / self.rate)
await asyncio.sleep(sleep_time)
self.tokens = 0
else:
self.tokens -= 1
@dataclass
class PerformanceMetrics:
operation: str
duration: float
success: bool
error: Optional[str] = None
class PerformanceMonitor:
def __init__(self, enabled: bool = False):
self.metrics: List[PerformanceMetrics] = []
self.enabled = enabled
@asynccontextmanager
async def measure(self, operation: str):
if not self.enabled:
yield
return
start = time.perf_counter()
try:
yield
self.metrics.append(PerformanceMetrics(
operation=operation,
duration=time.perf_counter() - start,
success=True
))
except Exception as e:
self.metrics.append(PerformanceMetrics(
operation=operation,
duration=time.perf_counter() - start,
success=False,
error=str(e)
))
raise
def get_metrics(self) -> List[PerformanceMetrics]:
return self.metrics.copy()
def clear_metrics(self) -> None:
self.metrics.clear()
class MessageHandler:
def __init__(self, db_path: str, config_manager):
self.db_path = db_path
self.config_manager = config_manager
self.performance_monitor = PerformanceMonitor(enabled=False) # disabled by default because its not working yet
self.message_cache: Dict[str, Dict[str, Any]] = {}
self.lock = asyncio.Lock()
self.batch_size = 100 # number of messages before batch update
self.background_task = None
async def start_background_task(self):
self.background_task = tasks.loop(seconds=60)(self.flush_cache)
self.background_task.start()
async def process_message(self, message: discord.Message) -> None:
if message.author.bot or not isinstance(message.channel, discord.TextChannel):
return
guild_id = str(message.guild.id)
member_id = str(message.author.id)
async with self.performance_monitor.measure(f"process_message_{guild_id}_{member_id}"):
guild_config = self.config_manager.get_guild_config(int(guild_id))
if not guild_config:
return
if self.member_has_ignore_role(message.author, guild_config):
return
async with self.lock:
member_data = self.message_cache.get(member_id)
message_time = message.created_at.isoformat()
if member_data:
member_data['message_count'] += 1
if message_time < member_data['first_message_date']:
member_data['first_message_date'] = message_time
if message_time > member_data['last_message_date']:
member_data['last_message_date'] = message_time
else:
member_data = {
'guild_id': guild_id,
'member_id': member_id,
'message_count': 1,
'join_date': message.author.joined_at.isoformat() if message.author.joined_at else None,
'displayname': message.author.display_name,
'username': str(message.author),
'first_message_date': message_time,
'last_message_date': message_time,
'category': '',
'left': 0
}
self.message_cache[member_id] = member_data
# flush cache if batch size is reached
if len(self.message_cache) >= self.batch_size:
await self.flush_cache()
async def flush_cache(self):
async with self.lock:
if not self.message_cache:
return
member_data_list = list(self.message_cache.values())
member_data = MemberData(self.db_path)
await member_data.batch_update_members(member_data_list[0]['guild_id'], member_data_list)
self.message_cache.clear()
logger.info(f"Flushed {len(member_data_list)} member records to the database.")
@staticmethod
def member_has_ignore_role(member: discord.Member, guild_config: Dict[str, Any]) -> bool:
ignore_role_id = guild_config.get('ignore_role_id')
if ignore_role_id:
try:
ignore_role_id = int(ignore_role_id)
role = member.guild.get_role(ignore_role_id)
return role and role in member.roles
except ValueError:
return False
return False
class PaginationHandler:
def __init__(self, bot: commands.Bot):
self.bot = bot
async def send_paginated_embed(self, ctx: commands.Context,
items: List[Any],
title: str,
items_per_page: int,
format_item_func) -> None:
"""
Sends a paginated embed message in the channel where the command was issued.
"""
if not items:
await ctx.send(f"No data to display for {title}.")
return
pages = [items[i:i + items_per_page] for i in range(0, len(items), items_per_page)]
current_page = 0
def create_embed(page_items: List[Any]) -> discord.Embed:
embed = discord.Embed(
title=f"{title} (Page {current_page + 1}/{len(pages)})",
color=discord.Color.blue()
)
for item in page_items:
name, value = format_item_func(item)
embed.add_field(name=name, value=value, inline=False)
embed.set_footer(text="Use ⬅️ ➡️ to navigate • Session expires in 60 seconds")
return embed
# send the message in the channel where command was issued
message = await ctx.send(embed=create_embed(pages[current_page]))
# page stuff
if len(pages) > 1:
await message.add_reaction('⬅️')
await message.add_reaction('➡️')
def check(reaction, user):
return (
user == ctx.author and
str(reaction.emoji) in ['⬅️', '➡️'] and
reaction.message.id == message.id
)
while True:
try:
reaction, user = await self.bot.wait_for(
'reaction_add',
timeout=60.0,
check=check
)
if str(reaction.emoji) == '➡️' and current_page < len(pages) - 1:
current_page += 1
await message.edit(embed=create_embed(pages[current_page]))
elif str(reaction.emoji) == '⬅️' and current_page > 0:
current_page -= 1
await message.edit(embed=create_embed(pages[current_page]))
await message.remove_reaction(reaction, user)
except asyncio.TimeoutError:
embed = create_embed(pages[current_page])
embed.set_footer(text=f"Page {current_page + 1}/{len(pages)} • Session expired")
await message.edit(embed=embed)
await message.clear_reactions()
break
def format_duration(seconds: float) -> str:
"""Formats a duration in seconds into a human-readable string."""
if seconds < 60:
return f"{seconds:.1f}s"
minutes = seconds / 60
if minutes < 60:
return f"{minutes:.1f}m"
hours = minutes / 60
return f"{hours:.1f}h"
def format_timestamp(timestamp: Optional[str]) -> str:
"""Formats an ISO timestamp into a human-readable string."""
if not timestamp:
return "Never"
try:
dt = datetime.fromisoformat(timestamp)
return dt.strftime("%Y-%m-%d %H:%M:%S UTC")
except ValueError:
return "Invalid timestamp"
# activity check stuff
class ActivityCheckManager:
def __init__(self, bot: commands.Bot, db_path: str, config_manager):
self.bot = bot
self.db_path = db_path
self.config_manager = config_manager
self.activity_data = ActivityCheckData(db_path)
self.reaction_data = ReactionData(db_path)
self.member_data = MemberData(db_path)
self.performance_monitor = PerformanceMonitor(enabled=False)
self.pagination = PaginationHandler(bot)
self.rate_limiter = RateLimiter(rate=1, per=1)
async def start_check(self, ctx: commands.Context, hours: int = 48) -> None:
"""Starts an activity check in the given context."""
guild_id = str(ctx.guild.id)
async with self.performance_monitor.measure(f"start_activity_check_{guild_id}"):
guild_config = self.config_manager.get_guild_config(ctx.guild.id)
if not guild_config:
await ctx.send("Guild configuration not found.")
return
if hours <= 0:
await ctx.send("Duration must be positive.")
return
existing_check = await self.activity_data.get_activity_check(guild_id)
if existing_check:
await ctx.send("An activity check is already in progress.")
return
try:
end_time = datetime.now(timezone.utc) + timedelta(hours=hours)
message = await ctx.send(guild_config['activity_check']['message'])
await message.add_reaction(guild_config['activity_check']['emoji'])
await self.activity_data.save_activity_check(
guild_id,
str(message.id),
str(ctx.channel.id),
end_time.isoformat()
)
await ctx.send(f"Activity check started. Ends in {hours} hours.")
except Exception as e:
logger.error(f"Error starting activity check: {e}", exc_info=True)
await ctx.send("Failed to start activity check.")
raise
async def process_check(self, ctx: commands.Context, force: bool = False) -> None:
"""Processes an ongoing activity check."""
guild_id = str(ctx.guild.id)
async with self.performance_monitor.measure(f"process_activity_check_{guild_id}"):
guild_config = self.config_manager.get_guild_config(ctx.guild.id)
if not guild_config:
await ctx.send("Guild configuration not found.")
return
check_data = await self.activity_data.get_activity_check(guild_id)
if not check_data:
await ctx.send("No active check found.")
return
end_time = datetime.fromisoformat(check_data['end_time'])
if datetime.now(timezone.utc) < end_time and not force:
await ctx.send("Check still ongoing.")
return
try:
# process member reactions and categorize
await self._categorize_members(ctx.guild, check_data)
# clean up
await self.activity_data.delete_activity_check(guild_id)
await self.reaction_data.delete_reactions(guild_id)
await ctx.send("Activity check processed successfully.")
except Exception as e:
logger.error(f"Error processing activity check: {e}", exc_info=True)
await ctx.send("Failed to process activity check.")
raise
async def _categorize_members(self, guild: discord.Guild, check_data: Dict[str, Any]) -> None:
"""Categorizes members based on their activity and reactions."""
guild_id = str(guild.id)
guild_config = self.config_manager.get_guild_config(guild.id)
# get all data
all_members = await self.member_data.get_all_members(guild_id)
reacted_users = set(await self.reaction_data.get_reacted_users(guild_id))
batch_updates = []
for member_data in all_members:
member_id = member_data['member_id']
member = guild.get_member(int(member_id))
if not member or member.bot:
continue
if self.member_has_ignore_role(member, guild_config):
continue
# determine category
if member_id in reacted_users:
category = 'lurkers' if member_data['message_count'] == 0 else 'active'
else:
category = 'inactive'
# prepare batch
member_data['category'] = category
batch_updates.append(member_data)
# rate limit
await self.rate_limiter.wait()
# now slam that bitch
if batch_updates:
await self.member_data.batch_update_members(guild_id, batch_updates)
@staticmethod
def member_has_ignore_role(member: discord.Member, guild_config: Dict[str, Any]) -> bool:
"""Checks if a member has the ignore role."""
ignore_role_id = guild_config.get('ignore_role_id')
if ignore_role_id:
try:
ignore_role_id = int(ignore_role_id)
role = member.guild.get_role(ignore_role_id)
return role and role in member.roles
except ValueError:
return False
return False
# main bot stuff
class AGSBot(commands.Bot):
def __init__(self):
self.config_manager = ConfigManager()
intents = discord.Intents(
guilds=True,
members=True,
messages=True,
reactions=True,
message_content=True
)
super().__init__(
command_prefix=self.get_prefix, # yes this needs to be callable, dont try to change it
intents=intents
)
self.token = os.getenv('BOT_TOKEN')
if not self.token:
logger.error("Bot token not found in environment variables.")
sys.exit(1)
# these dgaf about config.. do not set config stuff up here
self.performance_monitor = PerformanceMonitor(enabled=False)
self.rate_limiter = RateLimiter(rate=1, per=1)
# get rid of the default one
self.remove_command('help')
# load command checks
self.add_check(self.guild_only_check)
# setup reaction locks
self.reaction_locks: Dict[str, asyncio.Lock] = {}
async def get_prefix(self, message):
if not self.config_manager.config:
return '~' # default prefix
if message and message.guild:
guild_id = message.guild.id
guild_config = self.config_manager.get_guild_config(guild_id)
if guild_config:
return guild_config.get('bot', {}).get('prefix', '~')
else:
# for DMs or messages without a guild, return a default prefix, but this is still kinda dodgy
return '~'
# fallback to default
return self.config_manager.config['bot']['prefix']
async def setup_hook(self) -> None:
"""Initialize bot components during startup."""
try:
# load the config
await self.loop.run_in_executor(None, self.config_manager._load_config)
config = self.config_manager.config
# now you can set your config stuff
self.db_path = config['database']['filename']
self.member_data = MemberData(self.db_path)
await self.member_data.initialize()
self.activity_data = ActivityCheckData(self.db_path)
self.reaction_data = ReactionData(self.db_path)
self.message_handler = MessageHandler(self.db_path, self.config_manager)
await self.message_handler.start_background_task()
self.activity_manager = ActivityCheckManager(self, self.db_path, self.config_manager)
self.pagination = PaginationHandler(self)
# load any active activity checks
await self.load_active_checks()
# add commands
self.add_commands()
# events
self.event(self.on_ready)
self.event(self.on_message)
self.event(self.on_member_join)
self.event(self.on_member_remove)
self.event(self.on_raw_reaction_add)
self.event(self.on_raw_reaction_remove)
self.event(self.on_command_error)
except Exception as e:
logger.error(f"Error during bot setup: {e}", exc_info=True)
await self.close()
async def guild_only_check(self, ctx: commands.Context) -> bool:
"""Ensures commands are only used in guilds."""
if not ctx.guild:
await ctx.send("This command cannot be used in DMs.")
return False
return True
def is_authorized(self) -> commands.check:
"""Check if user is authorized to use admin commands."""
async def predicate(ctx: commands.Context) -> bool:
guild_config = self.config_manager.get_guild_config(ctx.guild.id)
if not guild_config:
await ctx.send("Guild configuration not found.")
return False
authorized_ids = guild_config.get('authorized_ids', [])
if ctx.author.id not in authorized_ids and not ctx.author.guild_permissions.administrator:
await ctx.send("You are not authorized to use this command.")
return False
return True
return commands.check(predicate)
def add_commands(self) -> None:
"""Register bot commands."""
@self.command(name='scan_members')
@self.is_authorized()
async def scan_members(ctx: commands.Context):
"""Scans and updates member activity data."""
asyncio.create_task(self.cmd_scan_members(ctx))
await ctx.send("🔄 Member scan started in the background. You will be notified upon completion.")
@self.command(name='start_activity_check')
@self.is_authorized()
async def start_activity_check(ctx: commands.Context, hours: int = 48):
"""Starts an activity check."""
await self.activity_manager.start_check(ctx, hours)
@self.command(name='process_activity_check')
@self.is_authorized()
async def process_activity_check(ctx: commands.Context, *, force: str = ''):
"""Processes the current activity check."""
await self.activity_manager.process_check(ctx, force.lower() == 'force')
@self.command(name='show_category')
@self.is_authorized()
async def show_category(ctx: commands.Context, category: str):
"""Shows members in a specific category."""
await self.cmd_show_category(ctx, category)
@self.command(name='query_user')
@self.is_authorized()
async def query_user(ctx: commands.Context, member: discord.Member):
"""Shows detailed information about a user."""
await self.cmd_query_user(ctx, member)
@self.command(name='help')
async def help(ctx: commands.Context):
"""Shows help information."""
await self.cmd_help(ctx)
@self.command(name='update_categories')
@self.is_authorized()
async def update_categories(ctx: commands.Context):
"""Updates member categories based on activity."""
await self.cmd_update_categories(ctx)
@self.command(name='kick_inactive')
@self.is_authorized()
async def kick_inactive(ctx: commands.Context):
"""Kicks inactive members."""
await self.cmd_kick_inactive(ctx)
@self.command(name='export')
@self.is_authorized()
async def export_data(ctx: commands.Context):
"""Exports member data to CSV."""
await self.cmd_export_data(ctx)
async def load_active_checks(self) -> None:
"""Load and synchronize active checks during startup."""
for guild in self.guilds:
guild_id = str(guild.id)
check_data = await self.activity_data.get_activity_check(guild_id)
if check_data:
try:
channel = self.get_channel(int(check_data['channel_id']))
if channel:
message = await channel.fetch_message(int(check_data['message_id']))
await self._sync_reactions(guild_id, message)
except Exception as e:
logger.error(f"Error loading activity check for guild {guild_id}: {e}", exc_info=True)
async def _sync_reactions(self, guild_id: str, message: discord.Message) -> None:
"""Synchronize reaction data with message reactions."""
guild_config = self.config_manager.get_guild_config(int(guild_id))
if not guild_config:
return
reaction_emoji = guild_config['activity_check']['emoji']
await self.reaction_data.delete_reactions(guild_id)
for reaction in message.reactions:
if str(reaction.emoji) == reaction_emoji:
async for user in reaction.users():
if not user.bot:
await self.reaction_data.save_reaction(guild_id, str(user.id), 1)
# event handlers
async def on_ready(self) -> None:
"""Handle bot ready event."""
logger.info(f'{self.user} has connected to Discord!')
# told u this needed to be callable
prefix = await self.get_prefix(None)
# custom status
activity = discord.Game(name=f"{prefix}help")
await self.change_presence(activity=activity)
logger.info(f"Status set to '{prefix}help'")
async def on_message(self, message: discord.Message) -> None:
"""Handle message events."""
if message.author == self.user:
return
await self.message_handler.process_message(message)
await self.process_commands(message)
async def on_member_join(self, member: discord.Member) -> None:
"""Handle member join events."""
if member.bot:
return
guild_id = str(member.guild.id)
member_id = str(member.id)
member_data = await self.member_data.get_member(guild_id, member_id)
if member_data:
member_data['left'] = 0
member_data['join_date'] = member.joined_at.isoformat()
else:
member_data = {
'member_id': member_id,
'message_count': 0,
'join_date': member.joined_at.isoformat(),
'displayname': member.display_name,
'username': str(member),
'first_message_date': None,
'last_message_date': None,
'category': '',
'left': 0
}
await self.member_data.update_member(guild_id, member_id, member_data)
async def on_member_remove(self, member: discord.Member) -> None:
"""Handle member remove events."""
if member.bot:
return
guild_id = str(member.guild.id)
member_id = str(member.id)
member_data = await self.member_data.get_member(guild_id, member_id)
if member_data:
member_data['left'] = 1
await self.member_data.update_member(guild_id, member_id, member_data)
async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent) -> None:
"""Handle raw reaction add events."""
if payload.user_id == self.user.id:
return
guild = self.get_guild(payload.guild_id)
if not guild:
return
guild_id = str(payload.guild_id)
guild_config = self.config_manager.get_guild_config(payload.guild_id)
if not guild_config:
return
check_data = await self.activity_data.get_activity_check(guild_id)
if (check_data and
str(payload.message_id) == check_data['message_id'] and
str(payload.emoji.name) == guild_config['activity_check']['emoji']):
if guild_id not in self.reaction_locks:
self.reaction_locks[guild_id] = asyncio.Lock()
async with self.reaction_locks[guild_id]:
await self.reaction_data.save_reaction(guild_id, str(payload.user_id), 1)
async def on_raw_reaction_remove(self, payload: discord.RawReactionActionEvent) -> None:
"""Handle raw reaction remove events."""
if payload.user_id == self.user.id:
return
guild = self.get_guild(payload.guild_id)
if not guild:
return
guild_id = str(payload.guild_id)
guild_config = self.config_manager.get_guild_config(payload.guild_id)
if not guild_config:
return
check_data = await self.activity_data.get_activity_check(guild_id)
if (check_data and
str(payload.message_id) == check_data['message_id'] and
str(payload.emoji.name) == guild_config['activity_check']['emoji']):
if guild_id not in self.reaction_locks:
self.reaction_locks[guild_id] = asyncio.Lock()
async with self.reaction_locks[guild_id]:
await self.reaction_data.save_reaction(guild_id, str(payload.user_id), 0)
async def on_command_error(self, ctx: commands.Context, error: Exception) -> None:
"""Handle command errors."""
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f"Command on cooldown. Try again in {error.retry_after:.1f}s")
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f"Missing required argument: {error.param}")
elif isinstance(error, commands.BadArgument):
await ctx.send(f"Invalid argument provided: {error}")
elif isinstance(error, commands.CommandNotFound):
pass # dont think this needs anything else
elif isinstance(error, commands.CheckFailure):
pass # we dont do auth errors here so dw about it
else:
logger.error(f"Unhandled error in command {ctx.command}: {error}", exc_info=True)
await ctx.send("An unexpected error occurred. Please try again later.")
# commands
async def cmd_scan_members(self, ctx: commands.Context) -> None:
"""Scan and update member activity data."""
guild_id = str(ctx.guild.id)
guild_config = self.config_manager.get_guild_config(ctx.guild.id)
if not guild_config:
await ctx.send("❌ Guild configuration not found.")