-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.py
987 lines (925 loc) · 46 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
Version = '3.0.2'
import os
import ffmpeg
import math
import discord
import aiohttp
import asyncio
import subprocess
import json
from requests import options
import youtube_dl
from youtube_search import YoutubeSearch
from discord_together import DiscordTogether
from dotenv import load_dotenv
from discord.ext import commands
from discord import Attachment, app_commands
import os
import datetime
from discord.ext.commands import Greedy
import typing
from discord.ext.commands import Context
import platform
import socket
import psutil
import cpuinfo
async def checkurl(url: str):
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
return resp.status == 200
except:
return False
if not os.path.exists('.env'):
x = input('What is your token?\n')
with open('.env', 'w') as f:
f.write('token = ' + x)
load_dotenv()
token = os.environ['token']
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
intents.reactions = True
bot = commands.Bot(command_prefix = '$',intents=intents, activity=discord.Game(name='Elden Ring'))
if not os.path.isdir('./Files'):
os.mkdir('./Files')
@bot.event
async def on_member_join(member):
with open(f'./Files/{member.guild.id}.json', 'r') as f:
data = json.load(f)
if data['xp'] == True:
if member.id not in data['xp']:
data['xp'][member.id] = 0
with open(f'./Files/{member.guild.id}.json', 'w') as f:
json.dump(data, f)
@bot.event
async def on_ready():
bot.togetherControl = await DiscordTogether(token)
for a in bot.guilds:
if not os.path.exists(f'./Files/{a.id}.json'):
with open(f'./Files/{a.id}.json', 'w') as f:
x = {"MuteRole":False,"xp":False}
json.dump(x, f)
for guild in bot.guilds:
bot.tree.copy_global_to(guild=guild)
await bot.tree.sync(guild=guild)
with open(f'./Files/{guild.id}.json', 'r') as f:
try:
x = json.load(f)
except:
x = {"MuteRole":False,"xp":False,"bannedwords":False}
with open(f'./Files/{guild.id}.json', 'w') as f:
json.dump(x, f)
if 'MuteRole' not in x:
x['MuteRole'] = False
with open(f'./Files/{guild.id}.json', 'w') as f:
json.dump(x, f)
if 'xp' not in x:
x['xp'] = False
with open(f'./Files/{guild.id}.json', 'w') as f:
json.dump(x, f)
if 'bannedwords' not in x:
x['bannedwords'] = False
with open(f'./Files/{guild.id}.json', 'w') as f:
json.dump(x, f)
if 'logchannel' not in x:
x['logchannel'] = False
with open(f'./Files/{guild.id}.json', 'w') as f:
json.dump(x, f)
if x['xp'] != False:
if len(guild.members) != len(x['xp']):
for member in guild.members:
if member.id not in x['xp']:
x['xp'][member.id] = 0
with open(f'./Files/{guild.id}.json', 'w') as f:
json.dump(x, f)
bot.starttime = datetime.datetime.now()
bot.musicqueue = {}
for guild in bot.guilds:
bot.musicqueue[guild.id] = []
print(f'{bot.user} has connected to Discord!')
@bot.command()
@commands.is_owner()
async def sync(ctx: Context, guilds: Greedy[discord.Object], spec: typing.Optional[typing.Literal["~"]] = None) -> None:
if not guilds:
if spec == "~":
bot.tree.copy_global_to(guild=ctx.guild)
fmt = await bot.tree.sync(guild=ctx.guild)
else:
fmt = await bot.tree.sync()
await ctx.send(
f"Synced {len(fmt)} commands {'globally' if spec is None else 'to the current guild.'}"
)
return
assert guilds is not None
fmt = 0
for guild in guilds:
try:
await bot.tree.sync(guild=guild)
except discord.HTTPException:
pass
else:
fmt += 1
await ctx.send(f"Synced the tree to {fmt}/{len(guilds)} guilds.")@commands.is_owner()
@discord.app_commands.checks.has_permissions(administrator=True)
@app_commands.command(name='mute', description='Mutes a user.')
async def mute(interaction: discord.Interaction, member: discord.Member, reason: str):
if member == bot.user:
await interaction.send('No.')
return
mute = ''
with open(f'./Files/{interaction.guild.id}.json', 'r') as f:
x = json.load(f)
if x['MuteRole'] == False:
await interaction.response.send_message(f'No mute role set.')
else:
mute = discord.utils.get(interaction.guild.roles, id=x['MuteRole'])
if mute not in member.roles:
try:
await member.add_roles(mute)
await interaction.response.send_message(f'{member.mention} has been muted for {reason}.')
except discord.Forbidden:
await interaction.response.send_message(f'I do not have permission to mute {member.mention}.')
else:
await interaction.response.send_message(f'{member.mention} has already been muted.')
@mute.autocomplete('reason')
async def mute_autocomplete(
interaction: discord.Interaction,
current: str,
) -> typing.List[app_commands.Choice[str]]:
mutes = ['repeated rule violations', 'spamming', 'advertising', 'harassment', 'threatening', 'insulting', 'flooding', 'other']
return [
app_commands.Choice(name=mute, value=mute)
for mute in mutes if current.lower() in mute.lower()
]
bot.tree.add_command(mute)
@mute.error
async def mute_error(interaction: discord.Interaction, error: Exception):
with open(f'./Files/{interaction.guild.id}.json', 'r') as f:
x = json.load(f)
mute = discord.utils.get(interaction.guild.roles, id=x['MuteRole'])
if mute == None:
await interaction.response.send_message(f'Mute role invalid.', ephemeral=True)
else:
await interaction.response.send_message('admin privileges are required to use this command.', ephemeral=True)
purge = discord.app_commands.Group(name='purge', description='Purges messages.')
@discord.app_commands.checks.has_permissions(administrator=True)
@purge.command(name='channel', description='Purges messages from a channel.')
async def purge_channel(interaction: discord.Interaction, channel: discord.TextChannel = None, amount: int = 0,):
if channel is None:
channel = interaction.channel
if amount == 0:
view=Buttons2()
await interaction.response.send_message('This will purge all messages, are you sure?',view=view,ephemeral=True)
time = 0
while view.show() is None:
time += 1
if time == 200:
await interaction.edit_original_message(content='Purge cancelled.',view=None)
return
await asyncio.sleep(.1)
if view.show() == False:
await interaction.edit_original_message(content='Purge cancelled.',view=None)
return
await channel.purge()
if channel == interaction.channel:
await interaction.followup.send(f'Purged all messages from channel {channel}.',ephemeral=True)
else:
await interaction.edit_original_message(content=f'Purged all messages from channel {channel}.',view=None)
else:
await interaction.channel.purge(limit=amount)
await interaction.response.send_message(f'Purged {amount} messages in {channel}',ephemeral=True)
@purge_channel.error
async def purge_channel_error(interaction: discord.Interaction, error: Exception):
await interaction.response.send_message('admin privileges are required to use this command.',ephemeral=True)
@discord.app_commands.checks.has_permissions(administrator=True)
@purge.command(name='user', description='Purges messages from a user.')
async def purge_user(interaction: discord.Interaction, user: discord.Member, amount: int = 0):
if user == bot.user:
await interaction.response.send_message('No.',ephemeral=True)
return
if amount == 0:
view=Buttons2()
await interaction.response.send_message(f'This will purge all messages from {user.mention}, are you sure?',view=view,ephemeral=True)
time = 0
while view.show() is None:
time += 1
if time == 300:
await interaction.edit_original_message(content='Purge cancelled.',view=None)
return
await asyncio.sleep(.1)
if view.show() == False:
await interaction.edit_original_message(content='Cancelled.',view=None)
return
await interaction.channel.purge(check=lambda m: m.author == user)
await interaction.edit_original_message(content=f'Purged all messages from {user.mention}.',view=None)
else:
await interaction.channel.purge(check=lambda m: m.author == user, limit=amount)
await interaction.response.send_message(f'Purged {amount} messages from {user.mention}',ephemeral=True)
@purge_user.error
async def purge_user_error(interaction: discord.Interaction, error: Exception):
await interaction.response.send_message('admin privileges are required to use this command.',ephemeral=True)
bot.tree.add_command(purge)
@discord.app_commands.checks.has_permissions(administrator=True)
@app_commands.command(name='unmute', description='unmutes a user.')
async def unmute(interaction: discord.Interaction, member: discord.Member):
mute = ''
with open(f'./Files/{interaction.guild.id}.json', 'r') as f:
x = json.load(f)
if x['MuteRole'] == False:
await interaction.response.send_message(f'No mute role set.')
else:
try:
mute = discord.utils.get(interaction.guild.roles, id=x['MuteRole'])
except:
await interaction.response.send_message('Mute role invalid.')
if mute in member.roles:
try:
await member.remove_roles(mute)
await interaction.response.send_message(f'{member.mention} has been unmuted.')
except discord.Forbidden:
await interaction.response.send_message(f'I do not have permission to unmute {member.mention}.')
else:
await interaction.response.send_message(f'{member.mention} is not muted.')
bot.tree.add_command(unmute)
@unmute.error
async def unmute_error(interaction: discord.Interaction, error: Exception):
with open(f'./Files/{interaction.guild.id}.json', 'r') as f:
x = json.load(f)
mute = discord.utils.get(interaction.guild.roles, id=x['MuteRole'])
if mute == None:
await interaction.response.send_message(f'Mute role invalid.', ephemeral=True)
else:
await interaction.response.send_message('admin privileges are required to use this command.', ephemeral=True)
@discord.app_commands.checks.has_permissions(administrator=True)
@app_commands.command(name='createmuterole', description='creates the mute role.')
async def createmuterole(interaction: discord.Interaction, role: str):
role = await interaction.guild.create_role(name=role)
await interaction.response.send_message(f'Creating MuteRole {role.mention}.')
for channel in interaction.guild.channels:
await channel.set_permissions(
role,
send_messages=False,
add_reactions=False,
speak=False,
)
with open(f'./Files/{interaction.guild.id}.json', 'r') as f:
x = json.load(f)
x['MuteRole'] = role.id
with open(f'./Files/{interaction.guild.id}.json', 'w') as f:
json.dump(x, f)
await interaction.edit_original_message(content=f'Mute role created and set to {role.mention}.')
@createmuterole.error
async def setmuterole_error(interaction: discord.Interaction, error: Exception):
await interaction.response.send_message('admin privilages are required to use this command.', ephemeral=True)
bot.tree.add_command(createmuterole)
@app_commands.command(name='uptime', description='check how long the bot has been online.')
async def uptime(interaction: discord.Interaction):
time = datetime.datetime.now() - bot.starttime
p = str(time).split('.')[0].split(':')
k = int(p[0]) if ',' not in str(p[0]) else int(p[0].split(',')[1])
m = False if ',' not in str(p[0]) else str(p[0].split(',')[0]).split(' ')[0]
x = f'''{f"{str(int(p[2]))} {'Seconds' if int(p[2]) > 1 else 'Second'}" if int(p[2]) > 0 else ''}'''
y = f'''{f"{str(int(p[1]))} {'Minutes' if int(p[1]) > 1 else 'Minute'}{', ' if int(p[2]) > 0 else ''}" if int(p[1]) > 0 else ""}'''
z = f'''{f"{str(int(k))} {'Hours' if int(k) > 1 else 'Hour'}{', ' if int(p[1]) > 0 or int(p[2]) > 0 else ''}" if int(k) != 0 else ""}'''
l = f'''{f'{m} {"Days" if int(m) > 1 else "Day"}{", " if int(k) > 0 or int(p[1]) > 0 or int(p[2]) > 0 else ""}' if m != False else ''}'''
await interaction.response.send_message('Uptime:\n' + l + z + y + x, ephemeral=True)
bot.tree.add_command(uptime)
@discord.app_commands.checks.has_permissions(administrator=True)
@app_commands.command(name='setmuterole', description='Sets the mute role.')
async def setmuterole(interaction: discord.Interaction, role: discord.Role):
with open(f'./Files/{interaction.guild.id}.json', 'r') as f:
x = json.load(f)
x['MuteRole'] = role.id
with open(f'./Files/{interaction.guild.id}.json', 'w') as f:
json.dump(x, f)
await interaction.response.send_message(f'Mute Role has been set to {role.name}')
bot.tree.add_command(setmuterole)
@setmuterole.error
async def setmuterole_error(interaction: discord.Interaction, error: Exception):
await interaction.response.send_message('admin privilages are required to use this command.', ephemeral=True)
@app_commands.command(name='ping', description='Gets the bots ping')
async def ping(interaction: discord.Interaction):
await interaction.response.send_message(f'Bots ping is {round(bot.latency, 2)}ms', ephemeral=True)
bot.tree.add_command(ping)
@app_commands.command(name='version', description='Bot version info.')
async def ver(interaction: discord.Interaction):
await interaction.response.send_message(f'I am {bot.user.name} version {Version}.\nMy source code can be found at {f"https://github.com/jumpers775/OneBot/releases/tag/{Version}" if await checkurl(f"https://github.com/jumpers775/OneBot/releases/tag/{Version}") else "https://github.com/jumpers775/OneBot"}', ephemeral=True, suppress_embeds=True)
bot.tree.add_command(ver)
@app_commands.command(name='invite', description='Invite link.')
async def invite(interaction: discord.Interaction):
await interaction.response.send_message(f'Invite link: https://discord.com/oauth2/authorize?client_id={bot.application_id}&permissions=8&scope=bot%20applications.commands', ephemeral=True)
bot.tree.add_command(invite)
# MUSIC STUFF
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, volume=0.5):
super().__init__(source, volume)
self.data = data
self.title = data.get('title')
self.url = data.get('url')
@classmethod
async def from_url(cls, url, *, loop=None, stream=False):
youtube_dl.utils.bug_reports_message = lambda: ''
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0'
}
ffmpeg_options = {
'options': '-vn',
}
ytdl = youtube_dl.YoutubeDL(ydl_opts)
loop = loop or asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
if 'entries' in data:
# take first item from a playlist
data = data['entries'][0]
filename = data['url'] if stream else ytdl.prepare_filename(data)
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
class SelectSong(discord.ui.Select):
def __init__(self,options: dict):
self.optionz = options['results']
super().__init__(placeholder="Select an option",max_values=1,min_values=1,options=options['options'])
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message(content=f"Now Playing {self.values[0]}!",ephemeral=True)
url = 'https://youtube.com'
for x in self.optionz:
if x['title'] == self.values[0]:
url += x['url_suffix']
bot.musicqueue[interaction.guild.id].append(url)
if not bot.musicqueue[interaction.guild.id][0] == url:
return
b = discord.utils.get(bot.voice_clients, guild=interaction.guild)
if b != None:
await interaction.guild.voice_client.disconnect()
try:
vc = await interaction.user.voice.channel.connect()
except:
await interaction.response.send_message(f"{interaction.message.author.mention}, you not in a voice channel.", ephemeral=True)
return
while not bot.musicqueue[interaction.guild.id] == []:
url = bot.musicqueue[interaction.guild.id][0]
audio = await YTDLSource.from_url(url=url, loop=bot.loop, stream=True)
try:
vc.play(audio)
except:
try:
vc.play(audio)
except:
pass
while vc.is_playing():
await asyncio.sleep(.1)
bot.musicqueue[interaction.guild.id].pop(0)
vc.stop()
await vc.disconnect()
class SelectView(discord.ui.View):
def __init__(self, *, timeout = 180, options: dict):
super().__init__(timeout=timeout)
self.add_item(SelectSong(options=options))
music = discord.app_commands.Group(name='music', description='music related commands.')
@music.command(name='play', description='plays a song from youtube.')
async def play(interaction: discord.Interaction, song: str):
message = await interaction.response.send_message('Searching...', ephemeral=True)
f = False
results = YoutubeSearch(song, max_results=10).to_json()
results = json.loads(results)
results = results['videos']
options = []
for i in results:
options.append(discord.SelectOption(label=i['title'], description=f'By {i["channel"]}', emoji='🎧'))
options = {'options': options, 'results': results}
view = SelectView(options=options)
try:
await interaction.edit_original_message(content='Select a song to play:',view=view)
except:
await interaction.edit_original_message(content='An error occured. Please try again.')
#stop playing audio
@music.command(name='stop', description='stops the audio.')
async def stop(interaction: discord.Interaction):
bot.musicqueue[interaction.guild.id] = []
b = discord.utils.get(bot.voice_clients, guild=interaction.guild)
if b != None:
await interaction.guild.voice_client.disconnect()
await interaction.response.send_message("Stopped playing audio.", ephemeral=True)
@music.command(name='showqueue', description='shows the current queue.')
async def showqueue(interaction: discord.Interaction):
if bot.musicqueue[interaction.guild.id] == []:
await interaction.response.send_message("No songs in queue.", ephemeral=True)
return
songs = []
youtube_dl_opts = {}
for a in bot.musicqueue[interaction.guild.id]:
with youtube_dl.YoutubeDL(youtube_dl_opts) as ydl:
info_dict = ydl.extract_info(a, download=False)
video_title = info_dict.get('title', None)
songs.append(f'{video_title}\n')
await interaction.response.send_message(f"Songs in queue: {songs}", ephemeral=True)
bot.tree.add_command(music)
class Buttons(discord.ui.View):
def __init__(self, *, timeout=180, num: str):
self.num = num
super().__init__(timeout=timeout)
@discord.ui.button(label="Yes",style=discord.ButtonStyle.green)
async def blurple_button(self,button:discord.ui.Button,interaction:discord.Interaction):
bot.musicqueue[interaction.guild.id].remove(self.num)
await interaction.response.edit_message(content=f"Removed {self.num} from queue.")
@discord.ui.button(label="No",style=discord.ButtonStyle.red)
async def gray_button(self,button:discord.ui.Button,interaction:discord.Interaction):
await interaction.response.edit_message(content='Cancelled.',)
@music.command(name='delqueue', description='removes a song from the queue.')
async def delqueue(interaction: discord.Interaction, song: str):
if bot.musicqueue[interaction.guild.id] == []:
await interaction.response.send_message("No songs in queue.", ephemeral=True)
return
songs = []
for a in bot.musicqueue[interaction.guild.id]:
if song in a:
songs.append(a)
view = Buttons(num=songs[0])
interaction.response.send_message(f"would you ike to remove {songs[0]} from the queue?", view=view)
# xp stuff
@bot.listen('on_message')
async def on_message(message):
if message.author.bot:
await bot.process_commands(message)
return
if message.guild is None:
await bot.process_commands(message)
return
with open(f'Files/{message.guild.id}.json', 'r') as f:
data = json.load(f)
if data['xp'] != False:
data['xp'][str(message.author.id)] += 1
p = int(data['xp'][str(message.author.id)])/100
if p.is_integer():
await message.add_reaction('🎉')
#get role for level p
try:
role = discord.utils.get(message.guild.roles, name=f'level {p}')
except:
role = await message.guild.create_role(name=f'level {p}')
await message.author.add_role(role)
await message.author.remove_role(discord.utils.get(message.guild.roles, name=f'level {p-1}'))
with open(f'Files/{message.guild.id}.json', 'w') as f:
json.dump(data, f)
try:
z = open(f'Files/{message.guild.id}.json', 'r')
data2 = json.load(z)
if data == data2:
await bot.process_commands(message)
return
except:
os.remove(f'Files/{message.guild.id}.json')
json.dump(data, f)
await bot.process_commands(message)
return
else:
await bot.process_commands(message)
return
@app_commands.command(name='stats', description='gets a users stats.')
async def stats(interaction: discord.Interaction, user: discord.Member = None):
if user == None:
user = interaction.user
embed = discord.Embed(title=f'{user.name} Stats', color=0x00ff00)
with open(f'Files/{interaction.guild.id}.json', 'r') as f:
data = json.load(f)
if data['xp'] != False:
if user.id != bot.user.id:
embed.add_field(name='XP', value=data['xp'][str(user.id)])
else:
embed.add_field(name='XP', value='∞')
else:
embed.add_field(name='XP', value=0)
await interaction.response.send_message(embed=embed)
bot.tree.add_command(stats)
xp = discord.app_commands.Group(name='xp', description='xp related commands.')
@discord.app_commands.checks.has_permissions(administrator=True)
@xp.command(name='disable', description='disables the xp system.')
async def disable(interaction: discord.Interaction):
with open(f'Files/{interaction.guild.id}.json', 'r') as f:
data = json.load(f)
if data['xp'] != False:
await interaction.response.send_message('Disabling XP...')
data['xp'] = False
with open(f'Files/{interaction.guild.id}.json', 'w') as f:
json.dump(data, f)
await interaction.edit_original_message(content='XP is now disabled!')
else:
await interaction.response.send_message('XP is already disabled!')
@disable.error
async def disable_error(interaction: discord.Interaction, error: Exception):
await interaction.response.send_message(f'{interaction.message.author.mention}, You are not an admin on {interaction.guild.name}.')
@discord.app_commands.checks.has_permissions(administrator=True)
@xp.command(name='enable', description='enables the xp system.')
async def enable(interaction: discord.Interaction):
with open(f'Files/{interaction.guild.id}.json', 'r') as f:
data = json.load(f)
if data['xp'] != False:
await interaction.response.send_message('XP is already enabled!')
return
await interaction.response.send_message('Enabling XP...\n this may take a while on some servers.')
data['xp'] = {}
for user in interaction.guild.members:
data['xp'][user.id] = 0
with open(f'Files/{interaction.guild.id}.json', 'w') as f:
json.dump(data, f)
await interaction.edit_original_message(content='XP is now enabled!')
@enable.error
async def enable_error(interaction: discord.Interaction, error: Exception):
await interaction.response.send_message(f'{interaction.user.mention}, You are not an admin on {interaction.guild.name}.')
@discord.app_commands.checks.has_permissions(administrator=True)
@xp.command(name='set', description='sets a users xp.')
async def set(interaction: discord.Interaction, user: discord.Member, amount: int):
with open(f'Files/{interaction.guild.id}.json', 'r') as f:
data = json.load(f)
x = math.trunc(data['xp'][str(user.id)]/100)
if data['xp'] == False:
await interaction.response.send_message('XP is not enabled!')
return
data['xp'][str(user.id)] = amount
with open(f'Files/{interaction.guild.id}.json', 'w') as f:
json.dump(data, f)
p = int(data['xp'][str(user.id)])/100
p = math.trunc(p)
role = discord.utils.get(interaction.guild.roles, name=f'level {p}')
if role is None:
role = await interaction.guild.create_role(name=f'level {str(p)}')
await user.add_roles(role)
try:
await user.remove_roles(discord.utils.get(interaction.guild.roles, name=f'level {x}'))
except:
pass
await interaction.response.send_message(f'{user.mention}\'s xp has been set to {amount}.')
@set.error
async def set_error(interaction: discord.Interaction, error: Exception):
await interaction.response.send_message(f'{interaction.user.mention}, You are not an admin on {interaction.guild.name}.')
@discord.app_commands.checks.has_permissions(administrator=True)
@xp.command(name='add', description='adds to a users xp.')
async def add(interaction: discord.Interaction, user: discord.Member, amount: int):
with open(f'Files/{interaction.guild.id}.json', 'r') as f:
data = json.load(f)
if data['xp'] == False:
await interaction.response.send_message('XP is not enabled!')
return
x = math.trunc(data['xp'][str(user.id)]/100)
data['xp'][str(user.id)] += amount
with open(f'Files/{interaction.guild.id}.json', 'w') as f:
json.dump(data, f)
p = int(data['xp'][str(user.id)])/100
p = math.trunc(p)
role = discord.utils.get(interaction.guild.roles, name=f'level {p}')
if role is None:
role = await interaction.guild.create_role(name=f'level {str(p)}')
await user.add_roles(role)
try:
await user.remove_roles(discord.utils.get(interaction.guild.roles, name=f'level {x}'))
except:
pass
await interaction.response.send_message(f'{amount} has been added to {user.mention}\'s .')
@add.error
async def add_error(interaction: discord.Interaction, error: Exception):
await interaction.response.send_message(f'{interaction.user.mention}, You are not an admin on {interaction.guild.name}.')
@discord.app_commands.checks.has_permissions(administrator=True)
@xp.command(name='remove', description='removes from a users xp.')
async def remove(interaction: discord.Interaction, user: discord.Member, amount: int):
with open(f'Files/{interaction.guild.id}.json', 'r') as f:
data = json.load(f)
if data['xp'] == False:
await interaction.response.send_message('XP is not enabled!')
return
x = math.trunc(data['xp'][str(user.id)]/100)
data['xp'][str(user.id)] -= amount
with open(f'Files/{interaction.guild.id}.json', 'w') as f:
json.dump(data, f)
p = int(data['xp'][str(user.id)])/100
p = math.trunc(p)
role = discord.utils.get(interaction.guild.roles, name=f'level {p}')
if role is None:
role = await interaction.guild.create_role(name=f'level {str(p)}')
await user.add_roles(role)
try:
await user.remove_roles(discord.utils.get(interaction.guild.roles, name=f'level {x}'))
except:
pass
await interaction.response.send_message(f'{amount} has been removed from {user.mention}\'s xp .')
@remove.error
async def remove_error(interaction: discord.Interaction, error: Exception):
await interaction.response.send_message(f'{interaction.user.mention}, You are not an admin on {interaction.guild.name}.')
bot.tree.add_command(xp)
@app_commands.command(name='games', description='plays a party game')
async def games(interaction: discord.Interaction, game: typing.Literal['youtube', 'poker', 'chess', 'betrayal', 'fishing', 'letter-league', 'word-snack', 'sketch-heads', 'spellcast', 'awkword', 'checkers', 'blazing-8s', 'land-io', 'putt-party']):
if interaction.user.voice is None:
await interaction.response.send_message('You must be in a voice channel to play a game.',ephemeral=True)
return
link = await bot.togetherControl.create_link(interaction.user.voice.channel.id, game)
await interaction.response.send_message(f"click the link to play!\n{link}", suppress_embeds=True, ephemeral=True)
bot.tree.add_command(games)
@bot.listen('on_message')
async def on_message(message):
if message.author == bot.user:
return
with open(f'Files/{message.guild.id}.json', 'r') as f:
data = json.load(f)
if data['bannedwords'] == False:
return
p = []
for word in data['bannedwords']:
if word in message.content:
if message.content.startswith(word+' '):
p.append(word)
elif message.content.endswith(' '+word):
p.append(word)
elif ' '+word+' ' in message.content:
p.append(word)
elif word == message.content:
p.append(word)
if len(p) != 0:
try:
await message.delete()
except:
return
string = ''
for word in p:
string += f'{word}{", " if word != p[len(p)-1] else ""} '
await message.channel.send(f'{message.author.mention}, please refrain from saying the following word{"s" if len(p) > 0 else ""}: {string}')
banwords = discord.app_commands.Group(name='banwords', description='manages banned words.')
@discord.app_commands.checks.has_permissions(administrator=True)
@banwords.command(name='set', description='sets the banword list to a custom list from a url.')
async def URL(interaction: discord.Interaction, url: str):
with open(f'Files/{interaction.guild.id}.json', 'r') as f:
data = json.load(f)
words = []
if await checkurl(url=url) != True:
await interaction.response.send_message('That is not a valid url. Please ensure that the url points to a text file, and all words are seperated with a newline.',ephemeral=True)
return
async with aiohttp.ClientSession() as session:
async with session.get(url) as r:
for line in str(await r.text()).split('\n'):
if line == '':
continue
words.append(line.strip())
with open('banwords.txt', 'w') as f:
for word in words:
f.write(f'{word}\n')
view = Buttons2()
await interaction.response.send_message('Does this look correct?',ephemeral=True,view=view,file=discord.File('banwords.txt'))
os.remove('banwords.txt')
time = 0
while view.show() == None:
await asyncio.sleep(.1)
time += .1
if time == 30:
await interaction.edit_original_message(content='You took too long to respond, please try again.',view=None,attachments=[])
return
if view.show() == True:
data['bannedwords'] = words
with open(f'Files/{interaction.guild.id}.json', 'w') as f:
json.dump(data, f)
await interaction.edit_original_message(content=f'The banword list has been set, use `/banwords show` to show it.', view=None,attachments=[])
else:
await interaction.edit_original_message(content='Cancelled.',view=None,attachments=[])
@discord.app_commands.checks.has_permissions(administrator=True)
@banwords.command(name='add', description='adds a word to the banned words list.')
async def add(interaction: discord.Interaction, word: str):
with open(f'Files/{interaction.guild.id}.json', 'r') as f:
data = json.load(f)
if data['bannedwords'] == False:
await interaction.response.send_message('Banned words are not enabled!')
return
if word in data['bannedwords']:
await interaction.response.send_message(f'{word} is already banned.')
return
data['bannedwords'].append(word)
with open(f'Files/{interaction.guild.id}.json', 'w') as f:
json.dump(data, f)
await interaction.response.send_message(f'{word} has been banned.')
@add.error
async def add_error(interaction: discord.Interaction, error: Exception):
await interaction.response.send_message(f'{interaction.user.mention}, You are not an admin on {interaction.guild.name}.')
@discord.app_commands.checks.has_permissions(administrator=True)
@banwords.command(name='remove', description='removes a word from the banned words list.')
async def remove(interaction: discord.Interaction, word: str):
with open(f'Files/{interaction.guild.id}.json', 'r') as f:
data = json.load(f)
if data['bannedwords'] == False:
await interaction.response.send_message('Banned words are not enabled!')
return
if word not in data['bannedwords']:
await interaction.response.send_message(f'{word} is not banned.')
return
data['bannedwords'].remove(word)
with open(f'Files/{interaction.guild.id}.json', 'w') as f:
json.dump(data, f)
await interaction.response.send_message(f'{word} has been unbanned.')
@remove.error
async def remove_error(interaction: discord.Interaction, error: Exception):
await interaction.response.send_message(f'{interaction.user.mention}, You are not an admin on {interaction.guild.name}.')
class Buttons2(discord.ui.View):
def __init__(self, *, timeout=180,):
self.num = None
super().__init__(timeout=timeout)
@discord.ui.button(label="Yes",style=discord.ButtonStyle.green)
async def blurple_button(self,button:discord.ui.Button,interaction:discord.Interaction):
self.num = True
@discord.ui.button(label="No",style=discord.ButtonStyle.red)
async def gray_button(self,button:discord.ui.Button,interaction:discord.Interaction):
self.num = False
def show(self):
return self.num
@discord.app_commands.checks.has_permissions(administrator=True)
@banwords.command(name='enable', description='enables banned words.')
async def enable(interaction: discord.Interaction):
with open(f'Files/{interaction.guild.id}.json', 'r') as f:
data = json.load(f)
if data['bannedwords'] != False:
await interaction.response.send_message('Banned words are already enabled!', ephemeral=True)
return
data['bannedwords'] = []
view = Buttons2()
await interaction.response.send_message('would you like to use a preset banwords list?', view=view, ephemeral=True)
time = 0
while view.show() is None:
if time == 300:
await interaction.edit_original_message('Timed out.')
return
await asyncio.sleep(.1)
time += .1
if view.show() == False:
with open(f'Files/{interaction.guild.id}.json', 'w') as f:
json.dump(data, f)
await interaction.edit_original_message(content='Banned words are now enabled, but no words have been added. Use `/banwords` to manage them.',view=None)
return
if view.show() == True:
async with aiohttp.ClientSession() as session:
async with session.get('https://www.cs.cmu.edu/~biglou/resources/bad-words.txt') as resp:
p = await resp.text()
f = []
for word in p.split('\n'):
if word != '':
f.append(word.strip())
with open(f'Files/{interaction.guild.id}.json', 'w') as z:
data['bannedwords'] = f
json.dump(data, z)
await interaction.edit_original_message(content='Banned words are now enabled using the default list (taken from https://www.cs.cmu.edu/~biglou/resources/bad-words.txt). Use `/banwords` to manage them.',view=None)
return
@enable.error
async def enable_error(interaction: discord.Interaction, error: Exception):
await interaction.response.send_message(f'{interaction.user.mention}, You are not an admin on {interaction.guild.name}.')
@banwords.command(name='disable', description='disables banned words.')
async def disable(interaction: discord.Interaction):
with open(f'Files/{interaction.guild.id}.json', 'r') as f:
data = json.load(f)
if data['bannedwords'] == False:
await interaction.response.send_message('Banned words are already disabled!', ephemeral=True)
return
data['bannedwords'] = False
with open(f'Files/{interaction.guild.id}.json', 'w') as f:
json.dump(data, f)
await interaction.response.send_message(content='Banned words are now disabled.')
@disable.error
async def disable_error(interaction: discord.Interaction, error: Exception):
await interaction.response.send_message(f'{interaction.user.mention}, You are not an admin on {interaction.guild.name}.')
@banwords.command(name='show', description='shows banned words.')
async def show(interaction: discord.Interaction):
with open(f'Files/{interaction.guild.id}.json', 'r') as f:
data = json.load(f)
if data['bannedwords'] == False:
await interaction.response.send_message('Banned words are not enabled!', ephemeral=True)
return
p = ''
if data['bannedwords'] == []:
await interaction.response.send_message('No words have been banned.', ephemeral=True)
return
if len(data['bannedwords']) < 21:
for word in data['bannedwords']:
p += f'{word}{", " if word != data["bannedwords"][len(data["bannedwords"])-1] else ""}'
await interaction.response.send_message(f'Banned words: {p}', ephemeral=True)
else:
for word in data['bannedwords']:
p += f'{word}{", " if word != data["bannedwords"][len(data["bannedwords"])-1] else ""}'
with open('banlist.txt', 'w') as f:
f.write(p)
await interaction.response.send_message('Banned words:', file=discord.File('banlist.txt'), ephemeral=True)
os.remove('banlist.txt')
bot.tree.add_command(banwords)
logs = discord.app_commands.Group(name='logs', description='manages logs.')
@discord.app_commands.checks.has_permissions(administrator=True)
@logs.command(name='enable', description='enables logs.')
async def enable(interaction: discord.Interaction, channel: discord.TextChannel):
with open(f'Files/{interaction.guild.id}.json', 'r') as f:
data = json.load(f)
if data['logchannel'] != False:
await interaction.response.send_message('Logs are already enabled!', ephemeral=True)
return
data['logchannel'] = channel.id
with open(f'Files/{interaction.guild.id}.json', 'w') as f:
json.dump(data, f)
await interaction.response.send_message(content='Logs are now enabled.', ephemeral=True)
@enable.error
async def enable_error(interaction: discord.Interaction, error: Exception):
await interaction.response.send_message(f'{interaction.user.mention}, You are not an admin on {interaction.guild.name}.')
@discord.app_commands.checks.has_permissions(administrator=True)
@logs.command(name='disable', description='disables logs.')
async def disable(interaction: discord.Interaction):
with open(f'Files/{interaction.guild.id}.json', 'r') as f:
data = json.load(f)
if data['logchannel'] == False:
await interaction.response.send_message('Logs are already disabled!', ephemeral=True)
return
data['logchannel'] = False
with open(f'Files/{interaction.guild.id}.json', 'w') as f:
json.dump(data, f)
await interaction.response.send_message(content='Logs are now disabled.', ephemeral=True)
@disable.error
async def disable_error(interaction: discord.Interaction, error: Exception):
await interaction.response.send_message(f'{interaction.user.mention}, You are not an admin on {interaction.guild.name}.')
@discord.app_commands.checks.has_permissions(administrator=True)
@logs.command(name='setchannel', description='sets a channel to send logs to.')
async def setchannel(interaction: discord.Interaction, channel: discord.TextChannel):
with open(f'Files/{interaction.guild.id}.json', 'r') as f:
data = json.load(f)
if data['logchannel'] == False:
await interaction.response.send_message('Logs are not enabled!', ephemeral=True)
return
data['logchannel'] = channel.id
with open(f'Files/{interaction.guild.id}.json', 'w') as f:
json.dump(data, f)
await interaction.response.send_message(content='Logs are now set to this channel.', ephemeral=True)
@setchannel.error
async def setchannel_error(interaction: discord.Interaction, error: Exception):
await interaction.response.send_message(f'{interaction.user.mention}, You are not an admin on {interaction.guild.name}.')
@discord.app_commands.checks.has_permissions(administrator=True)
@logs.command(name='create', description='creates a logs channel.')
async def create(interaction: discord.Interaction):
with open(f'Files/{interaction.guild.id}.json', 'r') as f:
data = json.load(f)
channel = await interaction.guild.create_text_channel(name='logs', reason='Logs channel created by the bot.')
p = False
if data['logchannel'] == False:
p = True
data['logchannel'] = channel.id
await channel.set_permissions(
discord.utils.get(interaction.guild.roles, name='@everyone'),
send_messages=False,
read_messages=False
)
with open(f'Files/{interaction.guild.id}.json', 'w') as f:
json.dump(data, f)
await interaction.response.send_message(content=f'lognnel has been created{", and logging has been enabled" if p else ""}.', ephemeral=True)
bot.tree.add_command(logs)
@bot.listen('on_message')
async def on_message(message: discord.Message):
if message.author.bot:
return
with open(f'Files/{message.guild.id}.json', 'r') as f:
data = json.load(f)
if data['logchannel'] == False:
return
if data['logchannel'] == message.channel.id:
return
channel = discord.utils.get(message.guild.channels, id=data['logchannel'])
if channel == None:
return
await channel.send(f'{message.author.mention}:{message.channel.mention}\n {message.content}')
@app_commands.command(name='sysinfo', description='gets info of host computor.')
async def sysinfo(interaction: discord.Interaction):
sysinfo = ''
if platform.system() == 'Linux':
with open('/etc/os-release', 'r') as f:
for a in f.readlines():
if a.startswith('NAME='):
sysinfo+=f'''OS: {a.split('"')[1]}{" Linux" if "Linux" not in a else ""} {platform.machine()}\n'''
if a.startswith('VERSION='):
sysinfo+=f'''Version: {a.split('"')[1]}\n'''
sysinfo+=f'''Kernel: {platform.release()}\n'''
try:
sysinfo+=f'''Cpu: {cpuinfo.cpu.info[0]['model name']}\n'''
except:
pass
sysinfo+=f'''Ram: {str(round(psutil.virtual_memory().total / (1024.0 **3)))+" GB"}'''
await interaction.response.send_message(sysinfo)
else:
await interaction.response.send_message('This computor runs a non-Linux OS, which is unsupported by this command at the moment')
bot.tree.add_command(sysinfo)
@app_commands.command(name='say', description='says something.')
async def say(interaction: discord.Interaction, *, something: str):
with open(f'Files/{interaction.guild.id}.json', 'r') as f:
data = json.load(f)
if data['bannedwords'] == False:
await interaction.response.send_message(something)
else:
for a in data['bannedwords']:
if a in something:
await interaction.response.send_message('You cannot make me say words that are blocked silly.', ephemeral=True)
return
await interaction.response.send_message(something)
bot.tree.add_command(say)
bot.run(token)