internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: Cog-Creators/Red-DiscordBot

Issue:
is_automod_immune errors when User object passed
#### What were you trying to do?

Use the automod_immune method

#### What were you expecting to happen?

Return a boolean

#### What actually happened?

Errors

#### How can we reproduce this issue?

Pass a User object into the method



Discussion:

Resolving patch:
diff --git a/redbot/core/bot.py b/redbot/core/bot.py
--- a/redbot/core/bot.py
+++ b/redbot/core/bot.py
@@ -653,7 +653,7 @@ async def is_automod_immune(
             ``True`` if immune
 
         """
-        guild = to_check.guild
+        guild = getattr(to_check, "guild", None)
         if not guild:
             return False
 
@@ -666,7 +666,8 @@ async def is_automod_immune(
             except AttributeError:
                 # webhook messages are a user not member,
                 # cheaper than isinstance
-                return True  # webhooks require significant permissions to enable.
+                if author.bot and author.discriminator == "0000":
+                    return True  # webhooks require significant permissions to enable.
             else:
                 ids_to_check.append(author.id)
 


Test patch:
Repository: Cog-Creators/Red-DiscordBot

Issue:
[Audio] Bot's status isn't cleared on auto-disconnect
# Other bugs

Bot's status isn't cleared on auto-disconnect. It was already happening before Draper's PR came in.

#### How can we reproduce this issue?

1. `[p]audioset emptydisconnect 10`
2. `[p]play audio url`
3. Leave channel and wait 10 seconds for the bot to leave it as well.
4. Status still shows up.



Discussion:
@jack1142 just to check, have you toggle `[p]audioset status` ? I assume so but just wanted to check.

Having a skim through the code and `_status_check()` is only called when status is set to True.

It then runs on `LavalinkEvents.TRACK_START`, `LavalinkEvents.TRACK_END` and `LavalinkEvents.QUEUE_END`

Auto disconnect should trigger a `QUEUE_END` so without doing any testing it seems that the only reason why this wouldn't reset the status is if the status was disabled after the track started playing.
@Drapersniper yes I do have `[p]audioset status` set to true, I forgot to put it in reproduction steps. 

Resolving patch:
diff --git a/redbot/cogs/audio/audio.py b/redbot/cogs/audio/audio.py
--- a/redbot/cogs/audio/audio.py
+++ b/redbot/cogs/audio/audio.py
@@ -6740,7 +6740,9 @@ async def disconnect_timer(self):
                     if (time.time() - stop_times[sid]) >= emptydc_timer:
                         stop_times.pop(sid)
                         try:
-                            await lavalink.get_player(sid).disconnect()
+                            player = lavalink.get_player(sid)
+                            await player.stop()
+                            await player.disconnect()
                         except Exception:
                             log.error("Exception raised in Audio's emptydc_timer.", exc_info=True)
                             pass


Test patch:
Repository: Cog-Creators/Red-DiscordBot

Issue:
[Bug] Downloader - Findcog
# Command bugs

<!-- 
Did you find a bug with a command? Fill out the following:
-->

#### Command name

findcog

#### What cog is this command from?

Downloader

To show the repository the cog is from.

#### What actually happened?

```py
Exception in command 'findcog'
Traceback (most recent call last):
  File "/data/venv/lib/python3.7/site-packages/discord/ext/commands/core.py", line 79, in wrapped
    ret = await coro(*args, **kwargs)
  File "/data/venv/lib/python3.7/site-packages/redbot/cogs/downloader/downloader.py", line 1203, in findcog
    msg = self.format_findcog_info(command_name, cog_installable)
  File "/data/venv/lib/python3.7/site-packages/redbot/cogs/downloader/downloader.py", line 1153, in format_findcog_info
    else cog_installable.repo.clean_url
  File "/data/venv/lib/python3.7/site-packages/redbot/cogs/downloader/repo_manager.py", line 155, in clean_url
    clean_url = url.with_user(None)
  File "/data/venv/lib/python3.7/site-packages/yarl/__init__.py", line 723, in with_user
    raise ValueError("user replacement is not allowed " "for relative URLs")
ValueError: user replacement is not allowed for relative URLs

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/data/venv/lib/python3.7/site-packages/discord/ext/commands/bot.py", line 863, in invoke
    await ctx.command.invoke(ctx)
  File "/data/venv/lib/python3.7/site-packages/discord/ext/commands/core.py", line 728, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/data/venv/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: ValueError: user replacement is not allowed for relative URLs
```

#### How can we reproduce this issue?

1. Add repo with SSH link
2. Use findcog on it

HTTP links work. 


Discussion:

Resolving patch:
diff --git a/redbot/cogs/downloader/repo_manager.py b/redbot/cogs/downloader/repo_manager.py
--- a/redbot/cogs/downloader/repo_manager.py
+++ b/redbot/cogs/downloader/repo_manager.py
@@ -149,11 +149,13 @@ def __init__(
         self._loop = loop if loop is not None else asyncio.get_event_loop()
 
     @property
-    def clean_url(self):
+    def clean_url(self) -> str:
         """Sanitized repo URL (with removed HTTP Basic Auth)"""
         url = yarl.URL(self.url)
-        clean_url = url.with_user(None)
-        return clean_url
+        try:
+            return url.with_user(None).human_repr()
+        except ValueError:
+            return self.url
 
     @classmethod
     async def convert(cls, ctx: commands.Context, argument: str) -> Repo:


Test patch:
Repository: Cog-Creators/Red-DiscordBot

Issue:
Emit events when a shared API token is changed
# Feature request
#### Select the type of feature you are requesting:

- [ ] Cog
- [ ] Command
- [X] API functionality

#### Describe your requested feature
Should emit the name of the service which was updated. This will allow cogs to cache the values and only update when if they change.


Discussion:

Resolving patch:
diff --git a/redbot/core/bot.py b/redbot/core/bot.py
--- a/redbot/core/bot.py
+++ b/redbot/core/bot.py
@@ -8,6 +8,7 @@
 from importlib.machinery import ModuleSpec
 from pathlib import Path
 from typing import Optional, Union, List, Dict, NoReturn
+from types import MappingProxyType
 
 import discord
 from discord.ext.commands import when_mentioned_or
@@ -582,6 +583,7 @@ async def set_shared_api_tokens(self, service_name: str, **tokens: str):
 
         async with self._config.custom(SHARED_API_TOKENS, service_name).all() as group:
             group.update(tokens)
+        self.dispatch("red_api_tokens_update", service_name, MappingProxyType(group))
 
     async def remove_shared_api_tokens(self, service_name: str, *token_names: str):
         """


Test patch:
Repository: Cog-Creators/Red-DiscordBot

Issue:
redbot-launcher CLI flags do not work correctly
# Other bugs

#### What were you trying to do?

Use the interactive redbot-launcher CLI flag selector

#### What were you expecting to happen?

To have an amazing time with the wonderful redbot-launcher

#### What actually happened?

Error:
```
You have selected the following cli flags:


--owner 234234

If this looks good to you, type y. If you wish to start over, type n
> y
Done selecting cli flags
Starting testingbot...
usage: redbot <instance_name> [arguments]
__main__.py: error: unrecognized arguments: --owner 234234
Press enter to continue.
```

#### How can we reproduce this issue?

`redbot-launcher`
`2`, launch the bot
Pick an instance
`y`, use CLI flags
`y`, set an owner
Put your user ID
`n` for every other CLI flag
`y` to confirm flags



Discussion:

Resolving patch:
diff --git a/redbot/launcher.py b/redbot/launcher.py
--- a/redbot/launcher.py
+++ b/redbot/launcher.py
@@ -201,7 +201,12 @@ def cli_flag_getter():
         choice = user_choice()
         if choice == "y":
             print("Done selecting cli flags")
-            return flags
+            # this is safe only because arguments like prefix and owner id can't have spaces
+            cli_flags = []
+            for flag_with_spaces in flags:
+                for flag in flag_with_spaces.split():
+                    cli_flags.append(flag)
+            return cli_flags
         else:
             print("Starting over")
             return cli_flag_getter()


Test patch:
Repository: Cog-Creators/Red-DiscordBot

Issue:
[Downloader] `[p]findcog` doesn't work if cog class is at different level than `cog_folder/somefile.py`
# Command bugs

#### Command name

`[p]findcog`

#### What cog is this command from?

Downloader

#### What were you expecting to happen?

Get cog the command is from

#### What actually happened?

Got error:
```
[2019-12-08 23:17:40] [ERROR] red: Exception in command 'findcog'
Traceback (most recent call last):
  File "venv\lib\site-packages\discord\ext\commands\core.py", line 79, in wrapped
    ret = await coro(*args, **kwargs)
  File "venv\lib\site-packages\redbot\cogs\downloader\downloader.py", line 1199, in findcog
    cog_name = self.cog_name_from_instance(cog)
  File "venv\lib\site-packages\redbot\cogs\downloader\downloader.py", line 1182, in cog_name_from_instance
    return splitted[-2]
IndexError: list index out of range
```

#### How can we reproduce this issue?

1. Create a cog with cog class placed in `__init__.py`
2. Load the cog.
3. Use `[p]findcog command_from_that_cog`
4. See error

---

In short, it looks like `Downloader.cog_name_from_instance` heavily relies on most common file structure in cogs where you have cog class in `cog_folder/somefile.py` file and it raises if it's in `cog_folder/__init__.py` and also determines wrong cog name if it's placed in `cog_folder/subpackage/somefile.py`



Discussion:

Resolving patch:
diff --git a/redbot/cogs/downloader/downloader.py b/redbot/cogs/downloader/downloader.py
--- a/redbot/cogs/downloader/downloader.py
+++ b/redbot/cogs/downloader/downloader.py
@@ -1179,7 +1179,7 @@ def cog_name_from_instance(self, instance: object) -> str:
 
         """
         splitted = instance.__module__.split(".")
-        return splitted[-2]
+        return splitted[0]
 
     @commands.command()
     async def findcog(self, ctx: commands.Context, command_name: str) -> None:


Test patch:
Repository: Cog-Creators/Red-DiscordBot

Issue:
[Downloader] `[p]cog uninstall` doesn't remove cog from `bot._config.packages`
# Command bugs

#### Command name

`[p]cog uninstall`

#### What cog is this command from?

Downloader

#### What were you expecting to happen?

The bot to unload the cog AND remove it from `bot._config.packages`

#### What actually happened?

Bot unloaded the cog, but it didn't remove it from `bot._config.packages` therefore causing error on next bot start:
```
Failed to load package cogboard
Traceback (most recent call last):
  File "venv\lib\site-packages\redbot\core\bot.py", line 409, in pre_flight
    await asyncio.wait_for(self.load_extension(spec), 30)
  File "C:\Python37\lib\asyncio\tasks.py", line 442, in wait_for
    return fut.result()
  File "lib\site-packages\redbot\core\bot.py", line 648, in load_extension
    name = spec.name.split(".")[-1]
AttributeError: 'NoneType' object has no attribute 'name'
```

#### How can we reproduce this issue?

1. Uninstall **loaded** cog that was installed through Downloader.
2. Restart bot.




Discussion:

Resolving patch:
diff --git a/redbot/cogs/downloader/downloader.py b/redbot/cogs/downloader/downloader.py
--- a/redbot/cogs/downloader/downloader.py
+++ b/redbot/cogs/downloader/downloader.py
@@ -647,6 +647,7 @@ async def _cog_uninstall(self, ctx: commands.Context, *cogs: InstalledCog) -> No
                 if poss_installed_path.exists():
                     with contextlib.suppress(commands.ExtensionNotLoaded):
                         ctx.bot.unload_extension(real_name)
+                        await ctx.bot.remove_loaded_package(real_name)
                     await self._delete_cog(poss_installed_path)
                     uninstalled_cogs.append(inline(real_name))
                 else:


Test patch:
Repository: Cog-Creators/Red-DiscordBot

Issue:
[Core] Users can lock out themselves with `[p]locablacklist add`
# Command bugs

#### Command name

`[p]localblacklist add`

#### What cog is this command from?

Core

#### What were you expecting to happen?

~~Well, to be honest, I was expecting this to happen.~~ I was expecting to get an error saying that I can't lock out myself from using the bot.

#### What actually happened?

I locked myself out.

#### How can we reproduce this issue?

1. Have permissions to use `[p]localblacklist` (e.g. have admin role), but don't be bot owner.
2. Use `[p]localblacklist add YOUR_USER_ID`



Discussion:

Resolving patch:
diff --git a/redbot/core/bot.py b/redbot/core/bot.py
--- a/redbot/core/bot.py
+++ b/redbot/core/bot.py
@@ -223,6 +223,11 @@ async def allowed_by_whitelist_blacklist(
         ------
         TypeError
             Did not provide ``who`` or ``who_id``
+            
+        Returns
+        -------
+        bool
+            `True` if user is allowed to run things, `False` otherwise
         """
         # Contributor Note:
         # All config calls are delayed until needed in this section
@@ -254,6 +259,9 @@ async def allowed_by_whitelist_blacklist(
                 return False
 
         if guild:
+            if guild.owner_id == who.id:
+                return True
+
             # The delayed expansion of ids to check saves time in the DM case.
             # Converting to a set reduces the total lookup time in section
             if mocked:
diff --git a/redbot/core/core_commands.py b/redbot/core/core_commands.py
--- a/redbot/core/core_commands.py
+++ b/redbot/core/core_commands.py
@@ -1903,9 +1903,16 @@ async def localblacklist_add(
             user_or_role = discord.Object(id=user_or_role)
             user = True
 
-        if user and await ctx.bot.is_owner(user_or_role):
-            await ctx.send(_("You cannot blacklist an owner!"))
-            return
+        if user:
+            if user_or_role.id == ctx.author.id:
+                await ctx.send(_("You cannot blacklist yourself!"))
+                return
+            if user_or_role.id == ctx.guild.owner_id and not await ctx.bot.is_owner(ctx.author):
+                await ctx.send(_("You cannot blacklist the guild owner!"))
+                return
+            if await ctx.bot.is_owner(user_or_role):
+                await ctx.send(_("You cannot blacklist a bot owner!"))
+                return
 
         async with ctx.bot._config.guild(ctx.guild).blacklist() as curr_list:
             if user_or_role.id not in curr_list:


Test patch:
Repository: Cog-Creators/Red-DiscordBot

Issue:
[Downloader] Cog update fails if cogs are already up-to-date
# Command bugs

#### Command name

`[p]cog update*` commands

#### What cog is this command from?

Downloader

#### What is the issue?

If cogs are already up-to-date, Downloader errors:
```
Exception in command 'cog updatetoversion'
Traceback (most recent call last):
  File "venv\lib\site-packages\discord\ext\commands\core.py", line 79, in wrapped
    ret = await coro(*args, **kwargs)
  File "venv\lib\site-packages\redbot\cogs\downloader\downloader.py", line 802, in _cog_updatetoversion
    await self._cog_update_logic(ctx, repo=repo, rev=rev, cogs=cogs)
  File "venv\lib\site-packages\redbot\cogs\downloader\downloader.py", line 909, in _cog_update_logic
    for module in cogs_to_update + libs_to_update
UnboundLocalError: local variable 'cogs_to_update' referenced before assignment
```

---

Regression introduced by #3106 


Discussion:

Resolving patch:
diff --git a/redbot/cogs/downloader/downloader.py b/redbot/cogs/downloader/downloader.py
--- a/redbot/cogs/downloader/downloader.py
+++ b/redbot/cogs/downloader/downloader.py
@@ -859,6 +859,7 @@ async def _cog_update_logic(
             pinned_cogs = {cog for cog in cogs_to_check if cog.pinned}
             cogs_to_check -= pinned_cogs
             if not cogs_to_check:
+                cogs_to_update = libs_to_update = ()
                 message += _("There were no cogs to check.")
                 if pinned_cogs:
                     cognames = [cog.name for cog in pinned_cogs]


Test patch:
Repository: Cog-Creators/Red-DiscordBot

Issue:
[Setup] Don't use working directory for storing setup logs
Currently `redbot-setup` command creates a folder named "red_setup_logs" in working directory and I think this behaviour is too invasive and unexpected. I am not entirely sure where the setup logs should be stored instead, possibly in appdirs location, but touching working directory without any information about it just isn't a good way to do it.


Discussion:
We could use the OS temp folders to store these logs, however this would cause them to be be wiped after a reboot 
I'm perfectly fine with redbot-setup not logging to disk

Resolving patch:
diff --git a/redbot/setup.py b/redbot/setup.py
--- a/redbot/setup.py
+++ b/redbot/setup.py
@@ -12,7 +12,6 @@
 import appdirs
 import click
 
-import redbot.logging
 from redbot.core.utils._internal_utils import safe_delete, create_backup as red_create_backup
 from redbot.core import config, data_manager, drivers
 from redbot.core.drivers import BackendType, IdentifierData
@@ -295,7 +294,15 @@ async def remove_instance_interaction():
 def cli(ctx, debug):
     """Create a new instance."""
     level = logging.DEBUG if debug else logging.INFO
-    redbot.logging.init_logging(level=level, location=Path.cwd() / "red_setup_logs")
+    base_logger = logging.getLogger("red")
+    base_logger.setLevel(level)
+    formatter = logging.Formatter(
+        "[{asctime}] [{levelname}] {name}: {message}", datefmt="%Y-%m-%d %H:%M:%S", style="{"
+    )
+    stdout_handler = logging.StreamHandler(sys.stdout)
+    stdout_handler.setFormatter(formatter)
+    base_logger.addHandler(stdout_handler)
+
     if ctx.invoked_subcommand is None:
         basic_setup()
 


Test patch:
Repository: Cog-Creators/Red-DiscordBot

Issue:
[V3/develop] "owner" config field is ignored
# Other bugs

#### What were you trying to do?

Start bot with owner permissions on me.

#### What were you expecting to happen?

I have owner permissions

#### What actually happened?

I don't have owner permissions, but owner is set in config.

#### How can we reproduce this issue?

1. Setup bot, token of which doesn't belongs directly to you (i.e. other user or just a team)
2. Set an owner through config (via `redbot --edit`)
3. Run bot: config is ignored, owner used from application's data


Discussion:

Resolving patch:
diff --git a/redbot/core/bot.py b/redbot/core/bot.py
--- a/redbot/core/bot.py
+++ b/redbot/core/bot.py
@@ -404,6 +404,9 @@ async def pre_flight(self, cli_flags):
         init_global_checks(self)
         init_events(self, cli_flags)
 
+        if self.owner_id is None:
+            self.owner_id = await self._config.owner()
+
         i18n_locale = await self._config.locale()
         i18n.set_locale(i18n_locale)
 


Test patch:
Repository: Cog-Creators/Red-DiscordBot

Issue:
(Audio cog) Bot no longer auto disconnects when notify is turned on.
# Other bugs - Audio Cog

Problem with core audio. When notify is turned on (audioset notify), bot will no longer disconnect when queue ends, even with auto disconnect setting on. Auto disconnect works after notify is turned off.


Discussion:
![image](https://user-images.githubusercontent.com/27962761/72222291-ef84ad80-355a-11ea-8ba1-ab756058e8a1.png)
Not reproducible, care do provide me with more details of when and how this happens what commands you are using etc ... please join the support server at https://discordapp.com/invite/red and We can look at it in more detail... for now this issue can be closed as there is no issues with the code

Resolving patch:
diff --git a/redbot/cogs/audio/audio.py b/redbot/cogs/audio/audio.py
--- a/redbot/cogs/audio/audio.py
+++ b/redbot/cogs/audio/audio.py
@@ -530,17 +530,18 @@ async def event_handler(
                 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 == lavalink.LavalinkEvents.QUEUE_END:
+            if not autoplay:
+                notify_channel = player.fetch("channel")
+                if notify_channel and notify:
+                    notify_channel = self.bot.get_channel(notify_channel)
+                    await self._embed_msg(notify_channel, title=_("Queue Ended."))
+                if disconnect:
+                    self.bot.dispatch("red_audio_audio_disconnect", guild)
+                    await player.disconnect()
+            if status:
+                player_check = await self._players_check()
+                await self._status_check(*player_check)
 
         if event_type in [
             lavalink.LavalinkEvents.TRACK_EXCEPTION,


Test patch: