gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _read_info_file(self) -> None:
    if not (self._info_file.exists() or self._info_file.is_file()):
        return

    try:
        with self._info_file.open(encoding="utf-8") as f:
            info = json.load(f)
    except json.JSONDecodeError:
        return
    else:
        self._info = info

    try:
        author = tuple(info.get("author", []))
    except ValueError:
        author = ()
    self.author = author

    self.install_msg = info.get("install_msg")
    self.short = info.get("short")
    self.description = info.get("description")


# Traceback (ValueError)
Traceback (most recent call last):
File "/home/ubuntu/redenv/lib/python3.8/site-packages/redbot/cogs/downloader/installable.py", line 172, in _process_info_file
min_bot_version = VersionInfo.from_str(str(info.get("min_bot_version", __version__)))
File "/home/ubuntu/redenv/lib/python3.8/site-packages/redbot/__init__.py", line 91, in from_str
raise ValueError(f"Invalid version string: {version_str}")
ValueError: Invalid version string: 3.2`

# Fixed code
def _read_info_file(self) -> None:
    if self._info_file.exists():
        try:
            with self._info_file.open(encoding="utf-8") as f:
                info = json.load(f)
        except json.JSONDecodeError as e:
            log.error(
                "Invalid JSON information file at path: %s\nError: %s",
                self._info_file,
                str(e),
            )
            info = {}
    else:
        info = {}
    if not isinstance(info, dict):
        log.warning(
            "Invalid top-level structure (expected dict, got %s)"
            " in JSON information file at path: %s",
            type(info).__name__,
            self._info_file,
        )
        info = {}
    self._info = info

    update_mixin(self, REPO_SCHEMA)
# Buggy code
async def create_and_invoke_context(
    realctx: commands.Context, command_str: str, user: discord.Member
):
    m = copy(realctx.message)
    m.content = command_str.format(user=user.mention, prefix=realctx.prefix)
    fctx = await realctx.bot.get_context(m, cls=commands.Context)
    try:
        await realctx.bot.invoke(fctx)
    except (commands.CheckFailure, commands.CommandOnCooldown):
        await fctx.reinvoke()


# Traceback (OSError)
Exception in command 'warnaction add'
Traceback (most recent call last):
File "/root/redenv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 83, in wrapped
File "/root/redenv/lib/python3.8/site-packages/redbot/cogs/warnings/warnings.py", line 103, in action_add
File "/root/redenv/lib/python3.8/site-packages/redbot/cogs/warnings/helpers.py", line 111, in get_command_for_exceeded_points
File "/root/redenv/lib/python3.8/site-packages/redbot/cogs/warnings/helpers.py", line 72, in get_command_from_input
File "/usr/lib/python3.8/inspect.py", line 985, in getsource
lines, lnum = getsourcelines(object)
File "/usr/lib/python3.8/inspect.py", line 967, in getsourcelines
lines, lnum = findsource(object)
File "/usr/lib/python3.8/inspect.py", line 798, in findsource
raise OSError('could not get source code')
OSError: could not get source code

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

Traceback (most recent call last):
File "/root/redenv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 892, in invoke
File "/root/redenv/lib/python3.8/site-packages/redbot/core/commands/commands.py", line 794, in invoke
File "/root/redenv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1234, in invoke
File "/root/redenv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 797, in invoke
File "/root/redenv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 92, in wrapped
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OSError: could not get source code

# Fixed code
async def create_and_invoke_context(
    realctx: commands.Context, command_str: str, user: discord.Member
):
    m = copy(realctx.message)
    m.content = command_str.format(user=user.mention, prefix=realctx.prefix)
    fctx = await realctx.bot.get_context(m, cls=commands.Context)
    try:
        await realctx.bot.invoke(fctx)
    except (commands.CheckFailure, commands.CommandOnCooldown):
        # reinvoke bypasses checks and we don't want to run bot owner only commands here
        if fctx.command.requires.privilege_level < PrivilegeLevel.BOT_OWNER:
            await fctx.reinvoke()
# Buggy code
def get_command_from_input(bot, userinput: str):
    com = None
    orig = userinput
    while com is None:
        com = bot.get_command(userinput)
        if com is None:
            userinput = " ".join(userinput.split(" ")[:-1])
        if len(userinput) == 0:
            break
    if com is None:
        return None, _("I could not find a command from that input!")

    check_str = inspect.getsource(checks.is_owner)
    if any(inspect.getsource(x) in check_str for x in com.checks):
        # command the user specified has the is_owner check
        return (
            None,
            _(
                "That command requires bot owner. I can't allow you to use that for an action"
            ),
        )
    return "{prefix}" + orig, None


# Traceback (OSError)
Exception in command 'warnaction add'
Traceback (most recent call last):
File "/root/redenv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 83, in wrapped
File "/root/redenv/lib/python3.8/site-packages/redbot/cogs/warnings/warnings.py", line 103, in action_add
File "/root/redenv/lib/python3.8/site-packages/redbot/cogs/warnings/helpers.py", line 111, in get_command_for_exceeded_points
File "/root/redenv/lib/python3.8/site-packages/redbot/cogs/warnings/helpers.py", line 72, in get_command_from_input
File "/usr/lib/python3.8/inspect.py", line 985, in getsource
lines, lnum = getsourcelines(object)
File "/usr/lib/python3.8/inspect.py", line 967, in getsourcelines
lines, lnum = findsource(object)
File "/usr/lib/python3.8/inspect.py", line 798, in findsource
raise OSError('could not get source code')
OSError: could not get source code

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

Traceback (most recent call last):
File "/root/redenv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 892, in invoke
File "/root/redenv/lib/python3.8/site-packages/redbot/core/commands/commands.py", line 794, in invoke
File "/root/redenv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1234, in invoke
File "/root/redenv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 797, in invoke
File "/root/redenv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 92, in wrapped
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OSError: could not get source code

# Fixed code
def get_command_from_input(bot, userinput: str):
    com = None
    orig = userinput
    while com is None:
        com = bot.get_command(userinput)
        if com is None:
            userinput = " ".join(userinput.split(" ")[:-1])
        if len(userinput) == 0:
            break
    if com is None:
        return None, _("I could not find a command from that input!")

    if com.requires.privilege_level >= PrivilegeLevel.BOT_OWNER:
        return (
            None,
            _(
                "That command requires bot owner. I can't allow you to use that for an action"
            ),
        )
    return "{prefix}" + orig, None
# Buggy code
def __init__(self, bot: Red, session: aiohttp.ClientSession):
    self.bot = bot
    self.session = session
    self.spotify_token = None
    self.client_id = None
    self.client_secret = None


# 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
def __init__(self, bot: Red, session: aiohttp.ClientSession):
    self.bot = bot
    self.session = session
    self.spotify_token: Optional[MutableMapping[str, Union[str, int]]] = None
    self.client_id = None
    self.client_secret = None
# Buggy code
async def _check_token(token: dict):
    now = int(time.time())
    return token["expires_at"] - now < 60


# 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 _check_token(token: MutableMapping):
    now = int(time.time())
    return token["expires_at"] - now < 60
# Buggy code
def _make_token_auth(client_id: Optional[str], client_secret: Optional[str]) -> dict:
    if client_id is None:
        client_id = ""
    if client_secret is None:
        client_secret = ""

    auth_header = base64.b64encode((client_id + ":" + client_secret).encode("ascii"))
    return {"Authorization": "Basic %s" % auth_header.decode("ascii")}


# 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
def _make_token_auth(
    client_id: Optional[str], client_secret: Optional[str]
) -> MutableMapping[str, Union[str, int]]:
    if client_id is None:
        client_id = ""
    if client_secret is None:
        client_secret = ""

    auth_header = base64.b64encode((client_id + ":" + client_secret).encode("ascii"))
    return {"Authorization": "Basic %s" % auth_header.decode("ascii")}
# Buggy code
async def _make_get(self, url: str, headers: dict = None, params: dict = None) -> dict:
    if params is None:
        params = {}
    async with self.session.request("GET", url, params=params, headers=headers) as r:
        if r.status != 200:
            log.debug(
                "Issue making GET request to {0}: [{1.status}] {2}".format(
                    url, r, await r.json()
                )
            )
        return await r.json()


# 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 _make_get(
    self, url: str, headers: MutableMapping = None, params: MutableMapping = None
) -> MutableMapping[str, str]:
    if params is None:
        params = {}
    async with self.session.request("GET", url, params=params, headers=headers) as r:
        if r.status != 200:
            log.debug(
                "Issue making GET request to {0}: [{1.status}] {2}".format(
                    url, r, await r.json()
                )
            )
        return await r.json()
# Buggy code
async def _get_auth(self):
    if self.client_id is None or self.client_secret is None:
        tokens = await self.bot.get_shared_api_tokens("spotify")
        self.client_id = tokens.get("client_id", "")
        self.client_secret = tokens.get("client_secret", "")


# 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 _get_auth(self) -> NoReturn:
    tokens = await self.bot.get_shared_api_tokens("spotify")
    self.client_id = tokens.get("client_id", "")
    self.client_secret = tokens.get("client_secret", "")
# Buggy code
async def _request_token(self) -> dict:
    await self._get_auth()

    payload = {"grant_type": "client_credentials"}
    headers = self._make_token_auth(self.client_id, self.client_secret)
    r = await self.post_call(
        "https://accounts.spotify.com/api/token", payload=payload, headers=headers
    )
    return r


# 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 _request_token(self) -> MutableMapping[str, Union[str, int]]:
    await self._get_auth()

    payload = {"grant_type": "client_credentials"}
    headers = self._make_token_auth(self.client_id, self.client_secret)
    r = await self.post_call(
        "https://accounts.spotify.com/api/token", payload=payload, headers=headers
    )
    return r
# Buggy code
async def post_call(self, url: str, payload: dict, headers: dict = None) -> dict:
    async with self.session.post(url, data=payload, headers=headers) as r:
        if r.status != 200:
            log.debug(
                "Issue making POST request to {0}: [{1.status}] {2}".format(
                    url, r, await r.json()
                )
            )
        return await r.json()


# 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 post_call(
    self, url: str, payload: MutableMapping, headers: MutableMapping = None
) -> MutableMapping[str, Union[str, int]]:
    async with self.session.post(url, data=payload, headers=headers) as r:
        if r.status != 200:
            log.debug(
                "Issue making POST request to {0}: [{1.status}] {2}".format(
                    url, r, await r.json()
                )
            )
        return await r.json()
# Buggy code
async def get_call(self, url: str, params: dict) -> dict:
    token = await self._get_spotify_token()
    return await self._make_get(
        url, params=params, headers={"Authorization": "Bearer {0}".format(token)}
    )


# 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 get_call(
    self, url: str, params: MutableMapping
) -> MutableMapping[str, Union[str, int]]:
    token = await self._get_spotify_token()
    return await self._make_get(
        url, params=params, headers={"Authorization": "Bearer {0}".format(token)}
    )
# Buggy code
async def get_categories(self) -> List[Dict[str, str]]:
    url = "https://api.spotify.com/v1/browse/categories"
    params = {}
    result = await self.get_call(url, params=params)
    with contextlib.suppress(KeyError):
        if result["error"]["status"] == 401:
            raise SpotifyFetchError(
                message=(
                    "The Spotify API key or client secret has not been set properly. "
                    "\nUse `{prefix}audioset spotifyapi` for instructions."
                )
            )
    categories = result.get("categories", {}).get("items", [])
    return [{c["name"]: c["id"]} for c in categories]


# 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 get_categories(self) -> List[MutableMapping]:
    url = "https://api.spotify.com/v1/browse/categories"
    params = {}
    result = await self.get_call(url, params=params)
    with contextlib.suppress(KeyError):
        if result["error"]["status"] == 401:
            raise SpotifyFetchError(
                message=(
                    "The Spotify API key or client secret has not been set properly. "
                    "\nUse `{prefix}audioset spotifyapi` for instructions."
                )
            )
    categories = result.get("categories", {}).get("items", [])
    return [{c["name"]: c["id"]} for c in categories]
# Buggy code
async def _get_api_key(
    self,
) -> Optional[str]:
    if self.api_key is None:
        tokens = await self.bot.get_shared_api_tokens("youtube")
        self.api_key = tokens.get("api_key", "")
    return self.api_key


# 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 _get_api_key(
    self,
) -> str:
    tokens = await self.bot.get_shared_api_tokens("youtube")
    self.api_key = tokens.get("api_key", "")
    return self.api_key
# Buggy code
def __init__(self, bot: Red, session: aiohttp.ClientSession, path: str):
    self.bot = bot
    self.spotify_api: SpotifyAPI = SpotifyAPI(bot, session)
    self.youtube_api: YouTubeAPI = YouTubeAPI(bot, session)
    self._session: aiohttp.ClientSession = session
    if HAS_SQL:
        self.database: Database = Database(
            f"sqlite:///{os.path.abspath(str(os.path.join(path, 'cache.db')))}"
        )
    else:
        self.database = None

    self._tasks: dict = {}
    self._lock: asyncio.Lock = asyncio.Lock()
    self.config: Optional[Config] = None


# 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
def __init__(self, bot: Red, session: aiohttp.ClientSession):
    self.bot = bot
    self.spotify_api: SpotifyAPI = SpotifyAPI(bot, session)
    self.youtube_api: YouTubeAPI = YouTubeAPI(bot, session)
    self._session: aiohttp.ClientSession = session
    self.database = _database

    self._tasks: MutableMapping = {}
    self._lock: asyncio.Lock = asyncio.Lock()
    self.config: Optional[Config] = None
# Buggy code
async def initialize(self, config: Config):
    if HAS_SQL:
        await self.database.connect()

        await self.database.execute(query="PRAGMA temp_store = 2;")
        await self.database.execute(query="PRAGMA journal_mode = wal;")
        await self.database.execute(query="PRAGMA wal_autocheckpoint;")
        await self.database.execute(query="PRAGMA read_uncommitted = 1;")

        await self.database.execute(query=_CREATE_LAVALINK_TABLE)
        await self.database.execute(query=_CREATE_UNIQUE_INDEX_LAVALINK_TABLE)
        await self.database.execute(query=_CREATE_YOUTUBE_TABLE)
        await self.database.execute(query=_CREATE_UNIQUE_INDEX_YOUTUBE_TABLE)
        await self.database.execute(query=_CREATE_SPOTIFY_TABLE)
        await self.database.execute(query=_CREATE_UNIQUE_INDEX_SPOTIFY_TABLE)
    self.config = config


# 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 initialize(self, config: Config):
    self.config = config
    await _database.init()
# Buggy code
def _spotify_format_call(qtype: str, key: str) -> Tuple[str, dict]:
    params = {}
    if qtype == "album":
        query = "https://api.spotify.com/v1/albums/{0}/tracks".format(key)
    elif qtype == "track":
        query = "https://api.spotify.com/v1/tracks/{0}".format(key)
    else:
        query = "https://api.spotify.com/v1/playlists/{0}/tracks".format(key)
    return query, params


# 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
def _spotify_format_call(qtype: str, key: str) -> Tuple[str, MutableMapping]:
    params = {}
    if qtype == "album":
        query = f"https://api.spotify.com/v1/albums/{key}/tracks"
    elif qtype == "track":
        query = f"https://api.spotify.com/v1/tracks/{key}"
    else:
        query = f"https://api.spotify.com/v1/playlists/{key}/tracks"
    return query, params
# Buggy code
def _get_spotify_track_info(track_data: dict) -> Tuple[str, ...]:
    artist_name = track_data["artists"][0]["name"]
    track_name = track_data["name"]
    track_info = f"{track_name} {artist_name}"
    song_url = track_data.get("external_urls", {}).get("spotify")
    uri = track_data["uri"]
    _id = track_data["id"]
    _type = track_data["type"]

    return song_url, track_info, uri, artist_name, track_name, _id, _type


# 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
def _get_spotify_track_info(track_data: MutableMapping) -> Tuple[str, ...]:
    artist_name = track_data["artists"][0]["name"]
    track_name = track_data["name"]
    track_info = f"{track_name} {artist_name}"
    song_url = track_data.get("external_urls", {}).get("spotify")
    uri = track_data["uri"]
    _id = track_data["id"]
    _type = track_data["type"]

    return song_url, track_info, uri, artist_name, track_name, _id, _type
# Buggy code
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,
            )
        )


# 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 _status_check(self, track, playing_servers):
    if playing_servers == 0:
        await self.bot.change_presence(activity=None)
    elif playing_servers == 1:
        await self.bot.change_presence(
            activity=discord.Activity(name=track, type=discord.ActivityType.listening)
        )
    elif playing_servers > 1:
        await self.bot.change_presence(
            activity=discord.Activity(
                name=_("music in {} servers").format(playing_servers),
                type=discord.ActivityType.playing,
            )
        )
# Buggy code
async def audioset(self, ctx: commands.Context):
    """Music configuration options."""
    pass


# 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 audioset(self, ctx: commands.Context):
    """Music configuration options."""