From 5a91d8a5ec0adc61f1d5ccd4ceac0e952b417e6d Mon Sep 17 00:00:00 2001 From: ekzyis Date: Sat, 2 Oct 2021 02:05:34 +0200 Subject: [PATCH] Add skip button as reaction on "Now playing:" --- src/bot.py | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/bot.py b/src/bot.py index c6a5771..c18804a 100644 --- a/src/bot.py +++ b/src/bot.py @@ -29,6 +29,7 @@ class Music(commands.Cog): self._bot = bot self._queue = asyncio.Queue() self._queue_lock = asyncio.Lock() + self._current_skip_message = None self._ytdl_params = { 'cookiefile': os.environ.get('YOUTUBE_COOKIES'), 'format': 'bestaudio/best', @@ -57,6 +58,7 @@ class Music(commands.Cog): def _next(self): """Trigger playback of next song.""" self._queue.task_done() + self._current_skip_message = None if self._queue_lock.locked(): self._queue_lock.release() @@ -80,7 +82,8 @@ class Music(commands.Cog): self._next() ctx.voice_client.play(audio, after=after) embed = NowPlayingMessage(title=song.title, url=song.webpage_url) - await ctx.send(embed=embed) + msg = await ctx.send(embed=embed) + await self._add_skip_button(msg) # pylint: disable=broad-except except Exception as err: print(f"Error during playback: {err}") @@ -89,6 +92,19 @@ class Music(commands.Cog): await ctx.send(embed=embed) self._next() + async def _add_skip_button(self, msg): + await msg.add_reaction("⏭️") + self._current_skip_message = msg + + @commands.Cog.listener() + async def on_reaction_add(self, reaction, user): + if not user.bot \ + and self._current_skip_message \ + and reaction.message.id == self._current_skip_message.id \ + and reaction.emoji == "⏭️": + voice_client = reaction.message.guild.voice_client + self._skip(voice_client) + @_handle_playback.before_loop async def before_handle_playback(self): await self._bot.wait_until_ready() @@ -109,12 +125,18 @@ class Music(commands.Cog): embed = QueuedMessage(title=song.title, url=song.webpage_url) await ctx.send(embed=embed) + def _skip(self, voice_client): + """Skip to next song.""" + if voice_client is None or not voice_client.is_playing(): + raise commands.CommandError("No song playing") + # This skips to next song because the bot does not differentiate between + # a song stopping because it is finished or because it was manually stopped. + voice_client.stop() + @commands.command() async def skip(self, ctx): async with ctx.typing(): - if ctx.voice_client is None or not ctx.voice_client.is_playing(): - raise commands.CommandError("No song playing") - ctx.voice_client.stop() + self._skip(ctx.voice_client) @commands.command() async def stop(self, ctx):