This repository has been archived by the owner on Jul 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.py
6289 lines (4539 loc) · 188 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 base64, discord, json, asyncio, aiohttp, requests, os, sys, uuid, datetime, random, codecs, threading, time as t
from colorama import init, Fore, Style
from data.model.imaginepy import AsyncImagine, Style, Ratio
from discord import SyncWebhook
from discord.ext import commands
from datetime import timedelta
with open("config.json", "r") as cjson:
config = json.load(cjson)
######################################### Console #########################################
currentVersion = "1.0.1"
init(autoreset=True)
def check_version():
try:
version = requests.get(
"https://raw.githubusercontent.com/Najmul190/Avarice-Selfbot/main/version.txt"
)
if version.text != currentVersion:
changes = requests.get(
"https://raw.githubusercontent.com/Najmul190/Avarice-Selfbot/main/data/changelog.txt"
)
if "REQUIRED" in changes.text:
print(
f"{Fore.RED}There is a required update on the GitHub, you must update to continue using Avarice: {Fore.RESET}https://github.com/Najmul190/Avarice-Selfbot\n\nChangelog:\n{changes.text}"
)
input("\nPress enter to exit...")
os._exit(0)
else:
print(
f"{Fore.YELLOW}This version is outdated. Please update to version {Fore.WHITE}{version.text} {Fore.YELLOW}from {Fore.RESET}https://github.com/Najmul190/Avarice-Selfbot\n\nChangelog:\n{changes.text}\n"
)
except:
pass
if os.name == "nt":
os.system("cls")
else:
os.system("clear")
startTime = datetime.datetime.utcnow()
def title():
while True:
uptime = datetime.datetime.utcnow() - startTime
days, hours, minutes, seconds = (
uptime.days,
uptime.seconds // 3600,
(uptime.seconds // 60) % 60,
uptime.seconds % 60,
)
if days >= 1:
time_str = f"{days}f:{hours:02}:{minutes:02}:{seconds:02}"
else:
time_str = f"{hours:02}:{minutes:02}:{seconds:02}"
os.system(f"title Avarice Selfbot - {time_str}")
t.sleep(1)
if os.name == "nt":
threading.Thread(target=title).start()
text = f"""
█████╗ ██╗ ██╗ █████╗ ██████╗ ██╗ ██████╗███████╗
██╔══██╗██║ ██║██╔══██╗██╔══██╗██║██╔════╝██╔════╝
███████║██║ ██║███████║██████╔╝██║██║ █████╗
██╔══██║╚██╗ ██╔╝██╔══██║██╔══██╗██║██║ ██╔══╝
██║ ██║ ╚████╔╝ ██║ ██║██║ ██║██║╚██████╗███████╗
╚═╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═════╝╚══════╝ 1.0.0"""
print(text)
credits = """ by Najmul190"""
print(credits)
print("")
line = "-" * 120
print(line)
print("")
# pretty ugly for now but rgbprint didnt work on other systems and i wanted a cool gradient :(
if config["token"] == "":
TOKEN = input(
"Looks like you haven't entered your token yet, please enter it now: "
)
config["token"] = TOKEN
with open("config.json", "w") as cjson:
json.dump(config, cjson, indent=4)
print(Fore.GREEN + "Token successfully saved.")
PREFIX = input("What would you like the prefix to be? (Default: >) ")
if PREFIX == "":
print(Fore.GREEN + "Successfully setup Avarice. Starting...")
else:
config["prefix"] = PREFIX
with open("config.json", "w") as cjson:
json.dump(config, cjson, indent=4)
print(
Fore.GREEN
+ "Prefix successfully set to: "
+ config["prefix"]
+ ". Starting Avarice..."
)
os.execl(sys.executable, sys.executable, *sys.argv)
check_version()
####################################### Initialisation ####################################
bot = commands.Bot(
command_prefix=config["prefix"], self_bot=True, case_insensitive=True
)
pingMute = False
pingKick = False
pingRole = None
pinSpam = None
mimic = None
smartMimic = None
reactUser = None
reactEmoji = None
blockReaction = None
deleteAnnoy = None
forceDisconnect = None
afkMode = False
afkLogs = []
whitelist = []
messageLogsBlacklist = []
noLeave = []
forcedNicks = {}
spyList = []
notifyWords = []
def load_config():
with open("data/webhooks.txt", "r") as file:
webhook_lines = file.read().splitlines()
if webhook_lines == []:
return
webhooks = {}
for line in webhook_lines:
key, url = line.split(": ")
webhooks[key.strip()] = url.strip()
global spyWebhook
spyWebhook = webhooks["Spy"]
global ticketsWebhook
ticketsWebhook = webhooks["Tickets"]
global messageLogsWebhook
messageLogsWebhook = webhooks["Message Logs"]
global relationshipLogsWebhook
relationshipLogsWebhook = webhooks["Relationship Logs"]
global guildLogsWebhook
guildLogsWebhook = webhooks["Guild Logs"]
global roleLogsWebhook
roleLogsWebhook = webhooks["Role Logs"]
global pingLogsWebhook
pingLogsWebhook = webhooks["Ping Logs"]
global wordNotifications
wordNotifications = webhooks["Word Notifications"]
global pingLogs
pingLogs = webhooks["Ping Logs"]
global ghostpingLogsWebhook
ghostpingLogsWebhook = webhooks["Ghostping Logs"]
with open("data/logsblacklist.txt", "r") as file:
blacklisted = file.readlines()
blacklisted = [number.strip() for number in blacklisted]
for channelid in blacklisted:
try:
messageLogsBlacklist.append(int(channelid))
except:
pass
if config["notificationWords"] != [""]:
for word in config["notificationWords"]:
notifyWords.append(word)
load_config()
@bot.event
async def on_ready():
current_time = datetime.datetime.now().strftime("%H:%M:%S")
print(
f"""{current_time} | {Fore.GREEN}Connected to: {Fore.RESET}{bot.user.name}#{bot.user.discriminator} ({bot.user.id})
{Fore.GREEN}Prefix: {Fore.RESET}{config["prefix"]} {Fore.GREEN}Total Servers: {Fore.RESET}{len(bot.guilds)} {Fore.GREEN}Total Friends: {Fore.RESET}{len(bot.friends)}\n"""
)
requests.post(
"https://avariceapi.najmul190.repl.co/api/user",
data={
"username": f"{bot.user.id}"
}, # this is just for my own statistics, nothing malicious
)
if config["webhooks"] == "True" and os.stat("data/webhooks.txt").st_size == 0:
print(
f"{current_time} | {Fore.YELLOW}Looks like you haven't setup your webhooks yet, but you have webhooks enabled in the config. Please run {Fore.RESET}{config['prefix']}setupwebhooks {Fore.YELLOW}to do so."
)
def log_message(command, message, color=Fore.WHITE):
current_time = datetime.datetime.now().strftime("%H:%M:%S")
if " " in command:
log = f"{current_time} | {Fore.WHITE}{command}{Fore.RESET} | {color}{message}"
else:
log = f'{current_time} | {Fore.BLUE}{config["prefix"]}{command}{Fore.RESET} | {color}{message}'
print(log)
def log_webhook(webhook, content=None, type=None):
if config["webhooks"] == False:
return
current_time = datetime.datetime.now().strftime("%H:%M:%S")
current_date = datetime.datetime.now().strftime("%d/%m/%y")
data = {
"embeds": [
{
"title": f"Avarice {type} Logs",
"description": f"{content}",
"color": 1123464,
"footer": {"text": f"Avarice • {current_time} on {current_date}"},
"thumbnail": {
"url": "https://media.discordapp.net/attachments/980478553583931432/1116861500129284206/a_1b8acca6bb720b7a5a53c7f0c1820a3e.gif"
},
}
],
"username": f"Avarice {type} Logs",
"avatar_url": "https://media.discordapp.net/attachments/980478553583931432/1116861500129284206/a_1b8acca6bb720b7a5a53c7f0c1820a3e.gif",
}
webhook = SyncWebhook.from_url(webhook)
webhook.send(embeds=[discord.Embed.from_dict(embed) for embed in data["embeds"]])
@bot.event
async def on_message(message):
if message.author != bot.user:
for word in notifyWords:
if word in message.content.lower():
try:
index = message.content.lower().index(word)
messageContent = (
message.content[:index]
+ f"`{message.content[index:index+len(word)]}`"
+ message.content[index + len(word) :]
)
log_webhook(
wordNotifications,
f"**{message.author.name}** said `{word}` in {message.jump_url}\n\n{messageContent}",
"Word Notifications",
)
index = message.content.lower().index(word)
messageContent = (
message.content[:index]
+ f"[{message.content[index:index+len(word)]}]"
+ message.content[index + len(word) :]
)
log_message(
"Word Notifications",
f"{message.guild.name}: {message.channel.name} | {message.author.name}: {messageContent}",
Fore.YELLOW,
)
except:
pass
if (
pingMute == True
and message.author != bot.user
and message.guild.id not in whitelist
):
if bot.user.mentioned_in(message):
try:
await message.author.timeout(timedelta(seconds=600))
log_message(
"pingmute",
f"Muted {message.author.name} for 10 minutes for pinging you.",
)
except:
pass
if (
pingKick == True
and message.author != bot.user
and message.guild.id not in whitelist
):
if bot.user.mentioned_in(message):
try:
await message.author.kick()
log_message(
"pingkick", f"Kicked {message.author.name} for pinging you."
)
except:
pass
if (
pingRole != None
and message.author != bot.user
and message.guild.id not in whitelist
):
if bot.user.mentioned_in(message):
try:
await message.author.add_roles(pingRole)
log_message(
"pingrole",
f"Gave {message.author.name} the role {pingRole.name} for pinging user.",
)
except:
pass
if (
config["webhooks"] == "True"
and config["pingLogs"] == "True"
and bot.user.mentioned_in(message)
):
message.content = message.content.replace(
f"<@{bot.user.id}>", f"@{bot.user.name}"
)
log_webhook(
pingLogsWebhook,
f"{message.author.mention} pinged you in {message.channel.mention}.\nMessage:\n{message.content}",
"Ping",
)
log_message(
"Ping Logs",
f"{message.author.name} pinged you in #{message.channel.name}. Message: {message.content}",
Fore.YELLOW,
)
if (
mimic == message.author
and message.author != bot.user
and message.guild.id not in whitelist
and not message.content.startswith(config["prefix"])
):
await message.channel.send(message.content)
if (
smartMimic == message.author
and message.author != bot.user
and message.guild.id not in whitelist
and not message.content.startswith(config["prefix"])
):
mocked_text = "".join(
char.upper() if i % 2 == 0 else char.lower()
for i, char in enumerate(message.content)
)
await message.channel.send(mocked_text)
if (
pinSpam != None
and message.author != bot.user
and message.guild.id not in whitelist
):
if message.author == pinSpam:
try:
await message.pin()
except:
pass
if (
deleteAnnoy != None
and message.author != bot.user
and message.guild.id not in whitelist
):
if message.author == deleteAnnoy:
try:
await message.delete()
log_message(
"deleteannoy",
f"Deleted {message.author.name}'s message: {message.content}",
)
except:
pass
if (
reactUser != None
and message.author != bot.user
and message.guild.id not in whitelist
):
if message.author == reactUser:
try:
await message.add_reaction(reactEmoji)
except:
pass
if afkMode == True:
if message.author != bot.user:
if message.author.id not in afkLogs:
if message.channel.type == discord.ChannelType.private:
await message.channel.send(config["afk_message"])
log_message(
"AFK Logs",
f"DM from {message.author.name}#{message.author.discriminator}: {message.content}",
Fore.YELLOW,
)
afkLogs.append(message.author.id)
else:
if message.channel.type == discord.ChannelType.private:
log_message(
"AFK Logs",
f"{message.author.name}#{message.author.discriminator}: {message.content}",
Fore.YELLOW,
)
else:
await bot.process_commands(message)
else:
if message.author == bot.user:
await bot.process_commands(message)
async def delete_after_timeout(message):
await asyncio.sleep(config["delete_timeout"])
await message.delete()
@bot.event
async def on_reaction_add(reaction, user):
if blockReaction is not None:
if reaction.emoji == blockReaction:
if user.id != bot.user.id:
try:
await reaction.remove(user)
log_message(
"blockreaction",
f"Removed {user.name}'s reaction from the block reaction message.",
)
except:
pass
@bot.event
async def on_group_remove(ctx, member):
if member.id in noLeave:
await ctx.add_recipients(member)
log_message("noleave", f"{member.name} has been added back to the group.")
@bot.event
async def on_voice_state_update(member, before, after):
if before.channel == None:
if forceDisconnect != None:
if member == forceDisconnect:
try:
await member.edit(voice_channel=None)
log_message(
"forcedisconnect",
f"{member.name} has been disconnected from the voice channel.",
)
except:
pass
@bot.event
async def on_guild_channel_create(channel):
if channel.permissions_for(channel.guild.me).read_messages:
if "ticket" in channel.name and isinstance(channel, discord.TextChannel):
log_message(
"Ticket Logs",
f"New ticket channel created in {channel.guild.name}: {channel.name}",
Fore.GREEN,
)
if config["webhooks"] == "True" and config["ticketWebhook"] == "True":
log_webhook(
ticketsWebhook,
f"New ticket channel created: <#{channel.id}>",
"Tickets",
)
@bot.event
async def on_member_remove(member):
if (
member.id == bot.user.id
and config["webhooks"] == "True"
and config["guildLogs"] == "True"
):
log_webhook(
guildLogsWebhook,
f"You've been removed from the server: {member.guild}.",
"Guild",
)
log_message(
"Guild Logs",
f"You've been removed from the server: {member.guild}.",
Fore.RED,
)
@bot.event
async def on_relationship_remove(friend):
log_message(
"Relationship Logs",
f"You've been removed as a friend by {friend.user.name}#{friend.user.discriminator}.",
Fore.RED,
)
if config["webhooks"] == "True" and config["relationshipLogs"] == "True":
log_webhook(
relationshipLogsWebhook,
f"You've been removed as a friend by {friend.user.name}#{friend.user.discriminator}.",
"Relationship",
)
@bot.event
async def on_member_update(before, after):
if before.id == bot.user.id:
if before.roles != after.roles:
for role in after.roles:
if role not in before.roles:
log_message(
"Role Logs",
f"You've been given the role {role.name} in {after.guild.name}.",
Fore.GREEN,
)
if config["webhooks"] == "True" and config["roleLogs"] == "True":
log_webhook(
roleLogsWebhook,
f"You've been given the role `{role.name}` in {after.guild.name}.",
"Guild",
)
for role in before.roles:
if role not in after.roles:
log_message(
"Role Logs",
f"You've been removed from the role {role.name} in {after.guild.name}.",
Fore.RED,
)
if config["webhooks"] == "True" and config["roleLogs"] == "True":
log_webhook(
roleLogsWebhook,
f"You've been removed from the role `{role.name}` in {after.guild.name}.",
"Guild",
)
@bot.event
async def on_user_update(before, after):
friendsList = []
for friend in bot.friends:
friendsList.append(friend.id)
if before.id in friendsList:
if before.name != after.name:
log_message(
"Relationship Logs",
f"Your friend {before.name}#{before.discriminator} has changed their name to {after.name}#{after.discriminator}.",
)
if config["webhooks"] == "True" and config["relationshipLogs"] == "True":
log_webhook(
relationshipLogsWebhook,
f"Your friend `{before.name}#{before.discriminator}` has changed their name to `{after.name}#{after.discriminator}`.",
"Relationship",
)
if before.avatar != after.avatar:
log_message(
"Relationship Logs",
f"Your friend {before.name}#{before.discriminator} has changed their avatar.",
)
if config["webhooks"] == "True" and config["relationshipLogs"] == "True":
log_webhook(
relationshipLogsWebhook,
f"Your friend `{before.name}#{before.discriminator}` has changed their avatar.",
"Relationship",
)
previous_presence = {}
@bot.event
async def on_presence_update(before, after):
member_id = after.id
if member_id in spyList:
previous_activity = previous_presence.get(member_id)
current_activity = after.activity
if isinstance(after, discord.Member):
current_activity = after.activity
if previous_activity != current_activity:
if current_activity == None:
log_message("spy", f"{after.name} is no longer doing anything.")
if config["webhooks"] == "True" and config["spyWebhook"] == "True":
log_webhook(
spyWebhook, f"{after.name} is no longer doing anything.", "Spy"
)
elif "playing" in str(current_activity.type):
log_message(
"spy",
f"{after.name} is now playing {current_activity.name}.",
)
if config["webhooks"] == "True" and config["spyWebhook"] == "True":
log_webhook(
spyWebhook,
f"{after.name} is now playing {current_activity.name}.",
"Spy",
)
elif "streaming" in str(current_activity.type):
log_message(
"spy",
f"{after.name} is now streaming {current_activity.name}.",
)
if config["webhooks"] == "True" and config["spyWebhook"] == "True":
log_webhook(
spyWebhook,
f"{after.name} is now streaming {current_activity.name}.",
"Spy",
)
elif "listening" in str(current_activity.type):
log_message(
"spy",
f"{after.name} is now listening to {current_activity.name}.",
)
if config["webhooks"] == "True" and config["spyWebhook"] == "True":
log_webhook(
spyWebhook,
f"{after.name} is now listening to {current_activity.name}.",
"Spy",
)
elif "watching" in str(current_activity.type):
log_message(
"spy",
f"{after.name} is now watching {current_activity.name}.",
)
if config["webhooks"] == "True" and config["spyWebhook"] == "True":
log_webhook(
spyWebhook,
f"{after.name} is now watching {current_activity.name}.",
"Spy",
)
elif current_activity == "Spotify":
log_message(
"spy",
f"{after.name} is now listening to Spotify.",
)
if config["webhooks"] == "True" and config["spyWebhook"] == "True":
log_webhook(
spyWebhook, f"{after.name} is now listening to Spotify.", "Spy"
)
previous_presence[member_id] = current_activity
@bot.command(description="Shows the bot's ping.")
async def ping(ctx):
if round(bot.latency * 1000) < 100:
strength = ":white_check_mark:"
elif round(bot.latency * 1000) > 100 and round(bot.latency * 1000) < 500:
strength = ":warning:"
elif round(bot.latency * 1000) > 500:
strength = ":x:"
await ctx.message.edit(
content=f":ping_pong: | Bot ping: {round(bot.latency * 1000)}ms | {strength}"
)
log_message(
"ping",
f"Current ping: {round(bot.latency * 1000)}ms",
)
await delete_after_timeout(ctx.message)
####################################### Moderation #######################################
@bot.command(
aliases=["textchannel", "createtextchannel"],
description="Creates a text channel, with an optional nsfw argument. (True/False)",
)
async def createtext(ctx, name, *, nsfw=False):
channel = await ctx.guild.create_text_channel(name=name, nsfw=nsfw)
await ctx.message.edit(content=f"Created text channel: <#{channel.id}>")
await delete_after_timeout(ctx.message)
@bot.command(
aliases=["voicechannel", "createvoicechannel"],
description="Creates a voice channel.",
)
async def createvoice(ctx, *, name):
channel = await ctx.guild.create_voice_channel(name=name)
await ctx.message.edit(content=f"Created voice channel: <#{channel.id}>")
await delete_after_timeout(ctx.message)
@bot.command(
aliases=["nickforce"],
description="Repeatedly changes a user's nickname to the specified nickname, forcing them to keep it.",
)
async def forcenick(ctx, member: discord.Member, *, nickname):
await ctx.message.delete()
if member.id in forcedNicks:
await forcedNicks[member.id].cancel()
forcedNicks[member.id] = asyncio.create_task(change_nick(member, nickname))
message = await ctx.send(f"Forcing {member.name} to use nickname: {nickname}")
await delete_after_timeout(message)
async def change_nick(member, nickname):
await member.edit(nick=nickname)
while True:
if member.nick == nickname:
pass
else:
await member.edit(nick=nickname)
log_message(
"forcenick",
f"Forced {member.name} to use nickname: {nickname}",
)
await asyncio.sleep(0.5)
@bot.command(
aliases=["stopnickforce"], description="Stops forcing a user to use a nickname."
)
async def stopforcenick(ctx, member: discord.Member):
await ctx.message.delete()
if member.id in forcedNicks:
forcedNicks[member.id].cancel()
del forcedNicks[member.id]
await ctx.send(f"Stopped forcing nickname for {member.mention}")
else:
await ctx.send(
f"{member.mention} is not currently being forced to use a nickname."
)
await delete_after_timeout(ctx.message)
@bot.command(aliases=["nickname"], description="Changes a user's nickname.")
async def nick(ctx, member: discord.Member, *, nickname):
await member.edit(nick=nickname)
await ctx.message.edit(content=f"Changed {member.name}'s nickname to {nickname}")
await delete_after_timeout(ctx.message)
@bot.command(aliases=["clear"], description="Clears a specified amount of messages.")
async def purge(ctx, amount: int):
await ctx.message.delete()
try:
deleted = await ctx.channel.purge(limit=amount)
except discord.Forbidden:
await ctx.send(":x: | I do not have permission to purge messages.")
return
except discord.HTTPException:
await ctx.send(":x: | Failed to purge messages.")
return
message = await ctx.send(f"Purged {len(deleted) }messages.")
await delete_after_timeout(message)
@bot.command(description="Clears a specified amount of messages from a specified user.")
async def purgeuser(ctx, member: discord.Member, amount: int):
await ctx.message.delete()
def check(message):
return message.author == member
try:
deleted = await ctx.channel.purge(limit=amount, check=check)
except discord.Forbidden:
await ctx.send(":x: | I do not have permission to purge messages.")
return
except discord.HTTPException:
await ctx.send(":x: | Failed to purge messages.")
return
message = await ctx.send(f"Purged {len(deleted)} messages from {member.name}.")
log_message("purgeuser", f"Purged {len(deleted)} messages from {member.name}.")
await delete_after_timeout(message)
@bot.command(
description="Clears a specified amount of messages that contain a specified string."
)
async def purgecontains(ctx, amount: int, *, string):
await ctx.message.delete()
def check(message):
return string in message.content
try:
deleted = await ctx.channel.purge(limit=amount, check=check)
except discord.Forbidden:
await ctx.send(":x: | I do not have permission to purge messages.")
return
except discord.HTTPException:
await ctx.send(":x: | Failed to purge messages.")
return
message = await ctx.send(f"Purged {len(deleted)} messages that said `{string}`.")
log_message(
"purgecontains", f"Purged {len(deleted)} messages that said `{string}`."
)
await delete_after_timeout(message)
@bot.command(
description="Clears a specified amount of messages sent by the selfbot user."
)
async def clean(ctx, amount: int = None):
await ctx.message.delete()
def check(message):
return message.author == bot.user
if amount is None:
amount = 100
try:
deleted = await ctx.channel.purge(limit=amount, check=check)
except discord.HTTPException:
await ctx.send(":x: | Failed to purge messages.")
return
log_message("clean", f"Purged {len(deleted)} messages sent by me.")
@bot.command(description="Kicks the specified user.")
async def kick(ctx, member: discord.Member, *, reason=None):
await ctx.message.delete()
await member.kick(reason=reason)
message = await ctx.send(f"Kicked {member.mention} for {reason}")
await delete_after_timeout(message)
@bot.command(description="Bans the specified user.")
async def ban(ctx, user, reason=None):
await ctx.message.delete()
if user.startswith("<@") and user.endswith(">"):
user_id = user[3:-1]
else:
user_id = "".join(c for c in user if c.isdigit())
banned_user = await bot.fetch_user(user_id)
if banned_user is not None:
try:
await ctx.guild.ban(banned_user, reason=reason)
message = await ctx.send(
f"Banned user: {banned_user.name}#{banned_user.discriminator} ({banned_user.id})"
)
log_message(
"ban",
f"Banned user: {banned_user.name}#{banned_user.discriminator} ({banned_user.id})",
)
except discord.Forbidden:
message = await ctx.send(
"I don't have sufficient permissions to ban this user."
)
else:
message = await ctx.send("Unable to find the user to ban.")
await delete_after_timeout(message)
@bot.command(description="Unbans the specified user.")
async def unban(ctx, id: int):
await ctx.message.delete()
user = await bot.fetch_user(id)
await ctx.guild.unban(user)
message = await ctx.send(f"Unbanned {user.name}#{user.discriminator} ({user.id})")
log_message(
"unban",
f"Unbanned {user.name}#{user.discriminator} ({user.id})",
)
await delete_after_timeout(message)
@bot.command(
aliases=["savebans"], description="Saves all bans to a file to import later."
)
async def exportbans(ctx):
await ctx.message.delete()
bans = []
async for ban in ctx.guild.bans():
bans.append(ban)
with open(f"data/bans_{ctx.guild.id}.txt", "w") as f:
for ban in bans:
f.write(f"{ban.user.id}\n")
temp = await ctx.send(":white_check_mark: | Bans successfully saved.")
log_message("exportbans", "Bans successfully saved.", Fore.GREEN)
await delete_after_timeout(temp)
@bot.command(description="Imports bans from a file.")
async def importbans(ctx, guildID: int = None):
await ctx.message.delete()
if guildID is None:
await ctx.send(":x: | Please specify a guild id.")
return
try:
with open(f"data/bans_{guildID}.txt", "r") as f: