-
Notifications
You must be signed in to change notification settings - Fork 2
/
music.py
986 lines (786 loc) · 46.4 KB
/
music.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
import random
import discord
from discord.ext import commands, tasks
import datetime
from discord.ui import Button, View
import wavelink
from wavelink.enums import TrackSource
from utils import Paginator, DescriptionEmbedPaginator
from core import Cog, Olympus, Context
from PIL import Image, ImageDraw, ImageFont, ImageOps
import io
import aiohttp
from typing import cast
import asyncio
from utils.Tools import *
track_histories = {}
import base64
import asyncio
import re
SPOTIFY_TRACK_REGEX = r"https?://open\.spotify\.com/track/([a-zA-Z0-9]+)"
SPOTIFY_PLAYLIST_REGEX = r"https?://open\.spotify\.com/playlist/([a-zA-Z0-9]+)"
SPOTIFY_ALBUM_REGEX = r"https?://open\.spotify\.com/album/([a-zA-Z0-9]+)"
class SpotifyAPI:
BASE_URL = "https://api.spotify.com/v1"
def __init__(self, client_id, client_secret):
self.client_id = client_id
self.client_secret = client_secret
self.token = None
async def get_token(self):
auth_url = "https://accounts.spotify.com/api/token"
auth_value = base64.b64encode(f"{self.client_id}:{self.client_secret}".encode('utf-8')).decode('utf-8')
headers = {"Authorization": f"Basic {auth_value}"}
data = {"grant_type": "client_credentials"}
async with aiohttp.ClientSession() as session:
async with session.post(auth_url, headers=headers, data=data) as response:
text = await response.text()
if response.status != 200:
raise Exception(f"Failed to fetch token: {response.status}, response: {text}")
self.token = (await response.json()).get("access_token")
async def get(self, endpoint, params=None):
retries = 2
for attempt in range(retries):
if not self.token or attempt > 0:
await self.get_token()
url = f"{self.BASE_URL}/{endpoint}"
headers = {"Authorization": f"Bearer {self.token}"}
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers, params=params) as response:
if response.status == 401 and attempt < retries - 1:
continue
elif response.status != 200:
raise Exception(f"Failed to fetch data from Spotify: {response.status}")
return await response.json()
raise Exception("Exceeded max retries to fetch Spotify data")
async def get_track(self, track_id):
return await self.get(f"tracks/{track_id}")
async def get_playlist(self, playlist_id):
return await self.get(f"playlists/{playlist_id}")
spotify_api = SpotifyAPI(client_id="ac2b614ca5ce46a18dfd1d3475fd6fd9", client_secret="df7bec95ae88438e8286db597bac8621")
class PlatformSelectView(View):
def __init__(self, ctx, query):
super().__init__(timeout=60)
self.ctx = ctx
self.query = query
platforms = [
("YouTube", "ytsearch", discord.ButtonStyle.red),
("JioSaavn", "jssearch", discord.ButtonStyle.green),
("SoundCloud", "scsearch", discord.ButtonStyle.grey),
]
for name, source, style in platforms:
button = Button(label=name, style=style)
button.callback = self.create_callback(source)
self.add_item(button)
def create_callback(self, source):
async def callback(interaction: discord.Interaction):
if interaction.user != self.ctx.author:
await interaction.response.send_message("Only the command author can select a platform.", ephemeral=True)
return
await interaction.response.send_message(f"Searching on {interaction.data['custom_id']}...", ephemeral=True)
await self.perform_search(source)
await interaction.message.delete()
return callback
async def perform_search(self, source):
results = await wavelink.Playable.search(self.query, source=source)
if not results:
return await self.ctx.send(embed=discord.Embed(description="No results found.", color=0xFF0000))
top_results = results[:5]
embed = discord.Embed(
title=f"Top 5 Results for '{self.query}' ({source})",
color=0x1DB954
)
for i, track in enumerate(top_results, start=1):
embed.add_field(name=f"{i}. {track.title}", value=f"Duration: {track.length // 1000 // 60}:{track.length // 1000 % 60} | [Link]({track.uri})", inline=False)
await self.ctx.send(embed=embed, view=SearchResultView(self.ctx, top_results))
class SearchResultView(View):
def __init__(self, ctx, results):
super().__init__(timeout=60)
self.ctx = ctx
self.results = results
for i in range(5):
button = Button(label=str(i + 1), style=discord.ButtonStyle.primary)
button.callback = self.create_callback(i)
self.add_item(button)
def create_callback(self, index):
async def callback(interaction: discord.Interaction):
if interaction.user != self.ctx.author:
await interaction.response.send_message("Only the command author can select a track.", ephemeral=True)
return
track = self.results[index]
vc = self.ctx.voice_client or await self.ctx.author.voice.channel.connect(cls=wavelink.Player)
vc.ctx = self.ctx
if not vc.playing:
await vc.play(track)
await interaction.response.send_message(f"Started playing `{track.title}`.")
await self.ctx.cog.display_player_embed(vc, track, self.ctx)
else:
await vc.queue.put_wait(track)
await interaction.response.send_message(f"Added `{track.title}` to the queue.")
return callback
class MusicControlView(View):
def __init__(self, player, ctx):
super().__init__(timeout=None)
self.player = player
self.ctx = ctx
async def interaction_check(self, interaction: discord.Interaction) -> bool:
if not self.ctx.voice_client or not self.player.playing:
await interaction.response.send_message("I'm not currently playing this anymore.", ephemeral=True)
return False
if interaction.user in self.ctx.voice_client.channel.members:
return True
await interaction.response.send_message(
embed=discord.Embed(description="Only members in the same voice channel as me can control the player.", color=0x000000),
ephemeral=True
)
return False
@discord.ui.button(emoji="<:o_autoplay:1302170665670934549>", style=discord.ButtonStyle.secondary)
async def autoplay_button(self, interaction: discord.Interaction, button: Button):
self.player.autoplay = (
wavelink.AutoPlayMode.enabled if self.player.autoplay != wavelink.AutoPlayMode.enabled else wavelink.AutoPlayMode.disabled
)
await interaction.response.send_message(f"Autoplay {'enabled' if self.player.autoplay == wavelink.AutoPlayMode.enabled else 'disabled'} by **{interaction.user.display_name}**.")
@discord.ui.button(emoji="<:o_previous:1303944619800662137>", style=discord.ButtonStyle.secondary)
async def previous_button(self, interaction: discord.Interaction, button: Button):
guild_id = interaction.guild.id
if guild_id in track_histories and len(track_histories[guild_id]) > 1:
track_histories[guild_id].pop()
previous_track = track_histories[guild_id][-1]
player = self.player
vc = self.ctx.voice_client
if player.playing:
await player.stop()
await vc.queue.put_wait(previous_track)
await interaction.response.send_message(f"Playing previous track: `{previous_track.title}`.")
else:
await interaction.response.send_message("No previous track available.", ephemeral=True)
@discord.ui.button(emoji="<:o_pause:1302172935951351821>", style=discord.ButtonStyle.success)
async def pause_button(self, interaction: discord.Interaction, button: Button):
if self.player.paused:
await self.player.pause(False)
await self.player.channel.edit(status=f"<:gvMusic:1213831433219481722> Playing: {self.player.current.title}")
button.emoji = "<:o_pause:1302172935951351821>"
await interaction.response.edit_message(view=self)
elif self.player.playing:
await self.player.pause(True)
await self.player.channel.edit(status=f"<:gvMusic:1213831433219481722> Paused: {self.player.current.title}")
button.emoji = "<:o_resume:1302173145980997712>"
await interaction.response.edit_message(view=self)
@discord.ui.button(emoji="<:o_skip:1303944716605198336>", style=discord.ButtonStyle.secondary)
async def skip_button(self, interaction: discord.Interaction, button: Button):
if self.player.autoplay == wavelink.AutoPlayMode.enabled:
await self.player.stop()
return await interaction.response.send_message(f"Skipped song by **{interaction.user.display_name}**.")
#await self.player.play(await self.player.queue.get_next_track())
if self.player and self.player.playing and not self.player.queue.is_empty:
await self.player.stop()
await interaction.response.send_message(f"Skipped song by **{interaction.user.display_name}**.")
else:
await interaction.response.send_message("No song in queue to skip.", ephemeral=True)
@discord.ui.button(emoji="<:o_loop:1302170497546715231>", style=discord.ButtonStyle.secondary)
async def loop_button(self, interaction: discord.Interaction, button: Button):
self.player.queue.mode = wavelink.QueueMode.loop if self.player.queue.mode != wavelink.QueueMode.loop else wavelink.QueueMode.normal
await interaction.response.send_message(f"Loop {'enabled' if self.player.queue.mode == wavelink.QueueMode.loop else 'disabled'} by **{interaction.user.display_name}**.")
@discord.ui.button(emoji="<:o_shuffle:1302173399900229633>", style=discord.ButtonStyle.secondary)
async def shuffle_button(self, interaction: discord.Interaction, button: Button):
if self.player.queue:
random.shuffle(self.player.queue)
await interaction.response.send_message(f"Queue shuffled by **{interaction.user.display_name}**.")
else:
await interaction.response.send_message("Queue is empty.", ephemeral=True)
@discord.ui.button(emoji="<:o_rewind:1302173207440261171>", style=discord.ButtonStyle.secondary)
async def rewind_button(self, interaction: discord.Interaction, button: Button):
if self.player.playing:
new_position = max(self.player.position - 10000, 0)
await self.player.seek(new_position)
await interaction.response.send_message("Rewinded 10 seconds.", ephemeral=True)
else:
await interaction.response.send_message("No track is currently playing.", ephemeral=True)
@discord.ui.button(emoji="<:o_pause:1303946981500125205>", style=discord.ButtonStyle.secondary)
async def stop_button(self, interaction: discord.Interaction, button: Button):
if self.player:
voice_channel = self.player.channel
if voice_channel:
await voice_channel.edit(status=None)
await self.player.disconnect()
await interaction.response.send_message(f"Stopped and disconnected by **{interaction.user.display_name}**.")
else:
await interaction.response.send_message("Not connected.", ephemeral=True)
@discord.ui.button(emoji="<:o_forward:1302173256085671976>", style=discord.ButtonStyle.secondary)
async def forward_button(self, interaction: discord.Interaction, button: Button):
if self.player.playing:
new_position = min(self.player.position + 10000, self.player.current.length)
await self.player.seek(new_position)
await interaction.response.send_message("Forwarded 10 seconds.", ephemeral=True)
else:
await interaction.response.send_message("No track is currently playing.", ephemeral=True)
@discord.ui.button(emoji="<:o_replay:1302173332312952873>", style=discord.ButtonStyle.secondary)
async def replay_button(self, interaction: discord.Interaction, button: Button):
if self.player.playing:
await self.player.seek(0)
await interaction.response.send_message("Replaying the current track.", ephemeral=True)
else:
await interaction.response.send_message("No track is currently playing.", ephemeral=True)
class Music(commands.Cog):
def __init__(self, client: Olympus):
self.client = client
self.client.loop.create_task(self.connect_nodes())
self.client.loop.create_task(self.monitor_inactivity())
self.inactivity_timeout = 120
self.player_inactivity = {}
async def monitor_inactivity(self):
while True:
for guild in self.client.guilds:
await self.check_inactivity(guild.id)
await asyncio.sleep(60)
async def check_inactivity(self, guild_id):
guild = self.client.get_guild(guild_id)
if not guild:
return
player = None
for vc in self.client.voice_clients:
if vc.guild.id == guild.id:
player = vc
break
if player and player.playing and len(player.channel.members) == 1:
await self.inactivity_timer(guild)
async def inactivity_timer(self, guild):
await asyncio.sleep(self.inactivity_timeout)
if len(guild.voice_channels[0].members) == 1:
player = None
for vc in self.client.voice_clients:
if vc.guild.id == guild.id:
player = vc
break
if player:
await player.disconnect(force=True)
try:
ended = discord.Embed(description="Bot has been disconnected due to inactivity (being idle in Voice Channel) for more than 2 minutes." , color=0xFF0000)
ended.set_author(name="Inactive Timeout", icon_url=self.client.user.avatar.url)
ended.set_footer(text="Thanks for choosing Olympus!")
support = Button(label='Support',
style=discord.ButtonStyle.link,
url=f'https://discord.gg/odx')
vote = Button(label='Vote',
style=discord.ButtonStyle.link,
url=f'https://top.gg/bot/1144179659735572640/vote')
view = View()
view.add_item(support)
view.add_item(vote)
await player.ctx.channel.send(embed=ended, view=view)
except:
pass
async def connect_nodes(self) -> None:
nodes = [wavelink.Node(uri="http://45.89.99.118:8000/", password="winkle@team")]
await wavelink.Pool.connect(nodes=nodes, client=self.client, cache_capacity=None)
async def display_player_embed(self, player, track, ctx, autoplay=False):
if track.artwork:
template_path = 'data/pictures/player.png'
font_path = 'utils/arial.ttf'
font = ImageFont.truetype(font_path, 40)
base_img = Image.open(template_path).convert("RGBA")
async with aiohttp.ClientSession() as session:
async with session.get(track.artwork) as resp:
if resp.status == 200:
track_img_data = io.BytesIO(await resp.read())
track_img = Image.open(track_img_data).convert("RGBA")
track_img = ImageOps.fit(track_img, (220, 220), centering=(0.5, 0.5))
mask = Image.new('L', (220, 220), 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0, 220, 220), fill=255)
track_img.putalpha(mask)
base_img.paste(track_img, (15, 125 - 85), track_img)
draw = ImageDraw.Draw(base_img)
draw.text((240, 50), track.title, font=font, fill="white")
image_bytes = io.BytesIO()
base_img.save(image_bytes, format="PNG")
image_bytes.seek(0)
file = discord.File(image_bytes, filename="player.png")
sec = track.length // 1000
duration= f"0{sec // 60}:{sec % 60}" if sec < 600 else f"{sec // 60}:{sec % 60}"
embed = discord.Embed(title=f"**{track.title}**",
color=0x1DB954 if "spotify" in track.source else 0x00E6A7 if "jiosaavn" in track.source else 0xFF0000 if "youtube" in track.source else 0xFF5500
)
#embed.set_author(name="Now Playing", icon_url="https://cdn.discordapp.com/emojis/1275556609958875218.gif")
embed.add_field(name="Author", value=f"`{track.author}`")
embed.add_field(name="Duration", value=f"`{duration}`")
embed.add_field(name="Source", value=f"[<:olympus_spotify:1247724797983719464> Listen on Spotify]({track.uri})" if "spotify" in track.source else f"[<:jiosaavn:1306976886047375430> Listen on JioSaavn]({track.uri})" if "jiosaavn" in track.source else f"[<:SoundCloud:1307002774738829413> Listen on SoundCloud]({track.uri})" if "soundcloud" in track.source else f"[<:youtube:1204225318295052371> Listen on YouTube]({track.uri})")
embed.set_image(url="attachment://player.png")
embed.set_footer(text="Requested by " + (ctx.author.display_name if not autoplay else f"{ctx.author.display_name} (Autoplay Mode)"), icon_url=ctx.author.avatar.url if ctx.author.avatar else ctx.author.default_avatar.url)
await ctx.send(embed=embed, file=file, view=MusicControlView(player, ctx))
else:
await ctx.send(embed=discord.Embed(description="Track has no artwork."), ephemeral=True)
async def on_track_end(self, payload: wavelink.TrackEndEventPayload):
player = payload.player
if not player.queue:
if player.queue.mode == wavelink.QueueMode.loop:
await player.play(payload.track)
#await self.display_player_embed(player, payload.track, player.ctx)
elif player.autoplay == wavelink.AutoPlayMode.enabled:
await asyncio.sleep(5)
if player.current:
await self.display_player_embed(player, player.current, player.ctx, autoplay=True)
else:
player.ctx.send("No suitable track found for autoplay.")
else:
await player.disconnect()
ended = discord.Embed(description="All tracks have been played, leaving the voice channel." , color=0xFF0000)
ended.set_author(name="Queue Ended", icon_url=self.client.user.avatar.url)
support = Button(label='Support',
style=discord.ButtonStyle.link,
url=f'https://discord.gg/odx')
vote = Button(label='Vote',
style=discord.ButtonStyle.link,
url=f'https://top.gg/bot/1144179659735572640/vote')
view = View()
view.add_item(support)
view.add_item(vote)
await player.ctx.send(embed=ended, view=view)
else:
next_track = await player.queue.get_wait()
await player.play(next_track)
await self.display_player_embed(player, next_track, player.ctx)
async def play_source(self, ctx, query):
if not ctx.author.voice:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> You need to be in a voice channel to use this command.", color=0x000000))
return
vc = ctx.voice_client or await ctx.author.voice.channel.connect(cls=wavelink.Player)
vc.ctx = ctx
if vc.playing:
if ctx.voice_client and ctx.voice_client.channel != ctx.author.voice.channel:
await ctx.send(embed=discord.Embed(description=f"You must be connected to {ctx.voice_client.channel.mention} to play.", color=0x000000))
return
vc.autoplay = wavelink.AutoPlayMode.disabled
"""if re.match(SPOTIFY_TRACK_REGEX, query):
await self.handle_spotify_link(ctx, vc, query, "track")
elif re.match(SPOTIFY_PLAYLIST_REGEX, query):
await self.handle_spotify_link(ctx, vc, query, "playlist")
elif re.match(SPOTIFY_ALBUM_REGEX, query):
await self.handle_spotify_link(ctx, vc, query, "album")
return"""
tracks = await wavelink.Playable.search(query)
if not tracks:
await ctx.send(embed=discord.Embed(description="No results found.", color=0x000000))
return
if isinstance(tracks, wavelink.Playlist):
await vc.queue.put_wait(tracks.tracks)
await ctx.send(embed=discord.Embed(description=f"<:add_white:1205381455505661952> Added playlist [{tracks.name}](https://discord.gg/odx) with **{len(tracks.tracks)} songs** to the queue.", color=0x000000))
if not vc.playing:
track = await vc.queue.get_wait()
await vc.play(track)
await self.display_player_embed(vc, track, ctx)
else:
track = tracks[0]
await vc.queue.put_wait(track)
await ctx.send(embed=discord.Embed(description=f"<:add_white:1205381455505661952> Added [{track.title}](https://discord.gg/odx) to the queue.", color=0x000000))
if not vc.playing:
await vc.play(await vc.queue.get_wait())
await self.display_player_embed(vc, track, ctx)
self.client.loop.create_task(self.check_inactivity(ctx.guild.id))
# await interaction.response.defer()
async def handle_spotify_link(self, ctx, vc, link, type_):
try:
if type_ == "track":
track_id = re.search(SPOTIFY_TRACK_REGEX, link).group(1)
track_info = await spotify_api.get_track(track_id)
title = track_info['name']
author = ', '.join(artist['name'] for artist in track_info['artists'])
search_query = f"{title} by {author}"
search_results = await wavelink.Playable.search(search_query, source=wavelink.enums.TrackSource.YouTube)
if not search_results:
await ctx.send("Can't play this track from Spotify, please try with another track.")
return
track = search_results[0]
await vc.queue.put_wait(track)
await ctx.send(embed=discord.Embed(description=f"<:add_white:1205381455505661952> Added [{track.title}](https://discord.gg/odx) to the queue.", color=0x000000))
if not vc.playing:
await vc.play(track)
await self.display_player_embed(vc, track, ctx)
#await self.display_player_embed(vc, track, ctx)
elif type_ == "playlist":
lmao = await ctx.send("⏳ Processing to add tracks from the playlist, this may take a while...")
playlist_id = re.search(SPOTIFY_PLAYLIST_REGEX, link).group(1)
playlist_info = await spotify_api.get(f"playlists/{playlist_id}")
tracks = playlist_info.get("tracks", {}).get("items", [])
playlist_length = len(tracks)
if not tracks:
await ctx.send("No tracks found in the playlist.")
return
c = 0
for track in tracks:
title = track['track']['name']
author = ', '.join(artist['name'] for artist in track['track']['artists'])
search_query = f"{title} {author}"
track_results = await wavelink.Playable.search(search_query, source=wavelink.enums.TrackSource.YouTube)
if track_results:
await vc.queue.put_wait(track_results[0])
c += 1
await ctx.message.add_reaction("✅")
await ctx.send(embed=discord.Embed(description=f"<:add_white:1205381455505661952> Added **{c}** of **{playlist_length}** tracks from **playlist** **[{playlist_info['name']}](https://discord.gg/odx)** to the queue.", color=0x000000))
await lmao.delete()
if not vc.playing:
next_track = await vc.queue.get_wait()
await vc.play(next_track)
await self.display_player_embed(vc, next_track, ctx)
elif type_ == "album":
await ctx.message.add_reaction("⌛")
album_id = re.search(SPOTIFY_ALBUM_REGEX, link).group(1)
album_info = await spotify_api.get(f"albums/{album_id}")
tracks = album_info.get("tracks", {}).get("items", [])
if not tracks:
await ctx.send("No tracks found in the album.")
return
for track in tracks:
title = track['name']
author = ', '.join(artist['name'] for artist in track['artists'])
search_query = f"{title} {author}"
track_results = await wavelink.Playable.search(search_query, source=wavelink.enums.TrackSource.YouTube)
if track_results:
await vc.queue.put_wait(track_results[0])
await ctx.send(embed=discord.Embed(description=f"<:add_white:1205381455505661952> Added all tracks from album **[{album_info['name']}](https://discord.gg/odx)** to the queue.", color=0x000000))
if not vc.playing:
next_track = await vc.queue.get_wait()
await vc.play(next_track)
await self.display_player_embed(vc, next_track, ctx)
except Exception as e:
await ctx.send(f"An error occurred while processing the Spotify link: {e}")
def create_progress_bar(self, completed, total, length=10):
filled_length = int(length * (completed / total))
bar = '█' * filled_length + '░' * (length - filled_length)
return bar
@commands.hybrid_command(name="play", aliases=['p'], usage="play <query>", help="Plays a song or playlist.")
@blacklist_check()
@ignore_check()
@commands.cooldown(1, 3, commands.BucketType.user)
async def play(self, ctx: commands.Context, *, query: str):
await self.play_source(ctx, query)
@commands.hybrid_command(name="search", usage="search <query>", help="Searches music from multiple platforms.")
@blacklist_check()
@ignore_check()
@commands.cooldown(1, 3, commands.BucketType.user)
async def search2(self, ctx: commands.Context, *, query: str):
if not ctx.author.voice:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> You need to be in a voice channel to use this command.", color=0x000000))
return
embed = discord.Embed(
title="Select a platform to search from:",
description="Click a button below to choose.",
color=0xff0000
)
await ctx.send(embed=embed, view=PlatformSelectView(ctx, query))
@commands.hybrid_command(name="nowplaying", aliases=["nop"], usage="nowplaying", help="Shows the info about current playing song.")
@blacklist_check()
@ignore_check()
@commands.cooldown(1, 3, commands.BucketType.user)
async def nowplaying(self, ctx: commands.Context):
vc = ctx.voice_client
if not vc or not vc.playing:
await ctx.send(embed=discord.Embed(description="No song is currently playing.", color=0xFF0000))
return
if not ctx.author.voice or ctx.author.voice.channel.id != vc.channel.id:
await ctx.send(embed=discord.Embed(description="You need to be in the same voice channel as me to use this command.", color=0xFF0000))
return
track = vc.current
position = vc.position / 1000
length = track.length / 1000
progress_bar = self.create_progress_bar(position, length, length=10)
position_str = f"{int(position // 60)}:{int(position % 60):02}"
length_str = f"{int(length // 60)}:{int(length % 60):02}"
queue_length = len(vc.queue) if vc.queue else 0
if "spotify" in track.uri:
source_name = "Spotify"
elif "youtube" in track.uri:
source_name = "YouTube"
elif "soundcloud" in track.uri:
source_name = "SoundCloud"
elif "jiosaavn" in track.uri:
source_name = "JioSaavn"
else:
source_name = "Unknown Source"
embed = discord.Embed(
title="Now Playing",
color=0x1DB954 if source_name == "Spotify" else 0xFF0000
)
embed.add_field(name="Track", value=f"[{track.title}]({track.uri})", inline=False)
embed.add_field(name="Song By", value=track.author, inline=False)
embed.add_field(name="Progress", value=f"{position_str} [{progress_bar}] {length_str}", inline=False)
embed.add_field(name="Duration", value=length_str, inline=False)
embed.add_field(name="Queue Length", value=str(queue_length), inline=False)
embed.add_field(name="Source", value=f"{source_name} - [Link]({track.uri})", inline=False)
embed.set_thumbnail(url=track.artwork if track.artwork else "")
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.avatar.url if ctx.author.avatar else ctx.author.default_avatar.url)
await ctx.send(embed=embed)
@commands.hybrid_command(name="autoplay", usage="autoplay", help="Toggles autoplay mode.")
@blacklist_check()
@ignore_check()
@commands.cooldown(1, 3, commands.BucketType.user)
async def autoplay(self, ctx: commands.Context):
vc = ctx.voice_client
if not vc or not vc.playing:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> No song is currently playing.", color=0x000000))
return
if not ctx.author.voice or ctx.author.voice.channel.id != vc.channel.id:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> You need to be in the same voice channel as me to use this command.", color=0xFF0000))
return
if vc:
vc.autoplay = (
wavelink.AutoPlayMode.enabled if vc.autoplay != wavelink.AutoPlayMode.enabled else wavelink.AutoPlayMode.disabled
)
await ctx.send(embed=discord.Embed(description=f"<:Ztick:1222750301233090600> Autoplay {'enabled' if vc.autoplay == wavelink.AutoPlayMode.enabled else 'disabled'} by {ctx.author.mention}.", color=0x000000))
@commands.hybrid_command(name="loop", usage="loop", help="Toggles loop mode.")
@blacklist_check()
@ignore_check()
@commands.cooldown(1, 3, commands.BucketType.user)
async def loop(self, ctx: commands.Context):
vc = ctx.voice_client
if not vc or not vc.playing:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> No song is currently playing.", color=0x000000))
return
if not ctx.author.voice or ctx.author.voice.channel.id != vc.channel.id:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> You need to be in the same voice channel as me to use this command.", color=0xFF0000))
return
if vc:
vc.queue.mode = wavelink.QueueMode.loop if vc.queue.mode != wavelink.QueueMode.loop else wavelink.QueueMode.normal
await ctx.send(embed=discord.Embed(description=f"<:Ztick:1222750301233090600> Loop {'enabled' if vc.queue.mode == wavelink.QueueMode.loop else 'disabled'} by {ctx.author.mention}.", color=0x000000))
else:
await ctx.send(embed=discord.Embed(description="I'm not connected to a voice channel.", color=0xFF0000))
@commands.hybrid_command(name="pause", usage="pause", help="Pauses the current song.")
@blacklist_check()
@ignore_check()
@commands.cooldown(1, 3, commands.BucketType.user)
async def pause(self, ctx: commands.Context):
vc = ctx.voice_client
if not vc or not vc.playing:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> No song is currently playing.", color=0x000000))
return
if not ctx.author.voice or ctx.author.voice.channel.id != vc.channel.id:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> You need to be in the same voice channel as me to use this command.", color=0xFF0000))
return
if vc and vc.playing and not vc.paused:
await vc.pause(True)
await vc.channel.edit(status=f"<:gvMusic:1213831433219481722> Paused: {vc.current.title}")
await ctx.send(embed=discord.Embed(description=f"Paused by {ctx.author.mention}.", color=0x000000))
else:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> Nothing is playing or already paused.", color=0xFF0000))
@commands.hybrid_command(name="resume", usage="resume", help="Resumes the paused song.")
@blacklist_check()
@ignore_check()
@commands.cooldown(1, 3, commands.BucketType.user)
async def resume(self, ctx: commands.Context):
vc = ctx.voice_client
if not vc or not vc.playing:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> No song is currently playing.", color=0x000000))
return
if not ctx.author.voice or ctx.author.voice.channel.id != vc.channel.id:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> You need to be in the same voice channel as me to use this command.", color=0xFF0000))
return
if vc and vc.paused:
await vc.pause(False)
await vc.channel.edit(status=f"<:gvMusic:1213831433219481722> Playing: {vc.current.title}")
await ctx.send(embed=discord.Embed(description=f"Resumed by {ctx.author.mention}.", color=0x000000))
else:
await ctx.send(embed=discord.Embed(description="Player is not paused.", color=0xFF0000))
@commands.hybrid_command(name="skip", usage="skip", help="Skips the current song.")
@blacklist_check()
@ignore_check()
@commands.cooldown(1, 3, commands.BucketType.user)
async def skip(self, ctx: commands.Context):
vc = ctx.voice_client
if not vc or not vc.playing:
await ctx.send(embed=discord.Embed(description="No song is currently playing.", color=0x000000))
return
if not ctx.author.voice or ctx.author.voice.channel.id != vc.channel.id:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> You need to be in the same voice channel as me to use this command.", color=0xFF0000))
return
if vc.autoplay == wavelink.AutoPlayMode.enabled:
await vc.stop()
return await ctx.send(embed=discord.Embed(description=f"Skipped by {ctx.author.mention}.", color=0x000000))
if vc and vc.playing and not vc.queue.is_empty:
await vc.stop()
await ctx.send(embed=discord.Embed(description=f"Skipped by {ctx.author.mention}.", color=0x000000))
else:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> No song is playing or in the queue to skip.", color=0xFF0000))
@commands.hybrid_command(name="shuffle", usage="shuffle", help="Shuffles the queue.")
@blacklist_check()
@ignore_check()
@commands.cooldown(1, 3, commands.BucketType.user)
async def shuffle(self, ctx: commands.Context):
vc = ctx.voice_client
if not vc or not vc.playing:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> No song is currently playing.", color=0x000000))
return
if not ctx.author.voice or ctx.author.voice.channel.id != vc.channel.id:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> You need to be in the same voice channel as me to use this command.", color=0xFF0000))
return
if vc and vc.queue:
random.shuffle(vc.queue)
await ctx.send(embed=discord.Embed(description=f"Queue shuffled by {ctx.author.mention}.", color=0x000000))
else:
await ctx.send(embed=discord.Embed(description="Queue is empty.", color=0xFF0000))
@commands.hybrid_command(name="stop", usage="stop", help="Stops the current song and clears the queue.")
@blacklist_check()
@ignore_check()
@commands.cooldown(1, 3, commands.BucketType.user)
async def stop(self, ctx: commands.Context):
player: wavelink.Player = cast(wavelink.Player, ctx.voice_client)
vc = ctx.voice_client
if not vc or not vc.playing:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> No song is currently playing.", color=0x000000))
return
if not ctx.author.voice or ctx.author.voice.channel.id != vc.channel.id:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> You need to be in the same voice channel as me to use this command.", color=0xFF0000))
return
if vc and player:
await vc.channel.edit(status=None)
vc.queue.clear()
await vc.disconnect(force=True)
await ctx.send(embed=discord.Embed(description=f"Stopped and queue cleared by {ctx.author.mention}.", color=0x000000))
else:
await ctx.send(embed=discord.Embed(description="Nothing is playing to stop.", color=0xFF0000))
@commands.hybrid_command(name="volume", aliases=["vol"], usage="volume <level>", help="Sets the volume of the player.")
@blacklist_check()
@ignore_check()
@commands.cooldown(1, 3, commands.BucketType.user)
async def volume(self, ctx: commands.Context, level: int):
vc = ctx.voice_client
if not vc:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> I'm not connected to a voice channel.", color=0xFF0000))
return
if not ctx.author.voice or ctx.author.voice.channel.id != vc.channel.id:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> You need to be in the same voice channel as me to use this command.", color=0xFF0000))
return
if vc:
if 1 <= level <= 150:
await vc.set_volume(level)
await ctx.send(embed=discord.Embed(description=f"<:Voice:1279464563150032991> Volume set to {level}% by {ctx.author.mention}.", color=0x000000))
else:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> Volume must be between 1 and 150.", color=0xFF0000))
else:
await ctx.send(embed=discord.Embed(description="Bot is not connected to a voice channel.", color=0xFF0000))
@commands.hybrid_command(name="queue", usage="queue", help="Shows the current queue.")
@blacklist_check()
@ignore_check()
@commands.cooldown(1, 3, commands.BucketType.user)
async def queue(self, ctx: commands.Context):
vc = ctx.voice_client
if not vc or not vc.queue or vc.queue.is_empty:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> The queue is currently empty.", color=0x000000))
return
if not ctx.author.voice or ctx.author.voice.channel.id != vc.channel.id:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> You need to be in the same voice channel as me to use this command.", color=0xFF0000))
return
entries = [f"{index + 1}. [{track.title} - {track.author}]({track.uri})" for index, track in enumerate(vc.queue)]
paginator = Paginator(source=DescriptionEmbedPaginator(
entries=entries,
title="Current Queue",
description="List of upcoming songs.",
per_page=10,
color=0x000000),
ctx=ctx)
await paginator.paginate()
@commands.hybrid_command(name="clearqueue", usage="clearqueue", help="Clears the queue.")
@blacklist_check()
@ignore_check()
@commands.cooldown(1, 3, commands.BucketType.user)
async def clearqueue(self, ctx: commands.Context):
vc = ctx.voice_client
if not vc or not vc.queue or vc.queue.is_empty:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> No Queue to clear.", color=0xFF0000))
return
if not ctx.author.voice or ctx.author.voice.channel.id != vc.channel.id:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> You need to be in the same voice channel as me to use this command.", color=0xFF0000))
return
if vc and vc.queue:
vc.queue.clear()
await ctx.send(embed=discord.Embed(description="Queue has been cleared.", color=0x1DB954))
else:
await ctx.send(embed=discord.Embed(description="No queue to clear.", color=0xFF0000))
@commands.hybrid_command(name="replay", usage="replay", help="Replays the current song.")
@blacklist_check()
@ignore_check()
@commands.cooldown(1, 3, commands.BucketType.user)
async def replay(self, ctx: commands.Context):
vc = ctx.voice_client
if not vc or not vc.playing:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> I'm not connected to any voice channel.", color=0xFF0000))
return
if not ctx.author.voice or ctx.author.voice.channel.id != vc.channel.id:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> You need to be in the same voice channel as me to use this command.", color=0xFF0000))
return
if vc and vc.playing:
await vc.seek(0)
await ctx.send(embed=discord.Embed(description="Replaying the current track.", color=0x1DB954))
else:
await ctx.send(embed=discord.Embed(description="No track is currently playing.", color=0xFF0000))
@commands.hybrid_command(name="join", aliases=["connect"], usage="join", help="Joins the voice channel.")
@blacklist_check()
@ignore_check()
@commands.cooldown(1, 3, commands.BucketType.user)
async def join(self, ctx: commands.Context):
if ctx.author.voice:
await ctx.author.voice.channel.connect(cls=wavelink.Player)
await ctx.send(embed=discord.Embed(description="Joined the voice channel.", color=0x1DB954))
else:
await ctx.send(embed=discord.Embed(description="You need to join a voice channel first.", color=0xFF0000))
@commands.hybrid_command(name="disconnect", aliases=["dc", "leave"], usage="disconnect", help="Disconnects the bot from the voice channel.")
@blacklist_check()
@ignore_check()
@commands.cooldown(1, 3, commands.BucketType.user)
async def disconnect(self, ctx: commands.Context):
vc = ctx.voice_client
if not vc:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> I'm not connected to any voice channel.", color=0xFF0000))
return
if not ctx.author.voice or ctx.author.voice.channel.id != vc.channel.id:
await ctx.send(embed=discord.Embed(description="<a:Warning:1299512982006665216> You need to be in the same voice channel as me to use this command.", color=0xFF0000))
return
if vc:
await vc.disconnect()
await ctx.send(embed=discord.Embed(description="Disconnected from the voice channel.", color=0x1DB954))
else:
await ctx.send(embed=discord.Embed(description="Bot is not connected to any voice channel.", color=0xFF0000))
@commands.hybrid_command(name="seek", usage="seek <percentage>", help="Seeks to a specific percentage of the song.")
@blacklist_check()
@ignore_check()
@commands.cooldown(1, 3, commands.BucketType.user)
async def seek(self, ctx: commands.Context, percentage: int):
if not 1 <= percentage <= 100:
await ctx.send(embed=discord.Embed(description="Please provide a percentage between 1 and 100.", color=0xFF0000))
return
vc = ctx.voice_client
if not vc or not vc.playing:
await ctx.send(embed=discord.Embed(description="No song is currently playing.", color=0xFF0000))
return
if not ctx.author.voice or ctx.author.voice.channel.id != vc.channel.id:
await ctx.send(embed=discord.Embed(description="You need to be in the same voice channel as me to use this command.", color=0xFF0000))
return
track = vc.current
target_position = int(track.length * (percentage / 100))
await vc.seek(target_position)
await ctx.send(embed=discord.Embed(description=f"Seeked to {percentage}% of the current track.", color=0x1DB954))
@commands.Cog.listener()
async def on_wavelink_track_start(self, payload: wavelink.TrackStartEventPayload):
player = payload.player
track = player.current
guild_id = player.guild.id
voice_channel = player.channel
if voice_channel:
await voice_channel.edit(status=f"<:gvMusic:1213831433219481722> Playing: {track.title}") # type: ignore
if guild_id not in track_histories:
track_histories[guild_id] = []
if not track_histories[guild_id] or track_histories[guild_id][-1] != track:
track_histories[guild_id].append(track)
if len(track_histories[guild_id]) > 10:
track_histories[guild_id].pop(0)
@commands.Cog.listener()
async def on_wavelink_track_end(self, payload: wavelink.TrackEndEventPayload):
player = payload.player
voice_channel = player.channel
if voice_channel:
await voice_channel.edit(status=None) # type: ignore
await self.on_track_end(payload)
"""
@Author: Sonu Jana
+ Discord: me.sonu
+ Community: https://discord.gg/odx (Olympus Development)
+ for any queries reach out Community or DM me.
"""