-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
audio.py
7050 lines (6469 loc) · 287 KB
/
audio.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import asyncio
import contextlib
import datetime
import heapq
import json
import logging
import random
import re
import time
import traceback
from collections import namedtuple, Counter
from io import StringIO
from typing import List, Optional, Tuple, Union, cast
import aiohttp
import discord
import lavalink
import math
from fuzzywuzzy import process
import redbot.core
from redbot.core import Config, bank, checks, commands
from redbot.core.data_manager import cog_data_path
from redbot.core.i18n import Translator, cog_i18n
from redbot.core.utils.chat_formatting import bold, box, humanize_number, inline, pagify
from redbot.core.utils.menus import (
DEFAULT_CONTROLS,
close_menu,
menu,
next_page,
prev_page,
start_adding_reactions,
)
from redbot.core.utils.predicates import MessagePredicate, ReactionPredicate
from . import audio_dataclasses
from .apis import MusicCache, HAS_SQL, _ERROR
from .checks import can_have_caching
from .converters import ComplexScopeParser, ScopeParser, get_lazy_converter, get_playlist_converter
from .equalizer import Equalizer
from .errors import LavalinkDownloadFailed, MissingGuild, SpotifyFetchError, TooManyMatches
from .manager import ServerManager
from .playlists import (
FakePlaylist,
Playlist,
PlaylistScope,
create_playlist,
delete_playlist,
get_all_playlist,
get_playlist,
humanize_scope,
)
from .utils import *
_ = Translator("Audio", __file__)
__version__ = "1.0.0"
__author__ = ["aikaterna", "Draper"]
log = logging.getLogger("red.audio")
_SCHEMA_VERSION = 2
LazyGreedyConverter = get_lazy_converter("--")
PlaylistConverter = get_playlist_converter()
@cog_i18n(_)
class Audio(commands.Cog):
"""Play audio through voice channels."""
_default_lavalink_settings = {
"host": "localhost",
"rest_port": 2333,
"ws_port": 2333,
"password": "youshallnotpass",
}
def __init__(self, bot):
super().__init__()
self.bot = bot
self.config = Config.get_conf(self, 2711759130, force_registration=True)
self.skip_votes = {}
self.session = aiohttp.ClientSession()
self._connect_task = None
self._disconnect_task = None
self._cleaned_up = False
self._connection_aborted = False
self.play_lock = {}
self._manager: Optional[ServerManager] = None
self._cog_name = None
self._cog_id = None
default_global = dict(
schema_version=1,
cache_level=0,
cache_age=365,
status=False,
use_external_lavalink=False,
restrict=True,
current_version=redbot.core.VersionInfo.from_str(__version__).to_json(),
localpath=str(cog_data_path(raw_name="Audio")),
**self._default_lavalink_settings,
)
default_guild = dict(
auto_play=False,
autoplaylist=dict(enabled=False, id=None, name=None, scope=None),
disconnect=False,
dj_enabled=False,
dj_role=None,
emptydc_enabled=False,
emptydc_timer=0,
emptypause_enabled=False,
emptypause_timer=0,
jukebox=False,
jukebox_price=0,
maxlength=0,
notify=False,
repeat=False,
shuffle=False,
thumbnail=False,
volume=100,
vote_enabled=False,
vote_percent=0,
room_lock=None,
url_keyword_blacklist=[],
url_keyword_whitelist=[],
)
_playlist = dict(id=None, author=None, name=None, playlist_url=None, tracks=[])
self.config.init_custom("EQUALIZER", 1)
self.config.register_custom("EQUALIZER", eq_bands=[], eq_presets={})
self.config.init_custom(PlaylistScope.GLOBAL.value, 1)
self.config.register_custom(PlaylistScope.GLOBAL.value, **_playlist)
self.config.init_custom(PlaylistScope.GUILD.value, 2)
self.config.register_custom(PlaylistScope.GUILD.value, **_playlist)
self.config.init_custom(PlaylistScope.USER.value, 2)
self.config.register_custom(PlaylistScope.USER.value, **_playlist)
self.config.register_guild(**default_guild)
self.config.register_global(**default_global)
self.music_cache = MusicCache(bot, self.session, path=str(cog_data_path(raw_name="Audio")))
self._error_counter = Counter()
self._error_timer = {}
self._disconnected_players = {}
self.play_lock = {}
self._manager: Optional[ServerManager] = None
# These has to be a task since this requires the bot to be ready
# If it waits for ready in startup, we cause a deadlock during initial load
# as initial load happens before the bot can ever be ready.
self._init_task = self.bot.loop.create_task(self.initialize())
self._ready_event = asyncio.Event()
@property
def owns_autoplay(self):
c = self.bot.get_cog(self._cog_name)
if c and id(c) == self._cog_id:
return c
@owns_autoplay.setter
def owns_autoplay(self, value: commands.Cog):
if self.owns_autoplay:
raise RuntimeError(
f"`{self._cog_name}` already has ownership of autoplay, "
f"please unload it if you wish to load `{value.qualified_name}`."
)
self._cog_name = value.qualified_name
self._cog_id = id(value)
@owns_autoplay.deleter
def owns_autoplay(self):
self._cog_name = None
self._cog_id = None
async def cog_before_invoke(self, ctx: commands.Context):
await self._ready_event.wait()
# check for unsupported arch
# Check on this needs refactoring at a later date
# so that we have a better way to handle the tasks
if self.llsetup in [ctx.command, ctx.command.root_parent]:
pass
elif self._connect_task and self._connect_task.cancelled():
await ctx.send(
"You have attempted to run Audio's Lavalink server on an unsupported"
" architecture. Only settings related commands will be available."
)
raise RuntimeError(
"Not running audio command due to invalid machine architecture for Lavalink."
)
dj_enabled = await self.config.guild(ctx.guild).dj_enabled()
if dj_enabled:
dj_role_obj = ctx.guild.get_role(await self.config.guild(ctx.guild).dj_role())
if not dj_role_obj:
await self.config.guild(ctx.guild).dj_enabled.set(None)
await self.config.guild(ctx.guild).dj_role.set(None)
await self._embed_msg(ctx, _("No DJ role found. Disabling DJ mode."))
async def initialize(self):
await self.bot.wait_until_ready()
# Unlike most cases, we want the cache to exit before migration.
await self.music_cache.initialize(self.config)
await self._migrate_config(
from_version=await self.config.schema_version(), to_version=_SCHEMA_VERSION
)
pass_config_to_dependencies(self.config, self.bot, await self.config.localpath())
self._restart_connect()
self._disconnect_task = self.bot.loop.create_task(self.disconnect_timer())
lavalink.register_event_listener(self.event_handler)
if not HAS_SQL:
error_message = (
"Audio version: {version}\nThis version requires some SQL dependencies to "
"access the caching features, "
"your Python install is missing some of them.\n\n"
"For instructions on how to fix it Google "
f"`{_ERROR}`.\n"
"You will need to install the missing SQL dependency.\n\n"
).format(version=__version__)
with contextlib.suppress(discord.HTTPException):
for page in pagify(error_message):
await self.bot.send_to_owners(page)
log.critical(error_message)
self._ready_event.set()
self.bot.dispatch("red_audio_initialized", self)
async def _migrate_config(self, from_version: int, to_version: int):
database_entries = []
time_now = str(datetime.datetime.now(datetime.timezone.utc))
if from_version == to_version:
return
elif from_version < to_version:
all_guild_data = await self.config.all_guilds()
all_playlist = {}
for guild_id, guild_data in all_guild_data.items():
temp_guild_playlist = guild_data.pop("playlists", None)
if temp_guild_playlist:
guild_playlist = {}
for count, (name, data) in enumerate(temp_guild_playlist.items(), 1):
if not data or not name:
continue
playlist = {"id": count, "name": name, "guild": int(guild_id)}
playlist.update(data)
guild_playlist[str(count)] = playlist
tracks_in_playlist = data.get("tracks", []) or []
for t in tracks_in_playlist:
uri = t.get("info", {}).get("uri")
if uri:
t = {"loadType": "V2_COMPAT", "tracks": [t], "query": uri}
database_entries.append(
{
"query": uri,
"data": json.dumps(t),
"last_updated": time_now,
"last_fetched": time_now,
}
)
if guild_playlist:
all_playlist[str(guild_id)] = guild_playlist
await self.config.custom(PlaylistScope.GUILD.value).set(all_playlist)
# new schema is now in place
await self.config.schema_version.set(_SCHEMA_VERSION)
# migration done, now let's delete all the old stuff
for guild_id in all_guild_data:
await self.config.guild(
cast(discord.Guild, discord.Object(id=guild_id))
).clear_raw("playlists")
if database_entries and HAS_SQL:
await self.music_cache.insert("lavalink", database_entries)
def _restart_connect(self):
if self._connect_task:
self._connect_task.cancel()
self._connect_task = self.bot.loop.create_task(self.attempt_connect())
async def attempt_connect(self, timeout: int = 50):
self._connection_aborted = False
max_retries = 5
retry_count = 0
while retry_count < max_retries:
external = await self.config.use_external_lavalink()
if external is False:
settings = self._default_lavalink_settings
host = settings["host"]
password = settings["password"]
rest_port = settings["rest_port"]
ws_port = settings["ws_port"]
if self._manager is not None:
await self._manager.shutdown()
self._manager = ServerManager()
try:
await self._manager.start()
except LavalinkDownloadFailed as exc:
await asyncio.sleep(1)
if exc.should_retry:
log.exception(
"Exception whilst starting internal Lavalink server, retrying...",
exc_info=exc,
)
retry_count += 1
continue
else:
log.exception(
"Fatal exception whilst starting internal Lavalink server, "
"aborting...",
exc_info=exc,
)
self._connection_aborted = True
raise
except asyncio.CancelledError:
log.exception("Invalid machine architecture, cannot run Lavalink.")
raise
except Exception as exc:
log.exception(
"Unhandled exception whilst starting internal Lavalink server, "
"aborting...",
exc_info=exc,
)
self._connection_aborted = True
raise
else:
break
else:
host = await self.config.host()
password = await self.config.password()
rest_port = await self.config.rest_port()
ws_port = await self.config.ws_port()
break
else:
log.critical(
"Setting up the Lavalink server failed after multiple attempts. See above "
"tracebacks for details."
)
self._connection_aborted = True
return
retry_count = 0
while retry_count < max_retries:
try:
await lavalink.initialize(
bot=self.bot,
host=host,
password=password,
rest_port=rest_port,
ws_port=ws_port,
timeout=timeout,
)
except asyncio.TimeoutError:
log.error("Connecting to Lavalink server timed out, retrying...")
if external is False and self._manager is not None:
await self._manager.shutdown()
retry_count += 1
await asyncio.sleep(1) # prevent busylooping
except Exception as exc:
log.exception(
"Unhandled exception whilst connecting to Lavalink, aborting...", exc_info=exc
)
self._connection_aborted = True
raise
else:
break
else:
self._connection_aborted = True
log.critical(
"Connecting to the Lavalink server failed after multiple attempts. See above "
"tracebacks for details."
)
async def error_reset(self, player: lavalink.Player):
guild = player.channel.guild
now = time.time()
seconds_allowed = 10
last_error = self._error_timer.setdefault(guild.id, now)
if now - seconds_allowed > last_error:
self._error_timer[guild.id] = 0
self._error_counter[guild.id] = 0
async def increase_error_counter(self, player: lavalink.Player) -> bool:
guild = player.channel.guild
now = time.time()
self._error_counter[guild.id] += 1
self._error_timer[guild.id] = now
return self._error_counter[guild.id] >= 5
@staticmethod
async def _players_check():
try:
get_single_title = lavalink.active_players()[0].current.title
query = audio_dataclasses.Query.process_input(lavalink.active_players()[0].current.uri)
if get_single_title == "Unknown title":
get_single_title = lavalink.active_players()[0].current.uri
if not get_single_title.startswith("http"):
get_single_title = get_single_title.rsplit("/", 1)[-1]
elif query.is_local:
get_single_title = "{} - {}".format(
lavalink.active_players()[0].current.author,
lavalink.active_players()[0].current.title,
)
else:
get_single_title = lavalink.active_players()[0].current.title
playing_servers = len(lavalink.active_players())
except IndexError:
get_single_title = None
playing_servers = 0
return get_single_title, playing_servers
async def _status_check(self, playing_servers):
if playing_servers == 0:
await self.bot.change_presence(activity=None)
if playing_servers == 1:
single_title = await self._players_check()
await self.bot.change_presence(
activity=discord.Activity(
name=single_title[0], type=discord.ActivityType.listening
)
)
if playing_servers > 1:
await self.bot.change_presence(
activity=discord.Activity(
name=_("music in {} servers").format(playing_servers),
type=discord.ActivityType.playing,
)
)
async def event_handler(
self, player: lavalink.Player, event_type: lavalink.LavalinkEvents, extra
):
disconnect = await self.config.guild(player.channel.guild).disconnect()
autoplay = await self.config.guild(player.channel.guild).auto_play() or self.owns_autoplay
notify = await self.config.guild(player.channel.guild).notify()
status = await self.config.status()
repeat = await self.config.guild(player.channel.guild).repeat()
await self.error_reset(player)
if event_type == lavalink.LavalinkEvents.TRACK_START:
self.skip_votes[player.channel.guild] = []
playing_song = player.fetch("playing_song")
requester = player.fetch("requester")
player.store("prev_song", playing_song)
player.store("prev_requester", requester)
player.store("playing_song", player.current)
player.store(
"requester", player.current.requester if player.current else player.current
)
self.bot.dispatch(
"red_audio_track_start",
player.channel.guild,
player.current,
player.current.requester,
)
if event_type == lavalink.LavalinkEvents.TRACK_END:
prev_song = player.fetch("prev_song")
prev_requester = player.fetch("prev_requester")
self.bot.dispatch(
"red_audio_track_end", player.channel.guild, prev_song, prev_requester
)
if event_type == lavalink.LavalinkEvents.QUEUE_END:
prev_song = player.fetch("prev_song")
prev_requester = player.fetch("prev_requester")
self.bot.dispatch(
"red_audio_queue_end", player.channel.guild, prev_song, prev_requester
)
if autoplay and not player.queue and player.fetch("playing_song") is not None:
if self.owns_autoplay is None:
await self.music_cache.autoplay(player)
else:
self.bot.dispatch(
"red_audio_should_auto_play",
player,
player.channel.guild,
player.channel,
self.play_query,
)
if event_type == lavalink.LavalinkEvents.TRACK_START and notify:
notify_channel = player.fetch("channel")
prev_song = player.fetch("prev_song")
if notify_channel:
notify_channel = self.bot.get_channel(notify_channel)
if player.fetch("notify_message") is not None:
with contextlib.suppress(discord.HTTPException):
await player.fetch("notify_message").delete()
if (
autoplay
and player.current.extras.get("autoplay")
and (prev_song is None or not prev_song.extras.get("autoplay"))
):
embed = discord.Embed(
colour=(await self.bot.get_embed_colour(notify_channel)),
title=_("Auto play started."),
)
await notify_channel.send(embed=embed)
query = audio_dataclasses.Query.process_input(player.current.uri)
if query.is_local if player.current else False:
if player.current.title != "Unknown title":
description = "**{} - {}**\n{}".format(
player.current.author,
player.current.title,
audio_dataclasses.LocalPath(player.current.uri).to_string_hidden(),
)
else:
description = "{}".format(
audio_dataclasses.LocalPath(player.current.uri).to_string_hidden()
)
else:
description = "**[{}]({})**".format(player.current.title, player.current.uri)
if player.current.is_stream:
dur = "LIVE"
else:
dur = lavalink.utils.format_time(player.current.length)
embed = discord.Embed(
colour=(await self.bot.get_embed_color(notify_channel)),
title=_("Now Playing"),
description=description,
)
embed.set_footer(
text=_("Track length: {length} | Requested by: {user}").format(
length=dur, user=player.current.requester
)
)
if (
await self.config.guild(player.channel.guild).thumbnail()
and player.current.thumbnail
):
embed.set_thumbnail(url=player.current.thumbnail)
notify_message = await notify_channel.send(embed=embed)
player.store("notify_message", notify_message)
if event_type == lavalink.LavalinkEvents.TRACK_START and status:
player_check = await self._players_check()
await self._status_check(player_check[1])
if event_type == lavalink.LavalinkEvents.TRACK_END and status:
await asyncio.sleep(1)
if not player.is_playing:
player_check = await self._players_check()
await self._status_check(player_check[1])
if not autoplay and event_type == lavalink.LavalinkEvents.QUEUE_END and notify:
notify_channel = player.fetch("channel")
if notify_channel:
notify_channel = self.bot.get_channel(notify_channel)
embed = discord.Embed(
colour=(await self.bot.get_embed_colour(notify_channel)),
title=_("Queue ended."),
)
await notify_channel.send(embed=embed)
elif not autoplay and event_type == lavalink.LavalinkEvents.QUEUE_END and disconnect:
await player.disconnect()
self.bot.dispatch("red_audio_audio_disconnect", player.channel.guild)
if event_type == lavalink.LavalinkEvents.QUEUE_END and status:
player_check = await self._players_check()
await self._status_check(player_check[1])
if event_type == lavalink.LavalinkEvents.TRACK_EXCEPTION:
message_channel = player.fetch("channel")
while True:
if player.current in player.queue:
player.queue.remove(player.current)
else:
break
if repeat:
player.current = None
self._error_counter.setdefault(player.channel.guild.id, 0)
if player.channel.guild.id not in self._error_counter:
self._error_counter[player.channel.guild.id] = 0
early_exit = await self.increase_error_counter(player)
if early_exit:
self._disconnected_players[player.channel.guild.id] = True
self.play_lock[player.channel.guild.id] = False
eq = player.fetch("eq")
player.queue = []
player.store("playing_song", None)
if eq:
await self.config.custom("EQUALIZER", player.channel.guild.id).eq_bands.set(
eq.bands
)
await player.stop()
await player.disconnect()
self.bot.dispatch("red_audio_audio_disconnect", player.channel.guild)
if message_channel:
message_channel = self.bot.get_channel(message_channel)
if early_exit:
embed = discord.Embed(
colour=(await self.bot.get_embed_color(message_channel)),
title=_("Multiple errors detected"),
description=_(
"Closing the audio player "
"due to multiple errors being detected. "
"If this persists, please inform the bot owner "
"as the Audio cog may be temporally unavailable."
),
)
await message_channel.send(embed=embed)
else:
query = audio_dataclasses.Query.process_input(player.current.uri)
if player.current and query.is_local:
query = audio_dataclasses.Query.process_input(player.current.uri)
if player.current.title == "Unknown title":
description = "{}".format(query.track.to_string_hidden())
else:
song = bold("{} - {}").format(
player.current.author, player.current.title
)
description = "{}\n{}".format(song, query.track.to_string_hidden())
else:
description = bold("[{}]({})").format(
player.current.title, player.current.uri
)
embed = discord.Embed(
colour=(await self.bot.get_embed_color(message_channel)),
title=_("Track Error"),
description="{}\n{}".format(extra, description),
)
embed.set_footer(text=_("Skipping..."))
await message_channel.send(embed=embed)
await player.skip()
async def play_query(
self,
query: str,
guild: discord.Guild,
channel: discord.VoiceChannel,
is_autoplay: bool = True,
):
if not self._player_check(guild.me):
try:
if (
not channel.permissions_for(guild.me).connect
or not channel.permissions_for(guild.me).move_members
and userlimit(channel)
):
log.error(f"I don't have permission to connect to {channel} in {guild}.")
await lavalink.connect(channel)
player = lavalink.get_player(guild.id)
player.store("connect", datetime.datetime.utcnow())
except IndexError:
log.debug(
f"Connection to Lavalink has not yet been established"
f" while trying to connect to to {channel} in {guild}."
)
return
player = lavalink.get_player(guild.id)
player.store("channel", channel.id)
player.store("guild", guild.id)
await self._data_check(guild.me)
query = audio_dataclasses.Query.process_input(query)
ctx = namedtuple("Context", "message")
results, called_api = await self.music_cache.lavalink_query(ctx(guild), player, query)
if not results.tracks:
log.debug(f"Query returned no tracks.")
return
track = results.tracks[0]
if not await is_allowed(
guild, f"{track.title} {track.author} {track.uri} {str(query._raw)}"
):
log.debug(f"Query is not allowed in {guild} ({guild.id})")
return
track.extras = {"autoplay": is_autoplay}
player.add(player.channel.guild.me, track)
self.bot.dispatch(
"red_audio_track_auto_play", player.channel.guild, track, player.channel.guild.me
)
if not player.current:
await player.play()
async def delegate_autoplay(self, cog: commands.Cog = None):
"""
Parameters
----------
cog: Optional[commands.Cog]
The Cog who is taking ownership of Audio's autoplay.
If :code:`None` gives ownership back to Audio
"""
if isinstance(cog, commands.Cog):
self.owns_autoplay = cog
else:
del self.owns_autoplay
@commands.group()
@commands.guild_only()
@commands.bot_has_permissions(embed_links=True)
async def audioset(self, ctx: commands.Context):
"""Music configuration options."""
pass
@audioset.command()
@checks.mod_or_permissions(manage_messages=True)
async def dc(self, ctx: commands.Context):
"""Toggle the bot auto-disconnecting when done playing.
This setting takes precedence over [p]audioset emptydisconnect.
"""
disconnect = await self.config.guild(ctx.guild).disconnect()
autoplay = await self.config.guild(ctx.guild).auto_play()
msg = ""
msg += _("Auto-disconnection at queue end: {true_or_false}.").format(
true_or_false=_("Enabled") if not disconnect else _("Disabled")
)
await self.config.guild(ctx.guild).repeat.set(not disconnect)
if disconnect is not True and autoplay is True:
msg += _("\nAuto-play has been disabled.")
await self.config.guild(ctx.guild).auto_play.set(False)
await self.config.guild(ctx.guild).disconnect.set(not disconnect)
embed = discord.Embed(
title=_("Auto-disconnection settings changed"),
description=msg,
colour=await ctx.embed_colour(),
)
await ctx.send(embed=embed)
@audioset.group(name="restrictions")
@checks.mod_or_permissions(manage_messages=True)
async def _perms(self, ctx: commands.Context):
"""Manages the keyword whitelist and blacklist."""
pass
@_perms.group(name="whitelist")
async def _perms_whitelist(self, ctx: commands.Context):
"""Manages the keyword whitelist."""
pass
@_perms.group(name="blacklist")
async def _perms_blacklist(self, ctx: commands.Context):
"""Manages the keyword blacklist."""
pass
@_perms_blacklist.command(name="add")
async def _perms_blacklist_add(self, ctx: commands.Context, *, keyword: str):
"""Adds a keyword to the blacklist."""
keyword = keyword.lower().strip()
if not keyword:
return await ctx.send_help()
exists = False
async with self.config.guild(ctx.guild).url_keyword_blacklist() as blacklist:
if keyword in blacklist:
exists = True
else:
blacklist.append(keyword)
if exists:
return await self._embed_msg(ctx, _("Keyword already in the blacklist."))
else:
embed = discord.Embed(title=_("Blacklist modified"), colour=await ctx.embed_colour())
embed.description = _("Added: `{blacklisted}` to the blacklist.").format(
blacklisted=keyword
)
await ctx.send(embed=embed)
@_perms_whitelist.command(name="add")
async def _perms_whitelist_add(self, ctx: commands.Context, *, keyword: str):
"""Adds a keyword to the whitelist.
If anything is added to whitelist, it will blacklist everything else.
"""
keyword = keyword.lower().strip()
if not keyword:
return await ctx.send_help()
exists = False
async with self.config.guild(ctx.guild).url_keyword_whitelist() as whitelist:
if keyword in whitelist:
exists = True
else:
whitelist.append(keyword)
if exists:
return await self._embed_msg(ctx, _("Keyword already in the whitelist."))
else:
embed = discord.Embed(title=_("Whitelist modified"), colour=await ctx.embed_colour())
embed.description = _("Added: `{whitelisted}` to the whitelist.").format(
whitelisted=keyword
)
await ctx.send(embed=embed)
@_perms_blacklist.command(name="delete", aliases=["del", "remove"])
async def _perms_blacklist_delete(self, ctx: commands.Context, *, keyword: str):
"""Removes a keyword from the blacklist."""
keyword = keyword.lower().strip()
if not keyword:
return await ctx.send_help()
exists = True
async with self.config.guild(ctx.guild).url_keyword_blacklist() as blacklist:
if keyword not in blacklist:
exists = False
else:
blacklist.remove(keyword)
if not exists:
return await self._embed_msg(ctx, _("Keyword is not in the blacklist."))
else:
embed = discord.Embed(title=_("Blacklist modified"), colour=await ctx.embed_colour())
embed.description = _("Removed: `{blacklisted}` from the blacklist.").format(
blacklisted=keyword
)
await ctx.send(embed=embed)
@_perms_whitelist.command(name="delete", aliases=["del", "remove"])
async def _perms_whitelist_delete(self, ctx: commands.Context, *, keyword: str):
"""Removes a keyword from the whitelist."""
keyword = keyword.lower().strip()
if not keyword:
return await ctx.send_help()
exists = True
async with self.config.guild(ctx.guild).url_keyword_whitelist() as whitelist:
if keyword not in whitelist:
exists = False
else:
whitelist.remove(keyword)
if not exists:
return await self._embed_msg(ctx, _("Keyword already in the whitelist."))
else:
embed = discord.Embed(title=_("Whitelist modified"), colour=await ctx.embed_colour())
embed.description = _("Removed: `{whitelisted}` from the whitelist.").format(
whitelisted=keyword
)
await ctx.send(embed=embed)
@_perms_whitelist.command(name="list")
async def _perms_whitelist_list(self, ctx: commands.Context):
"""List all keywords added to the whitelist."""
whitelist = await self.config.guild(ctx.guild).url_keyword_whitelist()
if not whitelist:
return await self._embed_msg(ctx, _("Nothing in the whitelist."))
whitelist.sort()
text = ""
total = len(whitelist)
pages = []
for i, entry in enumerate(whitelist, 1):
text += f"{i}. [{entry}]"
if i != total:
text += "\n"
if i % 10 == 0:
pages.append(box(text, lang="ini"))
text = ""
else:
pages.append(box(text, lang="ini"))
embed_colour = await ctx.embed_colour()
pages = list(
discord.Embed(title="Whitelist", description=page, colour=embed_colour)
for page in pages
)
await menu(ctx, pages, DEFAULT_CONTROLS)
@_perms_blacklist.command(name="list")
async def _perms_blacklist_list(self, ctx: commands.Context):
"""List all keywords added to the blacklist."""
blacklist = await self.config.guild(ctx.guild).url_keyword_blacklist()
if not blacklist:
return await self._embed_msg(ctx, _("Nothing in the blacklist."))
blacklist.sort()
text = ""
total = len(blacklist)
pages = []
for i, entry in enumerate(blacklist, 1):
text += f"{i}. [{entry}]"
if i != total:
text += "\n"
if i % 10 == 0:
pages.append(box(text, lang="ini"))
text = ""
else:
pages.append(box(text, lang="ini"))
embed_colour = await ctx.embed_colour()
pages = list(
discord.Embed(title="Whitelist", description=page, colour=embed_colour)
for page in pages
)
await menu(ctx, pages, DEFAULT_CONTROLS)
@_perms_whitelist.command(name="clear")
async def _perms_whitelist_clear(self, ctx: commands.Context):
"""Clear all keywords from the whitelist."""
whitelist = await self.config.guild(ctx.guild).url_keyword_whitelist()
if not whitelist:
return await self._embed_msg(ctx, _("Nothing in the whitelist."))
await self.config.guild(ctx.guild).url_keyword_whitelist.clear()
return await self._embed_msg(ctx, _("All entries have been removed from the whitelist."))
@_perms_blacklist.command(name="clear")
async def _perms_blacklist_clear(self, ctx: commands.Context):
"""Clear all keywords added to the blacklist."""
blacklist = await self.config.guild(ctx.guild).url_keyword_blacklist()
if not blacklist:
return await self._embed_msg(ctx, _("Nothing in the blacklist."))
await self.config.guild(ctx.guild).url_keyword_blacklist.clear()
return await self._embed_msg(ctx, _("All entries have been removed from the blacklist."))
@audioset.group(name="autoplay")
@checks.mod_or_permissions(manage_messages=True)
async def _autoplay(self, ctx: commands.Context):
"""Change auto-play setting."""
@_autoplay.command(name="toggle")
async def _autoplay_toggle(self, ctx: commands.Context):
"""Toggle auto-play when there no songs in queue."""
autoplay = await self.config.guild(ctx.guild).auto_play()
repeat = await self.config.guild(ctx.guild).repeat()
disconnect = await self.config.guild(ctx.guild).disconnect()
msg = _("Auto-play when queue ends: {true_or_false}.").format(
true_or_false=_("Enabled") if not autoplay else _("Disabled")
)
await self.config.guild(ctx.guild).auto_play.set(not autoplay)
if autoplay is not True and repeat is True:
msg += _("\nRepeat has been disabled.")
await self.config.guild(ctx.guild).repeat.set(False)
if autoplay is not True and disconnect is True:
msg += _("\nAuto-disconnecting at queue end has been disabled.")
await self.config.guild(ctx.guild).disconnect.set(False)
embed = discord.Embed(
title=_("Auto-play settings changed"), description=msg, colour=await ctx.embed_colour()
)
await ctx.send(embed=embed)
if self._player_check(ctx):
await self._data_check(ctx)
@_autoplay.command(name="playlist", usage="<playlist_name_OR_id> [args]")
async def __autoplay_playlist(
self,
ctx: commands.Context,
playlist_matches: PlaylistConverter,
*,
scope_data: ScopeParser = None,
):
"""Set a playlist to auto-play songs from.
**Usage**:
[p]audioset autoplay playlist_name_OR_id args
**Args**:
The following are all optional:
--scope <scope>
--author [user]
--guild [guild] **Only the bot owner can use this**
Scope is one of the following:
Global
Guild
User
Author can be one of the following:
User ID
User Mention
User Name#123
Guild can be one of the following:
Guild ID
Exact guild name
Example use:
[p]audioset autoplay MyGuildPlaylist
[p]audioset autoplay MyGlobalPlaylist --scope Global
[p]audioset autoplay PersonalPlaylist --scope User --author Draper
"""
if scope_data is None:
scope_data = [PlaylistScope.GUILD.value, ctx.author, ctx.guild, False]
scope, author, guild, specified_user = scope_data
try:
playlist_id, playlist_arg = await self._get_correct_playlist_id(
ctx, playlist_matches, scope, author, guild, specified_user
)
except TooManyMatches as e:
return await self._embed_msg(ctx, str(e))
if playlist_id is None:
return await self._embed_msg(
ctx, _("Could not match '{arg}' to a playlist").format(arg=playlist_arg)
)
try:
playlist = await get_playlist(playlist_id, scope, self.bot, guild, author)
tracks = playlist.tracks
if not tracks:
return await self._embed_msg(
ctx, _("Playlist {name} has no tracks.").format(name=playlist.name)
)
playlist_data = dict(enabled=True, id=playlist.id, name=playlist.name, scope=scope)
await self.config.guild(ctx.guild).autoplaylist.set(playlist_data)
except RuntimeError:
return await self._embed_msg(
ctx,
_("Playlist {id} does not exist in {scope} scope.").format(
id=playlist_id, scope=humanize_scope(scope, the=True)
),
)