# Buggy code
async def event_handler(
    self, player: lavalink.Player, event_type: lavalink.LavalinkEvents, extra
):
    disconnect = await self.config.guild(player.channel.guild).disconnect()
    autoplay = (
        await self.config.guild(player.channel.guild).auto_play() or self.owns_autoplay
    )
    notify = await self.config.guild(player.channel.guild).notify()
    status = await self.config.status()
    repeat = await self.config.guild(player.channel.guild).repeat()

    async def _players_check():
        try:
            get_single_title = lavalink.active_players()[0].current.title
            query = audio_dataclasses.Query.process_input(
                lavalink.active_players()[0].current.uri
            )
            if get_single_title == "Unknown title":
                get_single_title = lavalink.active_players()[0].current.uri
                if not get_single_title.startswith("http"):
                    get_single_title = get_single_title.rsplit("/", 1)[-1]
            elif query.is_local:
                get_single_title = "{} - {}".format(
                    lavalink.active_players()[0].current.author,
                    lavalink.active_players()[0].current.title,
                )
            else:
                get_single_title = lavalink.active_players()[0].current.title
            playing_servers = len(lavalink.active_players())
        except IndexError:
            get_single_title = None
            playing_servers = 0
        return get_single_title, playing_servers

    async def _status_check(playing_servers):
        if playing_servers == 0:
            await self.bot.change_presence(activity=None)
        if playing_servers == 1:
            single_title = await _players_check()
            await self.bot.change_presence(
                activity=discord.Activity(
                    name=single_title[0], type=discord.ActivityType.listening
                )
            )
        if playing_servers > 1:
            await self.bot.change_presence(
                activity=discord.Activity(
                    name=_("music in {} servers").format(playing_servers),
                    type=discord.ActivityType.playing,
                )
            )

    if event_type == lavalink.LavalinkEvents.TRACK_START:
        self.skip_votes[player.channel.guild] = []
        playing_song = player.fetch("playing_song")
        requester = player.fetch("requester")
        player.store("prev_song", playing_song)
        player.store("prev_requester", requester)
        player.store("playing_song", player.current)
        player.store(
            "requester", player.current.requester if player.current else player.current
        )
        self.bot.dispatch(
            "red_audio_track_start",
            player.channel.guild,
            player.current,
            player.current.requester,
        )
    if event_type == lavalink.LavalinkEvents.TRACK_END:
        prev_song = player.fetch("prev_song")
        prev_requester = player.fetch("prev_requester")
        self.bot.dispatch(
            "red_audio_track_end", player.channel.guild, prev_song, prev_requester
        )

    if event_type == lavalink.LavalinkEvents.QUEUE_END:
        prev_song = player.fetch("prev_song")
        prev_requester = player.fetch("prev_requester")
        self.bot.dispatch(
            "red_audio_queue_end", player.channel.guild, prev_song, prev_requester
        )
        if autoplay and not player.queue and player.fetch("playing_song") is not None:
            if self.owns_autoplay is None:
                try:
                    await self.music_cache.autoplay(player)
                except DatabaseError:
                    notify_channel = player.fetch("channel")
                    if notify_channel:
                        notify_channel = self.bot.get_channel(notify_channel)
                        await self._embed_msg(
                            notify_channel, _("Autoplay: Couldn't get a valid track.")
                        )
                    return
            else:
                self.bot.dispatch(
                    "red_audio_should_auto_play",
                    player,
                    player.channel.guild,
                    player.channel,
                    self.play_query,
                )

    if event_type == lavalink.LavalinkEvents.TRACK_START and notify:
        notify_channel = player.fetch("channel")
        prev_song = player.fetch("prev_song")
        if notify_channel:
            notify_channel = self.bot.get_channel(notify_channel)
            if player.fetch("notify_message") is not None:
                with contextlib.suppress(discord.HTTPException):
                    await player.fetch("notify_message").delete()

            if (
                autoplay
                and player.current.extras.get("autoplay")
                and (prev_song is None or not prev_song.extras.get("autoplay"))
            ):
                embed = discord.Embed(
                    colour=(await self.bot.get_embed_colour(notify_channel)),
                    title=_("Auto play started."),
                )
                await notify_channel.send(embed=embed)

            query = audio_dataclasses.Query.process_input(player.current.uri)

            if query.is_local if player.current else False:
                if player.current.title != "Unknown title":
                    description = "**{} - {}**\n{}".format(
                        player.current.author,
                        player.current.title,
                        audio_dataclasses.LocalPath(
                            player.current.uri
                        ).to_string_hidden(),
                    )
                else:
                    description = "{}".format(
                        audio_dataclasses.LocalPath(
                            player.current.uri
                        ).to_string_hidden()
                    )
            else:
                description = "**[{}]({})**".format(
                    player.current.title, player.current.uri
                )
            if player.current.is_stream:
                dur = "LIVE"
            else:
                dur = lavalink.utils.format_time(player.current.length)
            embed = discord.Embed(
                colour=(await self.bot.get_embed_color(notify_channel)),
                title=_("Now Playing"),
                description=description,
            )
            embed.set_footer(
                text=_("Track length: {length} | Requested by: {user}").format(
                    length=dur, user=player.current.requester
                )
            )
            if (
                await self.config.guild(player.channel.guild).thumbnail()
                and player.current.thumbnail
            ):
                embed.set_thumbnail(url=player.current.thumbnail)
            notify_message = await notify_channel.send(embed=embed)
            player.store("notify_message", notify_message)

    if event_type == lavalink.LavalinkEvents.TRACK_START and status:
        player_check = await _players_check()
        await _status_check(player_check[1])

    if event_type == lavalink.LavalinkEvents.TRACK_END and status:
        await asyncio.sleep(1)
        if not player.is_playing:
            player_check = await _players_check()
            await _status_check(player_check[1])

    if event_type == lavalink.LavalinkEvents.QUEUE_END and notify and not autoplay:
        notify_channel = player.fetch("channel")
        if notify_channel:
            notify_channel = self.bot.get_channel(notify_channel)
            embed = discord.Embed(
                colour=(await self.bot.get_embed_colour(notify_channel)),
                title=_("Queue ended."),
            )
            await notify_channel.send(embed=embed)

    elif (
        event_type == lavalink.LavalinkEvents.QUEUE_END and disconnect and not autoplay
    ):
        self.bot.dispatch("red_audio_audio_disconnect", player.channel.guild)
        await player.disconnect()

    if event_type == lavalink.LavalinkEvents.QUEUE_END and status:
        player_check = await _players_check()
        await _status_check(player_check[1])

    if event_type == lavalink.LavalinkEvents.TRACK_EXCEPTION:
        message_channel = player.fetch("channel")
        if message_channel:
            message_channel = self.bot.get_channel(message_channel)
            query = audio_dataclasses.Query.process_input(player.current.uri)
            if player.current and query.is_local:
                query = audio_dataclasses.Query.process_input(player.current.uri)
                if player.current.title == "Unknown title":
                    description = "{}".format(query.track.to_string_hidden())
                else:
                    song = bold("{} - {}").format(
                        player.current.author, player.current.title
                    )
                    description = "{}\n{}".format(song, query.track.to_string_hidden())
            else:
                description = bold("[{}]({})").format(
                    player.current.title, player.current.uri
                )

            embed = discord.Embed(
                colour=(await self.bot.get_embed_color(message_channel)),
                title=_("Track Error"),
                description="{}\n{}".format(extra, description),
            )
            embed.set_footer(text=_("Skipping..."))
            await message_channel.send(embed=embed)
        while True:
            if player.current in player.queue:
                player.queue.remove(player.current)
            else:
                break
        if repeat:
            player.current = None
        await player.skip()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/home/martinebots/martinebotsvenv/lib/python3.7/site-packages/discord/ext/commands/core.py", line 79, in wrapped
ret = await coro(*args, **kwargs)
File "/home/martinebots/martinebotscogs/cogs_modified/audio/audio.py", line 3183, in play
await self._enqueue_tracks(ctx, query)
File "/home/martinebots/martinebotscogs/cogs_modified/audio/audio.py", line 3885, in _enqueue_tracks
result, called_api = await self.music_cache.lavalink_query(ctx, player, query)
File "/home/martinebots/martinebotscogs/cogs_modified/audio/apis.py", line 911, in lavalink_query
results = await player.load_tracks(query)
File "/home/martinebots/martinebotsvenv/lib/python3.7/site-packages/lavalink/rest_api.py", line 300, in load_tracks
self.__check_node_ready()
File "/home/martinebots/martinebotsvenv/lib/python3.7/site-packages/lavalink/rest_api.py", line 268, in __check_node_ready
raise RuntimeError("Cannot execute REST request when node not ready.")
RuntimeError: Cannot execute REST request when node not ready.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/martinebots/martinebotsvenv/lib/python3.7/site-packages/discord/ext/commands/bot.py", line 863, in invoke
await ctx.command.invoke(ctx)
File "/home/martinebots/martinebotsvenv/lib/python3.7/site-packages/discord/ext/commands/core.py", line 728, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/martinebots/martinebotsvenv/lib/python3.7/site-packages/discord/ext/commands/core.py", line 88, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: Cannot execute REST request when node not ready.```

# Fixed code
async def event_handler(
    self, player: lavalink.Player, event_type: lavalink.LavalinkEvents, extra
):
    current_track = player.current
    current_channel = player.channel
    guild = rgetattr(current_channel, "guild", None)
    guild_id = rgetattr(guild, "id", None)
    current_requester = rgetattr(current_track, "requester", None)
    current_stream = rgetattr(current_track, "is_stream", None)
    current_length = rgetattr(current_track, "length", None)
    current_thumbnail = rgetattr(current_track, "thumbnail", None)
    current_extras = rgetattr(current_track, "extras", {})
    guild_data = await self.config.guild(guild).all()
    repeat = guild_data["repeat"]
    notify = guild_data["notify"]
    disconnect = guild_data["disconnect"]
    autoplay = guild_data["auto_play"]
    description = get_track_description(current_track)
    status = await self.config.status()

    await self.error_reset(player)

    if event_type == lavalink.LavalinkEvents.TRACK_START:
        self.skip_votes[guild] = []
        playing_song = player.fetch("playing_song")
        requester = player.fetch("requester")
        player.store("prev_song", playing_song)
        player.store("prev_requester", requester)
        player.store("playing_song", current_track)
        player.store("requester", current_requester)
        self.bot.dispatch(
            "red_audio_track_start", guild, current_track, current_requester
        )
    if event_type == lavalink.LavalinkEvents.TRACK_END:
        prev_song = player.fetch("prev_song")
        prev_requester = player.fetch("prev_requester")
        self.bot.dispatch("red_audio_track_end", guild, prev_song, prev_requester)
    if event_type == lavalink.LavalinkEvents.QUEUE_END:
        prev_song = player.fetch("prev_song")
        prev_requester = player.fetch("prev_requester")
        self.bot.dispatch("red_audio_queue_end", guild, prev_song, prev_requester)
        if autoplay and not player.queue and player.fetch("playing_song") is not None:
            try:
                await self.music_cache.autoplay(player)
            except DatabaseError:
                notify_channel = player.fetch("channel")
                if notify_channel:
                    notify_channel = self.bot.get_channel(notify_channel)
                    await self._embed_msg(
                        notify_channel, title=_("Couldn't get a valid track.")
                    )
                return
    if event_type == lavalink.LavalinkEvents.TRACK_START and notify:
        notify_channel = player.fetch("channel")
        prev_song = player.fetch("prev_song")
        if notify_channel:
            notify_channel = self.bot.get_channel(notify_channel)
            if player.fetch("notify_message") is not None:
                with contextlib.suppress(discord.HTTPException):
                    await player.fetch("notify_message").delete()

            if (
                autoplay
                and current_extras.get("autoplay")
                and (
                    prev_song is None
                    or (
                        hasattr(prev_song, "extras")
                        and not prev_song.extras.get("autoplay")
                    )
                )
            ):
                await self._embed_msg(notify_channel, title=_("Auto Play Started."))

            if not description:
                return
            if current_stream:
                dur = "LIVE"
            else:
                dur = lavalink.utils.format_time(current_length)

            thumb = None
            if await self.config.guild(guild).thumbnail() and current_thumbnail:
                thumb = current_thumbnail

            notify_message = await self._embed_msg(
                notify_channel,
                title=_("Now Playing"),
                description=description,
                footer=_("Track length: {length} | Requested by: {user}").format(
                    length=dur, user=current_requester
                ),
                thumbnail=thumb,
            )
            player.store("notify_message", notify_message)
    if event_type == lavalink.LavalinkEvents.TRACK_START and status:
        player_check = await self._players_check()
        await self._status_check(*player_check)

    if event_type == lavalink.LavalinkEvents.TRACK_END and status:
        await asyncio.sleep(1)
        if not player.is_playing:
            player_check = await self._players_check()
            await self._status_check(*player_check)

    if not autoplay and event_type == lavalink.LavalinkEvents.QUEUE_END and notify:
        notify_channel = player.fetch("channel")
        if notify_channel:
            notify_channel = self.bot.get_channel(notify_channel)
            await self._embed_msg(notify_channel, title=_("Queue Ended."))
    elif (
        not autoplay and event_type == lavalink.LavalinkEvents.QUEUE_END and disconnect
    ):
        self.bot.dispatch("red_audio_audio_disconnect", guild)
        await player.disconnect()
    if event_type == lavalink.LavalinkEvents.QUEUE_END and status:
        player_check = await self._players_check()
        await self._status_check(*player_check)

    if event_type in [
        lavalink.LavalinkEvents.TRACK_EXCEPTION,
        lavalink.LavalinkEvents.TRACK_STUCK,
    ]:
        message_channel = player.fetch("channel")
        while True:
            if current_track in player.queue:
                player.queue.remove(current_track)
            else:
                break
        if repeat:
            player.current = None
        if not guild_id:
            return
        self._error_counter.setdefault(guild_id, 0)
        if guild_id not in self._error_counter:
            self._error_counter[guild_id] = 0
        early_exit = await self.increase_error_counter(player)
        if early_exit:
            self._disconnected_players[guild_id] = True
            self.play_lock[guild_id] = False
            eq = player.fetch("eq")
            player.queue = []
            player.store("playing_song", None)
            if eq:
                await self.config.custom("EQUALIZER", guild_id).eq_bands.set(eq.bands)
            await player.stop()
            await player.disconnect()
            self.bot.dispatch("red_audio_audio_disconnect", guild)
        if message_channel:
            message_channel = self.bot.get_channel(message_channel)
            if early_exit:
                embed = discord.Embed(
                    colour=(await self.bot.get_embed_color(message_channel)),
                    title=_("Multiple errors detected"),
                    description=_(
                        "Closing the audio player "
                        "due to multiple errors being detected. "
                        "If this persists, please inform the bot owner "
                        "as the Audio cog may be temporally unavailable."
                    ),
                )
                return await message_channel.send(embed=embed)
            else:
                description = description or ""
                if event_type == lavalink.LavalinkEvents.TRACK_STUCK:
                    embed = discord.Embed(
                        title=_("Track Stuck"), description="{}".format(description)
                    )
                else:
                    embed = discord.Embed(
                        title=_("Track Error"),
                        description="{}\n{}".format(
                            extra.replace("\n", ""), description
                        ),
                    )
                await message_channel.send(embed=embed)
        await player.skip()