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

Issue:
[V3 Cleanup] "Cleanup user" does not clean up the command itself
# Command bugs

<!-- 
Did you find a bug with a command? Fill out the following:
-->

#### Command name

Cleanup user

#### What cog is this command from?

cleanup

#### What were you expecting to happen?

Bot deletes the command after it completes the task, as it was with with cleanup command in v2

#### What actually happened?

Bot removed the messages by the specified user, but the left command intact

#### How can we reproduce this issue?

1. Send some messages by user @A
2. Use the following command: !cleanup user @A 2
3. messages will be removed, but the command will stay



Discussion:

Resolving patch:
diff --git a/redbot/cogs/cleanup/cleanup.py b/redbot/cogs/cleanup/cleanup.py
--- a/redbot/cogs/cleanup/cleanup.py
+++ b/redbot/cogs/cleanup/cleanup.py
@@ -133,8 +133,6 @@ async def text(
         def check(m):
             if text in m.content:
                 return True
-            elif m == ctx.message:
-                return True
             else:
                 return False
 
@@ -145,6 +143,7 @@ def check(m):
             before=ctx.message,
             delete_pinned=delete_pinned,
         )
+        to_delete.append(ctx.message)
 
         reason = "{}({}) deleted {} messages containing '{}' in channel {}.".format(
             author.name, author.id, len(to_delete), text, channel.id
@@ -188,8 +187,6 @@ async def user(
         def check(m):
             if m.author.id == _id:
                 return True
-            elif m == ctx.message:
-                return True
             else:
                 return False
 
@@ -200,6 +197,8 @@ def check(m):
             before=ctx.message,
             delete_pinned=delete_pinned,
         )
+        to_delete.append(ctx.message)
+
         reason = (
             "{}({}) deleted {} messages "
             " made by {}({}) in channel {}."
@@ -231,6 +230,7 @@ async def after(self, ctx: commands.Context, message_id: int, delete_pinned: boo
         to_delete = await self.get_messages_for_deletion(
             channel=channel, number=None, after=after, delete_pinned=delete_pinned
         )
+        to_delete.append(ctx.message)
 
         reason = "{}({}) deleted {} messages in channel {}.".format(
             author.name, author.id, len(to_delete), channel.name
@@ -263,6 +263,7 @@ async def before(
         to_delete = await self.get_messages_for_deletion(
             channel=channel, number=number, before=before, delete_pinned=delete_pinned
         )
+        to_delete.append(ctx.message)
 
         reason = "{}({}) deleted {} messages in channel {}.".format(
             author.name, author.id, len(to_delete), channel.name


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

Issue:
[V3 Permissions] Rule precedence bug.
Applying a default to a Cog as well as to a command within a Cog (Default deny cog, allow command) does not allow the command. 

With current intended precedence, this should allow the command. 

Initially reported by <@203619925179236352> (Céli28), confirmed by me and <@218773382617890828> (TrustyJAID)



Discussion:

Resolving patch:
diff --git a/redbot/core/commands/requires.py b/redbot/core/commands/requires.py
--- a/redbot/core/commands/requires.py
+++ b/redbot/core/commands/requires.py
@@ -417,9 +417,13 @@ async def verify(self, ctx: "Context") -> bool:
 
         """
         await self._verify_bot(ctx)
-        # Owner-only commands are non-overrideable
+
+        # Owner should never be locked out of commands for user permissions.
+        if await ctx.bot.is_owner(ctx.author):
+            return True
+        # Owner-only commands are non-overrideable, and we already checked for owner.
         if self.privilege_level is PrivilegeLevel.BOT_OWNER:
-            return await ctx.bot.is_owner(ctx.author)
+            return False
 
         hook_result = await ctx.bot.verify_permissions_hooks(ctx)
         if hook_result is not None:


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

Issue:
is_automod_immune raises error on webhook messages
# Other bugs

#### What were you trying to do?

Checking `is_automod_immune` inside `on_message` with a webhook message update.

#### What were you expecting to happen?

`is_automod_immune` would return True or False depending on who sent the message.

#### What actually happened?

`is_automod_immune` raised AttributeError: 'User' object has no attribute 'roles' after a webhook message was sent.

#### How can we reproduce this issue?

Check `is_automod_immune` on incoming webhook messages.



Discussion:
This is very easily remedied, the question is should webhooks be considered automod immune though? My 2c is yes since they require manage_server to set up.
I'm going through our other methods which take a message, context, or author to ensure they don't run into the same issue, PR in a moment with them being considered immune from moderation actions, behavior on that can be changed if desired.

Resolving patch:
diff --git a/redbot/core/bot.py b/redbot/core/bot.py
--- a/redbot/core/bot.py
+++ b/redbot/core/bot.py
@@ -186,13 +186,23 @@ async def is_owner(self, user):
     async def is_admin(self, member: discord.Member):
         """Checks if a member is an admin of their guild."""
         admin_role = await self.db.guild(member.guild).admin_role()
-        return any(role.id == admin_role for role in member.roles)
+        try:
+            if any(role.id == admin_role for role in member.roles):
+                return True
+        except AttributeError:  # someone passed a webhook to this
+            pass
+        return False
 
     async def is_mod(self, member: discord.Member):
         """Checks if a member is a mod or admin of their guild."""
         mod_role = await self.db.guild(member.guild).mod_role()
         admin_role = await self.db.guild(member.guild).admin_role()
-        return any(role.id in (mod_role, admin_role) for role in member.roles)
+        try:
+            if any(role.id in (mod_role, admin_role) for role in member.roles):
+                return True
+        except AttributeError:  # someone passed a webhook to this
+            pass
+        return False
 
     async def get_context(self, message, *, cls=commands.Context):
         return await super().get_context(message, cls=cls)
@@ -334,8 +344,14 @@ async def is_automod_immune(
             ids_to_check = [to_check.id]
         else:
             author = getattr(to_check, "author", to_check)
-            ids_to_check = [r.id for r in author.roles]
-            ids_to_check.append(author.id)
+            try:
+                ids_to_check = [r.id for r in author.roles]
+            except AttributeError:
+                # webhook messages are a user not member,
+                # cheaper than isinstance
+                return True  # webhooks require significant permissions to enable.
+            else:
+                ids_to_check.append(author.id)
 
         immune_ids = await self.db.guild(guild).autoimmune_ids()
 


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

Issue:
[Permissions] Default rules being ignored sometimes
Whilst trying (and failing) to reproduce #2313, I came across a bug with default rules which was different to the one described there.

In particular, whenever a default rule was set for a command/cog, but an explicit rule was set for a subcommand, the default rule would be ignored for anyone the explicit rule applied to. One example for reproduction:
1. `[p]p setdefaultserverrule deny Core`
2. `[p]p setdefaultserverrule allow ping RandomUser`
3. `[p]p mock RandomUser info`, the user will be able to run info despite the default rule for `Core` being deny.



Discussion:

Resolving patch:
diff --git a/redbot/core/commands/requires.py b/redbot/core/commands/requires.py
--- a/redbot/core/commands/requires.py
+++ b/redbot/core/commands/requires.py
@@ -452,7 +452,20 @@ async def _transition_state(self, ctx: "Context") -> bool:
             should_invoke = await self._verify_user(ctx)
         elif isinstance(next_state, dict):
             # NORMAL to PASSIVE_ALLOW; should we proceed as normal or transition?
-            next_state = next_state[await self._verify_user(ctx)]
+            # We must check what would happen normally, if no explicit rules were set.
+            default_rule = PermState.NORMAL
+            if ctx.guild is not None:
+                default_rule = self.get_default_guild_rule(guild_id=ctx.guild.id)
+            if default_rule is PermState.NORMAL:
+                default_rule = self.default_global_rule
+
+            if default_rule == PermState.ACTIVE_DENY:
+                would_invoke = False
+            elif default_rule == PermState.ACTIVE_ALLOW:
+                would_invoke = True
+            else:
+                would_invoke = await self._verify_user(ctx)
+            next_state = next_state[would_invoke]
 
         ctx.permission_state = next_state
         return should_invoke


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

Issue:
[CustomCom] CC list markdown does not properly escape.
The CC list does not properly escape markdown causing the bellow issue. 

![image](https://user-images.githubusercontent.com/10947836/48375198-77f18f00-e6c7-11e8-8a3c-1481266bd43c.png)



Discussion:
I'm confused as to why the `>>epicstaff` command is not being placed on a new line, and it's also missing one of its right angle-brackets in the prefix. Maybe it has something to do with the content of the `>>creator` command?
It seems that Discord is inserting the new line into the URL, seeing as the [Hex character 0A](http://www.columbia.edu/kermit/ascii.html) is a line feed.

Resolving patch:
diff --git a/redbot/cogs/customcom/customcom.py b/redbot/cogs/customcom/customcom.py
--- a/redbot/cogs/customcom/customcom.py
+++ b/redbot/cogs/customcom/customcom.py
@@ -351,7 +351,6 @@ async def cc_list(self, ctx: commands.Context):
                 result = responses
             else:
                 continue
-            # Replace newlines with spaces
             # Cut preview to 52 characters max
             if len(result) > 52:
                 result = result[:49] + "..."
@@ -362,7 +361,8 @@ async def cc_list(self, ctx: commands.Context):
             results.append((f"{ctx.clean_prefix}{command}", result))
 
         if await ctx.embed_requested():
-            content = "\n".join(map("**{0[0]}** {0[1]}".format, results))
+            # We need a space before the newline incase the CC preview ends in link (GH-2295)
+            content = " \n".join(map("**{0[0]}** {0[1]}".format, results))
             pages = list(pagify(content, page_length=1024))
             embed_pages = []
             for idx, page in enumerate(pages, start=1):


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

Issue:
[V3 Backup] Uncaught exceptions
Backup command does not properly handle filesize issues or closed DMs. Needs fixing for RC3.


Discussion:

Resolving patch:
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
@@ -1142,6 +1142,9 @@ async def backup(self, ctx: commands.Context, backup_path: str = None):
             await ctx.send(
                 _("A backup has been made of this instance. It is at {}.").format(backup_file)
             )
+            if backup_file.stat().st_size > 8_000_000:
+                await ctx.send(_("This backup is to large to send via DM."))
+                return
             await ctx.send(_("Would you like to receive a copy via DM? (y/n)"))
 
             pred = MessagePredicate.yes_or_no(ctx)
@@ -1152,10 +1155,18 @@ async def backup(self, ctx: commands.Context, backup_path: str = None):
             else:
                 if pred.result is True:
                     await ctx.send(_("OK, it's on its way!"))
-                    async with ctx.author.typing():
-                        await ctx.author.send(
-                            _("Here's a copy of the backup"), file=discord.File(str(backup_file))
+                    try:
+                        async with ctx.author.typing():
+                            await ctx.author.send(
+                                _("Here's a copy of the backup"),
+                                file=discord.File(str(backup_file)),
+                            )
+                    except discord.Forbidden:
+                        await ctx.send(
+                            _("I don't seem to be able to DM you. Do you have closed DMs?")
                         )
+                    except discord.HTTPException:
+                        await ctx.send(_("I could not send the backup file."))
                 else:
                     await ctx.send(_("OK then."))
         else:


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

Issue:
[V3 Permissions] Permission hooks don't set state
Permission hooks forcibly allowing a command don't set the permission state to allowed, meaning it's impossible to detect that normal behavior was overridden in this case. 

As already shown in voice checks for mod cog, having access to the intended state is important.

It might be worth adding to the enum for allowed/denied by hook (denied by hook too for anyone logging check failures)


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
@@ -500,7 +500,12 @@ async def verify_permissions_hooks(self, ctx: commands.Context) -> Optional[bool
             if result is not None:
                 hook_results.append(result)
         if hook_results:
-            return all(hook_results)
+            if all(hook_results):
+                ctx.permission_state = commands.PermState.ALLOWED_BY_HOOK
+                return True
+            else:
+                ctx.permission_state = commands.PermState.DENIED_BY_HOOK
+                return False
 
 
 class Red(RedBase, discord.AutoShardedClient):
diff --git a/redbot/core/commands/requires.py b/redbot/core/commands/requires.py
--- a/redbot/core/commands/requires.py
+++ b/redbot/core/commands/requires.py
@@ -168,6 +168,17 @@ class PermState(enum.Enum):
     chain.
     """
 
+    # The below are valid states, but should not be transitioned to
+    # They should be set if they apply.
+
+    ALLOWED_BY_HOOK = enum.auto()
+    """This command has been actively allowed by a permission hook.
+    check validation doesn't need this, but is useful to developers"""
+
+    DENIED_BY_HOOK = enum.auto()
+    """This command has been actively denied by a permission hook
+    check validation doesn't need this, but is useful to developers"""
+
     def transition_to(
         self, next_state: "PermState"
     ) -> Tuple[Optional[bool], Union["PermState", Dict[bool, "PermState"]]]:


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

Issue:
[V3] ctx.send_interactive traceback on prompt deletion.
If the prompt is deleted before the bot tries to, you get a traceback.


Discussion:

Resolving patch:
diff --git a/redbot/core/commands/context.py b/redbot/core/commands/context.py
--- a/redbot/core/commands/context.py
+++ b/redbot/core/commands/context.py
@@ -1,4 +1,5 @@
 import asyncio
+import contextlib
 from typing import Iterable, List
 import discord
 from discord.ext import commands
@@ -167,7 +168,8 @@ async def send_interactive(
                         timeout=timeout,
                     )
                 except asyncio.TimeoutError:
-                    await query.delete()
+                    with contextlib.suppress(discord.HTTPException):
+                        await query.delete()
                     break
                 else:
                     try:
@@ -176,7 +178,8 @@ async def send_interactive(
                         # In case the bot can't delete other users' messages,
                         # or is not a bot account
                         # or channel is a DM
-                        await query.delete()
+                        with contextlib.suppress(discord.HTTPException):
+                            await query.delete()
         return ret
 
     async def embed_colour(self):


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

Issue:
[p]set locale does not have a check
# Command bugs

#### Command name

`[p]set locale`

#### What cog is this command from?

Core

#### What were you expecting to happen?

`[p]set locale randomtext` would respond saying that locale does not exist

#### What actually happened?

Any "locale" can be passed to this command an it will use the English locale (presumably because i18n handles any locale not explicitly existing as the default locale).

#### How can we reproduce this issue?

Run `[p]set locale randomtext`

#### Additional information

I am making a PR for this issue as discussed in #coding on the main server, this issue is just for logging this problem.



Discussion:

Resolving patch:
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
@@ -1009,11 +1009,20 @@ async def locale(self, ctx: commands.Context, locale_name: str):
 
         To reset to English, use "en-US".
         """
-        i18n.set_locale(locale_name)
-
-        await ctx.bot.db.locale.set(locale_name)
-
-        await ctx.send(_("Locale has been set."))
+        red_dist = pkg_resources.get_distribution("red-discordbot")
+        red_path = Path(red_dist.location) / "redbot"
+        locale_list = [loc.stem.lower() for loc in list(red_path.glob("**/*.po"))]
+        if locale_name.lower() in locale_list or locale_name.lower() == "en-us":
+            i18n.set_locale(locale_name)
+            await ctx.bot.db.locale.set(locale_name)
+            await ctx.send(_("Locale has been set."))
+        else:
+            await ctx.send(
+                _(
+                    "Invalid locale. Use `{prefix}listlocales` to get "
+                    "a list of available locales."
+                ).format(prefix=ctx.prefix)
+            )
 
     @_set.command()
     @checks.is_owner()
@@ -1134,7 +1143,9 @@ async def listlocales(self, ctx: commands.Context):
         async with ctx.channel.typing():
             red_dist = pkg_resources.get_distribution("red-discordbot")
             red_path = Path(red_dist.location) / "redbot"
-            locale_list = sorted(set([loc.stem for loc in list(red_path.glob("**/*.po"))]))
+            locale_list = [loc.stem for loc in list(red_path.glob("**/*.po"))]
+            locale_list.append("en-US")
+            locale_list = sorted(set(locale_list))
             if not locale_list:
                 await ctx.send("No languages found.")
                 return


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

Issue:
"Failed to install libraries" message outputs a raw list
# Command bugs

<!-- 
Did you find a bug with a command? Fill out the following:
-->

#### Command name

`[p]cog install`

#### What cog is this command from?

Downloader

#### What were you expecting to happen?

A nice pretty output from the "Failed to install libraries" message.

#### What actually happened?

A horrible no good very bad list was outputted. 

#### How can we reproduce this issue?

Install a cog that has a library that cannot be installed, look at the resulting message.

#### Additional Information

I am making a PR for this issue in a few seconds, this issue is just for logging this problem.


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
@@ -305,10 +305,11 @@ async def _cog_install(self, ctx, repo: Repo, cog_name: str):
             return
 
         if not await repo.install_requirements(cog, self.LIB_PATH):
+            libraries = humanize_list(tuple(map(inline, cog.requirements)))
             await ctx.send(
-                _(
-                    "Failed to install the required libraries for `{cog_name}`: `{libraries}`"
-                ).format(cog_name=cog.name, libraries=cog.requirements)
+                _("Failed to install the required libraries for `{cog_name}`: {libraries}").format(
+                    cog_name=cog.name, libraries=libraries
+                )
             )
             return
 


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

Issue:
humanize_list() throws IndexError on empty lists
#### What were you trying to do?

Use the *chat formatting* tool `humanize_list()`.

#### What were you expecting to happen?

To return a string, possibly an empty string.

#### What actually happened?

It crashed, IndexError:
https://i.gyazo.com/4c59a0299ed5988c3ec6a953d086c2a5.png

#### How can we reproduce this issue?

```
yaboobay = list()
humanize_list(yaboobay)
```



Discussion:

Resolving patch:
diff --git a/redbot/core/utils/chat_formatting.py b/redbot/core/utils/chat_formatting.py
--- a/redbot/core/utils/chat_formatting.py
+++ b/redbot/core/utils/chat_formatting.py
@@ -344,6 +344,11 @@ def humanize_list(items: Sequence[str]) -> str:
     items : Sequence[str]
         The items of the list to join together.
 
+    Raises
+    ------
+    IndexError
+        An empty sequence was passed
+
     Examples
     --------
     .. testsetup::


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

Issue:
[Audio] Error in `[p]audioset settings`
# Command bugs

#### Command name

[p]audioset settings

#### What cog is this command from?

audio

#### What were you expecting to happen?

Shows the settings of the audio cog

#### What actually happened?

The command throughs a Traceback:
```
[28/01/2019 21:17] ERROR events on_command_error 208: Exception in command 'audioset settings'
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 79, in wrapped
    ret = await coro(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/redbot/cogs/audio/audio.py", line 343, in settings
    msg += _("DJ Role:          [{role.name}]\n").format(role=dj_role_obj)
AttributeError: 'NoneType' object has no attribute 'name'
[28/01/2019 21:17] ERROR events on_command_error 213: Exception in command 'audioset settings'
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 79, in wrapped
    ret = await coro(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/redbot/cogs/audio/audio.py", line 343, in settings
    msg += _("DJ Role:          [{role.name}]\n").format(role=dj_role_obj)
AttributeError: 'NoneType' object has no attribute 'name'
```

This happens when DJ mode is enabled but there is no DJ role defined.

#### How can we reproduce this issue?
1. Update Red to 3.0.0
2. don't set a DJ role
3. enable DJ mode
4. try [p]audioset settings


Discussion:

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
@@ -293,7 +293,7 @@ async def dj(self, ctx):
         DJ mode allows users with the DJ role to use audio commands.
         """
         dj_role_id = await self.config.guild(ctx.guild).dj_role()
-        if dj_role_id is None and ctx.guild.get_role(dj_role_id):
+        if dj_role_id is None:
             await self._embed_msg(
                 ctx, _("Please set a role to use with DJ mode. Enter the role name or ID now.")
             )


Test patch: