-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmusic.py
More file actions
1920 lines (1648 loc) · 72.4 KB
/
music.py
File metadata and controls
1920 lines (1648 loc) · 72.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ruff: noqa: F403 F405
import discord
from discord.ext import commands
from discord import app_commands
import yt_dlp
import asyncio
import random
import concurrent.futures
from typing import List, Optional, Tuple
from util.constants import *
from util.music.queue import *
from modals.embeds import *
from lang.texts import *
from views.ticketviews import ActionsView
import json
import os
from datetime import datetime, timedelta
from ytmusicapi import YTMusic
import re
guild_queues = {}
def safe_avatar(user: discord.abc.User) -> Optional[str]:
try:
return user.display_avatar.url
except Exception:
return None
class AsyncSongLoader:
def __init__(self, max_workers=4):
self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=max_workers)
async def extract_info_async(self, url: str, loop=None):
if loop is None:
loop = asyncio.get_running_loop()
def run_yt():
with yt_dlp.YoutubeDL(YT_OPTS) as ydl:
return ydl.extract_info(url, download=False)
return await loop.run_in_executor(self.executor, run_yt)
async def preload_audio_source(self, stream_url: str, loop=None):
if loop is None:
loop = asyncio.get_running_loop()
def create_source():
ffmpeg_args = {
'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
'options': '-vn -bufsize 512k'
}
return discord.FFmpegOpusAudio(stream_url, **ffmpeg_args)
return await loop.run_in_executor(self.executor, create_source)
song_loader = AsyncSongLoader()
class OptimizedQueue:
def __init__(self):
self.queue: List[Tuple[discord.AudioSource, tuple]] = []
self.playing = False
self.lock = asyncio.Lock()
def add(self, song_data):
self.queue.append(song_data)
def get_next(self):
if self.queue:
return self.queue.pop(0)
return None
def peek(self):
return self.queue[0] if self.queue else None
def is_empty(self):
return len(self.queue) == 0
def clear(self):
self.queue.clear()
class MusicCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.background_tasks = set()
def make_embed(
self,
title: str,
description: Optional[str] = None,
*,
color: int = 0x5865F2,
thumbnail: Optional[str] = None,
author_name: Optional[str] = None,
author_icon: Optional[str] = None,
footer: Optional[str] = None,
footer_icon: Optional[str] = None,
fields: Optional[List[Tuple[str, str, bool]]] = None,
) -> discord.Embed:
embed = discord.Embed(title=title, description=description or "", color=color)
embed.timestamp = discord.utils.utcnow()
if thumbnail:
embed.set_thumbnail(url=thumbnail)
if author_name:
embed.set_author(name=author_name, icon_url=author_icon or discord.Embed.Empty)
if footer:
embed.set_footer(text=footer, icon_url=footer_icon or discord.Embed.Empty)
if fields:
for name, value, inline in fields:
embed.add_field(name=name, value=value, inline=inline)
return embed
def create_background_task(self, coro):
task = asyncio.create_task(coro)
self.background_tasks.add(task)
task.add_done_callback(self.background_tasks.discard)
return task
async def send_static_message(self):
try:
actions_embed = self.make_embed(
title="Music Controls",
description="Use the commands below to control music.",
color=0x5865F2,
thumbnail=safe_avatar(self.bot.user),
footer=f"Serving {len(self.bot.users)} users",
footer_icon=safe_avatar(self.bot.user),
fields=[
("Commands",
"```\n/play <url|search>\n/queue\n/skip\n/pause\n/shuffle\n/stop\n/chart\n/clearqueue\n```",
False),
("Status",
f"```\nServers: {len(self.bot.guilds)}\nUsers: {len(self.bot.users)}\n```",
True)
]
)
channel = await self.bot.fetch_channel(I_CHANNEL)
if channel:
async for message in channel.history(limit=100):
if (
message.author == self.bot.user and
message.embeds and
message.embeds[0].title and
"Music Controls" in message.embeds[0].title
):
await message.delete()
break
await channel.send(embed=actions_embed, view=ActionsView(bot=self.bot))
except Exception as e:
print(f"Error sending disconnect message: {e}")
async def play_next(self, guild, voice_client, interaction):
if guild.id not in guild_queues:
return
queue = guild_queues[guild.id]
next_song_data = queue.get_next()
if next_song_data:
try:
webpage_url = next_song_data['song_url']
fresh_info = await song_loader.extract_info_async(webpage_url)
if not fresh_info or "url" not in fresh_info:
print(f"Failed to get fresh stream URL for {webpage_url}")
queue.playing = False
await self.play_next(guild, voice_client, interaction)
return
stream_url = fresh_info["url"]
source = await song_loader.preload_audio_source(stream_url)
except Exception as e:
print(f"Error creating audio source: {e}")
queue.playing = False
await self.play_next(guild, voice_client, interaction)
return
queue.playing = True
def after_song(e):
if e:
print(f"Playback error: {e}")
queue.playing = False
pn = self.play_next(guild, voice_client, interaction)
asyncio.run_coroutine_threadsafe(pn, self.bot.loop)
try:
voice_client.play(source, after=after_song)
except Exception as e:
print(f"Error starting playback: {e}")
queue.playing = False
return
metadata = (
next_song_data['title'],
next_song_data['thumbnail'],
None,
next_song_data['duration'],
next_song_data['author'],
next_song_data['song_url'],
next_song_data['likes'],
next_song_data['views'],
next_song_data['upload_date']
)
embed = self.create_now_playing_embed(metadata, interaction)
try:
msg = await interaction.channel.send(embed=embed)
self.create_background_task(
self.update_progress(msg, embed, next_song_data['duration'])
)
except Exception as e:
print(f"Error sending now playing message: {e}")
elif AUTO_PLAY_ENABLED:
print("autoplaying")
song_link = None
channel = getattr(interaction, "channel", None) or await self.bot.fetch_channel(I_CHANNEL)
try:
async for msg in channel.history(limit=200):
if not msg.embeds:
continue
for emb in msg.embeds:
candidates = []
if getattr(emb, "url", None):
candidates.append(emb.url)
if getattr(emb, "title", None):
candidates.append(emb.title)
if getattr(emb, "description", None):
candidates.append(emb.description)
if getattr(emb, "fields", None):
for f in emb.fields:
candidates.append(f.name)
candidates.append(f.value)
url_re = re.compile(r"(https?://(?:music\.youtube\.com|(?:www\.)?youtube\.com|youtu\.be)[^\s]+)", re.IGNORECASE)
for text in candidates:
if not text:
continue
m = url_re.search(text)
if m:
song_link = m.group(1)
break
if song_link:
break
if song_link:
break
except Exception as e:
print(f"Error scanning history for embed song link: {e}")
try:
fresh_info = await song_loader.extract_info_async(song_link)
if not fresh_info or "url" not in fresh_info:
print(f"Failed to get fresh stream URL for autoplay {song_link}")
queue.playing = False
return
stream_url = fresh_info["url"]
source = await song_loader.preload_audio_source(stream_url)
except Exception as e:
print(f"Error creating audio source for autoplay: {e}")
queue.playing = False
return
try:
print("suggestions")
yt = YTMusic()
video_id_match = re.search(r"(?:v=|youtu\.be/)([\w-]{11})", song_link)
if not video_id_match:
print(f"Could not extract video ID from link: {song_link}")
return
video_id = video_id_match.group(1)
related_songs = yt.get_song_related(video_id)
suggestion = related_songs[0]["videoid"]
try:
webpage_url = f"https://www.youtube.com/watch?v={suggestion}"
fresh_info = await song_loader.extract_info_async(webpage_url)
if not fresh_info or "url" not in fresh_info:
print(f"Failed to get fresh stream URL for {webpage_url}")
queue.playing = False
await self.play_next(guild, voice_client, interaction)
return
stream_url = fresh_info["url"]
source = await song_loader.preload_audio_source(stream_url)
except Exception as e:
print(f"Error creating audio source: {e}")
queue.playing = False
await self.play_next(guild, voice_client, interaction)
return
queue.playing = True
def after_song(e):
if e:
print(f"Playback error: {e}")
queue.playing = False
pn = self.play_next(guild, voice_client, interaction)
asyncio.run_coroutine_threadsafe(pn, self.bot.loop)
try:
voice_client.play(source, after=after_song)
except Exception as e:
print(f"Error starting playback: {e}")
queue.playing = False
return
metadata = (
next_song_data['title'],
next_song_data['thumbnail'],
None,
next_song_data['duration'],
next_song_data['author'],
next_song_data['song_url'],
next_song_data['likes'],
next_song_data['views'],
next_song_data['upload_date']
)
embed = self.create_now_playing_embed(metadata, interaction)
try:
msg = await interaction.channel.send(embed=embed)
self.create_background_task(
self.update_progress(msg, embed, next_song_data['duration'])
)
except Exception as e:
print(f"Error sending now playing message: {e}")
except Exception as e:
print(f"Autoplay error: {e}")
else:
print("queue stopped")
queue.playing = False
def create_now_playing_embed(self, metadata, interaction):
title, thumbnail, _, duration, author, song_url, likes, views, upload_date = metadata
def format_time(seconds):
m, s = divmod(int(seconds), 60)
return f"{m:02}:{s:02}"
fields = [
("Artist", f"{author}", True),
("Duration", f"{format_time(duration)}", True),
("Link", f"{song_url}", True),
]
embed = self.make_embed(
title="Now playing",
description=title,
color=0x5865F2,
thumbnail=thumbnail,
author_name=f"Requested by {interaction.user.display_name}",
author_icon=safe_avatar(interaction.user),
footer="Use /skip to go to the next song",
footer_icon=safe_avatar(self.bot.user),
fields=[(n, f"```\n{v}\n```", True) for n, v, _ in fields]
)
return embed
async def update_progress(self, message, embed, duration):
try:
await asyncio.sleep(max(0, int(duration)))
embed.color = 0x95a5a6
embed.set_footer(text="Playback finished", icon_url=safe_avatar(self.bot.user))
await message.edit(embed=embed)
except (discord.HTTPException, asyncio.CancelledError):
pass
def format_time(self, seconds):
m, s = divmod(int(seconds), 60)
return f"{m:02}:{s:02}"
async def process_single_entry(self, entry: dict):
try:
if not entry or "url" not in entry:
print(f"Error processing entry: Missing 'url' key")
return None
return {
'entry_data': entry,
'title': entry.get("title", "Unknown title"),
'thumbnail': entry.get("thumbnail"),
'duration': entry.get("duration", 0),
'author': entry.get("uploader", "Unknown author"),
'song_url': entry.get("webpage_url", "Unknown URL"),
'likes': entry.get("like_count", 0),
'views': entry.get("view_count", 0),
'upload_date': entry.get("upload_date", "Unknown date")
}
except Exception as e:
print(f"Error processing entry: {e}")
return None
async def process_song_entries(self, entries: List[dict], guild_id: int):
if guild_id not in guild_queues:
guild_queues[guild_id] = OptimizedQueue()
queue = guild_queues[guild_id]
processed_songs = []
batch_size = 5
for i in range(0, len(entries), batch_size):
batch = entries[i:i + batch_size]
tasks = []
for entry in batch:
if entry:
tasks.append(self.process_single_entry(entry))
if tasks:
results = await asyncio.gather(*tasks, return_exceptions=True)
for result in results:
if isinstance(result, Exception) or not result:
continue
processed_songs.append(result)
queue.add(result)
return processed_songs
@app_commands.command(name="chart", description="Plays a random song from the YouTube Music charts")
async def play_chart(self, interaction: discord.Interaction):
if await self.check_timeout_decorator(interaction):
return
else:
await interaction.response.defer()
loading_embed = self.make_embed(
title="Loading chart",
description="Fetching popular songs...",
color=0x3498db,
)
loading_message = await interaction.followup.send(embed=loading_embed)
try:
chart_urls = [
"https://music.youtube.com/playlist?list=RDCLAK5uy_kmPRjHDECIcuVwnKsx5w4UBCp9jSEMzM",
"https://music.youtube.com/playlist?list=RDCLAK5uy_k8jhb5wP3rUqLOWFzVQNE_YdIcF7O4BN",
"https://www.youtube.com/playlist?list=PLFgquLnL59alCl_2TQvOiD5Vgm1hCaGSI",
]
playlist_opts = {
'quiet': True,
'no_warnings': True,
'extract_flat': True,
'playlist_items': '1-20',
}
trending_songs = []
for chart_url in chart_urls:
try:
def extract_playlist_info():
with yt_dlp.YoutubeDL(playlist_opts) as ydl:
return ydl.extract_info(chart_url, download=False)
chart_info = await asyncio.get_running_loop().run_in_executor(
song_loader.executor, extract_playlist_info
)
if "entries" in chart_info and chart_info["entries"]:
for entry in chart_info["entries"][:15]:
if entry and entry.get("title"):
title = entry["title"]
uploader = entry.get("uploader", "")
if uploader and uploader.lower() not in title.lower():
song_query = f"{title} {uploader}"
else:
song_query = title
trending_songs.append(song_query)
if trending_songs:
break
except Exception as e:
print(f"Fehler beim Laden der Playlist {chart_url}: {e}")
continue
if not trending_songs:
try:
search_queries = [
"ytsearch5:music charts 2024",
"ytsearch5:trending music now",
"ytsearch5:top songs 2024"
]
for search_query in search_queries:
try:
search_results = await song_loader.extract_info_async(search_query)
if "entries" in search_results:
for entry in search_results["entries"][:5]:
if entry and entry.get("title"):
title = entry["title"]
uploader = entry.get("uploader", "")
if uploader and uploader.lower() not in title.lower():
song_query = f"{title} {uploader}"
else:
song_query = title
trending_songs.append(song_query)
if trending_songs:
break
except Exception as e:
print(f"Fehler bei der Suche {search_query}: {e}")
continue
except Exception as e:
print(f"Fehler bei der Fallback-Suche: {e}")
if not trending_songs:
trending_songs = [
"Flowers Miley Cyrus",
"As It Was Harry Styles",
"Bad Habit Steve Lacy",
"About Damn Time Lizzo",
"Heat Waves Glass Animals",
"Stay The Kid LAROI Justin Bieber",
"Ghost Justin Bieber",
"Industry Baby Lil Nas X",
"Good 4 U Olivia Rodrigo",
"Levitating Dua Lipa"
]
random_chart_song = random.choice(trending_songs)
loading_embed = self.make_embed(
title="Loading chart",
description=f"Selected: {random_chart_song}\nPreparing...",
color=0x3498db,
)
await loading_message.edit(embed=loading_embed)
except Exception as e:
print(f"Fehler beim Abrufen der Charts: {e}")
fallback_songs = [
"Flowers Miley Cyrus",
"As It Was Harry Styles",
"Bad Habit Steve Lacy",
"About Damn Time Lizzo",
"Heat Waves Glass Animals"
]
random_chart_song = random.choice(fallback_songs)
loading_embed = self.make_embed(
title="Loading chart (fallback)",
description=f"Selected: {random_chart_song}\nPreparing...",
color=0xe67e22,
)
await loading_message.edit(embed=loading_embed)
search_query = f"ytsearch:{random_chart_song}"
try:
info = await song_loader.extract_info_async(search_query)
except Exception as e:
error_embed = self.make_embed(
title="Error",
description=f"Failed to load chart song.\n\n{e}",
color=0xe74c3c
)
await interaction.followup.send(embed=error_embed, ephemeral=True)
return
if interaction.guild.id not in guild_queues:
guild_queues[interaction.guild.id] = OptimizedQueue()
queue = guild_queues[interaction.guild.id]
entry = info["entries"][0] if "entries" in info and info["entries"] else info
processed_song = await self.process_single_entry(entry)
if processed_song:
queue.add(processed_song)
title = processed_song['title']
thumbnail = processed_song['thumbnail']
success_embed = self.make_embed(
title="Added to queue",
description=title,
color=0x2ecc71,
thumbnail=thumbnail,
fields=[
("Position", f"```\n#{len(queue.queue)}\n```", True)
]
)
await interaction.channel.send(embed=success_embed)
try:
await loading_message.delete()
except Exception:
pass
if not interaction.user.voice:
await interaction.followup.send(
embed=self.make_embed(
title="Voice channel required",
description="Join a voice channel and try again.",
color=0xe74c3c
),
ephemeral=True
)
return
voice_client = interaction.guild.voice_client
if not voice_client or not voice_client.is_connected():
channel = interaction.user.voice.channel
await channel.connect(self_deaf=True)
voice_client = interaction.guild.voice_client
voice_channel = voice_client.channel
if SET_VC_STATUS_TO_MUSIC_PLAYING:
current_song = (queue.peek()['title'] if queue.peek() else "Music")
try:
await voice_channel.edit(status=f"Listening to: {current_song}")
except Exception:
pass
if voice_client and voice_client.channel and interaction.user.voice.channel != voice_client.channel:
await interaction.followup.send(
embed=self.make_embed(
title="Wrong voice channel",
description="You must be in the same voice channel as the bot.",
color=0xe74c3c
),
ephemeral=True
)
else:
if not queue.playing and not voice_client.is_playing() and not queue.is_empty():
await self.play_next(guild=interaction.guild, voice_client=voice_client, interaction=interaction)
async def insipre_me(self, interaction: discord.Interaction):
if await self.check_timeout_decorator(interaction):
return
else:
await interaction.response.defer()
random_songs = [
"Never Gonna Give You Up Rick Astley",
"Bohemian Rhapsody Queen",
"Imagine Dragons Believer",
"The Weeknd Blinding Lights",
"Dua Lipa Levitating",
"Ed Sheeran Shape of You",
"Billie Eilish bad guy",
"Post Malone Circles",
"Ariana Grande 7 rings",
"Drake God's Plan",
"Taylor Swift Anti-Hero",
"Harry Styles As It Was",
"Olivia Rodrigo good 4 u",
"Doja Cat Kiss Me More",
"The Kid LAROI Stay",
"Lil Nas X Industry Baby",
"Glass Animals Heat Waves",
"Måneskin Beggin",
"Adele Easy On Me",
"Bruno Mars Uptown Funk",
"Queen Don't Stop Me Now",
"Journey Don't Stop Believin'",
"Michael Jackson Billie Jean",
"A-ha Take On Me",
"Whitney Houston I Wanna Dance with Somebody (Who Loves Me)",
"Toto Africa",
"Eurythmics Sweet Dreams (Are Made of This)",
"Guns N' Roses Sweet Child O' Mine",
"AC/DC Back In Black",
"Nirvana Smells Like Teen Spirit",
"The Police Every Breath You Take",
"Linkin Park In The End",
"The Killers Mr. Brightside",
"Arctic Monkeys Do I Wanna Know?",
"Coldplay Viva La Vida",
"Coldplay Yellow",
"OneRepublic Counting Stars",
"Lewis Capaldi Someone You Loved",
"James Arthur Say You Won't Let Go",
"Shawn Mendes Señorita",
"Miley Cyrus Flowers",
"SZA Kill Bill",
"Jung Kook Seven",
"Elton John Cold Heart",
"The Neighbourhood Sweater Weather",
"Hozier Take Me to Church",
"Lord Huron The Night We Met",
"Vance Joy Riptide",
"Tones And I Dance Monkey",
"Post Malone Rockstar",
"The Chainsmokers Closer",
"Justin Bieber Sorry",
"Shawn Mendes Treat You Better",
"Khalid Better",
"Cardi B WAP"
]
random_song = random.choice(random_songs)
loading_embed = self.make_embed(
title="Loading",
description=f"Selected: {random_song}\nPreparing...",
color=0x9b59b6
)
loading_message = await interaction.followup.send(embed=loading_embed)
search_query = f"ytsearch:{random_song}"
try:
info = await song_loader.extract_info_async(search_query)
except Exception as e:
await interaction.followup.send(
embed=self.make_embed(
title="Error",
description=f"Failed to load song.\n\n{e}",
color=0xe74c3c
),
ephemeral=True
)
return
if interaction.guild.id not in guild_queues:
guild_queues[interaction.guild.id] = OptimizedQueue()
queue = guild_queues[interaction.guild.id]
entry = info["entries"][0] if "entries" in info and info["entries"] else info
processed_song = await self.process_single_entry(entry)
if processed_song:
queue.add(processed_song)
title = processed_song['title']
thumbnail = processed_song['thumbnail']
success_embed = self.make_embed(
title="Added to queue",
description=title,
color=0x9b59b6,
thumbnail=thumbnail,
fields=[
("Position", f"```\n#{len(queue.queue)}\n```", True)
]
)
await interaction.channel.send(embed=success_embed)
try:
await loading_message.delete()
except Exception:
pass
if not interaction.user.voice:
await interaction.followup.send(
embed=self.make_embed(
title="Voice channel required",
description="Join a voice channel and try again.",
color=0xe74c3c
),
ephemeral=True
)
return
voice_client = interaction.guild.voice_client
if not voice_client or not voice_client.is_connected():
channel = interaction.user.voice.channel
await channel.connect(self_deaf=True)
voice_client = interaction.guild.voice_client
voice_channel = voice_client.channel
if SET_VC_STATUS_TO_MUSIC_PLAYING:
current_song = (queue.peek()['title'] if queue.peek() else "Music")
try:
await voice_channel.edit(status=f"Listening to: {current_song}")
except Exception:
pass
if voice_client and voice_client.channel and interaction.user.voice.channel != voice_client.channel:
await interaction.followup.send(
embed=self.make_embed(
title="Wrong voice channel",
description="You must be in the same voice channel as the bot.",
color=0xe74c3c
),
ephemeral=True
)
else:
if not queue.playing and not voice_client.is_playing() and not queue.is_empty():
await self.play_next(guild=interaction.guild, voice_client=voice_client, interaction=interaction)
async def mostplayed_callback(self, interaction: discord.Interaction, song: str):
await interaction.response.defer()
loading_embed = self.make_embed(
title="Loading",
description=f"Selected: {song}\nPreparing...",
color=0x3498db
)
loading_message = await interaction.followup.send(embed=loading_embed)
search_query = f"ytsearch:{song}"
try:
info = await song_loader.extract_info_async(search_query)
except Exception as e:
await interaction.followup.send(
embed=self.make_embed(
title="Error",
description=f"Failed to load song.\n\n{e}",
color=0xe74c3c
),
ephemeral=True
)
return
if interaction.guild.id not in guild_queues:
guild_queues[interaction.guild.id] = OptimizedQueue()
queue = guild_queues[interaction.guild.id]
entry = info["entries"][0] if "entries" in info and info["entries"] else info
processed_song = await self.process_single_entry(entry)
if processed_song:
queue.add(processed_song)
title = processed_song['title']
thumbnail = processed_song['thumbnail']
success_embed = self.make_embed(
title="Added to queue",
description=title,
color=0xf39c12,
thumbnail=thumbnail,
fields=[
("Position", f"```\n#{len(queue.queue)}\n```", True)
]
)
await interaction.channel.send(embed=success_embed)
try:
await loading_message.delete()
except Exception:
pass
if not interaction.user.voice:
await interaction.followup.send(
embed=self.make_embed(
title="Voice channel required",
description="Join a voice channel and try again.",
color=0xe74c3c
),
ephemeral=True
)
return
voice_client = interaction.guild.voice_client
if not voice_client or not voice_client.is_connected():
channel = interaction.user.voice.channel
await channel.connect(self_deaf=True)
voice_client = interaction.guild.voice_client
voice_channel = voice_client.channel
if SET_VC_STATUS_TO_MUSIC_PLAYING:
current_song = (queue.peek()['title'] if queue.peek() else "Music")
try:
await voice_channel.edit(status=f"Listening to: {current_song}")
except Exception:
pass
if voice_client and voice_client.channel and interaction.user.voice.channel != voice_client.channel:
await interaction.followup.send(
embed=self.make_embed(
title="Wrong voice channel",
description="You must be in the same voice channel as the bot.",
color=0xe74c3c
),
ephemeral=True
)
else:
if not queue.playing and not voice_client.is_playing() and not queue.is_empty():
await self.play_next(guild=interaction.guild, voice_client=voice_client, interaction=interaction)
@app_commands.command(name="play", description="Plays music")
@app_commands.describe(song="URL or search term")
async def play(self, interaction: discord.Interaction, song: str):
if await self.check_timeout_decorator(interaction):
return
else:
try:
await interaction.response.defer()
except:
pass
if interaction.guild.id not in guild_queues:
guild_queues[interaction.guild.id] = OptimizedQueue()
queue = guild_queues[interaction.guild.id]
voice_client = interaction.guild.voice_client
if voice_client and voice_client.channel and interaction.user.voice and interaction.user.voice.channel != voice_client.channel:
await interaction.followup.send(
embed=self.make_embed(
title="Wrong voice channel",
description="You must be in the same voice channel as the bot.",
color=0xe74c3c
),
ephemeral=True
)
return
if not interaction.user.voice:
await interaction.followup.send(
embed=self.make_embed(
title="Voice channel required",
description="Join a voice channel and try again.",
color=0xe74c3c
),
ephemeral=True
)
return
loading_embed = self.make_embed(
title="Loading",
description=f"Searching for: {song}",
color=0x3498db
)
loading_message = await interaction.followup.send(embed=loading_embed)
search_query = song if song.startswith("http") else f"ytsearch:{song}"
try:
info = await song_loader.extract_info_async(search_query)
except Exception as e:
await interaction.followup.send(
embed=self.make_embed(
title="Error",
description=f"Failed to load video/playlist.\n\n{e}",
color=0xe74c3c
),
ephemeral=True
)
return
processing_message = None
if "entries" in info:
entries = [e for e in info["entries"] if e]
processing_embed = self.make_embed(
title="Processing playlist",
description=f"Found {len(entries)} items.\nAdding to queue...",
color=0xf39c12
)
processing_message = await interaction.channel.send(embed=processing_embed)
processed_songs = await self.process_song_entries(entries, interaction.guild.id)
titles_list = "\n".join([f"- {song['title']}" for song in processed_songs[:10]])
if len(processed_songs) > 10:
titles_list += f"\n\n...and {len(processed_songs) - 10} more."
initial_len = max(0, len(queue.queue) - len(processed_songs))
wait_seconds = sum(song['duration'] for song in queue.queue[:initial_len]) if initial_len > 0 else 0
success_embed = self.make_embed(
title="Playlist added",
description=f"{len(processed_songs)} songs added to queue.\n\n{titles_list}",
color=0x2ecc71,
thumbnail=(entries[0].get("thumbnail") if entries else None),
fields=[
("Position", f"```\n#{initial_len + 1}\n```", True),
("Estimated time", f"```\n{self.format_time(wait_seconds)}\n```", True),
]
)
await interaction.channel.send(embed=success_embed)
else:
processed_song = await self.process_single_entry(info)
if processed_song:
queue.add(processed_song)
title = processed_song['title']
thumbnail = processed_song['thumbnail']
duration = processed_song['duration']
success_embed = self.make_embed(
title="Added to queue",