This repository has been archived by the owner on Nov 30, 2017. It is now read-only.
/
audio.py
2208 lines (1827 loc) · 78.1 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
#Written by Cog Creators @ Red Discord Bot | https://github.com/Twentysix26/Red-DiscordBot
import discord
from discord.ext import commands
import threading
import os
from random import shuffle, choice
from cogs.utils.dataIO import dataIO
from cogs.utils import checks
from cogs.utils.chat_formatting import pagify, escape
from urllib.parse import urlparse
from __main__ import settings
from json import JSONDecodeError
import re
import logging
import collections
import copy
import asyncio
import math
import time
import inspect
import subprocess
import urllib.parse
import youtube_dl
from enum import Enum
__author__ = "tekulvw"
__version__ = "0.1.1"
log = logging.getLogger("bot.audio")
try:
if not discord.opus.is_loaded():
discord.opus.load_opus('libopus-0.dll')
except OSError:
opus = False
except:
opus = None
else:
opus = True
youtube_dl_options = {
'source_address': '0.0.0.0',
'format': 'bestaudio/best',
'extractaudio': True,
'audioformat': "mp3",
'nocheckcertificate': True,
'ignoreerrors': False,
'quiet': True,
'no_warnings': True,
'outtmpl': "data/audio/cache/%(id)s",
'default_search': 'auto',
'encoding': 'utf-8'
}
class MaximumLength(Exception):
def __init__(self, m):
self.message = m
def __str__(self):
return self.message
class YouTubeDlError(Exception):
def __init__(self, m):
self.message = m
def __str__(self):
return self.message
class NotConnected(Exception):
pass
class AuthorNotConnected(NotConnected):
pass
class VoiceNotConnected(NotConnected):
pass
class UnauthorizedConnect(Exception):
pass
class UnauthorizedSpeak(Exception):
pass
class ChannelUserLimit(Exception):
pass
class UnauthorizedSave(Exception):
pass
class ConnectTimeout(NotConnected):
pass
class InvalidURL(Exception):
pass
class InvalidSong(InvalidURL):
pass
class InvalidPlaylist(InvalidSong):
pass
class deque(collections.deque):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def peek(self):
ret = self.pop()
self.append(ret)
return copy.deepcopy(ret)
def peekleft(self):
ret = self.popleft()
self.appendleft(ret)
return copy.deepcopy(ret)
class QueueKey(Enum):
REPEAT = 1
PLAYLIST = 2
VOICE_CHANNEL_ID = 3
QUEUE = 4
TEMP_QUEUE = 5
NOW_PLAYING = 6
NOW_PLAYING_CHANNEL = 7
class Song:
def __init__(self, **kwargs):
self.__dict__ = kwargs
self.title = kwargs.pop('title', None)
self.id = kwargs.pop('id', None)
self.url = kwargs.pop('url', None)
self.webpage_url = kwargs.pop('webpage_url', "")
self.duration = kwargs.pop('duration', 60)
self.start_time = kwargs.pop('start_time', None)
self.end_time = kwargs.pop('end_time', None)
class QueuedSong:
def __init__(self, url, channel):
self.url = url
self.channel = channel
class Playlist:
def __init__(self, server=None, sid=None, name=None, author=None, url=None,
playlist=None, path=None, main_class=None, **kwargs):
self.server = server
self._sid = sid
self.name = name
self.author = author
self.url = url
self.main_class = main_class
self.path = path
if url is None and "link" in kwargs:
self.url = kwargs.get('link')
self.playlist = playlist
@property
def filename(self):
f = "data/audio/playlists"
f = os.path.join(f, self.sid, self.name + ".txt")
return f
def to_json(self):
ret = {"author": self.author, "playlist": self.playlist,
"link": self.url}
return ret
def is_author(self, user):
"""checks if the user is the author of this playlist
Returns True/False"""
return user.id == self.author
def can_edit(self, user):
"""right now checks if user is mod or higher including server owner
global playlists are uneditable atm
dev notes:
should probably be defined elsewhere later or be dynamic"""
if self.main_class._playlist_exists_global(self.name):
return False
is_playlist_author = self.is_author(user)
is_bot_owner = user.id == settings.owner
is_server_owner = self.server.owner.id == self.author
is_dev = user.id == settings.dev
return any((is_playlist_author,
is_bot_owner,
is_server_owner,
is_dev))
def append_song(self, author, url):
if not self.can_edit(author):
raise UnauthorizedSave
elif not self.main_class._valid_playable_url(url):
raise InvalidURL
else:
self.playlist.append(url)
self.save()
def save(self):
dataIO.save_json(self.path, self.to_json())
@property
def sid(self):
if self._sid:
return self._sid
elif self.server:
return self.server.id
else:
return None
class Downloader(threading.Thread):
def __init__(self, url, max_duration=None, download=False,
cache_path="data/audio/cache", *args, **kwargs):
super().__init__(*args, **kwargs)
self.url = url
self.max_duration = max_duration
self.done = threading.Event()
self.song = None
self._download = download
self.hit_max_length = threading.Event()
self._yt = None
self.error = None
def run(self):
try:
self.get_info()
if self._download:
self.download()
except youtube_dl.utils.DownloadError as e:
self.error = str(e)
except MaximumLength:
self.hit_max_length.set()
except OSError as e:
log.warning("An OSError occurred while downloading URL '{}':\n'{}'".format(self.url, str(e)))
except KeyError as e:
log.warning("A KeyError occurred while downloading URL '{}':\n'{}'".format(self.url, str(e)))
self.done.set()
def download(self):
self.duration_check()
if not os.path.isfile('data/audio/cache' + self.song.id):
video = self._yt.extract_info(self.url)
self.song = Song(**video)
def duration_check(self):
log.debug("duration {} for songid {}".format(self.song.duration,
self.song.id))
if self.max_duration and self.song.duration > self.max_duration:
log.debug("songid {} too long".format(self.song.id))
raise MaximumLength("songid {} has duration {} > {}".format(
self.song.id, self.song.duration, self.max_duration))
def get_info(self):
if self._yt is None:
self._yt = youtube_dl.YoutubeDL(youtube_dl_options)
if "[SEARCH:]" not in self.url:
video = self._yt.extract_info(self.url, download=False,
process=False)
else:
try:
self.url = self.url[9:]
yt_id = self._yt.extract_info(
self.url, download=False)["entries"][0]["id"]
self.url = "https://youtube.com/watch?v={}".format(yt_id)
video = self._yt.extract_info(self.url, download=False,
process=False)
except AttributeError as e:
server = ctx.message.server
vc = self.voice_client(server)
log.warning("An AttributeError occurred downloading URL '{}'\n'{}'".format(self.url, str(e)))
vc.audio_player.stop()
return
if(video is not None):
self.song = Song(**video)
class Audio:
"""Music Streaming."""
def __init__(self, bot, player):
self.bot = bot
self.queue = {}
self.downloaders = {}
self.settings = dataIO.load_json("data/audio/settings.json")
self.server_specific_setting_keys = ["VOLUME", "VOTE_ENABLED",
"VOTE_THRESHOLD", "NOPPL_DISCONNECT"]
self.cache_path = "data/audio/cache"
self.local_playlist_path = "data/audio/localtracks"
self._old_game = False
self.skip_votes = {}
self.connect_timers = {}
if player == "ffmpeg":
self.settings["AVCONV"] = False
elif player == "avconv":
self.settings["AVCONV"] = True
self.save_settings()
async def _add_song_status(self, song):
if self._old_game is False:
self._old_game = list(self.bot.servers)[0].me.game
status = list(self.bot.servers)[0].me.status
game = discord.Game(name=song.title)
await self.bot.change_presence(status=status, game=game)
log.debug('Bot status changed to song title: ' + song.title)
def _add_to_queue(self, server, url, channel):
if server.id not in self.queue:
self._setup_queue(server)
queued_song = QueuedSong(url, channel)
self.queue[server.id][QueueKey.QUEUE].append(queued_song)
def _add_to_temp_queue(self, server, url, channel):
if server.id not in self.queue:
self._setup_queue(server)
queued_song = QueuedSong(url, channel)
self.queue[server.id][QueueKey.TEMP_QUEUE].append(queued_song)
def _addleft_to_queue(self, server, url, channel):
if server.id not in self.queue:
self._setup_queue()
queued_song = QueuedSong(url, channel)
self.queue[server.id][QueueKey.QUEUE].appendleft(queued_song)
def _cache_desired_files(self):
filelist = []
for server in self.downloaders:
song = self.downloaders[server].song
try:
filelist.append(song.id)
except AttributeError:
pass
shuffle(filelist)
return filelist
def _cache_max(self):
setting_max = self.settings["MAX_CACHE"]
return max([setting_max, self._cache_min()])
def _cache_min(self):
x = self._server_count()
return max([60, 48 * math.log(x) * x**0.3])
def _cache_required_files(self):
queue = copy.deepcopy(self.queue)
filelist = []
for server in queue:
now_playing = queue[server].get(QueueKey.NOW_PLAYING)
try:
filelist.append(now_playing.id)
except AttributeError:
pass
return filelist
def _cache_size(self):
songs = os.listdir(self.cache_path)
size = sum(map(lambda s: os.path.getsize(
os.path.join(self.cache_path, s)) / 10**6, songs))
return size
def _cache_too_large(self):
if self._cache_size() > self._cache_max():
return True
return False
def _clear_queue(self, server):
if server.id not in self.queue:
return
self.queue[server.id][QueueKey.QUEUE] = deque()
self.queue[server.id][QueueKey.TEMP_QUEUE] = deque()
async def _create_ffmpeg_player(self, server, filename, local=False, start_time=None, end_time=None):
"""This function will guarantee we have a valid voice client,
even if one doesn't exist previously."""
voice_channel_id = self.queue[server.id][QueueKey.VOICE_CHANNEL_ID]
voice_client = self.voice_client(server)
if voice_client is None:
log.debug("not connected when we should be in sid {}".format(
server.id))
to_connect = self.bot.get_channel(voice_channel_id)
if to_connect is None:
raise VoiceNotConnected("Okay somehow we're not connected and"
" we have no valid channel to"
" reconnect to. In other words...LOL"
" REKT.")
log.debug("valid reconnect channel for sid"
" {}, reconnecting...".format(server.id))
await self._join_voice_channel(to_connect)
elif voice_client.channel.id != voice_channel_id:
self.queue[server.id][QueueKey.VOICE_CHANNEL_ID] = voice_client.channel.id
log.debug("reconnect chan id for sid {} is wrong, fixing".format(
server.id))
if local:
song_filename = os.path.join(self.local_playlist_path, filename)
else:
song_filename = os.path.join(self.cache_path, filename)
use_avconv = self.settings["AVCONV"]
options = '-b:a 64k -bufsize 64k'
before_options = ''
if start_time:
before_options += '-ss {}'.format(start_time)
if end_time:
options += ' -to {} -copyts'.format(end_time)
try:
voice_client.audio_player.process.kill()
log.debug("killed old player")
except AttributeError:
pass
except ProcessLookupError:
pass
log.debug("making player on sid {}".format(server.id))
voice_client.audio_player = voice_client.create_ffmpeg_player(
song_filename, use_avconv=use_avconv, options=options, before_options=before_options)
vol = self.get_server_settings(server)['VOLUME'] / 100
voice_client.audio_player.volume = vol
return voice_client
def _delete_playlist(self, server, name):
if not name.endswith('.txt'):
name = name + ".txt"
try:
os.remove(os.path.join('data/audio/playlists', server.id, name))
except OSError:
pass
except WindowsError:
pass
async def _disconnect_voice_client(self, server):
if not self.voice_connected(server):
return
voice_client = self.voice_client(server)
await voice_client.disconnect()
async def _download_all(self, queued_song_list, channel):
"""
Doesn't actually download, just get's info for uses like queue_list
"""
downloaders = []
for queued_song in queued_song_list:
d = Downloader(queued_song.url)
d.start()
downloaders.append(d)
while any([d.is_alive() for d in downloaders]):
await asyncio.sleep(0.1)
songs = [d.song for d in downloaders if d.song is not None and d.error is None]
invalid_downloads = [d for d in downloaders if d.error is not None]
invalid_number = len(invalid_downloads)
if(invalid_number > 0):
await self.bot.send_message(channel, "{} item(s) in the current queue"
" can't be played.".format(invalid_number))
return songs
async def _download_next(self, server, curr_dl, next_dl):
"""Checks to see if we need to download the next, and does.
Both curr_dl and next_dl should already be started."""
if curr_dl.song is None:
return
max_length = self.settings["MAX_LENGTH"]
while next_dl.is_alive():
await asyncio.sleep(0.5)
error = next_dl.error
if(error is not None):
raise YouTubeDlError(error)
if curr_dl.song.id != next_dl.song.id:
log.debug("downloader ID's mismatch on sid {}".format(server.id) +
" gonna start dl-ing the next thing on the queue"
" id {}".format(next_dl.song.id))
try:
next_dl.duration_check()
except MaximumLength:
return
self.downloaders[server.id] = Downloader(next_dl.url, max_length,
download=True)
self.downloaders[server.id].start()
def _dump_cache(self, ignore_desired=False):
reqd = self._cache_required_files()
log.debug("required cache files:\n\t{}".format(reqd))
opt = self._cache_desired_files()
log.debug("desired cache files:\n\t{}".format(opt))
prev_size = self._cache_size()
for file in os.listdir(self.cache_path):
if file not in reqd:
if ignore_desired or file not in opt:
try:
os.remove(os.path.join(self.cache_path, file))
except OSError:
pass
except WindowsError:
pass
post_size = self._cache_size()
dumped = prev_size - post_size
if not ignore_desired and self._cache_too_large():
log.debug("must dump desired files")
return dumped + self._dump_cache(ignore_desired=True)
log.debug("dumped {} MB of audio files".format(dumped))
return dumped
def _get_active_voice_clients(self):
avcs = []
for vc in self.bot.voice_clients:
if hasattr(vc, 'audio_player') and not vc.audio_player.is_done():
avcs.append(vc)
return avcs
def _get_queue(self, server, limit):
if server.id not in self.queue:
return []
ret = []
for i in range(limit):
try:
ret.append(self.queue[server.id][QueueKey.QUEUE][i])
except IndexError:
pass
return ret
def _get_queue_nowplaying(self, server):
if server.id not in self.queue:
return None
return self.queue[server.id][QueueKey.NOW_PLAYING]
def _get_queue_nowplaying_channel(self, server):
if server.id not in self.queue:
return None
return self.queue[server.id][QueueKey.NOW_PLAYING_CHANNEL]
def _get_queue_playlist(self, server):
if server.id not in self.queue:
return None
return self.queue[server.id][QueueKey.PLAYLIST]
def _get_queue_repeat(self, server):
if server.id not in self.queue:
return None
return self.queue[server.id][QueueKey.REPEAT]
def _get_queue_tempqueue(self, server, limit):
if server.id not in self.queue:
return []
ret = []
for i in range(limit):
try:
ret.append(self.queue[server.id][QueueKey.TEMP_QUEUE][i])
except IndexError:
pass
return ret
async def _guarantee_downloaded(self, server, url):
max_length = self.settings["MAX_LENGTH"]
if server.id not in self.downloaders:
log.debug("sid {} not in downloaders, making one".format(
server.id))
self.downloaders[server.id] = Downloader(url, max_length)
if self.downloaders[server.id].url != url:
log.debug("sid {} in downloaders but wrong url".format(server.id))
self.downloaders[server.id] = Downloader(url, max_length)
try:
self.downloaders[server.id].start()
log.debug("starting our downloader for sid {}".format(server.id))
except RuntimeError:
pass
self.downloaders[server.id].done.wait()
error = self.downloaders[server.id].error
if(error is not None):
raise YouTubeDlError(error)
self.downloaders[server.id].duration_check()
song = self.downloaders[server.id].song
log.debug("sid {} wants to play songid {}".format(server.id, song.id))
cache_location = os.path.join(self.cache_path, song.id)
if not os.path.exists(cache_location):
log.debug("cache miss on song id {}".format(song.id))
self.downloaders[server.id] = Downloader(url, max_length,
download=True)
self.downloaders[server.id].start()
while self.downloaders[server.id].is_alive():
await asyncio.sleep(0.5)
song = self.downloaders[server.id].song
else:
log.debug("cache hit on song id {}".format(song.id))
return song
def _is_queue_playlist(self, server):
if server.id not in self.queue:
return False
return self.queue[server.id][QueueKey.PLAYLIST]
async def _join_voice_channel(self, channel):
server = channel.server
connect_time = self.connect_timers.get(server.id, 0)
if time.time() < connect_time:
diff = int(connect_time - time.time())
raise ConnectTimeout("You're on connect cooldown. Try again in {}"
" seconds.".format(diff))
if server.id in self.queue:
self.queue[server.id][QueueKey.VOICE_CHANNEL_ID] = channel.id
try:
await asyncio.wait_for(self.bot.join_voice_channel(channel),
timeout=5, loop=self.bot.loop)
except asyncio.futures.TimeoutError as e:
log.exception(e)
self.connect_timers[server.id] = time.time() + 300
raise ConnectTimeout("We timed out connecting to a voice channel,"
" please try again in a few minutes.")
def _list_local_playlists(self):
ret = []
for thing in os.listdir(self.local_playlist_path):
if os.path.isdir(os.path.join(self.local_playlist_path, thing)):
ret.append(thing)
log.debug("local playlists:\n\t{}".format(ret))
return ret
def _list_playlists(self, server):
try:
server = server.id
except:
pass
path = "data/audio/playlists"
old_playlists = [f[:-4] for f in os.listdir(path)
if f.endswith(".txt")]
path = os.path.join(path, server)
if os.path.exists(path):
new_playlists = [f[:-4] for f in os.listdir(path)
if f.endswith(".txt")]
else:
new_playlists = []
return list(set(old_playlists + new_playlists))
def _load_playlist(self, server, name, local=True):
try:
server = server.id
except:
pass
f = "data/audio/playlists"
if local:
f = os.path.join(f, server, name + ".txt")
else:
f = os.path.join(f, name + ".txt")
kwargs = dataIO.load_json(f)
kwargs['path'] = f
kwargs['main_class'] = self
kwargs['name'] = name
kwargs['sid'] = server
kwargs['server'] = self.bot.get_server(server)
return Playlist(**kwargs)
def _local_playlist_songlist(self, name):
dirpath = os.path.join(self.local_playlist_path, name)
return sorted(os.listdir(dirpath))
def _make_local_song(self, filename):
folder, song = os.path.split(filename)
return Song(name=song, id=filename, title=song, url=filename,
webpage_url=filename)
def _make_playlist(self, author, url, songlist):
try:
author = author.id
except:
pass
return Playlist(author=author, url=url, playlist=songlist)
def _match_sc_playlist(self, url):
return self._match_sc_url(url)
def _match_yt_playlist(self, url):
if not self._match_yt_url(url):
return False
yt_playlist = re.compile(
r'^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)'
r'((\/playlist\?)|\/watch\?).*(list=)(.*)(&|$)')
if yt_playlist.match(url):
return True
return False
def _match_sc_url(self, url):
sc_url = re.compile(
r'^(https?\:\/\/)?(www\.)?(soundcloud\.com\/)')
if sc_url.match(url):
return True
return False
def _match_yt_url(self, url):
yt_link = re.compile(
r'^(https?\:\/\/)?(www\.|m\.)?(youtube\.com|youtu\.?be)\/.+$')
if yt_link.match(url):
return True
return False
def _match_any_url(self, url):
url = urlparse(url)
if url.scheme and url.netloc and url.path:
return True
return False
async def _parse_playlist(self, url):
if self._match_sc_playlist(url):
return await self._parse_sc_playlist(url)
elif self._match_yt_playlist(url):
return await self._parse_yt_playlist(url)
raise InvalidPlaylist("Please enter a valid Soundcloud or"
" YouTube playlist URL.")
async def _parse_sc_playlist(self, url):
playlist = []
d = Downloader(url)
d.start()
while d.is_alive():
await asyncio.sleep(0.5)
error = d.error
if(error is not None):
raise YouTubeDlError(error)
for entry in d.song.entries:
if entry["url"][4] != "s":
song_url = "https{}".format(entry["url"][4:])
playlist.append(song_url)
else:
playlist.append(entry.url)
return playlist
async def _parse_yt_playlist(self, url):
d = Downloader(url)
d.start()
playlist = []
while d.is_alive():
await asyncio.sleep(0.5)
error = d.error
if(error is not None):
raise YouTubeDlError(error)
for entry in d.song.entries:
try:
song_url = "https://www.youtube.com/watch?v={}".format(
entry['id'])
playlist.append(song_url)
except AttributeError:
pass
except TypeError:
pass
log.debug("song list:\n\t{}".format(playlist))
return playlist
async def _play(self, sid, url, channel):
"""Returns the song object of what's playing"""
if type(sid) is not discord.Server:
server = self.bot.get_server(sid)
else:
server = sid
assert type(server) is discord.Server
log.debug('starting to play on "{}"'.format(server.name))
if self._valid_playable_url(url) or "[SEARCH:]" in url:
clean_url = self._clean_url(url)
try:
song = await self._guarantee_downloaded(server, url)
except YouTubeDlError as e:
message = ("An error occurred while trying to play '{}':\n"
"'{}'".format(clean_url, str(e)))
message = escape(message, mass_mentions=True)
await self.bot.send_message(channel, message)
return
except MaximumLength:
message = ("'{}' can't be played because "
"it exceeds the max length limit.".format(clean_url))
message = escape(message, mass_mentions=True)
await self.bot.send_message(channel, message)
return
local = False
else:
try:
song = self._make_local_song(url)
local = True
except FileNotFoundError:
raise
voice_client = await self._create_ffmpeg_player(server, song.id,
local=local,
start_time=song.start_time,
end_time=song.end_time)
voice_client.audio_player.start()
log.debug("starting player on sid {}".format(server.id))
return song
def _play_playlist(self, server, playlist, channel):
try:
songlist = playlist.playlist
name = playlist.name
except AttributeError:
songlist = playlist
name = True
songlist = self._songlist_change_url_to_queued_song(songlist, channel)
log.debug("setting up playlist {} on sid {}".format(name, server.id))
self._stop_player(server)
self._stop_downloader(server)
self._clear_queue(server)
log.debug("finished resetting state on sid {}".format(server.id))
self._setup_queue(server)
self._set_queue_playlist(server, name)
self._set_queue_repeat(server, True)
self._set_queue(server, songlist)
def _play_local_playlist(self, server, name, channel):
songlist = self._local_playlist_songlist(name)
ret = []
for song in songlist:
ret.append(os.path.join(name, song))
ret_playlist = Playlist(server=server, name=name, playlist=ret)
self._play_playlist(server, ret_playlist, channel)
def _songlist_change_url_to_queued_song(self, songlist, channel):
queued_songlist = []
for song in songlist:
queued_song = QueuedSong(song, channel)
queued_songlist.append(queued_song)
return queued_songlist
def _player_count(self):
count = 0
queue = copy.deepcopy(self.queue)
for sid in queue:
server = self.bot.get_server(sid)
try:
vc = self.voice_client(server)
if vc.audio_player.is_playing():
count += 1
except:
pass
return count
def _playlist_exists(self, server, name):
return self._playlist_exists_local(server, name) or \
self._playlist_exists_global(name)
def _playlist_exists_global(self, name):
f = "data/audio/playlists"
f = os.path.join(f, name + ".txt")
log.debug('checking for {}'.format(f))
return dataIO.is_valid_json(f)
def _playlist_exists_local(self, server, name):
try:
server = server.id
except AttributeError:
pass
f = "data/audio/playlists"
f = os.path.join(f, server, name + ".txt")
log.debug('checking for {}'.format(f))
return dataIO.is_valid_json(f)
def _remove_queue(self, server):
if server.id in self.queue:
del self.queue[server.id]
async def _remove_song_status(self):
if self._old_game is not False:
status = list(self.bot.servers)[0].me.status
await self.bot.change_presence(game=self._old_game,
status=status)
log.debug('Bot status returned to ' + str(self._old_game))
self._old_game = False
def _save_playlist(self, server, name, playlist):
sid = server.id
try:
f = playlist.filename
playlist = playlist.to_json()
log.debug("got playlist object")
except AttributeError:
f = os.path.join("data/audio/playlists", sid, name + ".txt")
head, _ = os.path.split(f)
if not os.path.exists(head):
os.makedirs(head)
log.debug("saving playlist '{}' to {}:\n\t{}".format(name, f,
playlist))
dataIO.save_json(f, playlist)
def _shuffle_queue(self, server):
shuffle(self.queue[server.id][QueueKey.QUEUE])
def _shuffle_temp_queue(self, server):
shuffle(self.queue[server.id][QueueKey.TEMP_QUEUE])
def _server_count(self):
return max([1, len(self.bot.servers)])
def _set_queue(self, server, songlist):
if server.id in self.queue:
self._clear_queue(server)
else:
self._setup_queue(server)
self.queue[server.id][QueueKey.QUEUE].extend(songlist)
def _set_queue_channel(self, server, channel):
if server.id not in self.queue:
return
try:
channel = channel.id
except AttributeError:
pass
self.queue[server.id][QueueKey.VOICE_CHANNEL_ID] = channel
def _set_queue_nowplaying(self, server, song, channel):
if server.id not in self.queue:
return