This repository has been archived by the owner on Mar 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
2171 lines (1709 loc) · 86.4 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 random
import discord
import asyncio
from discord import FFmpegPCMAudio, app_commands
from discord.ext import commands
from discord.ui import View
import pypresence
import yt_dlp
import youtubesearchpython
from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import json
from os import path, listdir
from mutagen.mp3 import MP3
import sys
from typing import Literal
import traceback
import datetime
from api_keys import api_key_testing as api_key
import functools
# ---------------- Bot class ------------
class Bot(commands.Bot):
def __init__(self):
intents = discord.Intents.all()
super().__init__(command_prefix=prefix, intents=intents)
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
print_message('no guild', "Trying to sync commands")
await self.tree.sync()
print_message('no guild', f"Synced slash commands for {self.user}")
await bot.change_presence(activity=discord.Game(name=f"/help"))
print_message('no guild', 'Logged in as:\n{0.user.name}\n{0.user.id}'.format(bot))
async def on_guild_join(self, guild_object):
guild[guild_object.id] = Guild(guild_object.id)
print_message(guild_object.id, f"Joined guild {guild_object.name} with {guild_object.member_count} members and {len(guild_object.voice_channels)} voice channels")
save_json()
text_channels = guild_object.text_channels
sys_channel = guild_object.system_channel
if sys_channel is not None:
if sys_channel.permissions_for(guild_object.me).send_messages:
await sys_channel.send(f"Hello **`{guild_object.name}`**! I am `{self.user.display_name}`. Thank you for inviting me.\n\nTo see what commands I have available type `/help`.")
return
else:
await text_channels[0].send(f"Hello **`{guild_object.name}`**! I am `{self.user.display_name}`. Thank you for inviting me.\n\nTo see what commands I have available type `/help`.")
async def on_voice_state_update(self, member, before, after):
voice_state = member.guild.voice_client
if voice_state is not None and len(voice_state.channel.members) == 1:
after.channel.guild.voice_client.stop()
await voice_state.disconnect()
print_message(member.guild.id, "Disconnecting when last person left")
if not member.id == self.user.id:
return
elif before.channel is None:
voice = after.channel.guild.voice_client
time = 0
while True:
await asyncio.sleep(1)
time += 1
if voice.is_playing() and not voice.is_paused():
time = 0
if time >= guild[member.guild.id].options.buffer: # how many seconds of inactivity to disconnect | 300 = 5min | 600 = 10min
guild[member.guild.id].options.stopped = True
voice.stop()
await voice.disconnect()
print_message(member.guild.id, f"Disconnecting after {guild[member.guild.id].options.buffer} seconds of nothing playing")
if not voice.is_connected():
break
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CheckFailure):
print_command(ctx, 'Permission Fail', ctx.command)
await ctx.reply("( ͡° ͜ʖ ͡°)つ━☆・。\n"
"⊂ ノ ・゜+.\n"
" しーJ °。+ ´¨)\n"
" .· ´¸.·´¨) ¸.·*¨)\n"
" (¸.·´ (¸.·' ☆ **Fuck off**\n"
"*You don't have permission to use this command*")
else:
print_message(ctx.guild.id, f"{error}")
await ctx.reply(f"{error} {bot.get_user(my_id).mention}", ephemeral=True)
# ---------------- Data Classes ------------
class Options:
def __init__(self, guild_id):
self.guild_id = guild_id
self.stopped = False
self.loop = False
self.is_radio = False
self.language = 'cs'
self.response_type = 'short' # long or short
self.search_query = 'Never gonna give you up'
self.buttons = False
self.volume = 1.0
self.buffer = 600 # how many seconds of nothing before it disconnects | 600 = 10min
# noinspection PyTypeChecker
class Video:
def __init__(self, url, author, title=None, picture=None, duration=None, channel_name=None, channel_link=None):
self.url = url
self.author = author
video = None
if title is None and picture is None and duration is None and channel_name is None and channel_link is None:
try:
video = youtubesearchpython.Video.getInfo(url) # mode=ResultMode.json
except Exception as e:
raise ValueError(f"Not a youtube link: {e}")
self.title = title
self.picture = picture
self.duration = duration
self.channel_name = channel_name
self.channel_link = channel_link
if video:
self.title = video['title']
self.picture = 'https://img.youtube.com/vi/' + video['id'] + '/default.jpg'
self.duration = video['duration']['secondsText']
self.channel_name = video['channel']['name']
self.channel_link = video['channel']['link']
def renew(self):
pass
class Radio:
def __init__(self, name, author):
self.author = author
self.url = radio_dict[name]['url']
self.picture = radio_dict[name]['thumbnail']
self.channel_name = radio_dict[name]['type']
self.channel_link = self.url
self.title = name
self.duration = 'Stream'
self.radio_website = radio_dict[name]['type']
def renew(self):
if self.radio_website == 'radia_cz':
html = urlopen(self.url).read()
soup = BeautifulSoup(html, features="lxml")
data1 = soup.find('div', attrs={'class': 'interpret-image'})
data2 = soup.find('div', attrs={'class': 'interpret-info'})
self.picture = data1.find('img')['src']
self.channel_name = data2.find('div', attrs={'class': 'nazev'}).text.lstrip().rstrip()
self.title = data2.find('div', attrs={'class': 'song'}).text.lstrip().rstrip()
self.duration = 'Stream'
if self.radio_website == 'actve':
r = requests.get(self.url).json()
self.picture = r['coverBase']
self.channel_name = r['artist']
self.title = r['title']
self.duration = 'Stream'
class LocalFile:
def __init__(self, title, duration, author):
self.url = None
self.author = author
self.title = title
self.picture = vlc_logo
self.duration = duration
self.channel_name = 'Local file'
self.channel_link = 'Local file'
def renew(self):
pass
class FromProbe:
def __init__(self, url, title, duration, author, channel_name, channel_link):
self.url = url
self.author = author
self.title = title
self.picture = vlc_logo
self.duration = duration
self.channel_name = channel_name
self.channel_link = channel_link
def renew(self):
pass
class Guild:
def __init__(self, guild_id):
self.options = Options(guild_id)
self.queue = []
self.search_list = []
self.now_playing = Video(url='https://www.youtube.com/watch?v=dQw4w9WgXcQ',
author=bot.get_user(my_id),
title='Never gonna give you up',
picture='https://img.youtube.com/vi/dQw4w9WgXcQ/default.jpg',
duration='3:33',
channel_name='Rick Astley',
channel_link='https://www.youtube.com/channel/UCuAXFkgsw1L7xaCfnd5JJOw')
# -------- Get SoundEffects ------------
def load_sound_effects():
# noinspection PyGlobalUndefined
global all_sound_effects
all_sound_effects = ["No sound effects found"]
try:
all_sound_effects = listdir('sound_effects')
for file_index, file_val in enumerate(all_sound_effects):
all_sound_effects[file_index] = all_sound_effects[file_index][:len(file_val) - 4]
except FileNotFoundError:
all_sound_effects = ["No sound effects found"]
print_message('no guild', 'Loaded sound_effects folder')
# ------------ PRINT --------------------
def print_command(ctx, text_data, opt, text_only=False):
now_time = datetime.datetime.now(datetime.timezone(datetime.timedelta(seconds=3600), 'CET'))
message = f"{now_time.strftime('(CET) %d/%m/%Y %X')} | {ctx.guild.id} | {text_data}: {opt}"
if not text_only:
message = f"{now_time.strftime('(CET) %d/%m/%Y %X')} | {ctx.guild.id} | Command ({text_data}) was requested by" \
f" ({ctx.message.author}) -- (options: {opt})"
print(message)
message += "\n"
with open("log.txt", "a", encoding="utf-8") as f:
f.write(message)
def print_message(guild_id, content):
now_time = datetime.datetime.now(datetime.timezone(datetime.timedelta(seconds=3600), 'CET'))
message = f"{now_time.strftime('(CET) %d/%m/%Y %X')} | {guild_id} | {content}"
print(message)
message += "\n"
with open("log.txt", "a", encoding="utf-8") as f:
f.write(message)
# ---------------------------------------------- GUILD TO JSON ---------------------------------------------------------
def video_to_json(video):
try:
author = video.author.id
except AttributeError:
author = my_id
video_dict = {'url': video.url,
'author': author,
'title': video.title,
'picture': video.picture,
'duration': video.duration,
'channel_name': video.channel_name,
'channel_link': video.channel_link}
return video_dict
def guild_to_json(guild_object):
guild_dict = {}
search_dict = {}
queue_dict = {}
if guild_object.search_list:
for index, video in enumerate(guild_object.search_list):
search_dict[index] = video_to_json(video)
if guild_object.queue:
for index, video in enumerate(guild_object.queue):
queue_dict[index] = video_to_json(video)
guild_dict['options'] = guild_object.options.__dict__
guild_dict['queue'] = queue_dict
guild_dict['search_list'] = search_dict
guild_dict['now_playing'] = video_to_json(guild_object.now_playing)
return guild_dict
def guilds_to_json(guild_dict):
guilds_dict = {}
for guild_id, guilds_object in guild_dict.items():
guilds_dict[int(guild_id)] = guild_to_json(guilds_object)
return guilds_dict
# ---------------------------------------------- JSON TO GUILD ---------------------------------------------------------
def json_to_video(video_dict):
try:
author = bot.get_user(video_dict['author'])
except AttributeError:
author = bot.get_user(bot_id)
video = Video(url=video_dict['url'],
author=author,
title=video_dict['title'],
picture=video_dict['picture'],
duration=video_dict['duration'],
channel_name=video_dict['channel_name'],
channel_link=video_dict['channel_link'])
return video
def json_to_guild(guild_dict):
guild_object = Guild(guild_dict['options']['guild_id'])
# guild_object.options = Options(guild_dict['options']['guild_id'])
# options_time = time.time() - start_time - guild_time
guild_object.options.__dict__ = guild_dict['options']
guild_object.queue = [json_to_video(video_dict) for video_dict in guild_dict['queue'].values()]
guild_object.search_list = [json_to_video(video_dict) for video_dict in guild_dict['search_list'].values()]
guild_object.now_playing = json_to_video(guild_dict['now_playing'])
return guild_object
def json_to_guilds(guilds_dict):
guilds_object = {}
for guild_id, guild_dict in guilds_dict.items():
guilds_object[int(guild_id)] = json_to_guild(guild_dict)
return guilds_object
# ---------------------------------------------- LOAD -------------------------------------------------------------
print_message('no guild', "--------------------------------------- NEW / REBOOTED ----------------------------------------")
build_new_guilds = False
with open('src/radio.json', 'r') as file:
radio_dict = json.load(file)
print_message('no guild', 'Loaded radio.json')
with open('src/languages.json', 'r') as file:
languages_dict = json.load(file)
text = languages_dict['en']
print_message('no guild', 'Loaded languages.json')
with open('src/other.json', 'r') as file:
other = json.load(file)
react_dict = other['reactions']
prefix = other['prefix']
my_id = other['my_id']
bot_id = other['bot_id']
vlc_logo = other['logo']
authorized_users = other['authorized']
print_message('no guild', 'Loaded other.json')
# ---------------------------------------------- BOT -------------------------------------------------------------------
bot = Bot()
print_message('no guild', 'Bot class initialized')
# ---------------- Rich Presence ------------
rp_bot_id = 1007004463933952120
rp = pypresence.Presence(rp_bot_id , loop=asyncio.get_event_loop())
rp.connect()
rp.update(state="Online",
details="Music & Radio Bot",
large_image="logo",
large_text="large_text",
buttons=[{"label": "Invite Bot", "url": "https://discord.com/api/oauth2/authorize?client_id=1007004463933952120&permissions=3198017&scope=bot"},
{"label": "GitHub", "url": "https://github.com/Tomer27cz/discord_bot_stanley_the_6th"}]
)
print_message('no guild', 'Rich Presence initialized')
# ----------------------------------------------------------------------------------------------------------------------
with open('src/guilds.json', 'r') as file:
guild = json_to_guilds(json.load(file))
print_message('no guild', 'Loaded guilds.json')
if build_new_guilds:
print_message('no guild', 'Building new guilds.json ...')
with open('src/guilds.json', 'r') as file:
jf = json.load(file)
guild = dict(zip(jf.keys(), [Guild(int(guild)) for guild in jf.keys()]))
with open('src/guilds.json', 'w') as file:
file.write(json.dumps(guilds_to_json(guild), indent=4))
exit(1)
all_sound_effects = ["No sound effects found"]
load_sound_effects()
# ---------------------------------------------- SAVE JSON -------------------------------------------------------------
def save_json():
with open('src/guilds.json', 'w') as f:
json.dump(guilds_to_json(guild), f, indent=4)
print_message(guild_id='all', content='Updated guilds.json')
# ---------------------------------------------- TEXT ----------------------------------------------------------
def tg(guild_id, content):
lang = guild[guild_id].options.language
return languages_dict[lang][content]
# --------- video_info / url --------
def get_playlist_from_url(url):
try:
code = url[url.index('&list=')+1:url.index('&index=')]
except ValueError:
code = url[url.index('&list=')+1:]
playlist_url = 'https://www.youtube.com/playlist?' + code
return playlist_url
# -------------- convert / get -----------
def mp3_length(path_of_mp3):
audio = MP3(path_of_mp3)
length = audio.info.length
return length
def convert_duration(duration):
try:
if duration is None or duration == 0 or duration == '0':
return 'Stream'
seconds = int(duration) % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
if hour:
if not minutes:
minutes = 00
if not seconds:
seconds = 00
return "%d:%02d:%02d" % (hour, minutes, seconds)
if not hour:
if not minutes:
minutes = 00
if not seconds:
seconds = 00
return "%02d:%02d" % (minutes, seconds)
except (ValueError, TypeError):
return duration
# ---------------EMBED--------------
def create_embed(video, name, guild_id):
# (link, title, picture, duration, user, author, author_link)
# ( 0 1 2 3 4 5 6 )
embed = (discord.Embed(title=name,
description=f'```\n{video.title}\n```',
color=discord.Color.blurple()))
if name == tg(guild_id, "Now playing"):
guild[guild_id].now_playing = video
embed.add_field(name=tg(guild_id, 'Duration'), value=convert_duration(video.duration))
try:
embed.add_field(name=tg(guild_id, 'Requested by'), value=video.author.mention)
except AttributeError:
embed.add_field(name=tg(guild_id, 'Requested by'), value=video.author)
embed.add_field(name=tg(guild_id, 'Author'), value=f'[{video.channel_name}]({video.channel_link})')
embed.add_field(name=tg(guild_id, 'URL'), value=f'[{video.url}]({video.url})')
embed.set_thumbnail(url=video.picture)
return embed
# ------------- Youtube DL classes -----------
YTDL_OPTIONS = {
'format': 'bestaudio/best',
'extractaudio': True,
'audioformat': 'mp3',
'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 = {
'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
'options': '-vn',
}
class YTDLError(Exception):
pass
class YTDLSource(discord.PCMVolumeTransformer):
YTDL_OPTIONS = {
'format': 'bestaudio/best',
'extractaudio': True,
'audioformat': 'mp3',
'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 = {
'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
'options': '-vn',
}
ytdl = yt_dlp.YoutubeDL(YTDL_OPTIONS)
def __init__(self, ctx: commands.Context, source: discord.FFmpegPCMAudio, *, data: dict):
super().__init__(source, guild[ctx.guild.id].options.volume)
self.requester = ctx.author
self.channel = ctx.channel
self.data = data
self.uploader = data.get('uploader')
self.uploader_url = data.get('uploader_url')
date = data.get('upload_date')
self.upload_date = date[6:8] + '.' + date[4:6] + '.' + date[0:4]
self.title = data.get('title')
self.thumbnail = data.get('thumbnail')
self.description = data.get('description')
self.tags = data.get('tags')
self.url = data.get('webpage_url')
self.views = data.get('view_count')
self.likes = data.get('like_count')
self.dislikes = data.get('dislike_count')
self.stream_url = data.get('url')
def __str__(self):
return '**{0.title}** by **{0.uploader}**'.format(self)
@classmethod
async def create_source(cls, ctx: commands.Context, cr_search: str, *, cr_loop: asyncio.BaseEventLoop = None):
cr_loop = cr_loop or asyncio.get_event_loop()
partial = functools.partial(cls.ytdl.extract_info, cr_search, download=False, process=False)
data = await cr_loop.run_in_executor(None, partial)
if data is None:
raise YTDLError('Couldn\'t find anything that matches `{}`'.format(cr_search))
if 'entries' not in data:
process_info = data
else:
process_info = None
for entry in data['entries']:
if entry:
process_info = entry
break
if process_info is None:
raise YTDLError('Couldn\'t find anything that matches `{}`'.format(cr_search))
webpage_url = process_info['webpage_url']
partial = functools.partial(cls.ytdl.extract_info, webpage_url, download=False)
processed_info = await cr_loop.run_in_executor(None, partial)
if processed_info is None:
raise YTDLError('Couldn\'t fetch `{}`'.format(webpage_url))
if 'entries' not in processed_info:
info = processed_info
else:
info = None
while info is None:
try:
info = processed_info['entries'].pop(0)
except IndexError:
raise YTDLError('Couldn\'t retrieve any matches for `{}`'.format(webpage_url))
return cls(ctx, discord.FFmpegPCMAudio(info['url'], **cls.FFMPEG_OPTIONS), data=info)
@staticmethod
def parse_duration(duration: int):
minutes, seconds = divmod(duration, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
duration = []
if days > 0:
duration.append('{} days'.format(days))
if hours > 0:
duration.append('{} hours'.format(hours))
if minutes > 0:
duration.append('{} minutes'.format(minutes))
if seconds > 0:
duration.append('{} seconds'.format(seconds))
return ', '.join(duration)
# ------------------------------------ View Classes --------------------------------------------------------------------
class PlayerControlView(View):
def __init__(self, ctx):
super().__init__(timeout=7200)
self.guild = ctx.guild
self.guild_id = ctx.guild.id
@discord.ui.button(emoji=react_dict['play'], style=discord.ButtonStyle.blurple, custom_id='play')
async def callback(self, interaction, button):
voice = discord.utils.get(bot.voice_clients, guild=self.guild)
if voice:
if voice.is_paused():
voice.resume()
# noinspection PyUnresolvedReferences
pause_button = [x for x in self.children if x.custom_id == 'pause'][0]
pause_button.style = discord.ButtonStyle.blurple
button.style = discord.ButtonStyle.grey
await interaction.response.edit_message(view=self)
elif voice.is_playing():
await interaction.response.send_message(tg(self.guild_id, "Player **already resumed!**"),
ephemeral=True)
else:
await interaction.response.send_message(tg(self.guild_id, "No audio playing"), ephemeral=True)
else:
await interaction.response.send_message(tg(self.guild_id, "No audio"), ephemeral=True)
@discord.ui.button(emoji=react_dict['pause'], style=discord.ButtonStyle.blurple, custom_id='pause')
async def pause_callback(self, interaction, button):
voice = discord.utils.get(bot.voice_clients, guild=self.guild)
if voice:
if voice.is_playing():
voice.pause()
# noinspection PyUnresolvedReferences
play_button = [x for x in self.children if x.custom_id == 'play'][0]
play_button.style = discord.ButtonStyle.blurple
button.style = discord.ButtonStyle.grey
await interaction.response.edit_message(view=self)
elif voice.is_paused():
await interaction.response.send_message(tg(self.guild_id, "Player **already paused!**"),
ephemeral=True)
else:
await interaction.response.send_message(tg(self.guild_id, "No audio playing"), ephemeral=True)
else:
await interaction.response.send_message(tg(self.guild_id, "No audio"), ephemeral=True)
# noinspection PyUnusedLocal
@discord.ui.button(emoji=react_dict['stop'], style=discord.ButtonStyle.red, custom_id='stop')
async def stop_callback(self, interaction, button):
voice = discord.utils.get(bot.voice_clients, guild=self.guild)
if voice:
if voice.is_playing() or voice.is_paused():
voice.stop()
guild[interaction.guild_id].options.stopped = True
await interaction.response.edit_message(view=None)
else:
await interaction.response.send_message(tg(self.guild_id, "No audio playing"), ephemeral=True)
else:
await interaction.response.send_message(tg(self.guild_id, "No audio"), ephemeral=True)
class SearchOptionView(View):
def __init__(self, ctx, force=False):
super().__init__(timeout=180)
self.ctx = ctx
self.guild = ctx.guild
self.guild_id = ctx.guild.id
self.force = force
# noinspection PyUnusedLocal
@discord.ui.button(emoji=react_dict['1'], style=discord.ButtonStyle.blurple, custom_id='1')
async def callback_1(self, interaction, button):
video = guild[self.guild_id].search_list[0]
if self.force:
guild[self.guild_id].queue.insert(0, video)
else:
guild[self.guild_id].queue.append(video)
await interaction.response.edit_message(content=f'[`{video.title}`](<{video.url}>) '
f'{tg(self.guild_id, "added to queue!")}', view=None)
# noinspection PyUnusedLocal
@discord.ui.button(emoji=react_dict['2'], style=discord.ButtonStyle.blurple, custom_id='2')
async def callback_2(self, interaction, button):
video = guild[self.guild_id].search_list[1]
if self.force:
guild[self.guild_id].queue.insert(0, video)
else:
guild[self.guild_id].queue.append(video)
await interaction.response.edit_message(content=f'[`{video.title}`](<{video.url}>) '
f'{tg(self.guild_id, "added to queue!")}', view=None)
# noinspection PyUnusedLocal
@discord.ui.button(emoji=react_dict['3'], style=discord.ButtonStyle.blurple, custom_id='3')
async def callback_3(self, interaction, button):
video = guild[self.guild_id].search_list[2]
if self.force:
guild[self.guild_id].queue.insert(0, video)
else:
guild[self.guild_id].queue.append(video)
await interaction.response.edit_message(content=f'[`{video.title}`](<{video.url}>) '
f'{tg(self.guild_id, "added to queue!")}', view=None)
# noinspection PyUnusedLocal
@discord.ui.button(emoji=react_dict['4'], style=discord.ButtonStyle.blurple, custom_id='4')
async def callback_4(self, interaction, button):
video = guild[self.guild_id].search_list[3]
if self.force:
guild[self.guild_id].queue.insert(0, video)
else:
guild[self.guild_id].queue.append(video)
await interaction.response.edit_message(content=f'[`{video.title}`](<{video.url}>) '
f'{tg(self.guild_id, "added to queue!")}', view=None)
# noinspection PyUnusedLocal
@discord.ui.button(emoji=react_dict['5'], style=discord.ButtonStyle.blurple, custom_id='5')
async def callback_5(self, interaction, button):
video = guild[self.guild_id].search_list[4]
if self.force:
guild[self.guild_id].queue.insert(0, video)
else:
guild[self.guild_id].queue.append(video)
await interaction.response.edit_message(content=f'[`{video.title}`](<{video.url}>) '
f'{tg(self.guild_id, "added to queue!")}', view=None)
# # noinspection PyUnusedLocal
# @discord.ui.button(emoji=react_dict['false'], style=discord.ButtonStyle.red, custom_id='6')
# async def callback_6(self, interaction, button):
# await interaction.response.edit_message(content=f'{tg(self.guild_id, "Nothing selected")}', view=None)
class PlaylistOptionView(View):
def __init__(self, ctx, url, force=False):
super().__init__(timeout=180)
self.ctx = ctx
self.url = url
self.guild = ctx.guild
self.guild_id = ctx.guild.id
self.force = force
# noinspection PyUnusedLocal
@discord.ui.button(label='Yes', style=discord.ButtonStyle.blurple)
async def callback_1(self, interaction, button):
playlist_url = get_playlist_from_url(self.url)
await interaction.response.edit_message(content=tg(self.guild_id, "Adding playlist to queue..."), view=None)
if self.force:
response = await queue_command(self.ctx, playlist_url, 0, True, self.force)
else:
response = await queue_command(self.ctx, playlist_url, None, True, self.force)
msg = await interaction.original_response()
await msg.edit(content=response[1])
# noinspection PyUnusedLocal
@discord.ui.button(label='No, just this', style=discord.ButtonStyle.blurple)
async def callback_2(self, interaction, button):
pure_url = self.url[:self.url.index('&list=')]
if self.force:
response = await queue_command(self.ctx, pure_url, 0, True, self.force)
else:
response = await queue_command(self.ctx, pure_url, None, True, self.force)
await interaction.response.edit_message(content=response[1], view=None)
await play(self.ctx)
# --------------------------------------- QUEUE --------------------------------------------------
@bot.hybrid_command(name='queue', with_app_command=True, description=text['queue_add'], help=text['queue_add'])
@app_commands.describe(url=text['url'], position=text['pos'], mute_response=text['mute_response'], force=text['force'])
async def queue_command(ctx: commands.Context,
url=None,
position: int = None,
mute_response: bool = None,
force: bool = False
):
print_command(ctx, 'queue', [url, position, mute_response])
guild_id = ctx.guild.id
author = ctx.author
if not url:
message = tg(guild_id, "`url` is **required**")
if not mute_response:
await ctx.reply(message, ephemeral=True)
return [False, message]
elif url[0:33] == "https://www.youtube.com/playlist?":
try:
# noinspection PyUnresolvedReferences
if not ctx.interaction.response.is_done():
await ctx.defer()
playlist_videos = youtubesearchpython.Playlist.getVideos(url)
except KeyError:
print_message(guild_id, "------------------------------- playlist -------------------------")
tb = traceback.format_exc()
print_message(guild_id, tb)
print_message(guild_id, "--------------------------------------------------------------")
message = f'This playlist is unviewable: `{url}`'
if not mute_response:
await ctx.reply(message)
return [False, message]
playlist_songs = 0
playlist_videos = playlist_videos['videos']
if position or position == 0:
playlist_videos = list(reversed(playlist_videos))
for index, val in enumerate(playlist_videos):
playlist_songs += 1
# noinspection PyTypeChecker
url = f"https://www.youtube.com/watch?v={playlist_videos[index]['id']}"
video = Video(url, author)
if position or position == 0: guild[guild_id].queue.insert(position, video)
else: guild[guild_id].queue.append(video)
message = f"`{playlist_songs}` {tg(guild_id, 'songs from playlist added to queue!')}"
if not mute_response:
await ctx.reply(message)
save_json()
return [True, message, None]
elif url:
if 'index=' in url or 'list=' in url:
view = PlaylistOptionView(ctx, url, force)
message = tg(guild_id,
'This video is from a **playlist**, do you want to add the playlist to **queue?**')
await ctx.reply(message, view=view)
return [False, message]
try:
video = Video(url, author)
if position or position == 0: guild[guild_id].queue.insert(position, video)
else: guild[guild_id].queue.append(video)
message = f'[`{video.title}`](<{video.url}>) {tg(guild_id, "added to queue!")}'
if not mute_response:
await ctx.reply(message)
save_json()
return [True, message, video]
except (ValueError, IndexError, TypeError):
try:
url_only_id = 'https://www.youtube.com/watch?v=' + url.split('watch?v=')[1]
video = Video(url_only_id, author)
if position or position == 0: guild[guild_id].queue.insert(position, video)
else: guild[guild_id].queue.append(video)
message = f'[`{video.title}`](<{video.url}>) {tg(guild_id, "added to queue!")}'
if not mute_response:
await ctx.reply(message)
save_json()
return [True, message, video]
except (ValueError, IndexError, TypeError):
try:
# https://www.youtube.com/shorts/JRPKE_A9yjw
url_shorts = url.replace('shorts/', 'watch?v=')
video = Video(url_shorts, author)
if position or position == 0: guild[guild_id].queue.insert(position, video)
else: guild[guild_id].queue.append(video)
message = f'[`{video.title}`](<{video.url}>) {tg(guild_id, "added to queue!")}'
if not mute_response:
await ctx.reply(message)
save_json()
return [True, message, video]
except (ValueError, IndexError, TypeError):
await search_command(ctx, url, 'short', force)
message = f'[`{url}`](<{url}>) {tg(guild_id, "is not supported!")}'
# await ctx.reply(message, ephemeral=True)
save_json()
return [False, message]
@bot.hybrid_command(name='next_up', with_app_command=True, description=text['next_up'], help=text['next_up'])
@app_commands.describe(url=text['url'], ephemeral=text['ephemeral'])
async def next_up(ctx: commands.Context,
url=None,
ephemeral: bool = False
):
print_command(ctx, 'next', [ephemeral])
response = await queue_command(ctx, url, 0, True, True)
if response[0]:
if ctx.voice_client:
if not ctx.voice_client.is_playing():
await play(ctx)
return
else:
await play(ctx)
return
await ctx.reply(response[1], ephemeral=ephemeral)
else:
return
save_json()
@bot.hybrid_command(name='skip', with_app_command=True, description=text['skip'], help=text['skip'])
async def skip(ctx: commands.Context):
guild_id = ctx.guild.id
print_command(ctx, 'skip', None)
if not ctx.voice_client.is_playing():
await ctx.reply(tg(guild_id, "There is **nothing to skip!**"), ephemeral=True)
if ctx.voice_client.is_playing():
await stop(ctx, True)
await asyncio.sleep(0.5)
await play(ctx)
@bot.hybrid_command(name='remove', with_app_command=True, description=text['queue_remove'], help=text['queue_remove'])
@app_commands.describe(number=text['number'], display_type=text['display_type'], ephemeral=text['ephemeral'])
async def remove(ctx: commands.Context,
number: int,
display_type: Literal['short', 'long'] = None,
ephemeral: bool = False
):
print_command(ctx, 'remove', [number, display_type, ephemeral])
guild_id = ctx.guild.id
if not display_type:
display_type = guild[guild_id].options.response_type
if number:
if number > len(guild[guild_id].queue):
if not guild[guild_id].queue:
await ctx.reply(tg(guild_id, "Nothing to **remove**, queue is **empty!**"), ephemeral=True)
return
await ctx.reply(tg(guild_id, "Index out of range!"), ephemeral=True)
return
video = guild[guild_id].queue[number]
if display_type == 'long':
embed = create_embed(video, f'{tg(guild_id, "REMOVED #")}{number}', guild_id)
await ctx.reply(embed=embed, ephemeral=ephemeral)
if display_type == 'short':
await ctx.reply(f'REMOVED #{number} : [`{video.title}`](<{video.url}>)', ephemeral=ephemeral)