-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnuevo1.txt
607 lines (478 loc) · 19.7 KB
/
nuevo1.txt
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
from discord.ext import commands
import asyncio
import sys
import datetime as dt
import random
from enum import Enum
import typing as t
import re
import aiohttp
import discord
import wavelink
URL_REGEX = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
LYRICS_URL = "https://some-random-api.ml/lyrics?title="
HZ_BANDS = (20, 40, 63, 100, 150, 250, 400, 450, 630, 1000, 1600, 2500, 4000, 10000, 16000)
TIME_REGEX = r"([0-9]{1,2})[:ms](([0-9]{1,2})s?)?"
OPTIONS = {
"1️⃣": 0,
"2⃣": 1,
"3⃣": 2,
"4⃣": 3,
"5⃣": 4,
}
class RepeatMode(Enum):
NONE = 0
ONE = 1
ALL = 2
class AlreadyConnectedToChannel(commands.CommandError):
pass
class NoVoiceChannel(commands.CommandError):
pass
class QueueIsEmpty(commands.CommandError):
pass
class NoTracksFound(commands.CommandError):
pass
class PlayerIsAlreadyPaused(commands.CommandError):
pass
class NoMoreTracks(commands.CommandError):
pass
class NoPreviousTracks(commands.CommandError):
pass
class InvalidRepeatMode(commands.CommandError):
pass
class VolumeTooLow(commands.CommandError):
pass
class VolumeTooHigh(commands.CommandError):
pass
class MaxVolume(commands.CommandError):
pass
class MinVolume(commands.CommandError):
pass
class NoLyricsFound(commands.CommandError):
pass
class InvalidEQPreset(commands.CommandError):
pass
class NonExistentEQBand(commands.CommandError):
pass
class EQGainOutOfBounds(commands.CommandError):
pass
class InvalidTimeString(commands.CommandError):
pass
class Queue(wavelink.Queue):
def __init__(self):
super().__init__()
self.position = 0
self.repeat_mode = RepeatMode.NONE
def set_repeat_mode(self, mode):
self.repeat_mode = RepeatMode[mode.upper()]
class Player(wavelink.Player):
def __init__(self):
super().__init__()
self.queue = Queue()
async def connect(self, ctx, channel=None):
if self.is_connected():
raise AlreadyConnectedToChannel
elif(channel := getattr(ctx.author.voice, "channel", channel)) is None:
raise NoVoiceChannel
await super().connect(ctx, channel)
return channel
async def teardown(self):
try:
await self.destroy()
except KeyError:
pass
async def add_tracks(self, ctx, tracks):
if not tracks:
raise NoTracksFound
if isinstance(tracks, wavelink.TrackPlaylist):
self.queue.__add__(*tracks.tracks)
elif len(tracks) == 1:
self.queue.__add__(tracks[0])
await ctx.send(f"Added {tracks[0].title} to the queue.")
else:
if (track := await self.choose_track(ctx, tracks)) is not None:
self.queue.__add__(track)
await ctx.send(f"Added {track.title} to the queue.")
if not self.is_playing and not self.queue.is_empty:
await self.start_playback()
async def choose_track(self, ctx, tracks):
def _check(r, u):
return (
r.emoji in OPTIONS.keys()
and u == ctx.author
and r.message.id == msg.id
)
embed = discord.Embed(
title="Choose a song",
description=(
"\n".join(
f"**{i + 1}.** {t.title} ({t.length // 60000}:{str(t.length % 60).zfill(2)})"
for i, t in enumerate(tracks[:5])
)
),
colour=ctx.author.colour,
timestamp=dt.datetime.utcnow()
)
embed.set_author(name="Query Results")
embed.set_footer(text=f"Invoked by {ctx.author.display_name}", icon_url=ctx.author.avatar_url)
msg = await ctx.send(embed=embed)
for emoji in list(OPTIONS.keys())[:min(len(tracks), len(OPTIONS))]:
await msg.add_reaction(emoji)
try:
reaction, _ = await self.bot.wait_for("reaction_add", timeout=60.0, check=_check)
except asyncio.TimeoutError:
await msg.delete()
await ctx.message.delete()
else:
await msg.delete()
return tracks[OPTIONS[reaction.emoji]]
async def start_playback(self):
await self.play(await self.queue.get())
async def advance(self):
try:
if (track := self.queue.pop()) is not None:
await self.play(track)
except QueueIsEmpty:
pass
async def repeat_track(self):
await self.play(await self.queue.get())
async def get_tracks(self, search: str):
if not re.match(URL_REGEX, search) or search.__contains__("youtube.com"):
tracks = await wavelink.YouTubeTrack.search(search)
elif(re.match(URL_REGEX, search) and search.__contains__("soundcloud.com")):
tracks = await wavelink.SoundCloudTrack.search(search)
return tracks
class Music(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.players = {}
#@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
if not member.bot and after.channel is None:
if not [m for m in before.channel.members if not m.bot]:
await self.get_player(member.guild).teardown()
async def on_player_stop(self, node, payload):
if payload.player.queue.repeat_mode == RepeatMode.ONE:
await payload.player.repeat_track()
else:
await payload.player.advance()
async def cog_check(self, ctx):
if isinstance(ctx.channel, discord.DMChannel):
await ctx.send("Music commands are not available in DMs.")
return False
return True
def get_player(self, obj):
if isinstance(obj, commands.Context):
return self.players[obj.guild.id]
elif isinstance(obj, discord.Guild):
return self.players[obj.id]
@commands.hybrid_command(name="connect",
description="connects to voicechannel")
async def connect_command(self, ctx, *, channel: t.Optional[discord.VoiceChannel]):
vc: Player = await ctx.author.voice.channel.connect(cls=Player)
self.players[vc.guild.id] = vc
channel = await vc.connect(ctx, channel)
await ctx.send(f"Connected to {channel.name}.")
@connect_command.error
async def connect_command_error(self, ctx, exc):
if isinstance(exc, AlreadyConnectedToChannel):
await ctx.send("Already connected to a voice channel.")
elif isinstance(exc, NoVoiceChannel):
await ctx.send("No suitable voice channel was provided.")
@commands.hybrid_command(name="disconnect",
description="Disconnect from channel")
async def disconnect_command(self, ctx):
vc: Player = ctx.voice_client
self.players.pop(ctx.guild.id)
await vc.disconnect()
await ctx.send("Disconnected.")
@commands.hybrid_command(name="play2", description="plays music")
async def play(ctx: commands.Context, *, search: str) -> None:
"""Simple play command."""
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
else:
vc: wavelink.Player = ctx.voice_client
tracks = await wavelink.YouTubeTrack.search(search)
if not tracks:
await ctx.send(f'No tracks found with query: `{search}`')
return
track = tracks[0]
await vc.play(track)
@commands.hybrid_command(name="play",
description="starts playing music")
async def play_command(self, ctx, *, query: t.Optional[str]):
vc: Player = self.players[ctx.guild.id]
if not vc.is_connected:
await vc.connect(ctx)
if query is None:
if vc.queue.is_empty:
raise QueueIsEmpty
await vc.set_pause(False)
await ctx.send("Playback resumed.")
else:
query = query.strip("<>")
if not re.match(URL_REGEX, query):
query = f"ytsearch:{query}"
await vc.__add__(ctx, await Player.get_tracks(query))
@play_command.error
async def play_command_error(self, ctx, exc):
if isinstance(exc, QueueIsEmpty):
await ctx.send("No songs to play as the queue is empty.")
elif isinstance(exc, NoVoiceChannel):
await ctx.send("No suitable voice channel was provided.")
@commands.command(name="pause")
async def pause_command(self, ctx):
player = self.get_player(ctx)
if player.is_paused:
raise PlayerIsAlreadyPaused
await player.set_pause(True)
await ctx.send("Playback paused.")
@pause_command.error
async def pause_command_error(self, ctx, exc):
if isinstance(exc, PlayerIsAlreadyPaused):
await ctx.send("Already paused.")
@commands.command(name="stop")
async def stop_command(self, ctx):
player = self.get_player(ctx)
player.queue.empty()
await player.stop()
await ctx.send("Playback stopped.")
@commands.command(name="next", aliases=["skip"])
async def next_command(self, ctx):
player = self.get_player(ctx)
if not player.queue.upcoming:
raise NoMoreTracks
await player.stop()
await ctx.send("Playing next track in queue.")
@next_command.error
async def next_command_error(self, ctx, exc):
if isinstance(exc, QueueIsEmpty):
await ctx.send("This could not be executed as the queue is currently empty.")
elif isinstance(exc, NoMoreTracks):
await ctx.send("There are no more tracks in the queue.")
@commands.command(name="previous")
async def previous_command(self, ctx):
player = self.get_player(ctx)
if not player.queue.history:
raise NoPreviousTracks
player.queue.position -= 2
await player.stop()
await ctx.send("Playing previous track in queue.")
@previous_command.error
async def previous_command_error(self, ctx, exc):
if isinstance(exc, QueueIsEmpty):
await ctx.send("This could not be executed as the queue is currently empty.")
elif isinstance(exc, NoPreviousTracks):
await ctx.send("There are no previous tracks in the queue.")
@commands.command(name="shuffle")
async def shuffle_command(self, ctx):
player = self.get_player(ctx)
player.queue.shuffle()
await ctx.send("Queue shuffled.")
@shuffle_command.error
async def shuffle_command_error(self, ctx, exc):
if isinstance(exc, QueueIsEmpty):
await ctx.send("The queue could not be shuffled as it is currently empty.")
@commands.command(name="repeat")
async def repeat_command(self, ctx, mode: str):
if mode not in ("none", "1", "all"):
raise InvalidRepeatMode
player = self.get_player(ctx)
player.queue.set_repeat_mode(mode)
await ctx.send(f"The repeat mode has been set to {mode}.")
@commands.command(name="queue")
async def queue_command(self, ctx, show: t.Optional[int] = 10):
player = self.get_player(ctx)
if player.queue.is_empty:
raise QueueIsEmpty
embed = discord.Embed(
title="Queue",
description=f"Showing up to next {show} tracks",
colour=ctx.author.colour,
timestamp=dt.datetime.utcnow()
)
embed.set_author(name="Query Results")
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.avatar_url)
embed.add_field(
name="Currently playing",
value=getattr(player.queue.get(), "title", "No tracks currently playing."),
inline=False
)
if upcoming := player.queue.upcoming:
embed.add_field(
name="Next up",
value="\n".join(t.title for t in upcoming[:show]),
inline=False
)
msg = await ctx.send(embed=embed)
@queue_command.error
async def queue_command_error(self, ctx, exc):
if isinstance(exc, QueueIsEmpty):
await ctx.send("The queue is currently empty.")
# Requests -----------------------------------------------------------------
@commands.group(name="volume", invoke_without_command=True)
async def volume_group(self, ctx, volume: int):
player = self.get_player(ctx)
if volume < 0:
raise VolumeTooLow
if volume > 150:
raise VolumeTooHigh
await player.set_volume(volume)
await ctx.send(f"Volume set to {volume:,}%")
@volume_group.error
async def volume_group_error(self, ctx, exc):
if isinstance(exc, VolumeTooLow):
await ctx.send("The volume must be 0% or above.")
elif isinstance(exc, VolumeTooHigh):
await ctx.send("The volume must be 150% or below.")
@volume_group.command(name="up")
async def volume_up_command(self, ctx):
player = self.get_player(ctx)
if player.volume == 150:
raise MaxVolume
await player.set_volume(value := min(player.volume + 10, 150))
await ctx.send(f"Volume set to {value:,}%")
@volume_up_command.error
async def volume_up_command_error(self, ctx, exc):
if isinstance(exc, MaxVolume):
await ctx.send("The player is already at max volume.")
@volume_group.command(name="down")
async def volume_down_command(self, ctx):
player = self.get_player(ctx)
if player.volume == 0:
raise MinVolume
await player.set_volume(value := max(0, player.volume - 10))
await ctx.send(f"Volume set to {value:,}%")
@volume_down_command.error
async def volume_down_command_error(self, ctx, exc):
if isinstance(exc, MinVolume):
await ctx.send("The player is already at min volume.")
@commands.command(name="lyrics")
async def lyrics_command(self, ctx, name: t.Optional[str]):
player = self.get_player(ctx)
name = name or player.queue.get().title
async with ctx.typing():
async with aiohttp.request("GET", LYRICS_URL + name, headers={}) as r:
if not 200 <= r.status <= 299:
raise NoLyricsFound
data = await r.json()
if len(data["lyrics"]) > 2000:
return await ctx.send(f"<{data['links']['genius']}>")
embed = discord.Embed(
title=data["title"],
description=data["lyrics"],
colour=ctx.author.colour,
timestamp=dt.datetime.utcnow(),
)
embed.set_thumbnail(url=data["thumbnail"]["genius"])
embed.set_author(name=data["author"])
await ctx.send(embed=embed)
@lyrics_command.error
async def lyrics_command_error(self, ctx, exc):
if isinstance(exc, NoLyricsFound):
await ctx.send("No lyrics could be found.")
"""
@commands.command(name="eq")
async def eq_command(self, ctx, preset: str):
player = self.get_player(ctx)
eq = getattr(wavelink.eqs.Equalizer, preset, None)
if not eq:
raise InvalidEQPreset
await player.set_eq(eq())
await ctx.send(f"Equaliser adjusted to the {preset} preset.")
@eq_command.error
async def eq_command_error(self, ctx, exc):
if isinstance(exc, InvalidEQPreset):
await ctx.send("The EQ preset must be either 'flat', 'boost', 'metal', or 'piano'.")
@commands.command(name="adveq", aliases=["aeq"])
async def adveq_command(self, ctx, band: int, gain: float):
player = self.get_player(ctx)
if not 1 <= band <= 15 and band not in HZ_BANDS:
raise NonExistentEQBand
if band > 15:
band = HZ_BANDS.index(band) + 1
if abs(gain) > 10:
raise EQGainOutOfBounds
player.eq_levels[band - 1] = gain / 10
eq = wavelink.eqs.Equalizer(levels=[(i, gain) for i, gain in enumerate(player.eq_levels)])
await player.set_eq(eq)
await ctx.send("Equaliser adjusted.")
@adveq_command.error
async def adveq_command_error(self, ctx, exc):
if isinstance(exc, NonExistentEQBand):
await ctx.send(
"This is a 15 band equaliser -- the band number should be between 1 and 15, or one of the following "
"frequencies: " + ", ".join(str(b) for b in HZ_BANDS)
)
elif isinstance(exc, EQGainOutOfBounds):
await ctx.send("The EQ gain for any band should be between 10 dB and -10 dB.")
@commands.command(name="playing", aliases=["np"])
async def playing_command(self, ctx):
player = self.get_player(ctx)
if not player.is_playing:
raise PlayerIsAlreadyPaused
embed = discord.Embed(
title="Now playing",
colour=ctx.author.colour,
timestamp=dt.datetime.utcnow(),
)
embed.set_author(name="Playback Information")
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.avatar_url)
embed.add_field(name="Track title", value=player.queue.get().title, inline=False)
embed.add_field(name="Artist", value=player.queue.get().author, inline=False)
position = divmod(player.position, 60000)
length = divmod(player.queue.get().length, 60000)
embed.add_field(
name="Position",
value=f"{int(position[0])}:{round(position[1] / 1000):02}/{int(length[0])}:{round(length[1] / 1000):02}",
inline=False
)
await ctx.send(embed=embed)
@playing_command.error
async def playing_command_error(self, ctx, exc):
if isinstance(exc, PlayerIsAlreadyPaused):
await ctx.send("There is no track currently playing.")
@commands.command(name="skipto", aliases=["playindex"])
async def skipto_command(self, ctx, index: int):
player = self.get_player(ctx)
if player.queue.is_empty:
raise QueueIsEmpty
if not 0 <= index <= player.queue.length:
raise NoMoreTracks
player.queue.position = index - 2
await player.stop()
await ctx.send(f"Playing track in position {index}.")
@skipto_command.error
async def skipto_command_error(self, ctx, exc):
if isinstance(exc, QueueIsEmpty):
await ctx.send("There are no tracks in the queue.")
elif isinstance(exc, NoMoreTracks):
await ctx.send("That index is out of the bounds of the queue.")
@commands.command(name="restart")
async def restart_command(self, ctx):
player = self.get_player(ctx)
if player.queue.is_empty:
raise QueueIsEmpty
await player.seek(0)
await ctx.send("Track restarted.")
@restart_command.error
async def restart_command_error(self, ctx, exc):
if isinstance(exc, QueueIsEmpty):
await ctx.send("There are no tracks in the queue.")
@commands.command(name="seek")
async def seek_command(self, ctx, position: str):
player = self.get_player(ctx)
if player.queue.is_empty:
raise QueueIsEmpty
if not (match := re.match(TIME_REGEX, position)):
raise InvalidTimeString
if match.group(3):
secs = (int(match.group(1)) * 60) + (int(match.group(3)))
else:
secs = int(match.group(1))
await player.seek(secs * 1000)
await ctx.send("Seeked.")
"""
async def setup(bot):
await bot.add_cog(Music(bot))