forked from Just-Some-Bots/MusicBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
2038 lines (1568 loc) · 78 KB
/
bot.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
import os
import sys
import time
import shlex
import shutil
import inspect
import aiohttp
import discord
import asyncio
import traceback
from discord import utils
from discord.object import Object
from discord.enums import ChannelType
from discord.voice_client import VoiceClient
from discord.ext.commands.bot import _get_variable
from io import BytesIO
from functools import wraps
from textwrap import dedent
from datetime import timedelta
from random import choice, shuffle
from collections import defaultdict
from musicbot.playlist import Playlist
from musicbot.player import MusicPlayer
from musicbot.config import Config, ConfigDefaults
from musicbot.permissions import Permissions, PermissionsDefaults
from musicbot.utils import load_file, write_file, sane_round_int
from . import exceptions
from . import downloader
from .opus_loader import load_opus_lib
from .constants import VERSION as BOTVERSION
from .constants import DISCORD_MSG_CHAR_LIMIT, AUDIO_CACHE_PATH
load_opus_lib()
class SkipState:
def __init__(self):
self.skippers = set()
self.skip_msgs = set()
@property
def skip_count(self):
return len(self.skippers)
def reset(self):
self.skippers.clear()
self.skip_msgs.clear()
def add_skipper(self, skipper, msg):
self.skippers.add(skipper)
self.skip_msgs.add(msg)
return self.skip_count
class Response:
def __init__(self, content, reply=False, delete_after=0):
self.content = content
self.reply = reply
self.delete_after = delete_after
class MusicBot(discord.Client):
def __init__(self, config_file=ConfigDefaults.options_file, perms_file=PermissionsDefaults.perms_file):
self.players = {}
self.the_voice_clients = {}
self.locks = defaultdict(asyncio.Lock)
self.voice_client_connect_lock = asyncio.Lock()
self.voice_client_move_lock = asyncio.Lock()
self.config = Config(config_file)
self.permissions = Permissions(perms_file, grant_all=[self.config.owner_id])
self.blacklist = set(load_file(self.config.blacklist_file))
self.autoplaylist = load_file(self.config.auto_playlist_file)
self.downloader = downloader.Downloader(download_folder='audio_cache')
self.exit_signal = None
self.init_ok = False
self.cached_client_id = None
if not self.autoplaylist:
print("Warning: Autoplaylist is empty, disabling.")
self.config.auto_playlist = False
# TODO: Do these properly
ssd_defaults = {'last_np_msg': None, 'auto_paused': False}
self.server_specific_data = defaultdict(lambda: dict(ssd_defaults))
super().__init__()
self.aiosession = aiohttp.ClientSession(loop=self.loop)
self.http.user_agent += ' MusicBot/%s' % BOTVERSION
# TODO: Add some sort of `denied` argument for a message to send when someone else tries to use it
def owner_only(func):
@wraps(func)
async def wrapper(self, *args, **kwargs):
# Only allow the owner to use these commands
orig_msg = _get_variable('message')
if not orig_msg or orig_msg.author.id == self.config.owner_id:
return await func(self, *args, **kwargs)
else:
raise exceptions.PermissionsError("only the owner can use this command", expire_in=30)
return wrapper
@staticmethod
def _fixg(x, dp=2):
return ('{:.%sf}' % dp).format(x).rstrip('0').rstrip('.')
def _get_owner(self, voice=False):
if voice:
for server in self.servers:
for channel in server.channels:
for m in channel.voice_members:
if m.id == self.config.owner_id:
return m
else:
return discord.utils.find(lambda m: m.id == self.config.owner_id, self.get_all_members())
def _delete_old_audiocache(self, path=AUDIO_CACHE_PATH):
try:
shutil.rmtree(path)
return True
except:
try:
os.rename(path, path + '__')
except:
return False
try:
shutil.rmtree(path)
except:
os.rename(path + '__', path)
return False
return True
# TODO: autosummon option to a specific channel
async def _auto_summon(self):
owner = self._get_owner(voice=True)
if owner:
self.safe_print("Found owner in \"%s\", attempting to join..." % owner.voice_channel.name)
# TODO: Effort
await self.cmd_summon(owner.voice_channel, owner, None)
return owner.voice_channel
async def _autojoin_channels(self, channels):
joined_servers = []
for channel in channels:
if channel.server in joined_servers:
print("Already joined a channel in %s, skipping" % channel.server.name)
continue
if channel and channel.type == discord.ChannelType.voice:
self.safe_print("Attempting to autojoin %s in %s" % (channel.name, channel.server.name))
chperms = channel.permissions_for(channel.server.me)
if not chperms.connect:
self.safe_print("Cannot join channel \"%s\", no permission." % channel.name)
continue
elif not chperms.speak:
self.safe_print("Will not join channel \"%s\", no permission to speak." % channel.name)
continue
try:
player = await self.get_player(channel, create=True)
if player.is_stopped:
player.play()
if self.config.auto_playlist:
await self.on_player_finished_playing(player)
joined_servers.append(channel.server)
except Exception as e:
if self.config.debug_mode:
traceback.print_exc()
print("Failed to join", channel.name)
elif channel:
print("Not joining %s on %s, that's a text channel." % (channel.name, channel.server.name))
else:
print("Invalid channel thing: " + channel)
async def _wait_delete_msg(self, message, after):
await asyncio.sleep(after)
await self.safe_delete_message(message)
# TODO: Check to see if I can just move this to on_message after the response check
async def _manual_delete_check(self, message, *, quiet=False):
if self.config.delete_invoking:
await self.safe_delete_message(message, quiet=quiet)
async def _check_ignore_non_voice(self, msg):
vc = msg.server.me.voice_channel
# If we've connected to a voice chat and we're in the same voice channel
if not vc or vc == msg.author.voice_channel:
return True
else:
raise exceptions.PermissionsError(
"you cannot use this command when not in the voice channel (%s)" % vc.name, expire_in=30)
async def generate_invite_link(self, *, permissions=None, server=None):
if not self.cached_client_id:
appinfo = await self.application_info()
self.cached_client_id = appinfo.id
return discord.utils.oauth_url(self.cached_client_id, permissions=permissions, server=server)
async def get_voice_client(self, channel):
if isinstance(channel, Object):
channel = self.get_channel(channel.id)
if getattr(channel, 'type', ChannelType.text) != ChannelType.voice:
raise AttributeError('Channel passed must be a voice channel')
with await self.voice_client_connect_lock:
server = channel.server
if server.id in self.the_voice_clients:
return self.the_voice_clients[server.id]
s_id = self.ws.wait_for('VOICE_STATE_UPDATE', lambda d: d.get('user_id') == self.user.id)
_voice_data = self.ws.wait_for('VOICE_SERVER_UPDATE', lambda d: True)
await self.ws.voice_state(server.id, channel.id)
s_id_data = await asyncio.wait_for(s_id, timeout=10, loop=self.loop)
voice_data = await asyncio.wait_for(_voice_data, timeout=10, loop=self.loop)
session_id = s_id_data.get('session_id')
kwargs = {
'user': self.user,
'channel': channel,
'data': voice_data,
'loop': self.loop,
'session_id': session_id,
'main_ws': self.ws
}
voice_client = VoiceClient(**kwargs)
self.the_voice_clients[server.id] = voice_client
retries = 3
for x in range(retries):
try:
print("Attempting connection...")
await asyncio.wait_for(voice_client.connect(), timeout=10, loop=self.loop)
print("Connection established.")
break
except:
traceback.print_exc()
print("Failed to connect, retrying (%s/%s)..." % (x+1, retries))
await asyncio.sleep(1)
await self.ws.voice_state(server.id, None, self_mute=True)
await asyncio.sleep(1)
if x == retries-1:
raise exceptions.HelpfulError(
"Cannot establish connection to voice chat. "
"Something may be blocking outgoing UDP connections.",
"This may be an issue with a firewall blocking UDP. "
"Figure out what is blocking UDP and disable it. "
"It's most likely a system firewall or overbearing anti-virus firewall. "
)
return voice_client
async def mute_voice_client(self, channel, mute):
await self._update_voice_state(channel, mute=mute)
async def deafen_voice_client(self, channel, deaf):
await self._update_voice_state(channel, deaf=deaf)
async def move_voice_client(self, channel):
await self._update_voice_state(channel)
async def reconnect_voice_client(self, server):
if server.id not in self.the_voice_clients:
return
vc = self.the_voice_clients.pop(server.id)
_paused = False
player = None
if server.id in self.players:
player = self.players[server.id]
if player.is_playing:
player.pause()
_paused = True
try:
await vc.disconnect()
except:
print("Error disconnecting during reconnect")
traceback.print_exc()
await asyncio.sleep(0.1)
if player:
new_vc = await self.get_voice_client(vc.channel)
player.reload_voice(new_vc)
if player.is_paused and _paused:
player.resume()
async def disconnect_voice_client(self, server):
if server.id not in self.the_voice_clients:
return
if server.id in self.players:
self.players.pop(server.id).kill()
await self.the_voice_clients.pop(server.id).disconnect()
async def disconnect_all_voice_clients(self):
for vc in self.the_voice_clients.copy().values():
await self.disconnect_voice_client(vc.channel.server)
async def _update_voice_state(self, channel, *, mute=False, deaf=False):
if isinstance(channel, Object):
channel = self.get_channel(channel.id)
if getattr(channel, 'type', ChannelType.text) != ChannelType.voice:
raise AttributeError('Channel passed must be a voice channel')
# I'm not sure if this lock is actually needed
with await self.voice_client_move_lock:
server = channel.server
payload = {
'op': 4,
'd': {
'guild_id': server.id,
'channel_id': channel.id,
'self_mute': mute,
'self_deaf': deaf
}
}
await self.ws.send(utils.to_json(payload))
self.the_voice_clients[server.id].channel = channel
async def get_player(self, channel, create=False) -> MusicPlayer:
server = channel.server
if server.id not in self.players:
if not create:
raise exceptions.CommandError(
'The bot is not in a voice channel. '
'Use %ssummon to summon it to your voice channel.' % self.config.command_prefix)
voice_client = await self.get_voice_client(channel)
playlist = Playlist(self)
player = MusicPlayer(self, voice_client, playlist) \
.on('play', self.on_player_play) \
.on('resume', self.on_player_resume) \
.on('pause', self.on_player_pause) \
.on('stop', self.on_player_stop) \
.on('finished-playing', self.on_player_finished_playing) \
.on('entry-added', self.on_player_entry_added)
player.skip_state = SkipState()
self.players[server.id] = player
return self.players[server.id]
async def on_player_play(self, player, entry):
await self.update_now_playing(entry)
player.skip_state.reset()
channel = entry.meta.get('channel', None)
author = entry.meta.get('author', None)
if channel and author:
last_np_msg = self.server_specific_data[channel.server]['last_np_msg']
if last_np_msg and last_np_msg.channel == channel:
async for lmsg in self.logs_from(channel, limit=1):
if lmsg != last_np_msg and last_np_msg:
await self.safe_delete_message(last_np_msg)
self.server_specific_data[channel.server]['last_np_msg'] = None
break # This is probably redundant
if self.config.now_playing_mentions:
newmsg = '%s - your song **%s** is now playing in %s!' % (
entry.meta['author'].mention, entry.title, player.voice_client.channel.name)
else:
newmsg = 'Now playing in %s: **%s**' % (
player.voice_client.channel.name, entry.title)
if self.server_specific_data[channel.server]['last_np_msg']:
self.server_specific_data[channel.server]['last_np_msg'] = await self.safe_edit_message(last_np_msg, newmsg, send_if_fail=True)
else:
self.server_specific_data[channel.server]['last_np_msg'] = await self.safe_send_message(channel, newmsg)
async def on_player_resume(self, entry, **_):
await self.update_now_playing(entry)
async def on_player_pause(self, entry, **_):
await self.update_now_playing(entry, True)
async def on_player_stop(self, **_):
await self.update_now_playing()
async def on_player_finished_playing(self, player, **_):
if not player.playlist.entries and not player.current_entry and self.config.auto_playlist:
while self.autoplaylist:
song_url = choice(self.autoplaylist)
info = await self.downloader.safe_extract_info(player.playlist.loop, song_url, download=False, process=False)
if not info:
self.autoplaylist.remove(song_url)
self.safe_print("[Info] Removing unplayable song from autoplaylist: %s" % song_url)
write_file(self.config.auto_playlist_file, self.autoplaylist)
continue
if info.get('entries', None): # or .get('_type', '') == 'playlist'
pass # Wooo playlist
# Blarg how do I want to do this
# TODO: better checks here
try:
await player.playlist.add_entry(song_url, channel=None, author=None)
except exceptions.ExtractionError as e:
print("Error adding song from autoplaylist:", e)
continue
break
if not self.autoplaylist:
print("[Warning] No playable songs in the autoplaylist, disabling.")
self.config.auto_playlist = False
async def on_player_entry_added(self, playlist, entry, **_):
pass
async def update_now_playing(self, entry=None, is_paused=False):
game = None
if self.user.bot:
activeplayers = sum(1 for p in self.players.values() if p.is_playing)
if activeplayers > 1:
game = discord.Game(name="music on %s servers" % activeplayers)
entry = None
elif activeplayers == 1:
player = discord.utils.get(self.players.values(), is_playing=True)
entry = player.current_entry
if entry:
prefix = u'\u275A\u275A ' if is_paused else ''
name = u'{}{}'.format(prefix, entry.title)[:128]
game = discord.Game(name=name)
await self.change_status(game)
async def safe_send_message(self, dest, content, *, tts=False, expire_in=0, also_delete=None, quiet=False):
msg = None
try:
msg = await self.send_message(dest, content, tts=tts)
if msg and expire_in:
asyncio.ensure_future(self._wait_delete_msg(msg, expire_in))
if also_delete and isinstance(also_delete, discord.Message):
asyncio.ensure_future(self._wait_delete_msg(also_delete, expire_in))
except discord.Forbidden:
if not quiet:
self.safe_print("Warning: Cannot send message to %s, no permission" % dest.name)
except discord.NotFound:
if not quiet:
self.safe_print("Warning: Cannot send message to %s, invalid channel?" % dest.name)
return msg
async def safe_delete_message(self, message, *, quiet=False):
try:
return await self.delete_message(message)
except discord.Forbidden:
if not quiet:
self.safe_print("Warning: Cannot delete message \"%s\", no permission" % message.clean_content)
except discord.NotFound:
if not quiet:
self.safe_print("Warning: Cannot delete message \"%s\", message not found" % message.clean_content)
async def safe_edit_message(self, message, new, *, send_if_fail=False, quiet=False):
try:
return await self.edit_message(message, new)
except discord.NotFound:
if not quiet:
self.safe_print("Warning: Cannot edit message \"%s\", message not found" % message.clean_content)
if send_if_fail:
if not quiet:
print("Sending instead")
return await self.safe_send_message(message.channel, new)
def safe_print(self, content, *, end='\n', flush=True):
sys.stdout.buffer.write((content + end).encode('utf-8', 'replace'))
if flush: sys.stdout.flush()
async def send_typing(self, destination):
try:
return await super().send_typing(destination)
except discord.Forbidden:
if self.config.debug_mode:
print("Could not send typing to %s, no permssion" % destination)
async def edit_profile(self, **fields):
if self.user.bot:
return await super().edit_profile(**fields)
else:
return await super().edit_profile(self.config._password,**fields)
def _cleanup(self):
try:
self.loop.run_until_complete(self.logout())
except: # Can be ignored
pass
pending = asyncio.Task.all_tasks()
gathered = asyncio.gather(*pending)
try:
gathered.cancel()
self.loop.run_until_complete(gathered)
gathered.exception()
except: # Can be ignored
pass
# noinspection PyMethodOverriding
def run(self):
try:
self.loop.run_until_complete(self.start(*self.config.auth))
except discord.errors.LoginFailure:
# Add if token, else
raise exceptions.HelpfulError(
"Bot cannot login, bad credentials.",
"Fix your Email or Password or Token in the options file. "
"Remember that each field should be on their own line.")
finally:
try:
self._cleanup()
except Exception as e:
print("Error in cleanup:", e)
self.loop.close()
if self.exit_signal:
raise self.exit_signal
async def logout(self):
await self.disconnect_all_voice_clients()
return await super().logout()
async def on_error(self, event, *args, **kwargs):
ex_type, ex, stack = sys.exc_info()
if ex_type == exceptions.HelpfulError:
print("Exception in", event)
print(ex.message)
await asyncio.sleep(2) # don't ask
await self.logout()
elif issubclass(ex_type, exceptions.Signal):
self.exit_signal = ex_type
await self.logout()
else:
traceback.print_exc()
async def on_resumed(self):
for vc in self.the_voice_clients.values():
vc.main_ws = self.ws
async def on_ready(self):
print('\rConnected! Musicbot v%s\n' % BOTVERSION)
if self.config.owner_id == self.user.id:
raise exceptions.HelpfulError(
"Your OwnerID is incorrect or you've used the wrong credentials.",
"The bot needs its own account to function. "
"The OwnerID is the id of the owner, not the bot. "
"Figure out which one is which and use the correct information.")
self.init_ok = True
self.safe_print("Bot: %s/%s#%s" % (self.user.id, self.user.name, self.user.discriminator))
owner = self._get_owner(voice=True) or self._get_owner()
if owner and self.servers:
self.safe_print("Owner: %s/%s#%s\n" % (owner.id, owner.name, owner.discriminator))
print('Server List:')
[self.safe_print(' - ' + s.name) for s in self.servers]
elif self.servers:
print("Owner could not be found on any server (id: %s)\n" % self.config.owner_id)
print('Server List:')
[self.safe_print(' - ' + s.name) for s in self.servers]
else:
print("Owner unknown, bot is not on any servers.")
if self.user.bot:
print("\nTo make the bot join a server, paste this link in your browser.")
print("Note: You should be logged into your main account and have \n"
"manage server permissions on the server you want the bot to join.\n")
print(" " + await self.generate_invite_link())
print()
if self.config.bound_channels:
chlist = set(self.get_channel(i) for i in self.config.bound_channels if i)
chlist.discard(None)
invalids = set()
invalids.update(c for c in chlist if c.type == discord.ChannelType.voice)
chlist.difference_update(invalids)
self.config.bound_channels.difference_update(invalids)
print("Bound to text channels:")
[self.safe_print(' - %s/%s' % (ch.server.name.strip(), ch.name.strip())) for ch in chlist if ch]
if invalids and self.config.debug_mode:
print("\nNot binding to voice channels:")
[self.safe_print(' - %s/%s' % (ch.server.name.strip(), ch.name.strip())) for ch in invalids if ch]
print()
else:
print("Not bound to any text channels")
if self.config.autojoin_channels:
chlist = set(self.get_channel(i) for i in self.config.autojoin_channels if i)
chlist.discard(None)
invalids = set()
invalids.update(c for c in chlist if c.type == discord.ChannelType.text)
chlist.difference_update(invalids)
self.config.autojoin_channels.difference_update(invalids)
print("Autojoining voice chanels:")
[self.safe_print(' - %s/%s' % (ch.server.name.strip(), ch.name.strip())) for ch in chlist if ch]
if invalids and self.config.debug_mode:
print("\nCannot join text channels:")
[self.safe_print(' - %s/%s' % (ch.server.name.strip(), ch.name.strip())) for ch in invalids if ch]
autojoin_channels = chlist
else:
print("Not autojoining any voice channels")
autojoin_channels = set()
print()
print("Options:")
self.safe_print(" Command prefix: " + self.config.command_prefix)
print(" Default volume: %s%%" % int(self.config.default_volume * 100))
print(" Skip threshold: %s votes or %s%%" % (
self.config.skips_required, self._fixg(self.config.skip_ratio_required * 100)))
print(" Now Playing @mentions: " + ['Disabled', 'Enabled'][self.config.now_playing_mentions])
print(" Auto-Summon: " + ['Disabled', 'Enabled'][self.config.auto_summon])
print(" Auto-Playlist: " + ['Disabled', 'Enabled'][self.config.auto_playlist])
print(" Auto-Pause: " + ['Disabled', 'Enabled'][self.config.auto_pause])
print(" Delete Messages: " + ['Disabled', 'Enabled'][self.config.delete_messages])
if self.config.delete_messages:
print(" Delete Invoking: " + ['Disabled', 'Enabled'][self.config.delete_invoking])
print(" Debug Mode: " + ['Disabled', 'Enabled'][self.config.debug_mode])
print(" Downloaded songs will be %s" % ['deleted', 'saved'][self.config.save_videos])
print()
# maybe option to leave the ownerid blank and generate a random command for the owner to use
# wait_for_message is pretty neato
if not self.config.save_videos and os.path.isdir(AUDIO_CACHE_PATH):
if self._delete_old_audiocache():
print("Deleting old audio cache")
else:
print("Could not delete old audio cache, moving on.")
if self.config.autojoin_channels:
await self._autojoin_channels(autojoin_channels)
elif self.config.auto_summon:
print("Attempting to autosummon...", flush=True)
# waitfor + get value
owner_vc = await self._auto_summon()
if owner_vc:
print("Done!", flush=True) # TODO: Change this to "Joined server/channel"
if self.config.auto_playlist:
print("Starting auto-playlist")
await self.on_player_finished_playing(await self.get_player(owner_vc))
else:
print("Owner not found in a voice channel, could not autosummon.")
print()
# t-t-th-th-that's all folks!
async def cmd_help(self, command=None):
"""
Usage:
{command_prefix}help [command]
Prints a help message.
If a command is specified, it prints a help message for that command.
Otherwise, it lists the available commands.
"""
if command:
cmd = getattr(self, 'cmd_' + command, None)
if cmd:
return Response(
"```\n{}```".format(
dedent(cmd.__doc__),
command_prefix=self.config.command_prefix
),
delete_after=60
)
else:
return Response("No such command", delete_after=10)
else:
helpmsg = "**Commands**\n```"
commands = []
for att in dir(self):
if att.startswith('cmd_') and att != 'cmd_help':
command_name = att.replace('cmd_', '').lower()
commands.append("{}{}".format(self.config.command_prefix, command_name))
helpmsg += ", ".join(commands)
helpmsg += "```"
helpmsg += "https://github.com/SexualRhinoceros/MusicBot/wiki/Commands-list"
return Response(helpmsg, reply=True, delete_after=60)
async def cmd_remove(self, player, author, permissions, index):
try:
index = int(index) - 1
except ValueError:
return Response('Index must be a number! You played yourself.')
try:
if author.id == self.config.owner_id \
or permissions.instaskip \
or author == player.playlist.entries[index].meta.get('author', None):
song = player.playlist.entries[index]
del player.playlist.entries[index]
else:
raise exceptions.PermissionsError("only the owner or the song selector can remove"
" a song from the play queue")
except KeyError:
return Response('Song at index {} does not exist'.format(index))
else:
return Response('Removed {} from the play queue'.format(song.title))
async def cmd_blacklist(self, message, user_mentions, option, something):
"""
Usage:
{command_prefix}blacklist [ + | - | add | remove ] @UserName [@UserName2 ...]
Add or remove users to the blacklist.
Blacklisted users are forbidden from using bot commands.
"""
if not user_mentions:
raise exceptions.CommandError("No users listed.", expire_in=20)
if option not in ['+', '-', 'add', 'remove']:
raise exceptions.CommandError(
'Invalid option "%s" specified, use +, -, add, or remove' % option, expire_in=20
)
for user in user_mentions.copy():
if user.id == self.config.owner_id:
print("[Commands:Blacklist] The owner cannot be blacklisted.")
user_mentions.remove(user)
old_len = len(self.blacklist)
if option in ['+', 'add']:
self.blacklist.update(user.id for user in user_mentions)
write_file(self.config.blacklist_file, self.blacklist)
return Response(
'%s users have been added to the blacklist' % (len(self.blacklist) - old_len),
reply=True, delete_after=10
)
else:
if self.blacklist.isdisjoint(user.id for user in user_mentions):
return Response('none of those users are in the blacklist.', reply=True, delete_after=10)
else:
self.blacklist.difference_update(user.id for user in user_mentions)
write_file(self.config.blacklist_file, self.blacklist)
return Response(
'%s users have been removed from the blacklist' % (old_len - len(self.blacklist)),
reply=True, delete_after=10
)
async def cmd_id(self, author, user_mentions):
"""
Usage:
{command_prefix}id [@user]
Tells the user their id or the id of another user.
"""
if not user_mentions:
return Response('your id is `%s`' % author.id, reply=True, delete_after=35)
else:
usr = user_mentions[0]
return Response("%s's id is `%s`" % (usr.name, usr.id), reply=True, delete_after=35)
@owner_only
async def cmd_joinserver(self, message, server_link=None):
"""
Usage:
{command_prefix}joinserver invite_link
Asks the bot to join a server. Note: Bot accounts cannot use invite links.
"""
if self.user.bot:
url = await self.generate_invite_link()
return Response(
"Bot accounts can't use invite links! Click here to invite me: \n{}".format(url),
reply=True, delete_after=30
)
try:
if server_link:
await self.accept_invite(server_link)
return Response(":+1:")
except:
raise exceptions.CommandError('Invalid URL provided:\n{}\n'.format(server_link), expire_in=30)
async def cmd_play(self, player, channel, author, permissions, leftover_args, song_url):
"""
Usage:
{command_prefix}play song_link
{command_prefix}play text to search for
Adds the song to the playlist. If a link is not provided, the first
result from a youtube search is added to the queue.
"""
song_url = song_url.strip('<>')
if permissions.max_songs and player.playlist.count_for_user(author) >= permissions.max_songs:
raise exceptions.PermissionsError(
"You have reached your enqueued song limit (%s)" % permissions.max_songs, expire_in=30
)
await self.send_typing(channel)
if leftover_args:
song_url = ' '.join([song_url, *leftover_args])
try:
info = await self.downloader.extract_info(player.playlist.loop, song_url, download=False, process=False)
except Exception as e:
raise exceptions.CommandError(e, expire_in=30)
if not info:
raise exceptions.CommandError("That video cannot be played.", expire_in=30)
# abstract the search handling away from the user
# our ytdl options allow us to use search strings as input urls
if info.get('url', '').startswith('ytsearch'):
# print("[Command:play] Searching for \"%s\"" % song_url)
info = await self.downloader.extract_info(
player.playlist.loop,
song_url,
download=False,
process=True, # ASYNC LAMBDAS WHEN
on_error=lambda e: asyncio.ensure_future(
self.safe_send_message(channel, "```\n%s\n```" % e, expire_in=120), loop=self.loop),
retry_on_error=True
)
if not info:
raise exceptions.CommandError(
"Error extracting info from search string, youtubedl returned no data. "
"You may need to restart the bot if this continues to happen.", expire_in=30
)
if not all(info.get('entries', [])):
# empty list, no data
return
song_url = info['entries'][0]['webpage_url']
info = await self.downloader.extract_info(player.playlist.loop, song_url, download=False, process=False)
# Now I could just do: return await self.cmd_play(player, channel, author, song_url)
# But this is probably fine
# TODO: Possibly add another check here to see about things like the bandcamp issue
# TODO: Where ytdl gets the generic extractor version with no processing, but finds two different urls
if 'entries' in info:
# I have to do exe extra checks anyways because you can request an arbitrary number of search results
if not permissions.allow_playlists and ':search' in info['extractor'] and len(info['entries']) > 1:
raise exceptions.PermissionsError("You are not allowed to request playlists", expire_in=30)
# The only reason we would use this over `len(info['entries'])` is if we add `if _` to this one
num_songs = sum(1 for _ in info['entries'])
if permissions.max_playlist_length and num_songs > permissions.max_playlist_length:
raise exceptions.PermissionsError(
"Playlist has too many entries (%s > %s)" % (num_songs, permissions.max_playlist_length),
expire_in=30
)
# This is a little bit weird when it says (x + 0 > y), I might add the other check back in
if permissions.max_songs and player.playlist.count_for_user(author) + num_songs > permissions.max_songs:
raise exceptions.PermissionsError(
"Playlist entries + your already queued songs reached limit (%s + %s > %s)" % (
num_songs, player.playlist.count_for_user(author), permissions.max_songs),
expire_in=30
)
if info['extractor'].lower() in ['youtube:playlist', 'soundcloud:set', 'bandcamp:album']:
try:
return await self._cmd_play_playlist_async(player, channel, author, permissions, song_url, info['extractor'])
except exceptions.CommandError:
raise
except Exception as e:
traceback.print_exc()
raise exceptions.CommandError("Error queuing playlist:\n%s" % e, expire_in=30)
t0 = time.time()
# My test was 1.2 seconds per song, but we maybe should fudge it a bit, unless we can
# monitor it and edit the message with the estimated time, but that's some ADVANCED SHIT
# I don't think we can hook into it anyways, so this will have to do.
# It would probably be a thread to check a few playlists and get the speed from that
# Different playlists might download at different speeds though
wait_per_song = 1.2
procmesg = await self.safe_send_message(
channel,
'Gathering playlist information for {} songs{}'.format(
num_songs,
', ETA: {} seconds'.format(self._fixg(
num_songs * wait_per_song)) if num_songs >= 10 else '.'))
# We don't have a pretty way of doing this yet. We need either a loop
# that sends these every 10 seconds or a nice context manager.
await self.send_typing(channel)
# TODO: I can create an event emitter object instead, add event functions, and every play list might be asyncified
# Also have a "verify_entry" hook with the entry as an arg and returns the entry if its ok
entry_list, position = await player.playlist.import_from(song_url, channel=channel, author=author)
tnow = time.time()
ttime = tnow - t0
listlen = len(entry_list)
drop_count = 0
if permissions.max_song_length:
for e in entry_list.copy():
if e.duration > permissions.max_song_length:
player.playlist.entries.remove(e)
entry_list.remove(e)
drop_count += 1
# Im pretty sure there's no situation where this would ever break
# Unless the first entry starts being played, which would make this a race condition
if drop_count:
print("Dropped %s songs" % drop_count)
print("Processed {} songs in {} seconds at {:.2f}s/song, {:+.2g}/song from expected ({}s)".format(