forked from nilyas/rhinobot_heroku
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
2885 lines (2242 loc) · 121 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 random
import inspect
import logging
import asyncio
import pathlib
import traceback
import math
import re
import aiohttp
import discord
import colorlog
from io import BytesIO, StringIO
from functools import wraps
from textwrap import dedent
from datetime import timedelta
from collections import defaultdict
from discord.enums import ChannelType
from . import exceptions
from . import downloader
from .playlist import Playlist
from .player import MusicPlayer
from .entry import StreamPlaylistEntry
from .opus_loader import load_opus_lib
from .config import Config, ConfigDefaults
from .permissions import Permissions, PermissionsDefaults
from .constructs import SkipState, Response
from .utils import load_file, write_file, fixg, ftimedelta, _func_, _get_variable
from .spotify import Spotify
from .json import Json
from .constants import VERSION as BOTVERSION
from .constants import DISCORD_MSG_CHAR_LIMIT, AUDIO_CACHE_PATH
load_opus_lib()
log = logging.getLogger(__name__)
class MusicBot(discord.Client):
def __init__(self, config_file=None, perms_file=None):
try:
sys.stdout.write("\x1b]2;MusicBot {}\x07".format(BOTVERSION))
except:
pass
print()
if config_file is None:
config_file = ConfigDefaults.options_file
if perms_file is None:
perms_file = PermissionsDefaults.perms_file
self.players = {}
self.exit_signal = None
self.init_ok = False
self.cached_app_info = None
self.last_status = None
self.config = Config(config_file)
self.permissions = Permissions(perms_file, grant_all=[self.config.owner_id])
self.str = Json(self.config.i18n_file)
self.blacklist = set(load_file(self.config.blacklist_file))
self.autoplaylist = load_file(self.config.auto_playlist_file)
self.aiolocks = defaultdict(asyncio.Lock)
self.downloader = downloader.Downloader(download_folder='audio_cache')
self._setup_logging()
log.info('Starting MusicBot {}'.format(BOTVERSION))
if not self.autoplaylist:
log.warning("Autoplaylist is empty, disabling.")
self.config.auto_playlist = False
else:
log.info("Loaded autoplaylist with {} entries".format(len(self.autoplaylist)))
if self.blacklist:
log.debug("Loaded blacklist with {} entries".format(len(self.blacklist)))
# TODO: Do these properly
ssd_defaults = {
'last_np_msg': None,
'auto_paused': False,
'availability_paused': False
}
self.server_specific_data = defaultdict(ssd_defaults.copy)
super().__init__()
self.aiosession = aiohttp.ClientSession(loop=self.loop)
self.http.user_agent += ' MusicBot/%s' % BOTVERSION
self.spotify = None
if self.config._spotify:
try:
self.spotify = Spotify(self.config.spotify_clientid, self.config.spotify_clientsecret, aiosession=self.aiosession, loop=self.loop)
if not self.spotify.token:
log.warning('Spotify did not provide us with a token. Disabling.')
self.config._spotify = False
else:
log.info('Authenticated with Spotify successfully using client ID and secret.')
except exceptions.SpotifyError as e:
log.warning('There was a problem initialising the connection to Spotify. Is your client ID and secret correct? Details: {0}. Continuing anyway in 5 seconds...'.format(e))
self.config._spotify = False
time.sleep(5) # make sure they see the problem
def __del__(self):
# These functions return futures but it doesn't matter
try: self.http.session.close()
except: pass
# 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:
# noinspection PyCallingNonCallable
return await func(self, *args, **kwargs)
else:
raise exceptions.PermissionsError("Only the owner can use this command.", expire_in=30)
return wrapper
def dev_only(func):
@wraps(func)
async def wrapper(self, *args, **kwargs):
orig_msg = _get_variable('message')
if str(orig_msg.author.id) in self.config.dev_ids:
# noinspection PyCallingNonCallable
return await func(self, *args, **kwargs)
else:
raise exceptions.PermissionsError("Only dev users can use this command.", expire_in=30)
wrapper.dev_cmd = True
return wrapper
def ensure_appinfo(func):
@wraps(func)
async def wrapper(self, *args, **kwargs):
await self._cache_app_info()
# noinspection PyCallingNonCallable
return await func(self, *args, **kwargs)
return wrapper
def _get_owner(self, *, server=None, voice=False):
return discord.utils.find(
lambda m: m.id == self.config.owner_id and (m.voice if voice else True),
server.members if server else 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
def _setup_logging(self):
if len(logging.getLogger(__package__).handlers) > 1:
log.debug("Skipping logger setup, already set up")
return
shandler = logging.StreamHandler(stream=sys.stdout)
shandler.setFormatter(colorlog.LevelFormatter(
fmt = {
'DEBUG': '{log_color}[{levelname}:{module}] {message}',
'INFO': '{log_color}{message}',
'WARNING': '{log_color}{levelname}: {message}',
'ERROR': '{log_color}[{levelname}:{module}] {message}',
'CRITICAL': '{log_color}[{levelname}:{module}] {message}',
'EVERYTHING': '{log_color}[{levelname}:{module}] {message}',
'NOISY': '{log_color}[{levelname}:{module}] {message}',
'VOICEDEBUG': '{log_color}[{levelname}:{module}][{relativeCreated:.9f}] {message}',
'FFMPEG': '{log_color}[{levelname}:{module}][{relativeCreated:.9f}] {message}'
},
log_colors = {
'DEBUG': 'cyan',
'INFO': 'white',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'bold_red',
'EVERYTHING': 'white',
'NOISY': 'white',
'FFMPEG': 'bold_purple',
'VOICEDEBUG': 'purple',
},
style = '{',
datefmt = ''
))
shandler.setLevel(self.config.debug_level)
logging.getLogger(__package__).addHandler(shandler)
log.debug("Set logging level to {}".format(self.config.debug_level_str))
if self.config.debug_mode:
dlogger = logging.getLogger('discord')
dlogger.setLevel(logging.DEBUG)
dhandler = logging.FileHandler(filename='logs/discord.log', encoding='utf-8', mode='w')
dhandler.setFormatter(logging.Formatter('{asctime}:{levelname}:{name}: {message}', style='{'))
dlogger.addHandler(dhandler)
@staticmethod
def _check_if_empty(vchannel: discord.abc.GuildChannel, *, excluding_me=True, excluding_deaf=False):
def check(member):
if excluding_me and member == vchannel.guild.me:
return False
if excluding_deaf and any([member.deaf, member.self_deaf]):
return False
return True
return not sum(1 for m in vchannel.members if check(m))
async def _join_startup_channels(self, channels, *, autosummon=True):
joined_servers = set()
channel_map = {c.guild: c for c in channels}
def _autopause(player):
if self._check_if_empty(player.voice_client.channel):
log.info("Initial autopause in empty channel")
player.pause()
self.server_specific_data[player.voice_client.channel.guild]['auto_paused'] = True
for guild in self.guilds:
if guild.unavailable or guild in channel_map:
continue
if guild.me.voice:
log.info("Found resumable voice channel {0.guild.name}/{0.name}".format(guild.me.voice.channel))
channel_map[guild] = guild.me.voice.channel
if autosummon:
owner = self._get_owner(server=guild, voice=True)
if owner:
log.info("Found owner in \"{}\"".format(owner.voice.channel.name))
channel_map[guild] = owner.voice.channel
for guild, channel in channel_map.items():
if guild in joined_servers:
log.info("Already joined a channel in \"{}\", skipping".format(guild.name))
continue
if channel and isinstance(channel, discord.VoiceChannel):
log.info("Attempting to join {0.guild.name}/{0.name}".format(channel))
chperms = channel.permissions_for(guild.me)
if not chperms.connect:
log.info("Cannot join channel \"{}\", no permission.".format(channel.name))
continue
elif not chperms.speak:
log.info("Will not join channel \"{}\", no permission to speak.".format(channel.name))
continue
try:
player = await self.get_player(channel, create=True, deserialize=self.config.persistent_queue)
joined_servers.add(guild)
log.info("Joined {0.guild.name}/{0.name}".format(channel))
if player.is_stopped:
player.play()
if self.config.auto_playlist:
if self.config.auto_pause:
player.once('play', lambda player, **_: _autopause(player))
if not player.playlist.entries:
await self.on_player_finished_playing(player)
except Exception:
log.debug("Error joining {0.guild.name}/{0.name}".format(channel), exc_info=True)
log.error("Failed to join {0.guild.name}/{0.name}".format(channel))
elif channel:
log.warning("Not joining {0.guild.name}/{0.name}, that's a text channel.".format(channel))
else:
log.warning("Invalid channel thing: {}".format(channel))
async def _wait_delete_msg(self, message, after):
await asyncio.sleep(after)
await self.safe_delete_message(message, quiet=True)
# 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.guild.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 _cache_app_info(self, *, update=False):
if not self.cached_app_info and not update and self.user.bot:
log.debug("Caching app info")
self.cached_app_info = await self.application_info()
return self.cached_app_info
async def remove_from_autoplaylist(self, song_url:str, *, ex:Exception=None, delete_from_ap=False):
if song_url not in self.autoplaylist:
log.debug("URL \"{}\" not in autoplaylist, ignoring".format(song_url))
return
async with self.aiolocks[_func_()]:
self.autoplaylist.remove(song_url)
log.info("Removing unplayable song from session autoplaylist: %s" % song_url)
with open(self.config.auto_playlist_removed_file, 'a', encoding='utf8') as f:
f.write(
'# Entry removed {ctime}\n'
'# Reason: {ex}\n'
'{url}\n\n{sep}\n\n'.format(
ctime=time.ctime(),
ex=str(ex).replace('\n', '\n#' + ' ' * 10), # 10 spaces to line up with # Reason:
url=song_url,
sep='#' * 32
))
if delete_from_ap:
log.info("Updating autoplaylist")
write_file(self.config.auto_playlist_file, self.autoplaylist)
@ensure_appinfo
async def generate_invite_link(self, *, permissions=discord.Permissions(70380544), guild=None):
return discord.utils.oauth_url(self.cached_app_info.id, permissions=permissions, guild=guild)
async def get_voice_client(self, channel: discord.abc.GuildChannel):
if isinstance(channel, discord.Object):
channel = self.get_channel(channel.id)
if not isinstance(channel, discord.VoiceChannel):
raise AttributeError('Channel passed must be a voice channel')
if channel.guild.voice_client:
return channel.guild.voice_client
else:
return await channel.connect(timeout=60, reconnect=True)
async def disconnect_voice_client(self, guild):
vc = self.voice_client_in(guild)
if not vc:
return
if guild.id in self.players:
self.players.pop(guild.id).kill()
await vc.disconnect()
async def disconnect_all_voice_clients(self):
for vc in list(self.voice_clients).copy():
await self.disconnect_voice_client(vc.channel.guild)
async def set_voice_state(self, vchannel, *, mute=False, deaf=False):
if isinstance(vchannel, discord.Object):
vchannel = self.get_channel(vchannel.id)
if getattr(vchannel, 'type', ChannelType.text) != ChannelType.voice:
raise AttributeError('Channel passed must be a voice channel')
await self.ws.voice_state(vchannel.guild.id, vchannel.id, mute, deaf)
# I hope I don't have to set the channel here
# instead of waiting for the event to update it
def get_player_in(self, guild:discord.Guild) -> MusicPlayer:
return self.players.get(guild.id)
async def get_player(self, channel, create=False, *, deserialize=False) -> MusicPlayer:
guild = channel.guild
async with self.aiolocks[_func_() + ':' + str(guild.id)]:
if deserialize:
voice_client = await self.get_voice_client(channel)
player = await self.deserialize_queue(guild, voice_client)
if player:
log.debug("Created player via deserialization for guild %s with %s entries", guild.id, len(player.playlist))
# Since deserializing only happens when the bot starts, I should never need to reconnect
return self._init_player(player, guild=guild)
if guild.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)
self._init_player(player, guild=guild)
return self.players[guild.id]
def _init_player(self, player, *, guild=None):
player = player.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) \
.on('error', self.on_player_error)
player.skip_state = SkipState()
if guild:
self.players[guild.id] = player
return player
async def on_player_play(self, player, entry):
log.debug('Running on_player_play')
await self.update_now_playing_status(entry)
player.skip_state.reset()
# This is the one event where its ok to serialize autoplaylist entries
await self.serialize_queue(player.voice_client.channel.guild)
if self.config.write_current_song:
await self.write_current_song(player.voice_client.channel.guild, entry)
channel = entry.meta.get('channel', None)
author = entry.meta.get('author', None)
if channel and author:
last_np_msg = self.server_specific_data[channel.guild]['last_np_msg']
if last_np_msg and last_np_msg.channel == channel:
async for lmsg in channel.history(limit=1):
if lmsg != last_np_msg and last_np_msg:
await self.safe_delete_message(last_np_msg)
self.server_specific_data[channel.guild]['last_np_msg'] = None
break # This is probably redundant
author_perms = self.permissions.for_user(author)
if author not in player.voice_client.channel.members and author_perms.skip_when_absent:
newmsg = 'Skipping next song in `%s`: `%s` added by `%s` as queuer not in voice' % (
player.voice_client.channel.name, entry.title, entry.meta['author'].name)
player.skip()
elif 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` added by `%s`' % (
player.voice_client.channel.name, entry.title, entry.meta['author'].name)
if self.server_specific_data[channel.guild]['last_np_msg']:
self.server_specific_data[channel.guild]['last_np_msg'] = await self.safe_edit_message(last_np_msg, newmsg, send_if_fail=True)
else:
self.server_specific_data[channel.guild]['last_np_msg'] = await self.safe_send_message(channel, newmsg)
# TODO: Check channel voice state?
async def on_player_resume(self, player, entry, **_):
log.debug('Running on_player_resume')
await self.update_now_playing_status(entry)
async def on_player_pause(self, player, entry, **_):
log.debug('Running on_player_pause')
await self.update_now_playing_status(entry, True)
# await self.serialize_queue(player.voice_client.channel.guild)
async def on_player_stop(self, player, **_):
log.debug('Running on_player_stop')
await self.update_now_playing_status()
async def on_player_finished_playing(self, player, **_):
log.debug('Running on_player_finished_playing')
def _autopause(player):
if self._check_if_empty(player.voice_client.channel):
log.info("Player finished playing, autopaused in empty channel")
player.pause()
self.server_specific_data[player.voice_client.channel.guild]['auto_paused'] = True
if not player.playlist.entries and not player.current_entry and self.config.auto_playlist:
if not player.autoplaylist:
if not self.autoplaylist:
# TODO: When I add playlist expansion, make sure that's not happening during this check
log.warning("No playable songs in the autoplaylist, disabling.")
self.config.auto_playlist = False
else:
log.debug("No content in current autoplaylist. Filling with new music...")
player.autoplaylist = list(self.autoplaylist)
while player.autoplaylist:
if self.config.auto_playlist_random:
random.shuffle(player.autoplaylist)
song_url = random.choice(player.autoplaylist)
else:
song_url = player.autoplaylist[0]
player.autoplaylist.remove(song_url)
info = {}
try:
info = await self.downloader.extract_info(player.playlist.loop, song_url, download=False, process=False)
except downloader.youtube_dl.utils.DownloadError as e:
if 'YouTube said:' in e.args[0]:
# url is bork, remove from list and put in removed list
log.error("Error processing youtube url:\n{}".format(e.args[0]))
else:
# Probably an error from a different extractor, but I've only seen youtube's
log.error("Error processing \"{url}\": {ex}".format(url=song_url, ex=e))
await self.remove_from_autoplaylist(song_url, ex=e, delete_from_ap=self.config.remove_ap)
continue
except Exception as e:
log.error("Error processing \"{url}\": {ex}".format(url=song_url, ex=e))
log.exception()
self.autoplaylist.remove(song_url)
continue
if info.get('entries', None): # or .get('_type', '') == 'playlist'
log.debug("Playlist found but is unsupported at this time, skipping.")
# TODO: Playlist expansion
# Do I check the initial conditions again?
# not (not player.playlist.entries and not player.current_entry and self.config.auto_playlist)
if self.config.auto_pause:
player.once('play', lambda player, **_: _autopause(player))
try:
await player.playlist.add_entry(song_url, channel=None, author=None)
except exceptions.ExtractionError as e:
log.error("Error adding song from autoplaylist: {}".format(e))
log.debug('', exc_info=True)
continue
break
if not self.autoplaylist:
# TODO: When I add playlist expansion, make sure that's not happening during this check
log.warning("No playable songs in the autoplaylist, disabling.")
self.config.auto_playlist = False
else: # Don't serialize for autoplaylist events
await self.serialize_queue(player.voice_client.channel.guild)
async def on_player_entry_added(self, player, playlist, entry, **_):
log.debug('Running on_player_entry_added')
if entry.meta.get('author') and entry.meta.get('channel'):
await self.serialize_queue(player.voice_client.channel.guild)
async def on_player_error(self, player, entry, ex, **_):
if 'channel' in entry.meta:
await self.safe_send_message(
entry.meta['channel'],
"```\nError from FFmpeg:\n{}\n```".format(ex)
)
else:
log.exception("Player error", exc_info=ex)
async def update_now_playing_status(self, entry=None, is_paused=False):
game = None
if not self.config.status_message:
if self.user.bot:
activeplayers = sum(1 for p in self.players.values() if p.is_playing)
if activeplayers > 1:
game = discord.Game(type=0, name="music on %s guilds" % 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(type=0, name=name)
else:
game = discord.Game(type=0, name=self.config.status_message.strip()[:128])
async with self.aiolocks[_func_()]:
if game != self.last_status:
await self.change_presence(activity=game)
self.last_status = game
async def update_now_playing_message(self, guild, message, *, channel=None):
lnp = self.server_specific_data[guild]['last_np_msg']
m = None
if message is None and lnp:
await self.safe_delete_message(lnp, quiet=True)
elif lnp: # If there was a previous lp message
oldchannel = lnp.channel
if lnp.channel == oldchannel: # If we have a channel to update it in
async for lmsg in self.logs_from(channel, limit=1):
if lmsg != lnp and lnp: # If we need to resend it
await self.safe_delete_message(lnp, quiet=True)
m = await self.safe_send_message(channel, message, quiet=True)
else:
m = await self.safe_edit_message(lnp, message, send_if_fail=True, quiet=False)
elif channel: # If we have a new channel to send it to
await self.safe_delete_message(lnp, quiet=True)
m = await self.safe_send_message(channel, message, quiet=True)
else: # we just resend it in the old channel
await self.safe_delete_message(lnp, quiet=True)
m = await self.safe_send_message(oldchannel, message, quiet=True)
elif channel: # No previous message
m = await self.safe_send_message(channel, message, quiet=True)
self.server_specific_data[guild]['last_np_msg'] = m
async def serialize_queue(self, guild, *, dir=None):
"""
Serialize the current queue for a server's player to json.
"""
player = self.get_player_in(guild)
if not player:
return
if dir is None:
dir = 'data/%s/queue.json' % guild.id
async with self.aiolocks['queue_serialization' + ':' + str(guild.id)]:
log.debug("Serializing queue for %s", guild.id)
with open(dir, 'w', encoding='utf8') as f:
f.write(player.serialize(sort_keys=True))
async def serialize_all_queues(self, *, dir=None):
coros = [self.serialize_queue(s, dir=dir) for s in self.guilds]
await asyncio.gather(*coros, return_exceptions=True)
async def deserialize_queue(self, guild, voice_client, playlist=None, *, dir=None) -> MusicPlayer:
"""
Deserialize a saved queue for a server into a MusicPlayer. If no queue is saved, returns None.
"""
if playlist is None:
playlist = Playlist(self)
if dir is None:
dir = 'data/%s/queue.json' % guild.id
async with self.aiolocks['queue_serialization' + ':' + str(guild.id)]:
if not os.path.isfile(dir):
return None
log.debug("Deserializing queue for %s", guild.id)
with open(dir, 'r', encoding='utf8') as f:
data = f.read()
return MusicPlayer.from_json(data, self, voice_client, playlist)
async def write_current_song(self, guild, entry, *, dir=None):
"""
Writes the current song to file
"""
player = self.get_player_in(guild)
if not player:
return
if dir is None:
dir = 'data/%s/current.txt' % guild.id
async with self.aiolocks['current_song' + ':' + str(guild.id)]:
log.debug("Writing current song for %s", guild.id)
with open(dir, 'w', encoding='utf8') as f:
f.write(entry.title)
@ensure_appinfo
async def _on_ready_sanity_checks(self):
# Ensure folders exist
await self._scheck_ensure_env()
# Server permissions check
await self._scheck_server_permissions()
# playlists in autoplaylist
await self._scheck_autoplaylist()
# config/permissions async validate?
await self._scheck_configs()
async def _scheck_ensure_env(self):
log.debug("Ensuring data folders exist")
for guild in self.guilds:
pathlib.Path('data/%s/' % guild.id).mkdir(exist_ok=True)
with open('data/server_names.txt', 'w', encoding='utf8') as f:
for guilds in sorted(self.guilds, key=lambda s:int(s.id)):
f.write('{:<22} {}\n'.format(guild.id, guild.name))
if not self.config.save_videos and os.path.isdir(AUDIO_CACHE_PATH):
if self._delete_old_audiocache():
log.debug("Deleted old audio cache")
else:
log.debug("Could not delete old audio cache, moving on.")
async def _scheck_server_permissions(self):
log.debug("Checking server permissions")
pass # TODO
async def _scheck_autoplaylist(self):
log.debug("Auditing autoplaylist")
pass # TODO
async def _scheck_configs(self):
log.debug("Validating config")
await self.config.async_validate(self)
log.debug("Validating permissions config")
await self.permissions.async_validate(self)
#######################################################################################################################
async def safe_send_message(self, dest, content, **kwargs):
tts = kwargs.pop('tts', False)
quiet = kwargs.pop('quiet', False)
expire_in = kwargs.pop('expire_in', 0)
allow_none = kwargs.pop('allow_none', True)
also_delete = kwargs.pop('also_delete', None)
msg = None
lfunc = log.debug if quiet else log.warning
try:
if content is not None or allow_none:
if isinstance(content, discord.Embed):
msg = await dest.send(embed=content)
else:
msg = await dest.send(content, tts=tts)
except discord.Forbidden:
lfunc("Cannot send message to \"%s\", no permission", dest.name)
except discord.NotFound:
lfunc("Cannot send message to \"%s\", invalid channel?", dest.name)
except discord.HTTPException:
if len(content) > DISCORD_MSG_CHAR_LIMIT:
lfunc("Message is over the message size limit (%s)", DISCORD_MSG_CHAR_LIMIT)
else:
lfunc("Failed to send message")
log.noise("Got HTTPException trying to send message to %s: %s", dest, content)
finally:
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))
return msg
async def safe_delete_message(self, message, *, quiet=False):
lfunc = log.debug if quiet else log.warning
try:
return await message.delete()
except discord.Forbidden:
lfunc("Cannot delete message \"{}\", no permission".format(message.clean_content))
except discord.NotFound:
lfunc("Cannot delete message \"{}\", message not found".format(message.clean_content))
async def safe_edit_message(self, message, new, *, send_if_fail=False, quiet=False):
lfunc = log.debug if quiet else log.warning
try:
return await message.edit(content=new)
except discord.NotFound:
lfunc("Cannot edit message \"{}\", message not found".format(message.clean_content))
if send_if_fail:
lfunc("Sending message instead")
return await self.safe_send_message(message.channel, new)
async def send_typing(self, destination):
try:
return await destination.trigger_typing()
except discord.Forbidden:
log.warning("Could not send typing to {}, no permission".format(destination))
async def restart(self):
self.exit_signal = exceptions.RestartSignal()
await self.logout()
def restart_threadsafe(self):
asyncio.run_coroutine_threadsafe(self.restart(), self.loop)
def _cleanup(self):
try:
self.loop.run_until_complete(self.logout())
self.loop.run_until_complete(self.aiosession.close())
except: pass
pending = asyncio.Task.all_tasks()
gathered = asyncio.gather(*pending)
try:
gathered.cancel()
self.loop.run_until_complete(gathered)
gathered.exception()
except: 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 token in the options file. "
"Remember that each field should be on their own line."
) # ^^^^ In theory self.config.auth should never have no items
finally:
try:
self._cleanup()
except Exception:
log.error("Error in cleanup", exc_info=True)
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:
log.error("Exception in {}:\n{}".format(event, 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:
log.error("Exception in {}".format(event), exc_info=True)
async def on_resumed(self):
log.info("\nReconnected to discord.\n")
async def on_ready(self):
dlogger = logging.getLogger('discord')
for h in dlogger.handlers:
if getattr(h, 'terminator', None) == '':
dlogger.removeHandler(h)
print()
log.debug("Connection established, ready to go.")
self.ws._keep_alive.name = 'Gateway Keepalive'
if self.init_ok:
log.debug("Received additional READY event, may have failed to resume")
return
await self._on_ready_sanity_checks()
self.init_ok = True
################################
log.info("Connected: {0}/{1}#{2}".format(
self.user.id,
self.user.name,
self.user.discriminator
))
owner = self._get_owner(voice=True) or self._get_owner()
if owner and self.guilds:
log.info("Owner: {0}/{1}#{2}\n".format(
owner.id,
owner.name,
owner.discriminator
))
log.info('Guild List:')
for s in self.guilds:
ser = ('{} (unavailable)'.format(s.name) if s.unavailable else s.name)
log.info(' - ' + ser)
elif self.guilds:
log.warning("Owner could not be found on any guild (id: %s)\n" % self.config.owner_id)
log.info('Guild List:')
for s in self.guilds:
ser = ('{} (unavailable)'.format(s.name) if s.unavailable else s.name)
log.info(' - ' + ser)
else:
log.warning("Owner unknown, bot is not on any guilds.")
if self.user.bot:
log.warning(
"To make the bot join a guild, paste this link in your browser. \n"
"Note: You should be logged into your main account and have \n"
"manage server permissions on the guild you want the bot to join.\n"
" " + await self.generate_invite_link()
)
print(flush=True)
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 isinstance(c, discord.VoiceChannel))
chlist.difference_update(invalids)
self.config.bound_channels.difference_update(invalids)
if chlist:
log.info("Bound to text channels:")
[log.info(' - {}/{}'.format(ch.guild.name.strip(), ch.name.strip())) for ch in chlist if ch]
else:
print("Not bound to any text channels")
if invalids and self.config.debug_mode:
print(flush=True)
log.info("Not binding to voice channels:")
[log.info(' - {}/{}'.format(ch.guild.name.strip(), ch.name.strip())) for ch in invalids if ch]
print(flush=True)
else:
log.info("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 isinstance(c, discord.TextChannel))
chlist.difference_update(invalids)
self.config.autojoin_channels.difference_update(invalids)