-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmusic.py
492 lines (411 loc) · 16.5 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
import asyncio
from typing import List, cast
import discord
import spotipy
import wavelink
from discord.commands import Option, OptionChoice
from discord.ext import commands
from spotipy import SpotifyClientCredentials
from helpers.utils import format_time, load_config, truncate_text
config = load_config()
sp = spotipy.Spotify(
auth_manager=SpotifyClientCredentials(
client_id=config["spotify"]["client_id"],
client_secret=config["spotify"]["client_secret"],
)
)
# TODO: Music functionality is not working as expected. It needs to be fixed.
class EffectsSelect(discord.ui.Select):
def __init__(self):
options = [
discord.SelectOption(label="Bass Boost", value="bass-boost"),
discord.SelectOption(label="8D", value="8d"),
discord.SelectOption(label="Slowed & reverb ", value="reverb"),
discord.SelectOption(label="Speed up", value="speed-up"),
discord.SelectOption(label="Reset", value="reset"),
]
super().__init__(
placeholder="Apply an effect",
min_values=1,
max_values=1,
options=options,
)
self.effect_emojis = {
"bass-boost": "<:volume:1195610066901028975>",
"8d": "<:spiral:1195609586074398860>",
"reverb": "<:hourglass:1195609480801558568>",
"speed-up": "<:speed:1195609908171780176>",
"reset": "",
}
self.active_effects = []
async def callback(self, interaction: discord.Interaction):
player = cast(wavelink.Player, interaction.guild.voice_client)
if not player or not player.connected or not player.playing:
return
filters: wavelink.Filters = player.filters
selected_effect = self.values[0]
embed = interaction.message.embeds[0]
if selected_effect == "reset":
self.active_effects = []
if len(embed.fields) > 0 and embed.fields[-1].name == "Effects":
embed.remove_field(-1)
else:
if self.effect_emojis[selected_effect] in self.active_effects:
await interaction.response.send_message(
"This effect is already active.", ephemeral=True
)
return
self.active_effects.append(self.effect_emojis[selected_effect])
if len(embed.fields) > 0 and embed.fields[-1].name == "Effects":
embed.set_field_at(
-1,
name="Effects",
value=" | ".join(self.active_effects),
inline=False,
)
else:
embed.add_field(
name="Effects", value=" ".join(self.active_effects), inline=False
)
if selected_effect == "bass-boost":
await self.apply_bass_boost(filters, player)
elif selected_effect == "8d":
await self.apply_8d(filters, player)
elif selected_effect == "reverb":
await self.apply_reverb(filters, player)
elif selected_effect == "speed-up":
filters.timescale.set(rate=1.2)
await player.set_filters(filters, seek=True)
elif selected_effect == "reset":
filters.reset()
await player.set_filters(filters, seek=True)
await interaction.response.edit_message(embed=embed, view=self.view)
async def apply_bass_boost(self, filters, player):
if filters.equalizer.payload[0]["gain"] == 1:
filters.reset()
(await player.set_filters(filters, seek=True),)
return
# TODO improve this
filters.equalizer.set(bands=[{"band": 0, "gain": 1}])
await player.set_filters(filters, seek=True)
async def apply_8d(self, filters, player):
if (
filters.rotation.payload.get("rotationHz") == 0.125
and filters.tremolo.payload.get("depth") == 0.3
and filters.tremolo.payload.get("frequency") == 14
):
filters.reset()
(await player.set_filters(filters, seek=True),)
return
filters.timescale.set(pitch=1.05)
filters.tremolo.set(depth=0.3, frequency=14)
filters.rotation.set(rotation_hz=0.125)
filters.equalizer.set(bands=[{"band": 1, "gain": -0.2}])
(await player.set_filters(filters, seek=True),)
async def apply_reverb(self, filters, player):
if (
filters.timescale.payload.get("pitch") == 0.8
and filters.timescale.payload.get("rate") == 0.9
and filters.reverb.payload.get("wet") == 0.35
):
filters.reset()
(await player.set_filters(filters, seek=True),)
return
filters.timescale.set(pitch=0.8, rate=0.9)
(await player.set_filters(filters, seek=True),)
class MusicPlayerView(discord.ui.View):
def __init__(
self,
player: wavelink.Player,
bot: commands.Bot,
playing_messages: dict,
):
super().__init__(timeout=None)
self.player = player
self.playing_messages = playing_messages
self.bot = bot
select_menu = EffectsSelect()
self.add_item(select_menu)
@discord.ui.button(label="Pause", style=discord.ButtonStyle.gray)
async def pause_resume(
self, button: discord.ui.Button, interaction: discord.Interaction
):
if self.player.paused:
button.label = "Pause"
button.style = discord.ButtonStyle.gray
await self.player.pause(False)
else:
button.label = "Resume"
button.style = discord.ButtonStyle.green
await self.player.pause(True)
await interaction.response.edit_message(view=self)
@discord.ui.button(label="Skip", style=discord.ButtonStyle.gray)
async def skip(self, button: discord.ui.Button, interaction: discord.Interaction):
player = cast(wavelink.Player, interaction.guild.voice_client)
if not player:
return
if not player.playing:
return
await player.skip(force=True)
await interaction.response.defer()
@discord.ui.button(label="Stop", style=discord.ButtonStyle.red)
async def stop(self, button: discord.ui.Button, interaction: discord.Interaction):
player = cast(wavelink.Player, interaction.guild.voice_client)
if not player:
return
if not player.playing:
return
await player.disconnect()
player_context = self.playing_messages.get(player.ctx.guild.id)
if player_context is not None:
message = await self.bot.get_channel(
player_context["channel_id"]
).fetch_message(player_context["message_id"])
await message.delete()
del self.playing_messages[player.ctx.guild.id]
await interaction.response.defer()
@discord.ui.button(emoji="🔀", style=discord.ButtonStyle.gray)
async def shuffle(
self, button: discord.ui.Button, interaction: discord.Interaction
):
player = cast(wavelink.Player, interaction.guild.voice_client)
if not player:
return
if not player.playing:
return
player.queue.shuffle()
button.style = discord.ButtonStyle.green
await interaction.response.edit_message(view=self)
class Music(commands.Cog):
def __init__(self, bot_: discord.Bot):
self.bot = bot_
self.bot.loop.create_task(self.connect_nodes())
self.playing_messages = {}
async def connect_nodes(self):
await self.bot.wait_until_ready()
nodes = [
wavelink.Node(
uri="http://localhost:2333",
password="youshallnotpass",
)
]
await wavelink.Pool.connect(nodes=nodes, client=self.bot, cache_capacity=100)
@commands.Cog.listener()
async def on_wavelink_node_ready(self, payload: wavelink.NodeReadyEventPayload):
print(f"🎹 Wavelink node {payload.node.identifier} ready.")
@commands.Cog.listener()
async def on_wavelink_track_end(
self, payload: wavelink.TrackEndEventPayload
) -> None:
player: wavelink.Player = payload.player
if player is None:
return
if player.queue and player.autoplay == wavelink.AutoPlayMode.disabled:
await player.play(player.queue.get())
elif not player.queue:
await player.stop()
await player.disconnect()
player_context = self.playing_messages.get(player.ctx.guild.id)
if player_context is not None:
message = await self.bot.get_channel(
player_context["channel_id"]
).fetch_message(player_context["message_id"])
await message.delete()
del self.playing_messages[player.ctx.guild.id]
@commands.Cog.listener()
async def on_wavelink_track_start(
self, payload: wavelink.TrackStartEventPayload
) -> None:
player: wavelink.Player = payload.player
if player is None:
return
player_context = self.playing_messages.get(player.ctx.guild.id)
if player_context is None:
return
message = await self.bot.get_channel(
player_context["channel_id"]
).fetch_message(player_context["message_id"])
embed = discord.Embed(color=discord.Color.embed_background(), description="")
now_playing = f"{format_time(player.current.length)} - " + (
f"{truncate_text(player.current.title, 13)}"
if player.current.source != "youtube"
else player.current.title
)
now_playing += (
f" - {truncate_text(player.current.author, 10)}"
if player.current.source != "youtube"
else ""
)
now_playing = f"{now_playing: <31}"
description = f"**Now Playing**\n```{now_playing}```\n"
if len(player.queue) > 0:
next_track = player.queue[0]
next_up = f"{format_time(next_track.length)} - " + (
f"{truncate_text(next_track.title, 13)}"
if next_track.source != "youtube"
else next_track.title
)
next_up += (
f" - {truncate_text(next_track.author, 10)}"
if next_track.source != "youtube"
else ""
)
next_up = f"{next_up: <31}"
description += f"**Next Up**\n```{next_up}```"
embed.description = description
filters: wavelink.Filters = player.filters
active_effects = []
if filters.equalizer.payload[0]["gain"] == 1:
active_effects.append("<:volume:1195610066901028975>")
if (
filters.rotation.payload.get("rotationHz") == 0.125
and filters.tremolo.payload.get("depth") == 0.3
and filters.tremolo.payload.get("frequency") == 14
):
active_effects.append("<:spiral:1195609586074398860>")
if (
filters.timescale.payload.get("pitch") == 0.8
and filters.timescale.payload.get("rate") == 0.9
and filters.reverb.payload.get("wet") == 0.35
):
active_effects.append("<:hourglass:1195609480801558568>")
if filters.timescale.payload.get("rate") == 1.2:
active_effects.append("<:speed:1195609908171780176>")
if active_effects:
embed.add_field(
name="Effects", value=" | ".join(active_effects), inline=False
)
if player.current.artwork:
embed_method = (
embed.set_image
if player.current.source == "youtube"
else embed.set_thumbnail
)
embed_method(url=player.current.artwork)
await message.edit("", embed=embed)
await message.edit("", embed=embed)
async def voice_channel_autocomplete(
self, ctx: discord.AutocompleteContext
) -> List[discord.OptionChoice]:
"""Autocomplete callback function to suggest voice channels."""
guild = ctx.interaction.guild
voice_channels = await guild.fetch_channels()
return [
OptionChoice(name=channel.name, value=channel.id)
for channel in voice_channels
if isinstance(channel, discord.VoiceChannel)
]
async def ensure_voice(self, ctx: discord.ApplicationContext) -> bool:
player = cast(wavelink.Player, ctx.voice_client)
if not ctx.author.voice or not ctx.author.voice.channel:
await ctx.respond(
"You are not connected to any voice channel.",
ephemeral=True,
delete_after=10,
)
return False
if player is not None and player.connected:
if player.channel.id != ctx.author.voice.channel.id:
await ctx.respond(
"We are not in the same voice channel.",
ephemeral=True,
delete_after=10,
)
return False
else:
(
await asyncio.gather(
ctx.author.voice.channel.connect(cls=wavelink.Player),
ctx.respond(
f"Joined {ctx.author.voice.channel.mention}.",
),
),
)
return True
@discord.slash_command(name="join", description="Joins a voice channel.")
async def join_voice(
self,
ctx: discord.ApplicationContext,
channel: Option(
discord.VoiceChannel,
"Select a voice channel",
autocomplete=voice_channel_autocomplete,
required=False,
),
):
if not await self.ensure_voice(ctx):
return await ctx.respond(
"You are not connected to any voice channel.",
ephemeral=True,
delete_after=10,
)
try:
await channel.connect(cls=wavelink.Player)
await ctx.respond(
f"Joined {channel.mention}.",
)
await ctx.guild.me.edit(deafen=True)
except Exception as e:
await ctx.respond(f"An error occurred: {e}")
@discord.slash_command(name="play", description="Plays a song/playlist.")
async def play_music(
self,
ctx: discord.ApplicationContext,
query: Option(
str,
"Enter a song name or a Spotify playlist link.",
required=True,
),
shuffle: Option(
bool,
"Shuffle the playlist?",
required=False,
default=False,
),
):
if not await self.ensure_voice(ctx):
return
tracks: wavelink.Search = await wavelink.Playable.search(query)
player = cast(wavelink.Player, ctx.voice_client)
player.ctx = ctx
if not tracks:
return await ctx.respond("No tracks were found.", ephemeral=True)
self.view = MusicPlayerView(player, self.bot, self.playing_messages)
if isinstance(tracks, wavelink.Playlist):
if player.playing:
response = await ctx.respond(
f"Queued **{tracks.name}** (**{len(tracks)}** tracks)",
view=self.view,
)
self.playing_messages[ctx.guild.id] = {
"message_id": response.id,
"guild_id": ctx.guild.id,
"channel_id": ctx.channel.id,
}
await player.queue.put_wait(tracks)
else:
response = await ctx.respond(
f"Playing **{tracks.name}** (**{len(tracks)}** tracks)",
view=self.view,
)
self.playing_messages[ctx.guild.id] = {
"message_id": response.id,
"guild_id": ctx.guild.id,
"channel_id": ctx.channel.id,
}
await player.play(tracks[0])
await player.queue.put_wait(tracks[1:])
elif not player.playing:
response = await ctx.respond(
f"Playing **{tracks[0].title}**", delete_after=10
)
await player.play(tracks[0])
else:
response = await ctx.respond(
f"Queued **{tracks[0].title}**", delete_after=10
)
await player.queue.put_wait(tracks[0])
if shuffle:
player.queue.shuffle()
def setup(bot_: discord.Bot):
bot_.add_cog(Music(bot_))