-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin.py
More file actions
2194 lines (1850 loc) · 87.6 KB
/
admin.py
File metadata and controls
2194 lines (1850 loc) · 87.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
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 discord
from discord.ext import commands
import random
import os
import asyncio
import re
from discord.ext.commands import has_permissions
import json
from datetime import datetime, timedelta
from collections import defaultdict
import pathlib
class AdminCog(commands.Cog):
def __init__(self, client):
self.client = client
self.pending_cclear = {} # Store pending clear operations
# Create data directory if it doesn't exist
self.data_dir = pathlib.Path("data")
self.data_dir.mkdir(exist_ok=True)
# Cache file paths
self.message_cache_file = self.data_dir / "message_cache.json"
self.message_index_file = self.data_dir / "message_index.json"
self.last_scan_file = self.data_dir / "last_scan.txt"
self.word_index = defaultdict(list) # In-memory index for faster searching
# Role saver file paths
self.roles_file = self.data_dir / "saved_roles.json"
self.roles_info_file = self.data_dir / "roles_info.json"
# Nickname history file path
self.nickname_file = self.data_dir / "nickname_history.json"
# Auto reactions file path
self.reactions_file = self.data_dir / "auto_reactions.json"
# Reaction roles file path
self.reaction_roles_file = self.data_dir / "reaction_roles.json"
# Warnings file path
self.warnings_file = self.data_dir / "warnings.json"
# User actions file path
self.user_actions_file = self.data_dir / "user_actions.json"
# Initialize role saving task
self.role_save_task = None
self.last_save_time = None
self.next_save_time = None
# Load role save info if exists
self.load_role_save_info()
# Initialize nickname history
self.load_nickname_history()
# Initialize auto reactions
self.auto_reactions = self.load_auto_reactions()
# Initialize reaction roles
self.reaction_roles = self.load_reaction_roles()
# Initialize warnings
self.warnings = self.load_warnings()
# Initialize user actions
self.user_actions = self.load_user_actions()
def cog_unload(self):
# Cancel the role save task when the cog is unloaded
if self.role_save_task:
self.role_save_task.cancel()
async def cog_load(self):
# Start the role save task when the cog is loaded
self.role_save_task = self.client.loop.create_task(self.role_save_loop())
# Load user actions from file
def load_user_actions(self):
try:
if os.path.exists(self.user_actions_file):
with open(self.user_actions_file, 'r') as f:
return json.load(f)
else:
# Create empty user actions file
with open(self.user_actions_file, 'w') as f:
json.dump({}, f)
return {}
except Exception as e:
print(f"Error loading user actions: {e}")
return {}
# Save user actions to file
def save_user_actions(self):
try:
with open(self.user_actions_file, 'w') as f:
json.dump(self.user_actions, f, indent=2)
return True
except Exception as e:
print(f"Error saving user actions: {e}")
return False
# Add action to user history
async def add_user_action(self, guild_id, user_id, action_type, reason=None, duration=None):
try:
# Load current actions
if not self.user_actions:
self.user_actions = self.load_user_actions()
# Initialize guild section if not exists
guild_id_str = str(guild_id)
if guild_id_str not in self.user_actions:
self.user_actions[guild_id_str] = {}
# Initialize user section if not exists
user_id_str = str(user_id)
if user_id_str not in self.user_actions[guild_id_str]:
self.user_actions[guild_id_str][user_id_str] = []
# Add new action with timestamp
action = {
"action": action_type,
"timestamp": datetime.utcnow().isoformat()
}
if reason:
action["reason"] = reason
if duration:
action["duration"] = duration
self.user_actions[guild_id_str][user_id_str].append(action)
# Save updated actions
self.save_user_actions()
return True
except Exception as e:
print(f"Error adding user action: {e}")
return False
# Load warnings from file
def load_warnings(self):
try:
if os.path.exists(self.warnings_file):
with open(self.warnings_file, 'r') as f:
return json.load(f)
else:
# Create empty warnings file
with open(self.warnings_file, 'w') as f:
json.dump({}, f)
return {}
except Exception as e:
print(f"Error loading warnings: {e}")
return {}
# Save warnings to file
def save_warnings(self):
try:
with open(self.warnings_file, 'w') as f:
json.dump(self.warnings, f, indent=2)
return True
except Exception as e:
print(f"Error saving warnings: {e}")
return False
# Add warning to history
async def add_warning(self, guild_id, user_id, reason):
try:
# Load current warnings
if not self.warnings:
self.warnings = self.load_warnings()
# Initialize guild section if not exists
guild_id_str = str(guild_id)
if guild_id_str not in self.warnings:
self.warnings[guild_id_str] = {}
# Initialize user section if not exists
user_id_str = str(user_id)
if user_id_str not in self.warnings[guild_id_str]:
self.warnings[guild_id_str][user_id_str] = []
# Add new warning with timestamp
self.warnings[guild_id_str][user_id_str].append({
"reason": reason,
"timestamp": datetime.utcnow().isoformat()
})
# Save updated warnings
self.save_warnings()
return True
except Exception as e:
print(f"Error adding warning: {e}")
return False
@commands.command()
@has_permissions(administrator=True)
async def warn(self, ctx, member: discord.Member, *, reason=None):
if reason is None:
reason = "No reason provided"
try:
# Add warning to history
await self.add_warning(ctx.guild.id, member.id, reason)
# Add to user actions - REMOVED to prevent double counting
# await self.add_user_action(ctx.guild.id, member.id, "warn", reason)
# Create DM embed
dm_embed = discord.Embed(
title="Warning",
description=f"You have been warned in **{ctx.guild.name}**",
color=discord.Color.yellow()
)
dm_embed.add_field(name="Reason", value=reason, inline=False)
dm_embed.set_footer(text=f"Time: {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S UTC')}")
# Send DM to user
try:
await member.send(embed=dm_embed)
dm_sent = True
except discord.Forbidden:
dm_sent = False
# Create confirmation embed for the channel
channel_embed = discord.Embed(
title="User Warned",
description=f"{member.mention} has been warned.",
color=discord.Color.yellow()
)
channel_embed.add_field(name="Reason", value=reason, inline=False)
if not dm_sent:
channel_embed.add_field(name="Note", value="Could not send DM to user (DMs disabled)", inline=False)
await ctx.send(embed=channel_embed)
except Exception as e:
raise commands.CommandError(f"Failed to warn user: {str(e)}")
@commands.command(aliases=["o"])
@has_permissions(administrator=True)
async def overview(self, ctx, member: discord.Member):
try:
guild_id_str = str(ctx.guild.id)
user_id_str = str(member.id)
# Create embed
embed = discord.Embed(
title=f"User Overview: {member.display_name}",
description=f"History of admin actions for {member.mention}",
color=discord.Color.blue()
)
# Add user info
embed.add_field(name="User ID", value=member.id, inline=True)
embed.add_field(name="Account Created", value=member.created_at.strftime("%Y-%m-%d"), inline=True)
embed.add_field(name="Joined Server", value=member.joined_at.strftime("%Y-%m-%d") if member.joined_at else "Unknown", inline=True)
# Get warnings count
warnings_count = 0
if guild_id_str in self.warnings and user_id_str in self.warnings[guild_id_str]:
warnings_count = len(self.warnings[guild_id_str][user_id_str])
# Get user actions
action_counts = {"ban": 0, "kick": 0, "mute": 0, "jail": 0, "warn": 0}
recent_actions = []
if guild_id_str in self.user_actions and user_id_str in self.user_actions[guild_id_str]:
actions = self.user_actions[guild_id_str][user_id_str]
# Count actions by type
for action in actions:
action_type = action["action"]
if action_type in action_counts:
action_counts[action_type] += 1
else:
action_counts[action_type] = 1
# Get 5 most recent actions
sorted_actions = sorted(actions, key=lambda x: x["timestamp"], reverse=True)
recent_actions = sorted_actions[:5]
# Set warnings count from warnings file (not from user_actions)
action_counts["warn"] = warnings_count
# Add action counts to embed
action_summary = "\n".join([f"**{action.title()}s:** {count}" for action, count in action_counts.items() if count > 0])
if action_summary:
embed.add_field(name="Action Summary", value=action_summary, inline=False)
else:
embed.add_field(name="Action Summary", value="No actions recorded", inline=False)
# Add recent actions to embed
if recent_actions:
recent_list = []
for action in recent_actions:
action_time = datetime.fromisoformat(action["timestamp"])
time_str = action_time.strftime("%Y-%m-%d %H:%M")
reason = action.get("reason", "No reason provided")
duration = f" ({action['duration']})" if "duration" in action else ""
recent_list.append(f"**{action['action'].title()}**{duration} - {time_str}\n> {reason}")
embed.add_field(name="Recent Actions", value="\n\n".join(recent_list), inline=False)
# Add warnings detail if any
if warnings_count > 0:
warnings = self.warnings[guild_id_str][user_id_str]
sorted_warnings = sorted(warnings, key=lambda x: x["timestamp"], reverse=True)
# Only show up to 5 most recent warnings
warnings_to_show = sorted_warnings[:5]
warnings_list = []
for i, warning in enumerate(warnings_to_show, 1):
warning_time = datetime.fromisoformat(warning["timestamp"])
time_str = warning_time.strftime("%Y-%m-%d %H:%M")
reason = warning.get("reason", "No reason provided")
warnings_list.append(f"**Warning {i}/{warnings_count}** - {time_str}\n> {reason}")
if warnings_count > 5:
warnings_list.append(f"*...and {warnings_count - 5} more warnings*")
embed.add_field(name="Warning History", value="\n\n".join(warnings_list), inline=False)
await ctx.send(embed=embed)
except Exception as e:
raise commands.CommandError(f"Failed to get user overview: {str(e)}")
@warn.error
@overview.error
async def admin_command_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions):
embed = discord.Embed(
title="Permission Denied",
description="You don't have permission to use this command.",
color=discord.Color.red()
)
await ctx.send(embed=embed)
return True
elif isinstance(error, commands.MemberNotFound):
embed = discord.Embed(
title="Error",
description="Member not found.",
color=discord.Color.red()
)
await ctx.send(embed=embed)
return True
elif isinstance(error, commands.CommandError):
embed = discord.Embed(
title="Error",
description=str(error),
color=discord.Color.red()
)
await ctx.send(embed=embed)
return True
return False
# Load nickname history from file
def load_nickname_history(self):
try:
if os.path.exists(self.nickname_file):
with open(self.nickname_file, 'r') as f:
return json.load(f)
else:
# Create empty nickname history file
with open(self.nickname_file, 'w') as f:
json.dump({}, f)
return {}
except Exception as e:
print(f"Error loading nickname history: {e}")
return {}
# Save nickname history to file
def save_nickname_history(self, history):
try:
with open(self.nickname_file, 'w') as f:
json.dump(history, f, indent=2)
return True
except Exception as e:
print(f"Error saving nickname history: {e}")
return False
# Add nickname change to history
async def add_nickname_change(self, guild_id, user_id, old_nick, new_nick):
try:
# Load current history
history = self.load_nickname_history()
# Initialize guild section if not exists
guild_id_str = str(guild_id)
if guild_id_str not in history:
history[guild_id_str] = {}
# Initialize user section if not exists
user_id_str = str(user_id)
if user_id_str not in history[guild_id_str]:
history[guild_id_str][user_id_str] = []
# Add new nickname change with timestamp
history[guild_id_str][user_id_str].append({
"old_nick": old_nick,
"new_nick": new_nick,
"timestamp": datetime.utcnow().isoformat()
})
# Save updated history
self.save_nickname_history(history)
return True
except Exception as e:
print(f"Error adding nickname change: {e}")
return False
# Get previous nickname from history
async def get_previous_nickname(self, guild_id, user_id):
try:
# Load current history
history = self.load_nickname_history()
# Check if we have history for this user in this guild
guild_id_str = str(guild_id)
user_id_str = str(user_id)
if (guild_id_str in history and
user_id_str in history[guild_id_str] and
len(history[guild_id_str][user_id_str]) > 0):
# Get the most recent nickname change
changes = history[guild_id_str][user_id_str]
if changes:
return changes[-1]["old_nick"]
return None
except Exception as e:
print(f"Error getting previous nickname: {e}")
return None
@commands.command()
@has_permissions(administrator=True)
async def nick(self, ctx, member: discord.Member = None, *, new_nickname = None):
# If no member is specified, use the command author
if member is None and new_nickname is None:
raise commands.CommandError("Please provide a nickname.")
# If only one argument is provided, it's the new nickname for the author
if new_nickname is None:
new_nickname = str(member)
member = ctx.author
try:
# Store the old nickname before changing
old_nickname = member.nick or member.name
# Change the nickname
await member.edit(nick=new_nickname)
# Add to nickname history
await self.add_nickname_change(ctx.guild.id, member.id, old_nickname, new_nickname)
embed = discord.Embed(
title="Nickname Changed",
description=f"Changed {member.mention}'s nickname to: **{new_nickname}**",
color=discord.Color.green()
)
await ctx.send(embed=embed)
except discord.Forbidden:
raise commands.CommandError("I don't have permission to change that user's nickname.")
except discord.HTTPException as e:
raise commands.CommandError(f"Failed to change nickname: {str(e)}")
@commands.command()
@has_permissions(administrator=True)
async def nickremove(self, ctx, member: discord.Member = None):
# If no member is specified, use the command author
if member is None:
member = ctx.author
try:
# Store the old nickname before removing
old_nickname = member.nick or member.name
# Remove the nickname by setting it to None
await member.edit(nick=None)
# Add to nickname history
await self.add_nickname_change(ctx.guild.id, member.id, old_nickname, None)
embed = discord.Embed(
title="Nickname Removed",
description=f"Removed {member.mention}'s nickname. They are now displayed as: **{member.name}**",
color=discord.Color.green()
)
await ctx.send(embed=embed)
except discord.Forbidden:
raise commands.CommandError("I don't have permission to change that user's nickname.")
except discord.HTTPException as e:
raise commands.CommandError(f"Failed to remove nickname: {str(e)}")
@commands.command()
@has_permissions(administrator=True)
async def nickrevert(self, ctx, member: discord.Member = None):
# If no member is specified, use the command author
if member is None:
member = ctx.author
try:
# Get the previous nickname
previous_nickname = await self.get_previous_nickname(ctx.guild.id, member.id)
if previous_nickname is None:
raise commands.CommandError(f"No previous nickname found for {member.mention}.")
# Store the current nickname before changing
current_nickname = member.nick or member.name
# Change the nickname to the previous one
await member.edit(nick=previous_nickname)
# Add to nickname history
await self.add_nickname_change(ctx.guild.id, member.id, current_nickname, previous_nickname)
embed = discord.Embed(
title="Nickname Reverted",
description=f"Reverted {member.mention}'s nickname to: **{previous_nickname}**",
color=discord.Color.green()
)
await ctx.send(embed=embed)
except discord.Forbidden:
raise commands.CommandError("I don't have permission to change that user's nickname.")
except discord.HTTPException as e:
raise commands.CommandError(f"Failed to revert nickname: {str(e)}")
@nick.error
@nickremove.error
@nickrevert.error
async def nickname_command_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions):
embed = discord.Embed(
title="Permission Denied",
description="You don't have permission to use this command.",
color=discord.Color.red()
)
await ctx.send(embed=embed)
return True
elif isinstance(error, commands.MemberNotFound):
embed = discord.Embed(
title="Error",
description="Member not found.",
color=discord.Color.red()
)
await ctx.send(embed=embed)
return True
elif isinstance(error, commands.CommandError):
embed = discord.Embed(
title="Error",
description=str(error),
color=discord.Color.red()
)
await ctx.send(embed=embed)
return True
return False
@commands.command()
async def nickme(self, ctx, *, new_nickname=None):
if new_nickname is None:
raise commands.CommandError("Please provide a new nickname.")
try:
# Store the old nickname before changing
old_nickname = ctx.author.nick or ctx.author.name
# Change the nickname
await ctx.author.edit(nick=new_nickname)
# Add to nickname history
await self.add_nickname_change(ctx.guild.id, ctx.author.id, old_nickname, new_nickname)
embed = discord.Embed(
title="Nickname Changed",
description=f"Changed your nickname to: **{new_nickname}**",
color=discord.Color.green()
)
await ctx.send(embed=embed)
except discord.Forbidden:
raise commands.CommandError("I don't have permission to change your nickname.")
except discord.HTTPException as e:
raise commands.CommandError(f"Failed to change nickname: {str(e)}")
@commands.command()
async def nickmeremove(self, ctx):
try:
# Store the old nickname before removing
old_nickname = ctx.author.nick or ctx.author.name
# Remove the nickname by setting it to None
await ctx.author.edit(nick=None)
# Add to nickname history
await self.add_nickname_change(ctx.guild.id, ctx.author.id, old_nickname, None)
embed = discord.Embed(
title="Nickname Removed",
description=f"Removed your nickname. You are now displayed as: **{ctx.author.name}**",
color=discord.Color.green()
)
await ctx.send(embed=embed)
except discord.Forbidden:
raise commands.CommandError("I don't have permission to change your nickname.")
except discord.HTTPException as e:
raise commands.CommandError(f"Failed to remove nickname: {str(e)}")
@commands.command()
async def nickmerevert(self, ctx):
try:
# Get the previous nickname
previous_nickname = await self.get_previous_nickname(ctx.guild.id, ctx.author.id)
if previous_nickname is None:
raise commands.CommandError("No previous nickname found for you.")
# Store the current nickname before changing
current_nickname = ctx.author.nick or ctx.author.name
# Change the nickname to the previous one
await ctx.author.edit(nick=previous_nickname)
# Add to nickname history
await self.add_nickname_change(ctx.guild.id, ctx.author.id, current_nickname, previous_nickname)
embed = discord.Embed(
title="Nickname Reverted",
description=f"Reverted your nickname to: **{previous_nickname}**",
color=discord.Color.green()
)
await ctx.send(embed=embed)
except discord.Forbidden:
raise commands.CommandError("I don't have permission to change your nickname.")
except discord.HTTPException as e:
raise commands.CommandError(f"Failed to revert nickname: {str(e)}")
@nickme.error
@nickmeremove.error
@nickmerevert.error
async def nickme_command_error(self, ctx, error):
if isinstance(error, commands.CommandError):
embed = discord.Embed(
title="Error",
description=str(error),
color=discord.Color.red()
)
await ctx.send(embed=embed)
return True
return False
async def role_save_loop(self):
await self.client.wait_until_ready()
while not self.client.is_closed():
try:
# Save roles for all guilds
for guild in self.client.guilds:
await self.save_roles(guild)
# Update save times
self.last_save_time = datetime.utcnow()
self.next_save_time = self.last_save_time + timedelta(hours=6)
self.save_role_save_info()
# Wait for 6 hours
await asyncio.sleep(6 * 60 * 60) # 6 hours in seconds
except asyncio.CancelledError:
break
except Exception as e:
print(f"Error in role save loop: {e}")
# Wait a bit before retrying if there was an error
await asyncio.sleep(300) # 5 minutes
async def save_roles(self, guild):
try:
# Load existing saved roles if any
saved_roles = {}
if os.path.exists(self.roles_file):
with open(self.roles_file, 'r') as f:
saved_roles = json.load(f)
# Initialize guild section if not exists
if str(guild.id) not in saved_roles:
saved_roles[str(guild.id)] = {}
# Save roles for each member
for member in guild.members:
# Skip bots
if member.bot:
continue
# Save role IDs for the member
role_ids = [role.id for role in member.roles if role.id != guild.default_role.id]
saved_roles[str(guild.id)][str(member.id)] = role_ids
# Save to file
with open(self.roles_file, 'w') as f:
json.dump(saved_roles, f, indent=2)
return True
except Exception as e:
print(f"Error saving roles: {e}")
return False
def load_role_save_info(self):
try:
if os.path.exists(self.roles_info_file):
with open(self.roles_info_file, 'r') as f:
info = json.load(f)
if 'last_save' in info:
self.last_save_time = datetime.fromisoformat(info['last_save'])
if 'next_save' in info:
self.next_save_time = datetime.fromisoformat(info['next_save'])
except Exception as e:
print(f"Error loading role save info: {e}")
# Set default times if loading fails
self.last_save_time = None
self.next_save_time = datetime.utcnow() + timedelta(hours=6)
def save_role_save_info(self):
try:
info = {
'last_save': self.last_save_time.isoformat() if self.last_save_time else None,
'next_save': self.next_save_time.isoformat() if self.next_save_time else None
}
with open(self.roles_info_file, 'w') as f:
json.dump(info, f, indent=2)
except Exception as e:
print(f"Error saving role save info: {e}")
@commands.Cog.listener()
async def on_member_join(self, member):
# Skip bots
if member.bot:
return
try:
# Check if we have saved roles for this member
if not os.path.exists(self.roles_file):
return
with open(self.roles_file, 'r') as f:
saved_roles = json.load(f)
guild_id = str(member.guild.id)
member_id = str(member.id)
# Check if we have roles saved for this member in this guild
if guild_id in saved_roles and member_id in saved_roles[guild_id]:
role_ids = saved_roles[guild_id][member_id]
# Get valid roles that still exist in the server
roles_to_add = []
for role_id in role_ids:
role = member.guild.get_role(int(role_id))
if role and not role.managed: # Skip managed roles (bots, integrations)
roles_to_add.append(role)
# Add roles if any
if roles_to_add:
await member.add_roles(*roles_to_add, reason="Restoring saved roles")
# Log in system channel if available
system_channel = member.guild.system_channel
if system_channel:
role_mentions = [role.mention for role in roles_to_add]
role_list = ", ".join(role_mentions) if role_mentions else "None"
embed = discord.Embed(
title="Roles Restored",
description=f"Restored roles for {member.mention}: {role_list}",
color=discord.Color.green()
)
await system_channel.send(embed=embed)
except Exception as e:
print(f"Error restoring roles: {e}")
@commands.command()
@has_permissions(administrator=True)
async def saveroles(self, ctx, option: str = None):
if option and option.lower() == "info":
# Show save info
if not self.last_save_time:
last_save_str = "Never"
else:
# Format as relative time
time_diff = datetime.utcnow() - self.last_save_time
hours, remainder = divmod(time_diff.seconds, 3600)
minutes, _ = divmod(remainder, 60)
if time_diff.days > 0:
last_save_str = f"{time_diff.days} days, {hours} hours ago"
elif hours > 0:
last_save_str = f"{hours} hours, {minutes} minutes ago"
else:
last_save_str = f"{minutes} minutes ago"
if not self.next_save_time:
next_save_str = "Not scheduled"
else:
# Format as relative time
time_diff = self.next_save_time - datetime.utcnow()
hours, remainder = divmod(time_diff.seconds, 3600)
minutes, _ = divmod(remainder, 60)
if time_diff.days > 0:
next_save_str = f"In {time_diff.days} days, {hours} hours"
elif hours > 0:
next_save_str = f"In {hours} hours, {minutes} minutes"
else:
next_save_str = f"In {minutes} minutes"
embed = discord.Embed(
title="Role Save Information",
description="Status of the automatic role saving system",
color=discord.Color.blue()
)
embed.add_field(name="Last Save", value=last_save_str, inline=False)
embed.add_field(name="Next Save", value=next_save_str, inline=False)
await ctx.send(embed=embed)
else:
# Save roles now
status_msg = await ctx.send(embed=discord.Embed(
title="Saving Roles",
description="Saving roles for all members...",
color=discord.Color.blue()
))
success = await self.save_roles(ctx.guild)
if success:
# Update save times
self.last_save_time = datetime.utcnow()
self.next_save_time = self.last_save_time + timedelta(hours=6)
self.save_role_save_info()
await status_msg.edit(embed=discord.Embed(
title="Roles Saved",
description=f"Successfully saved roles for all members in {ctx.guild.name}",
color=discord.Color.green()
))
else:
await status_msg.edit(embed=discord.Embed(
title="Error",
description="Failed to save roles. Check console for details.",
color=discord.Color.red()
))
@saveroles.error
async def saveroles_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions):
embed = discord.Embed(
title="Permission Denied",
description="You don't have permission to use this command.",
color=discord.Color.red()
)
await ctx.send(embed=embed)
return True
elif isinstance(error, commands.CommandError):
embed = discord.Embed(
title="Error",
description=str(error),
color=discord.Color.red()
)
await ctx.send(embed=embed)
return True
return False
@commands.command()
@has_permissions(administrator=True)
async def ban(self, ctx, member: discord.Member, *, reason=None):
await member.ban(reason=reason)
# Add to user actions
await self.add_user_action(ctx.guild.id, member.id, "ban", reason)
embed = discord.Embed(
title="Ban",
description=f"{member.mention} has been banned.\nReason: {reason or 'No reason provided'}",
color=discord.Color.red()
)
await ctx.send(embed=embed)
@commands.command()
@has_permissions(administrator=True)
async def kick(self, ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
# Add to user actions
await self.add_user_action(ctx.guild.id, member.id, "kick", reason)
embed = discord.Embed(
title="Kick",
description=f"{member.mention} has been kicked.\nReason: {reason or 'No reason provided'}",
color=discord.Color.red()
)
await ctx.send(embed=embed)
@commands.command()
@has_permissions(administrator=True)
async def mute(self, ctx, member: discord.Member, duration: str = "10m", *, reason=None):
muted_role = await self.get_or_create_muted_role(ctx)
if muted_role in member.roles:
raise commands.CommandError(f"{member.mention} is already muted.")
# Add to user actions
await self.add_user_action(ctx.guild.id, member.id, "mute", reason, duration)
await self.apply_mute(ctx, member, muted_role, duration, reason)
async def get_or_create_muted_role(self, ctx):
muted_role = discord.utils.get(ctx.guild.roles, name="Muted")
if not muted_role:
muted_role = await ctx.guild.create_role(name="Muted")
for channel in ctx.guild.channels:
await channel.set_permissions(muted_role, speak=False, send_messages=False)
return muted_role
async def apply_mute(self, ctx, member, muted_role, duration, reason):
await member.add_roles(muted_role)
embed = discord.Embed(
title="Mute",
description=f"{member.mention} has been muted for {duration}.\nReason: {reason or 'No reason provided'}",
color=discord.Color.red()
)
await ctx.send(embed=embed)
asyncio.create_task(self.schedule_unmute(ctx, member, muted_role, duration))
async def schedule_unmute(self, ctx, member, muted_role, duration):
if duration.endswith('s'):
duration_seconds = int(duration[:-1])
elif duration.endswith('m'):
duration_seconds = int(duration[:-1]) * 60
elif duration.endswith('h'):
duration_seconds = int(duration[:-1]) * 3600
elif duration.endswith('d'):
duration_seconds = int(duration[:-1]) * 86400
else:
try:
duration_seconds = int(duration) * 60
except ValueError:
raise commands.CommandError(f"Invalid duration format: {duration}. Use formats like '30s', '10m', '1h', or '1d'.")
await asyncio.sleep(duration_seconds)
try:
member = await ctx.guild.fetch_member(member.id)
except discord.NotFound:
return # Member left the server, no need to unmute
if muted_role in member.roles:
await member.remove_roles(muted_role)
unmute_embed = discord.Embed(
title="Unmute",
description=f"{member.mention} has been automatically unmuted.",
color=discord.Color.green()
)
await ctx.send(embed=unmute_embed)
@commands.command()
@has_permissions(administrator=True)
async def unmute(self, ctx, member: discord.Member):
muted_role = discord.utils.get(ctx.guild.roles, name="Muted")
if muted_role and muted_role in member.roles:
await member.remove_roles(muted_role)
embed = discord.Embed(
title="Unmute",
description=f"{member.mention} has been unmuted.",
color=discord.Color.green()
)
await ctx.send(embed=embed)
else:
raise commands.CommandError(f"{member.mention} is not muted.")
@commands.command()
@has_permissions(administrator=True)
async def addbalance(self, ctx, member: discord.Member, amount: int):
economy_cog = self.client.get_cog("EconomyCog")
if economy_cog:
await economy_cog.add_balance(member.id, amount)
embed = discord.Embed(
title="Balance Added",
description=f"Added {amount} coins to {member.mention}'s balance.",
color=discord.Color.green()