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

Issue:
[V3 Downloader] cog list lists too much
# Command bugs

<!-- 
Did you find a bug with a command? Fill out the following:
-->

#### Command name

`cog list`

#### What cog is this command from?

Downloader 

#### What were you expecting to happen?

List available cogs from provided Repo

#### What actually happened?

Lists many duplicates, more for larger cogs
![image](https://user-images.githubusercontent.com/955640/39630434-4c795c04-4f7d-11e8-9d1d-566e39a6ca91.png)

#### How can we reproduce this issue?

`[p]repo add Fox-V3 https://github.com/bobloy/Fox-V3`
`[p]cog list Fox-V3` 



Discussion:
Can confirm (Two pingtimes and three eventmakers):

![capture](https://user-images.githubusercontent.com/841141/39633405-e5b4948a-4f85-11e8-9970-d17578b33683.PNG)

Seems to show an entry for each `.py` in a cog. But only seems to happen to installed cogs in a repo. (same issue here)
I can't reproduce, someone's gonna have to sit in chat with me and help me debug this. Ping me on discord when any of you are available.

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
@@ -155,7 +155,8 @@ def _update_available_modules(self) -> Tuple[str]:
         for file_finder, name, is_pkg in pkgutil.walk_packages(
             path=[str(self.folder_path)], onerror=lambda name: None
         ):
-            curr_modules.append(Installable(location=self.folder_path / name))
+            if is_pkg:
+                curr_modules.append(Installable(location=self.folder_path / name))
         self.available_modules = curr_modules
 
         # noinspection PyTypeChecker


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

Issue:
[V3 Mongo] Error when removing instance
### Type:

- [ ] Suggestion
- [x] Bug

When removing an instance with the launcher, this error occurs
```Py
pi@raspberrypi:~ $ export PATH=.local/bin/
pi@raspberrypi:~ $ redbot-launcher
==========================
Red Discord Bot - Launcher
==========================

1. Run Red w/ autorestart in case of issues
2. Run Red
3. Update Red
4. Update Red (development version)
5. Create Instance
6. Remove Instance
7. Debug information (use this if having issues with the launcher or bot)
0. Exit
> 6
You have chosen to remove an instance. The following is a list of instances that currently exist:

Oxibot

Red

Please select one of the above by entering its name
> Red
Would you like to make a backup of the data for this instance? (y/n)n
Removing the instance...
Traceback (most recent call last):
  File ".local/bin/redbot-launcher", line 11, in <module>
    sys.exit(main())
  File "/home/pi/.local/lib/python3.6/site-packages/redbot/launcher.py", line 358, in main
    main_menu()
  File "/home/pi/.local/lib/python3.6/site-packages/redbot/launcher.py", line 323, in main_menu
    asyncio.get_event_loop().run_until_complete(remove_instance())
  File "/usr/local/lib/python3.6/asyncio/base_events.py", line 468, in run_until_complete
    return future.result()
  File "/home/pi/.local/lib/python3.6/site-packages/redbot/setup.py", line 379, in remove_instance
    m = Mongo("Core", **instance_data["STORAGE_DETAILS"])
NameError: name 'Mongo' is not defined
```


Discussion:

Resolving patch:
diff --git a/redbot/setup.py b/redbot/setup.py
--- a/redbot/setup.py
+++ b/redbot/setup.py
@@ -4,7 +4,6 @@
 import asyncio
 import json
 import os
-import shutil
 import sys
 import tarfile
 from copy import deepcopy
@@ -319,8 +318,9 @@ async def create_backup(selected, instance_data):
 
 
 async def remove_instance(selected, instance_data):
-    instance_list = load_existing_config()
     if instance_data["STORAGE_TYPE"] == "MongoDB":
+        from redbot.core.drivers.red_mongo import Mongo
+
         m = Mongo("Core", **instance_data["STORAGE_DETAILS"])
         db = m.db
         collections = await db.collection_names(include_system_collections=False)


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

Issue:
[V3] Error thrown in [p]now if reacting with something other than what bot is looking for.
# Command bugs

<!-- 
Did you find a bug with a command? Fill out the following:
-->

#### Command name

[p]now

#### What cog is this command from?

audio

#### What were you expecting to happen?

nothing

#### What actually happened?

Error thrown.

`Exception in command 'now'
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/discord/ext/commands/core.py", line 62, in wrapped
    ret = yield from coro(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/redbot/cogs/audio/audio.py", line 379, in now
    react = reacts[r.emoji]
KeyError: PartialEmoji(animated=False, name='ahegao', id=400894350340390913)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/discord/ext/commands/bot.py", line 886, in invoke
    yield from ctx.command.invoke(ctx)
  File "/usr/local/lib/python3.6/dist-packages/discord/ext/commands/core.py", line 514, in invoke
    yield from injected(*ctx.args, **ctx.kwargs)
  File "/usr/local/lib/python3.6/dist-packages/discord/ext/commands/core.py", line 71, in wrapped
    raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: PartialEmoji(animated=False, name='ahegao', id=400894350340390913)`

#### How can we reproduce this issue?

1. Call command [p]now
2. React with emoji that it does not look for


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
@@ -425,7 +425,11 @@ async def now(self, ctx):
                 await message.add_reaction(expected[i])
 
         def check(r, u):
-            return r.message.id == message.id and u == ctx.message.author
+            return (
+                r.message.id == message.id
+                and u == ctx.message.author
+                and any(e in str(r.emoji) for e in expected)
+            )
 
         try:
             (r, u) = await self.bot.wait_for("reaction_add", check=check, timeout=10.0)


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

Issue:
[V3 Audio] Error on skip
# Other bugs

<!-- 
Did you find a bug with something other than a command? Fill out the following:
-->

#### What were you trying to do?

Skip a song using the command

#### What were you expecting to happen?

Make the bot skip the song

#### What actually happened?


```Py
Exception in command 'skip'
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/discord/ext/commands/core.py", line 62, in wrapped
    ret = yield from coro(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/redbot/cogs/audio/audio.py", line 1428, in skip
    return await self._skip_action(ctx)
  File "/usr/local/lib/python3.6/dist-packages/redbot/cogs/audio/audio.py", line 1492, in _skip_action
    pos, dur = player.position, player.current.length
AttributeError: 'NoneType' object has no attribute 'length'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/discord/ext/commands/bot.py", line 886, in invoke
    yield from ctx.command.invoke(ctx)
  File "/usr/local/lib/python3.6/dist-packages/discord/ext/commands/core.py", line 514, in invoke
    yield from injected(*ctx.args, **ctx.kwargs)
  File "/usr/local/lib/python3.6/dist-packages/discord/ext/commands/core.py", line 71, in wrapped
    raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'length'
```

#### How can we reproduce this issue?

Get a queue with less than one song, then skip



Discussion:
Was a song playing?
This is when a user with elevated audio privileges queues a song, the song/queue runs out, the person leaves the channel, and then uses [p]skip.

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
@@ -1488,11 +1488,13 @@ async def _has_dj_role(self, ctx, member):
         else:
             return False
 
-    @staticmethod
-    async def _skip_action(ctx):
+    async def _skip_action(self, ctx):
         player = lavalink.get_player(ctx.guild.id)
         if not player.queue:
-            pos, dur = player.position, player.current.length
+            try:
+                pos, dur = player.position, player.current.length
+            except AttributeError:
+                return await self._embed_msg(ctx, "There's nothing in the queue.")
             time_remain = lavalink.utils.format_time(dur - pos)
             if player.current.is_stream:
                 embed = discord.Embed(


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

Issue:
[V3] More stuff with the token and resetting.
Bot has no prompt for inserting a new token after a successful token reset from `python -m redbot instancename`, and launching again afterwards leads to the bot not asking for a new token. running `redbot-setup` again does not completely work either as there is no option for just a settings update here.


Discussion:

Resolving patch:
diff --git a/redbot/__main__.py b/redbot/__main__.py
--- a/redbot/__main__.py
+++ b/redbot/__main__.py
@@ -124,7 +124,7 @@ def main():
     loop.run_until_complete(_get_prefix_and_token(red, tmp_data))
     token = os.environ.get("RED_TOKEN", tmp_data["token"])
     prefix = cli_flags.prefix or tmp_data["prefix"]
-    if token is None or not prefix:
+    if not (token and prefix):
         if cli_flags.no_prompt is False:
             new_token = interactive_config(red, token_set=bool(token), prefix_set=bool(prefix))
             if new_token:


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

Issue:
[V3 Backup] Error when backing up repos
```
Exception in command 'backup'
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/discord/ext/commands/core.py", line 62, in wrapped
    ret = yield from coro(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/redbot/core/core_commands.py", line 1091, in backup
    for n, repo in repo_mgr._repos:
ValueError: too many values to unpack (expected 2)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/discord/ext/commands/bot.py", line 886, in invoke
    yield from ctx.command.invoke(ctx)
  File "/usr/local/lib/python3.6/dist-packages/discord/ext/commands/core.py", line 514, in invoke
    yield from injected(*ctx.args, **ctx.kwargs)
  File "/usr/local/lib/python3.6/dist-packages/discord/ext/commands/core.py", line 71, in wrapped
    raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: too many values to unpack (expected 2)
```


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
@@ -1113,10 +1113,8 @@ async def backup(self, ctx, backup_path: str = None):
             if downloader_cog and hasattr(downloader_cog, "_repo_manager"):
                 repo_output = []
                 repo_mgr = downloader_cog._repo_manager
-                for n, repo in repo_mgr._repos:
-                    repo_output.append(
-                        {{"url": repo.url, "name": repo.name, "branch": repo.branch}}
-                    )
+                for repo in repo_mgr._repos.values():
+                    repo_output.append({"url": repo.url, "name": repo.name, "branch": repo.branch})
                 repo_filename = data_dir / "cogs" / "RepoManager" / "repos.json"
                 with open(str(repo_filename), "w") as f:
                     f.write(json.dumps(repo_output, indent=4))


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

Issue:
[V3 Help] Displaying the bot's mention as a prefix
@Kowlin has given a good example of how this is currently displayed here:
![screenshot](https://media.discordapp.net/attachments/251782448629809152/453437266119884811/unknown.png?width=432&height=465)

Obviously this is ugly and undesired - I think in this circumstance the help formatter should detect that the prefix was a mention, and replace it with `@BotName` instead.


Discussion:

Resolving patch:
diff --git a/redbot/core/help_formatter.py b/redbot/core/help_formatter.py
--- a/redbot/core/help_formatter.py
+++ b/redbot/core/help_formatter.py
@@ -40,7 +40,7 @@
 from redbot.core.utils import fuzzy_command_search
 
 
-EMPTY_STRING = u"\u200b"
+EMPTY_STRING = "\u200b"
 
 _mentions_transforms = {"@everyone": "@\u200beveryone", "@here": "@\u200bhere"}
 
@@ -60,6 +60,12 @@ def __init__(self, *args, **kwargs):
     def pm_check(self, ctx):
         return isinstance(ctx.channel, discord.DMChannel)
 
+    @property
+    def clean_prefix(self):
+        maybe_member = self.context.guild.me if self.context.guild else self.context.bot.user
+        pretty = f"@{maybe_member.display_name}"
+        return self.context.prefix.replace(maybe_member.mention, pretty)
+
     @property
     def me(self):
         return self.context.me


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

Issue:
[Economy] Using [p]leaderboard in DM causes an error
# Command bugs

#### Command name

(prefix)leaderboard

#### What cog is this command from?

Economy

#### What were you expecting to happen?

Display the global leaderboard, or display a message stating that the command isn't available in DMs.

#### What actually happened?

https://drive.google.com/file/d/1-9V_y2KJ9oCJQLUpmvY6kvd1LBG5b39Q/view?usp=drivesdk

#### How can we reproduce this issue?

I found out that I did it in a DM and not in a server. I got it working on my server, however, should
say something like: "That command is not available in DMs." and she did not say that.


Discussion:
It looks like the link to your screenshot is broken. Can you update your issue with a new link?
Fixed, someone needs to stop changing the link.
I'm unable to reproduce that error as I'm getting the intended behavior when doing the command in a DM (i.e. getting the leaderboard if the bank is global, or a message stating that I can't run the command if it's not)
That is weird.
Can you screenshot the output of `[p]info`? I suspect you might be on an older version after rereading the traceback in the screenshot you provided
Actually, another reread leads me to believe you're on V2, not V3
How? I keep shoving the update command.
you can't update from V2 to V3 the way you would update V2 itself because V3 is a massive breaking change compared to V2. Cogs written for V2 won't work on V3 without being rewritten to work with V3.

If you're interested in getting started with V3, see https://red-discordbot.readthedocs.io/en/v3-develop/ (note that you will probably want to use a virtualenv if you want to try V3 while also continuing to use V2 because they use different versions of discord.py).

All that being said, you definitely did find a bug in V2's economy cog, so I will leave this open
I shoud upgrade to the latest version if you guys stop support v2. I don't have money to get a VPS. Yes this is a bug in version 2, and you can keep it open if you want.
Oh, I didn't mean a VPS, I meant something like https://virtualenv.pypa.io/en/stable/ or https://docs.python.org/3/library/venv.html
Oh, or vitural box.

Resolving patch:
diff --git a/cogs/economy.py b/cogs/economy.py
--- a/cogs/economy.py
+++ b/cogs/economy.py
@@ -454,11 +454,14 @@ async def payday(self, ctx):  # TODO
     async def leaderboard(self, ctx):
         """Server / global leaderboard
 
-        Defaults to server"""
+        Defaults to \"server\" if not issued in DM"""
         if ctx.invoked_subcommand is None:
-            await ctx.invoke(self._server_leaderboard)
+            if ctx.message.server:
+                await ctx.invoke(self._server_leaderboard)
+            else:
+                await ctx.invoke(self._global_leaderboard)
 
-    @leaderboard.command(name="server", pass_context=True)
+    @leaderboard.command(name="server", pass_context=True, no_pm=True)
     async def _server_leaderboard(self, ctx, top: int=10):
         """Prints out the server's leaderboard
 


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

Issue:
[V3 Config] Detect changes on backend, and only write when there are changes.
- [ ] Cog
- [ ] Command
- [X] API functionality

Right now, config will always write when using a context manager, there's no need for this since we should be returning a copy of the data, not the original (see #1855 ). While this can be avoided in some cases by a design choice, there may also be cases where the code doesn't know if something needs to change in the mutable data until checking it. We should instead modify Config's handling of this to be more IO aware, and not make unneeded writes.



Discussion:

Resolving patch:
diff --git a/redbot/core/config.py b/redbot/core/config.py
--- a/redbot/core/config.py
+++ b/redbot/core/config.py
@@ -29,12 +29,15 @@ class _ValueCtxManager:
     def __init__(self, value_obj, coro):
         self.value_obj = value_obj
         self.coro = coro
+        self.raw_value = None
+        self.__original_value = None
 
     def __await__(self):
         return self.coro.__await__()
 
     async def __aenter__(self):
         self.raw_value = await self
+        self.__original_value = deepcopy(self.raw_value)
         if not isinstance(self.raw_value, (list, dict)):
             raise TypeError(
                 "Type of retrieved value must be mutable (i.e. "
@@ -44,7 +47,8 @@ async def __aenter__(self):
         return self.raw_value
 
     async def __aexit__(self, *exc_info):
-        await self.value_obj.set(self.raw_value)
+        if self.raw_value != self.__original_value:
+            await self.value_obj.set(self.raw_value)
 
 
 class Value:


Test patch:
diff --git a/tests/core/test_config.py b/tests/core/test_config.py
--- a/tests/core/test_config.py
+++ b/tests/core/test_config.py
@@ -1,3 +1,4 @@
+from unittest.mock import patch
 import pytest
 
 
@@ -399,6 +400,16 @@ async def test_ctxmgr_no_shared_default(config, member_factory):
     assert 1 not in await config.member(m2).foo()
 
 
+@pytest.mark.asyncio
+async def test_ctxmgr_no_unnecessary_write(config):
+    config.register_global(foo=[])
+    foo_value_obj = config.foo
+    with patch.object(foo_value_obj, "set") as set_method:
+        async with foo_value_obj() as foo:
+            pass
+        set_method.assert_not_called()
+
+
 @pytest.mark.asyncio
 async def test_get_then_mutate(config):
     """Tests that mutating an object after getting it as a value doesn't mutate the data store."""
Repository: Cog-Creators/Red-DiscordBot

Issue:
[V2] Audio voice
# Other bugs

<!-- 
Did you find a bug with something other than a command? Fill out the following:
-->

#### What were you trying to do?

Trying to play music while bot is idle in a voice channel will eror out if that voice channel is full with the bot in the channel. 

#### What were you expecting to happen?

For the bot to keep playing.

#### What actually happened?

Bot errors out with "Your voice channel is full."

#### How can we reproduce this issue?
1. Create a voice channel with 2 slots.
2. Join voice channel and [p]play rickroll
3. After bot has joined and song has finished or you can do [p]stop try to
4. Try to play again while it is you and bot in the VC and channel is 2/2
5. Error



Discussion:
Not going to fix on V2 due to featurelock.
Feature lock doesn't mean no bug fixes.

Resolving patch:
diff --git a/cogs/audio.py b/cogs/audio.py
--- a/cogs/audio.py
+++ b/cogs/audio.py
@@ -2239,6 +2239,7 @@ def has_connect_perm(self, author, server):
         channel = author.voice_channel
 
         if channel:
+            in_channel = bool(server.me in channel.voice_members)
             is_admin = channel.permissions_for(server.me).administrator
             if channel.user_limit == 0:
                 is_full = False
@@ -2247,11 +2248,11 @@ def has_connect_perm(self, author, server):
 
         if channel is None:
             raise AuthorNotConnected
-        elif channel.permissions_for(server.me).connect is False:
+        elif channel.permissions_for(server.me).connect is False and not in_channel:
             raise UnauthorizedConnect
         elif channel.permissions_for(server.me).speak is False:
             raise UnauthorizedSpeak
-        elif is_full and not is_admin:
+        elif is_full and not is_admin and not in_channel:
             raise ChannelUserLimit
         else:
             return True


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

Issue:
[v2 Downloader] requirements with dotted package names crash the library check
#### Command name

`cog install calebj captcha`

#### What cog is this command from?

Downloader

#### What were you expecting to happen?

Downloader should have pulled in the dependencies like normal using pip before installing the cog.

#### What actually happened?

Best guess is that since `wheezy.captcha` is a namespace package with a dot in the PyPI name, it's confusing the check. The `wheezy` module will import successfully when any subpackages are installed, but there is no package named just `wheezy` on PyPI. This doesn't happen when the package is already installed.

```
Exception in command 'cog install'
Traceback (most recent call last):
  File "/data/red/.local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 50, in wrapped
    ret = yield from coro(*args, **kwargs)
  File "/data/red/cogs/downloader.py", line 397, in _install
    install_cog = await self.install(repo_name, cog, notify_reqs=True)
  File "/data/red/cogs/downloader.py", line 447, in install
    requirements = [r for r in requirements
  File "/data/red/cogs/downloader.py", line 448, in <listcomp>
    if not self.is_lib_installed(r)]
  File "/data/red/cogs/downloader.py", line 530, in is_lib_installed
    return bool(find_spec(name))
  File "/usr/lib/python3.5/importlib/util.py", line 88, in find_spec
    parent = __import__(parent_name, fromlist=['__path__'])
ImportError: No module named 'wheezy'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/data/red/.local/lib/python3.5/site-packages/discord/ext/commands/bot.py", line 846, in process_commands
    yield from command.invoke(ctx)
  File "/data/red/.local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 634, in invoke
    yield from ctx.invoked_subcommand.invoke(ctx)
  File "/data/red/.local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 374, in invoke
    yield from injected(*ctx.args, **ctx.kwargs)
  File "/data/red/.local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 54, in wrapped
    raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ImportError: No module named 'wheezy'
```

#### How can we reproduce this issue?

1. Attempt to install Captcha from my [cog repo's develop branch](https://github.com/calebj/calebj-cogs/tree/develop/)
2. Cry. Cry a lot.



Discussion:

Resolving patch:
diff --git a/cogs/downloader.py b/cogs/downloader.py
--- a/cogs/downloader.py
+++ b/cogs/downloader.py
@@ -527,7 +527,10 @@ def get_dir_name(self, url):
         return git_name[:-4]
 
     def is_lib_installed(self, name):
-        return bool(find_spec(name))
+        try:
+            return bool(find_spec(name))
+        except ImportError:
+            return False
 
     def _do_first_run(self):
         save = False


Test patch: