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

Issue:
[Audio] bumpplay command reports an innacurate time till play
# Command bugs

#### Command name

bumpplay

#### What cog is this command from?

Audio

#### What were you expecting to happen?

Expected a relatively accurate time in the footer

#### What actually happened?

Time was calculated as if it was appended to the queue rather than put in front

#### How can we reproduce this issue?

queue a bunch of songs then bumpplay something



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
@@ -2954,8 +2954,7 @@ async def bumpplay(
             return await self._embed_msg(ctx, embed=embed)
         elif isinstance(tracks, discord.Message):
             return
-        queue_dur = await queue_duration(ctx)
-        lavalink.utils.format_time(queue_dur)
+        queue_dur = await track_remaining_duration(ctx)
         index = query.track_index
         seek = 0
         if query.start_time:
diff --git a/redbot/cogs/audio/audio_dataclasses.py b/redbot/cogs/audio/audio_dataclasses.py
--- a/redbot/cogs/audio/audio_dataclasses.py
+++ b/redbot/cogs/audio/audio_dataclasses.py
@@ -211,7 +211,7 @@ def to_string_user(self, arg: str = None):
 
     def tracks_in_tree(self):
         tracks = []
-        for track in self.multirglob(*[f"*{ext}" for ext in self._all_music_ext]):
+        for track in self.multirglob(*[f"{ext}" for ext in self._all_music_ext]):
             if track.exists() and track.is_file() and track.parent != self.localtrack_folder:
                 tracks.append(Query.process_input(LocalPath(str(track.absolute()))))
         return sorted(tracks, key=lambda x: x.to_string_user().lower())
diff --git a/redbot/cogs/audio/utils.py b/redbot/cogs/audio/utils.py
--- a/redbot/cogs/audio/utils.py
+++ b/redbot/cogs/audio/utils.py
@@ -43,6 +43,7 @@
     "CacheLevel",
     "format_playlist_picker_data",
     "get_track_description_unformatted",
+    "track_remaining_duration",
     "Notifier",
     "PlaylistScope",
 ]
@@ -126,6 +127,20 @@ async def queue_duration(ctx) -> int:
     return queue_total_duration
 
 
+async def track_remaining_duration(ctx) -> int:
+    player = lavalink.get_player(ctx.guild.id)
+    if not player.current:
+        return 0
+    try:
+        if not player.current.is_stream:
+            remain = player.current.length - player.position
+        else:
+            remain = 0
+    except AttributeError:
+        remain = 0
+    return remain
+
+
 async def draw_time(ctx) -> str:
     player = lavalink.get_player(ctx.guild.id)
     paused = player.paused


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

Issue:
[Cleanup] `[p]cleanup messages 50`
```
Traceback (most recent call last):
  File "/home/bb8/redenv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 79, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/bb8/redenv/lib/python3.8/site-packages/redbot/cogs/cleanup/cleanup.py", line 379, in messages
    await mass_purge(to_delete, channel)
  File "/home/bb8/redenv/lib/python3.8/site-packages/redbot/core/utils/mod.py", line 45, in mass_purge
    await messages[0].delete()
  File "/home/bb8/redenv/lib/python3.8/site-packages/discord/message.py", line 700, in delete
    await self._state.http.delete_message(self.channel.id, self.id)
  File "/home/bb8/redenv/lib/python3.8/site-packages/discord/http.py", line 220, in request
    raise NotFound(r, data)
discord.errors.NotFound: 404 NOT FOUND (error code: 10008): Unknown Message

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/bb8/redenv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 863, in invoke
    await ctx.command.invoke(ctx)
  File "/home/bb8/redenv/lib/python3.8/site-packages/redbot/core/commands/commands.py", line 587, in invoke
    await super().invoke(ctx)
  File "/home/bb8/redenv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1158, in invoke
    await ctx.invoked_subcommand.invoke(ctx)
  File "/home/bb8/redenv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 728, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/bb8/redenv/lib/python3.8/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: NotFound: 404 NOT FOUND (error code: 10008): Unknown Message
```


Discussion:
I'm pretty sure this is being caused by `[p]modset deletedelay` interfering with cleanup attempting to delete the invoking message. However, it shouldn't reach the part of the code that it did (where there is only 1 message left in the list after removing groups of 100) unless that was the first message. I'm going to look into this.

Resolving patch:
diff --git a/redbot/core/utils/mod.py b/redbot/core/utils/mod.py
--- a/redbot/core/utils/mod.py
+++ b/redbot/core/utils/mod.py
@@ -38,12 +38,13 @@ async def mass_purge(messages: List[discord.Message], channel: discord.TextChann
 
     """
     while messages:
-        if len(messages) > 1:
+        # discord.NotFound can be raised when `len(messages) == 1` and the message does not exist.
+        # As a result of this obscure behavior, this error needs to be caught just in case.
+        try:
             await channel.delete_messages(messages[:100])
-            messages = messages[100:]
-        else:
-            await messages[0].delete()
-            messages = []
+        except discord.errors.HTTPException:
+            pass
+        messages = messages[100:]
         await asyncio.sleep(1.5)
 
 


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

Issue:
[Audio] [p]audioset dc turns on repeat toggle
# Command bugs

#### Command name

[p]audioset dc

#### What cog is this command from?

Audio

#### What were you expecting to happen?

For it to toggle the auto disconnect setting and nothing else.

#### What actually happened?

Using [p]audioset dc and toggling it on will toggle repeat to True

#### How can we reproduce this issue?

Have a bot with repeat off.
Use [p]audioset dc, toggling it on.
Use [p]audioset settings, repeat will now show that it is on.



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
@@ -705,7 +705,6 @@ async def dc(self, ctx: commands.Context):
         msg += _("Auto-disconnection at queue end: {true_or_false}.").format(
             true_or_false=_("Enabled") if not disconnect else _("Disabled")
         )
-        await self.config.guild(ctx.guild).repeat.set(not disconnect)
         if disconnect is not True and autoplay is True:
             msg += _("\nAuto-play has been disabled.")
             await self.config.guild(ctx.guild).auto_play.set(False)


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

Issue:
No username in modlog entries
# Command bugs


#### Command name

hackban, reason

#### What cog is this command from?

Mod, ModLog

#### What were you expecting to happen?

ModLog entry should show a nickname and/or username.

#### What actually happened?

For users that aren't in the server, the ModLog entry shows no information indicating what user the entry is for.

#### How can we reproduce this issue?

Moderate or update a ModLog entry for any user not in the server or not in the bot's cache.

![modlog](https://user-images.githubusercontent.com/10516759/73109603-9d844600-3ed1-11ea-9f2a-33985f4bde61.png)


Discussion:
This is intended behavior. If the user isn't cached in the bot it will be unknown user. It was done to reduce the amount of fetch calls done to discord server to avoid 403s. 
Intentional, Modlog fetching user info was causing *rate-limit* issues. Fetching user info is an extremely limited operation compared to many others.
Could it not keep at least the user ID or username that is already in the modlog entry, instead of wiping it?
![image](https://user-images.githubusercontent.com/22035876/73116601-033ef500-3f07-11ea-885a-c02f6dc01102.png)

This image uses the non-embedded form but the scenarios do not differ between the two here.

In the first one, the user was in the bot's cache, so we kept the name and ID.
In the second one, the user wasn't in the bot's cache. We don't have the name and don't fetch it, but we keep the ID.
In the third one, we had both the name and id, but we discard the name to avoid modlog being used by bots to advertise, keeping the ID.

In no circumstance do we not at least store the ID. We are guaranteed to always have this when the bot is performing a ban.


My mistake. Misunderstood a piece of what was said when reading this before. The embedded form is differing in an unintended way and this is the issue, not the name not being present itself.

Resolving patch:
diff --git a/redbot/core/modlog.py b/redbot/core/modlog.py
--- a/redbot/core/modlog.py
+++ b/redbot/core/modlog.py
@@ -324,9 +324,7 @@ async def message_content(self, embed: bool = True):
 
         if embed:
             emb = discord.Embed(title=title, description=reason)
-
-            if avatar_url is not None:
-                emb.set_author(name=user, icon_url=avatar_url)
+            emb.set_author(name=user)
             emb.add_field(name=_("Moderator"), value=moderator, inline=False)
             if until and duration:
                 emb.add_field(name=_("Until"), value=until)


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

Issue:
[Core] Add a cli flag for setting a max size of message cache
# Feature request

#### Describe your requested feature

I think it would be nice to have a cli flag for setting max size of message cache (`discord.Client.max_messages`) and maybe also disabling it.



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
@@ -149,6 +149,12 @@ async def prefix_manager(bot, message) -> List[str]:
         if "command_not_found" not in kwargs:
             kwargs["command_not_found"] = "Command {} not found.\n{}"
 
+        message_cache_size = cli_flags.message_cache_size
+        if cli_flags.no_message_cache:
+            message_cache_size = None
+        kwargs["max_messages"] = message_cache_size
+        self._max_messages = message_cache_size
+
         self._uptime = None
         self._checked_time_accuracy = None
         self._color = discord.Embed.Empty  # This is needed or color ends up 0x000000
@@ -271,6 +277,10 @@ def color(self) -> NoReturn:
     def colour(self) -> NoReturn:
         raise AttributeError("Please fetch the embed colour with `get_embed_colour`")
 
+    @property
+    def max_messages(self) -> Optional[int]:
+        return self._max_messages
+
     async def allowed_by_whitelist_blacklist(
         self,
         who: Optional[Union[discord.Member, discord.User]] = None,
diff --git a/redbot/core/cli.py b/redbot/core/cli.py
--- a/redbot/core/cli.py
+++ b/redbot/core/cli.py
@@ -74,6 +74,22 @@ async def interactive_config(red, token_set, prefix_set, *, print_header=True):
     return token
 
 
+def positive_int(arg: str) -> int:
+    try:
+        x = int(arg)
+    except ValueError:
+        raise argparse.ArgumentTypeError("Message cache size has to be a number.")
+    if x < 1000:
+        raise argparse.ArgumentTypeError(
+            "Message cache size has to be greater than or equal to 1000."
+        )
+    if x > sys.maxsize:
+        raise argparse.ArgumentTypeError(
+            f"Message cache size has to be lower than or equal to {sys.maxsize}."
+        )
+    return x
+
+
 def parse_cli_flags(args):
     parser = argparse.ArgumentParser(
         description="Red - Discord Bot", usage="redbot <instance_name> [arguments]"
@@ -212,6 +228,15 @@ def parse_cli_flags(args):
             "all of the data on the host machine."
         ),
     )
+    parser.add_argument(
+        "--message-cache-size",
+        type=positive_int,
+        default=1000,
+        help="Set the maximum number of messages to store in the internal message cache.",
+    )
+    parser.add_argument(
+        "--no-message-cache", action="store_true", help="Disable the internal message cache.",
+    )
 
     args = parser.parse_args(args)
 


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

Issue:
[Mod] Hackban stopped working.
#### Command name

Hackban

#### What cog is this command from?

Mod

#### What were you expecting to happen?

For it to work and ban someone that isn't on the server any longer.

#### What actually happened?

Nothing. it didn't work, and Red decided to throw an error in the Console instead.
This error: http://prntscr.com/quxb5i (screenshot link)

#### How can we reproduce this issue?

1. Find someone that isn't on the server to hackban.
2. Type [p]hackban UserID reason
3. Red will return an error.



Discussion:

Resolving patch:
diff --git a/redbot/cogs/mod/kickban.py b/redbot/cogs/mod/kickban.py
--- a/redbot/cogs/mod/kickban.py
+++ b/redbot/cogs/mod/kickban.py
@@ -308,6 +308,9 @@ def remove_processed(ids):
             await ctx.send_help()
             return
 
+        if days is None:
+            days = await self.settings.guild(guild).default_days()
+
         if not (0 <= days <= 7):
             await ctx.send(_("Invalid days. Must be between 0 and 7."))
             return
@@ -329,9 +332,6 @@ def remove_processed(ids):
             await show_results()
             return
 
-        if days is None:
-            days = await self.settings.guild(guild).default_days()
-
         for user_id in user_ids:
             user = guild.get_member(user_id)
             if user is not None:


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

Issue:
[Core] DMing the bot errors out
# Command bugs

#### Command name

[p]dm

#### What cog is this command from?

Core

#### What were you expecting to happen?

For an message informing me that the bot can't dm itself or something similar.

#### What actually happened?

```
Traceback (most recent call last):
  File "/.../lib/python3.8/site-packages/discord/ext/commands/core.py", line 83, in wrapped
    ret = await coro(*args, **kwargs)
  File "/.../lib/python3.8/site-packages/redbot/core/core_commands.py", line 1609, in dm
    await destination.send(embed=e)
  File "/.../lib/python3.8/site-packages/discord/abc.py", line 824, in send
    channel = await self._get_channel()
  File "/.../lib/python3.8/site-packages/discord/member.py", line 248, in _get_channel
    ch = await self.create_dm()
  File "/.../lib/python3.8/site-packages/discord/member.py", line 109, in general
    return getattr(self._user, x)(*args, **kwargs)
AttributeError: 'ClientUser' object has no attribute 'create_dm'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/.../lib/python3.8/site-packages/discord/ext/commands/bot.py", line 892, in invoke
    await ctx.command.invoke(ctx)
  File "/.../lib/python3.8/site-packages/discord/ext/commands/core.py", line 797, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/.../lib/python3.8/site-packages/discord/ext/commands/core.py", line 92, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'ClientUser' object has no attribute 'create_dm'
```

#### How can we reproduce this issue?

Use [p]dm and dm the bot's ID.



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
@@ -1581,12 +1581,12 @@ async def dm(self, ctx: commands.Context, user_id: int, *, message: str):
         settings, 'appearance' tab. Then right click a user
         and copy their id"""
         destination = discord.utils.get(ctx.bot.get_all_members(), id=user_id)
-        if destination is None:
+        if destination is None or destination.bot:
             await ctx.send(
                 _(
-                    "Invalid ID or user not found. You can only "
-                    "send messages to people I share a server "
-                    "with."
+                    "Invalid ID, user not found, or user is a bot. "
+                    "You can only send messages to people I share "
+                    "a server with."
                 )
             )
             return


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

Issue:
Permissions licenseinfo prompt
The problem is first command leaves no indication that this was disallowed.
![Discord_sfrRBRPY0T](https://user-images.githubusercontent.com/1307729/73268686-b5164400-41db-11ea-87d2-9129ec93e43f.png)



Discussion:
Same happens with setdefaultglobalrule. 

Resolving patch:
diff --git a/redbot/cogs/permissions/permissions.py b/redbot/cogs/permissions/permissions.py
--- a/redbot/cogs/permissions/permissions.py
+++ b/redbot/cogs/permissions/permissions.py
@@ -427,6 +427,14 @@ async def permissions_setdefaultguildrule(
         `<cog_or_command>` is the cog or command to set the default
         rule for. This is case sensitive.
         """
+        if isinstance(cog_or_command.obj, commands.commands._AlwaysAvailableCommand):
+            await ctx.send(
+                _(
+                    "This command is designated as being always available and "
+                    "cannot be modified by permission rules."
+                )
+            )
+            return
         await self._set_default_rule(
             rule=cast(Optional[bool], allow_or_deny),
             cog_or_cmd=cog_or_command,
@@ -450,6 +458,14 @@ async def permissions_setdefaultglobalrule(
         `<cog_or_command>` is the cog or command to set the default
         rule for. This is case sensitive.
         """
+        if isinstance(cog_or_command.obj, commands.commands._AlwaysAvailableCommand):
+            await ctx.send(
+                _(
+                    "This command is designated as being always available and "
+                    "cannot be modified by permission rules."
+                )
+            )
+            return
         await self._set_default_rule(
             rule=cast(Optional[bool], allow_or_deny), cog_or_cmd=cog_or_command, guild_id=GLOBAL
         )


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

Issue:
[p]unban fails when using a mention
# Command bugs

#### Command name

[p]unban

#### What cog is this command from?

Mod

#### What were you expecting to happen?

After banning a user, I expected to be able to unban them with a mention, e.g. `.unban @user#1234`

#### What actually happened?

It produces `Converting to "int" failed for parameter "user_id".`

#### How can we reproduce this issue?

Ban a user, then try to use the "unban" command to unban them while using a mention (instead of their user ID, which works fine).

The mentions already do contain the user ID, in the form of something like `<@123456789>`, so I assume the bug is related to the special characters at either end not being properly stripped out before it's converted to an integer.



Discussion:
This is intentional, the user is banned you won’t be able to mention him after he is no longer in the cache, if you look at the unban command you should see that you are supposed to use a user id and it doesn’t accept other arguments

Resolving patch:
diff --git a/redbot/cogs/mod/converters.py b/redbot/cogs/mod/converters.py
--- a/redbot/cogs/mod/converters.py
+++ b/redbot/cogs/mod/converters.py
@@ -1,16 +1,20 @@
+import re
 from redbot.core.commands import Converter, BadArgument
 from redbot.core.i18n import Translator
 
 _ = Translator("Mod", __file__)
 
+_id_regex = re.compile(r"([0-9]{15,21})$")
+_mention_regex = re.compile(r"<@!?([0-9]{15,21})>$")
+
 
 class RawUserIds(Converter):
     async def convert(self, ctx, argument):
-        # This is for the hackban command, where we receive IDs that
+        # This is for the hackban and unban commands, where we receive IDs that
         # are most likely not in the guild.
-        # As long as it's numeric and long enough, it makes a good candidate
-        # to attempt a ban on
-        if argument.isnumeric() and len(argument) >= 17:
-            return int(argument)
+        # Mentions are supported, but most likely won't ever be in cache.
+
+        if match := _id_regex.match(argument) or _mention_regex.match(argument):
+            return int(match.group(1))
 
         raise BadArgument(_("{} doesn't look like a valid user ID.").format(argument))
diff --git a/redbot/cogs/mod/kickban.py b/redbot/cogs/mod/kickban.py
--- a/redbot/cogs/mod/kickban.py
+++ b/redbot/cogs/mod/kickban.py
@@ -581,7 +581,7 @@ async def voicekick(
     @commands.guild_only()
     @commands.bot_has_permissions(ban_members=True)
     @checks.admin_or_permissions(ban_members=True)
-    async def unban(self, ctx: commands.Context, user_id: int, *, reason: str = None):
+    async def unban(self, ctx: commands.Context, user_id: RawUserIds, *, reason: str = None):
         """Unban a user from this server.
 
         Requires specifying the target user's ID. To find this, you may either:


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

Issue:
Mod cog won't load on bot startup because of discord api call
# Other bugs

#### What were you trying to do?

Start bot with mod cog loaded

#### What were you expecting to happen?

Bot to start with mod cog loaded

#### What actually happened?

Bot timed out trying to load mod cog

#### How can we reproduce this issue?

1. Install Red 3.3.1
2. Create a new instance.
3. Start the new instance
4. Load mod cog
5. Shutdown the bot
6. Update to V3/develop
7. Start the bot

Fixing this should only involve, creating a task instead for the coro `self.bot.send_to_owners(msg)` instead of awaiting it.




Discussion:

Resolving patch:
diff --git a/redbot/cogs/mod/__init__.py b/redbot/cogs/mod/__init__.py
--- a/redbot/cogs/mod/__init__.py
+++ b/redbot/cogs/mod/__init__.py
@@ -4,5 +4,5 @@
 
 async def setup(bot: Red):
     cog = Mod(bot)
-    await cog.initialize()
     bot.add_cog(cog)
+    await cog.initialize()
diff --git a/redbot/cogs/mod/mod.py b/redbot/cogs/mod/mod.py
--- a/redbot/cogs/mod/mod.py
+++ b/redbot/cogs/mod/mod.py
@@ -1,6 +1,7 @@
+import asyncio
+from abc import ABC
 from collections import defaultdict
 from typing import List, Tuple
-from abc import ABC
 
 import discord
 from redbot.core import Config, modlog, commands
@@ -77,8 +78,14 @@ def __init__(self, bot: Red):
         self.tban_expiry_task = self.bot.loop.create_task(self.check_tempban_expirations())
         self.last_case: dict = defaultdict(dict)
 
+        self._ready = asyncio.Event()
+
     async def initialize(self):
         await self._maybe_update_config()
+        self._ready.set()
+
+    async def cog_before_invoke(self, ctx: commands.Context) -> None:
+        await self._ready.wait()
 
     def cog_unload(self):
         self.tban_expiry_task.cancel()
@@ -102,7 +109,7 @@ async def _maybe_update_config(self):
                 "Please use `{prefix}moveignoredchannels` if "
                 "you were previously using these functions."
             ).format(prefix=prefixes[0])
-            await self.bot.send_to_owners(msg)
+            self.bot.loop.create_task(self.bot.send_to_owners(msg))
             await self.settings.version.set(__version__)
 
     @commands.command()


Test patch: