internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: python-discord/bot

Issue:
Duck pond may fail to fetch reaction message due to a missing channel
Sentry Issue: [BOT-8T](https://sentry.io/organizations/python-discord/issues/1892623782/?referrer=github_integration)

Possibly a cache issue. I believe that a channel object isn't really needed. There's likely a direct way to get the message via a method in `bot.http`. After all, the actual endpoint only needs a channel ID and a message ID.

```
AttributeError: 'NoneType' object has no attribute 'fetch_message'
  File "discord/client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "bot/cogs/duck_pond.py", line 158, in on_raw_reaction_remove
    message = await channel.fetch_message(payload.message_id)

Unhandled exception in on_raw_reaction_remove.
```


Discussion:

Resolving patch:
diff --git a/bot/exts/fun/duck_pond.py b/bot/exts/fun/duck_pond.py
--- a/bot/exts/fun/duck_pond.py
+++ b/bot/exts/fun/duck_pond.py
@@ -145,6 +145,10 @@ async def on_raw_reaction_add(self, payload: RawReactionActionEvent) -> None:
         amount of ducks specified in the config under duck_pond/threshold, it will
         send the message off to the duck pond.
         """
+        # Ignore other guilds and DMs.
+        if payload.guild_id != constants.Guild.id:
+            return
+
         # Was this reaction issued in a blacklisted channel?
         if payload.channel_id in constants.DuckPond.channel_blacklist:
             return
@@ -154,6 +158,9 @@ async def on_raw_reaction_add(self, payload: RawReactionActionEvent) -> None:
             return
 
         channel = discord.utils.get(self.bot.get_all_channels(), id=payload.channel_id)
+        if channel is None:
+            return
+
         message = await channel.fetch_message(payload.message_id)
         member = discord.utils.get(message.guild.members, id=payload.user_id)
 
@@ -175,7 +182,13 @@ async def on_raw_reaction_add(self, payload: RawReactionActionEvent) -> None:
     @Cog.listener()
     async def on_raw_reaction_remove(self, payload: RawReactionActionEvent) -> None:
         """Ensure that people don't remove the green checkmark from duck ponded messages."""
+        # Ignore other guilds and DMs.
+        if payload.guild_id != constants.Guild.id:
+            return
+
         channel = discord.utils.get(self.bot.get_all_channels(), id=payload.channel_id)
+        if channel is None:
+            return
 
         # Prevent the green checkmark from being removed
         if payload.emoji.name == "✅":


Test patch:
Repository: python-discord/bot

Issue:
Add fuzzy matching to the role(s) command. 
Right now, if you want to use the role name for the `!role(s)` commands, you have to type the *exact* role name, which can be quite frustrating sometimes. 

It would be nice to support fuzzy matching, like we do here with the `Tags` cog.

https://github.com/python-discord/bot/blob/9e95fb0a34733d6ce9d9619e892a860a54567606/bot/exts/info/tags.py#L69-L83


Discussion:
make a pull request

Resolving patch:
diff --git a/bot/exts/info/information.py b/bot/exts/info/information.py
--- a/bot/exts/info/information.py
+++ b/bot/exts/info/information.py
@@ -6,7 +6,8 @@
 from string import Template
 from typing import Any, Mapping, Optional, Tuple, Union
 
-from discord import ChannelType, Colour, Embed, Guild, Message, Role, Status, utils
+import fuzzywuzzy
+from discord import ChannelType, Colour, Embed, Guild, Message, Role, Status
 from discord.abc import GuildChannel
 from discord.ext.commands import BucketType, Cog, Context, Paginator, command, group, has_any_role
 
@@ -106,22 +107,28 @@ async def role_info(self, ctx: Context, *roles: Union[Role, str]) -> None:
 
         To specify multiple roles just add to the arguments, delimit roles with spaces in them using quotation marks.
         """
-        parsed_roles = []
-        failed_roles = []
+        parsed_roles = set()
+        failed_roles = set()
 
+        all_roles = {role.id: role.name for role in ctx.guild.roles}
         for role_name in roles:
             if isinstance(role_name, Role):
                 # Role conversion has already succeeded
-                parsed_roles.append(role_name)
+                parsed_roles.add(role_name)
                 continue
 
-            role = utils.find(lambda r: r.name.lower() == role_name.lower(), ctx.guild.roles)
+            match = fuzzywuzzy.process.extractOne(
+                role_name, all_roles, score_cutoff=80,
+                scorer=fuzzywuzzy.fuzz.ratio
+            )
 
-            if not role:
-                failed_roles.append(role_name)
+            if not match:
+                failed_roles.add(role_name)
                 continue
 
-            parsed_roles.append(role)
+            # `match` is a (role name, score, role id) tuple
+            role = ctx.guild.get_role(match[2])
+            parsed_roles.add(role)
 
         if failed_roles:
             await ctx.send(f":x: Could not retrieve the following roles: {', '.join(failed_roles)}")


Test patch:
diff --git a/tests/bot/exts/info/test_information.py b/tests/bot/exts/info/test_information.py
--- a/tests/bot/exts/info/test_information.py
+++ b/tests/bot/exts/info/test_information.py
@@ -65,7 +65,7 @@ async def test_role_info_command(self):
             permissions=discord.Permissions(0),
         )
 
-        self.ctx.guild.roles.append([dummy_role, admin_role])
+        self.ctx.guild.roles.extend([dummy_role, admin_role])
 
         self.cog.role_info.can_run = unittest.mock.AsyncMock()
         self.cog.role_info.can_run.return_value = True
Repository: python-discord/bot

Issue:
Bug: ` chars are not escaped when parsing !source
![Screenshot](https://arse.ee/zi7A9lec.png)

When responding to faulty `!source` commands, the backticks aren't escaped and a formatting issue occurs.

This _might_ lead to being able to ping roles/users, should Discord ever decide to change the embed ping behavior.


Discussion:
You can't ping people or roles in embeds 
I am aware of this. Not particularly relevant regardless.
It's safe regardless because of the "allowed mentions" feature. We have to explicitly allow mentioning a certain role when sending a message. The only ones whitelisted by default are mod+ roles (which users can mention normally anyway).

In any case, markdown should be escaped just for the sake of readability.
I can work on this, can I get assigned?


Resolving patch:
diff --git a/bot/exts/info/source.py b/bot/exts/info/source.py
--- a/bot/exts/info/source.py
+++ b/bot/exts/info/source.py
@@ -2,7 +2,7 @@
 from pathlib import Path
 from typing import Optional, Tuple, Union
 
-from discord import Embed
+from discord import Embed, utils
 from discord.ext import commands
 
 from bot.bot import Bot
@@ -35,8 +35,10 @@ async def convert(self, ctx: commands.Context, argument: str) -> SourceType:
         elif argument.lower() in tags_cog._cache:
             return argument.lower()
 
+        escaped_arg = utils.escape_markdown(argument)
+
         raise commands.BadArgument(
-            f"Unable to convert `{argument}` to valid command{', tag,' if show_tag else ''} or Cog."
+            f"Unable to convert '{escaped_arg}' to valid command{', tag,' if show_tag else ''} or Cog."
         )
 
 


Test patch:
Repository: python-discord/bot

Issue:
feature suggestion: add url in title instead of description in !pep command
currently the link when you use the !pep command is located in the description, but with the discord.Embed.url parameter, the title is now able to become a link (as shown in second image)

![image](https://user-images.githubusercontent.com/50557523/94292440-34e6e080-ff1a-11ea-8986-4e025379fd73.png)
![image](https://user-images.githubusercontent.com/50557523/94292605-695a9c80-ff1a-11ea-99ef-fc02f83e9d61.png)



Discussion:
That sounds good to me. Can't think of a reason for not doing it.
I can work on this. can I get assigned?
Go for it!
> I can work on this. can I get assigned?

this should be pretty easy, just replace this line:
description=f"[Link]({self.base_pep_url}{pep_number:04})",
with this line:
url=f"{self.base_pep_url}{pep_number:04}"

Resolving patch:
diff --git a/bot/exts/utils/utils.py b/bot/exts/utils/utils.py
--- a/bot/exts/utils/utils.py
+++ b/bot/exts/utils/utils.py
@@ -84,7 +84,7 @@ async def pep_command(self, ctx: Context, pep_number: str) -> None:
                 # Assemble the embed
                 pep_embed = Embed(
                     title=f"**PEP {pep_number} - {pep_header['Title']}**",
-                    description=f"[Link]({self.base_pep_url}{pep_number:04})",
+                    url=f"{self.base_pep_url}{pep_number:04}"
                 )
 
                 pep_embed.set_thumbnail(url=ICON_URL)
@@ -250,7 +250,7 @@ async def send_pep_zero(self, ctx: Context) -> None:
         """Send information about PEP 0."""
         pep_embed = Embed(
             title="**PEP 0 - Index of Python Enhancement Proposals (PEPs)**",
-            description="[Link](https://www.python.org/dev/peps/)"
+            url="https://www.python.org/dev/peps/"
         )
         pep_embed.set_thumbnail(url=ICON_URL)
         pep_embed.add_field(name="Status", value="Active")


Test patch:
Repository: python-discord/bot

Issue:
Add Missing Voice Channels To Config
The default config (and constants file) is missing the following channels:
- Code/Help 1 (voice)
- Code/Help 2 (voice)
- General/Offtopic (voice)
- code-help-voice-1 (text)
- code-help-voice-2 (text)
- staff-voice (text)
- admin-voice (text)

A lot of these channels either have the voice portion or the text portion, but not both. I've prepared a PR to address this.


Discussion:

Resolving patch:
diff --git a/bot/constants.py b/bot/constants.py
--- a/bot/constants.py
+++ b/bot/constants.py
@@ -391,12 +391,15 @@ class Channels(metaclass=YAMLGetter):
     admin_announcements: int
     admin_spam: int
     admins: int
+    admins_voice: int
     announcements: int
     attachment_log: int
     big_brother_logs: int
     bot_commands: int
     change_log: int
-    code_help_voice: int
+    code_help_chat_1: int
+    code_help_chat_2: int
+    code_help_voice_1: int
     code_help_voice_2: int
     cooldown: int
     defcon: int
@@ -405,6 +408,7 @@ class Channels(metaclass=YAMLGetter):
     dev_log: int
     dm_log: int
     esoteric: int
+    general_voice: int
     helpers: int
     incidents: int
     incidents_archive: int
@@ -425,6 +429,8 @@ class Channels(metaclass=YAMLGetter):
     python_news: int
     reddit: int
     staff_announcements: int
+    staff_voice: int
+    staff_voice_chat: int
     talent_pool: int
     user_event_announcements: int
     user_log: int


Test patch:
Repository: python-discord/bot

Issue:
Command for snowflake info
When verifying users reports and when searching for information about an issue, it's helpful to be able to take a discord ID and get relevant information from it. All discord ID's encode their date+time of creation within them, so this can be used to date a dm channel's creation, a DM's timing, and in some cases can be used to jump directly back into a channel to find the actual conversation a deleted message was present in by manually constructing a channel/message link (as discord's default behavior when given a link to a message that doesn't exist is to jump as close as it can).

A command to do this manually, rather than having to rely on manual conversion or the !user command, would be helpful. 

Discord.py provides a utility function for getting the creation time from a snowflake conveniently--`discord.utils.snowflake_time`. When I personally used this, I returned the exact time of creation in UTC, and the delta between now and then, looking like this:

```
Snowflake created at 2020-11-08 16:17:58.949000, 9h 24m 12s ago.
```

A proposed name is `!snf` or `!snowflake`.

This could probably be made nicer, and dropped into an embed perhaps? I'm not sure if embedification is desired or necessary. 



Discussion:

Resolving patch:
diff --git a/bot/exts/utils/utils.py b/bot/exts/utils/utils.py
--- a/bot/exts/utils/utils.py
+++ b/bot/exts/utils/utils.py
@@ -9,13 +9,16 @@
 
 from discord import Colour, Embed, utils
 from discord.ext.commands import BadArgument, Cog, Context, clean_content, command, has_any_role
+from discord.utils import snowflake_time
 
 from bot.bot import Bot
 from bot.constants import Channels, MODERATION_ROLES, STAFF_ROLES
+from bot.converters import Snowflake
 from bot.decorators import in_whitelist
 from bot.pagination import LinePaginator
 from bot.utils import messages
 from bot.utils.cache import AsyncCache
+from bot.utils.time import time_since
 
 log = logging.getLogger(__name__)
 
@@ -166,6 +169,21 @@ async def zen(self, ctx: Context, *, search_value: Union[int, str, None] = None)
         embed.description = best_match
         await ctx.send(embed=embed)
 
+    @command(aliases=("snf", "snfl", "sf"))
+    @in_whitelist(channels=(Channels.bot_commands,), roles=STAFF_ROLES)
+    async def snowflake(self, ctx: Context, snowflake: Snowflake) -> None:
+        """Get Discord snowflake creation time."""
+        created_at = snowflake_time(snowflake)
+        embed = Embed(
+            description=f"**Created at {created_at}** ({time_since(created_at, max_units=3)}).",
+            colour=Colour.blue()
+        )
+        embed.set_author(
+            name=f"Snowflake: {snowflake}",
+            icon_url="https://github.com/twitter/twemoji/blob/master/assets/72x72/2744.png?raw=true"
+        )
+        await ctx.send(embed=embed)
+
     @command(aliases=("poll",))
     @has_any_role(*MODERATION_ROLES)
     async def vote(self, ctx: Context, title: clean_content(fix_channel_mentions=True), *options: str) -> None:


Test patch:
Repository: python-discord/bot

Issue:
ZeroDivisionError: division by zero
Sentry Issue: [BOT-KQ](https://sentry.io/organizations/python-discord/issues/2158550250/?referrer=github_integration)

```
ZeroDivisionError: division by zero
(3 additional frame(s) were not displayed)
...
  File "bot/exts/info/tags.py", line 223, in display_tag
    temp_founds = self._get_tag(tag_name)
  File "bot/exts/info/tags.py", line 109, in _get_tag
    return self._get_suggestions(tag_name)
  File "bot/exts/info/tags.py", line 87, in _get_suggestions
    scores: Dict[str, int] = {
  File "bot/exts/info/tags.py", line 88, in <dictcomp>
    tag_title: Tags._fuzzy_search(tag_name, tag['title'])
  File "bot/exts/info/tags.py", line 83, in _fuzzy_search
    return current / len(_search) * 100

Unhandled exception in on_command_error.
```


Discussion:

Resolving patch:
diff --git a/bot/exts/backend/error_handler.py b/bot/exts/backend/error_handler.py
--- a/bot/exts/backend/error_handler.py
+++ b/bot/exts/backend/error_handler.py
@@ -159,12 +159,7 @@ async def try_get_tag(self, ctx: Context) -> None:
                     return
 
         if not any(role.id in MODERATION_ROLES for role in ctx.author.roles):
-            tags_cog = self.bot.get_cog("Tags")
-            command_name = ctx.invoked_with
-            sent = await tags_cog.display_tag(ctx, command_name)
-
-            if not sent:
-                await self.send_command_suggestion(ctx, command_name)
+            await self.send_command_suggestion(ctx, ctx.invoked_with)
 
         # Return to not raise the exception
         return


Test patch:
Repository: python-discord/bot

Issue:
Trying to run a command with a non-existing infraction ID result in a traceback
If a conversion is tried on a non-existing infraction, it should be gracefully handled instead of throwing a 404 exception. 

Sentry Issue: [BOT-M2](https://sentry.io/organizations/python-discord/issues/2170320668/?referrer=github_integration)

```
ResponseCodeError: Status: 404 Response: {'detail': 'Not found.'}
  File "bot/api.py", line 67, in maybe_raise_for_status
    raise ResponseCodeError(response=response, response_json=response_json)
  File "bot/api.py", line 75, in request
    await self.maybe_raise_for_status(resp, raise_for_status)
  File "bot/api.py", line 80, in get
    return await self.request("GET", endpoint, raise_for_status=raise_for_status, **kwargs)
  File "bot/converters.py", line 578, in convert
    return await ctx.bot.api_client.get(f"bot/infractions/{arg}")
  File "discord/ext/commands/core.py", line 451, in _actual_conversion
    ret = await instance.convert(ctx, argument)

ConversionError: (<class 'bot.converters.Infraction'>, ResponseCodeError())
  File "discord/ext/commands/core.py", line 464, in _actual_conversion
    raise ConversionError(converter, exc) from exc
  File "discord/ext/commands/core.py", line 505, in do_conversion
    return await self._actual_conversion(ctx, converter, argument, param)
  File "discord/ext/commands/core.py", line 552, in transform
    return await self.do_conversion(ctx, converter, argument, param)
  File "discord/ext/commands/core.py", line 697, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "discord/ext/commands/core.py", line 790, in prepare
    await self._parse_arguments(ctx)
...
(3 additional frame(s) were not displayed)

Error executing command invoked by [REDACTED]: !i e 26984Bye bye | [REDACTED] 
```


Discussion:

Resolving patch:
diff --git a/bot/exts/backend/error_handler.py b/bot/exts/backend/error_handler.py
--- a/bot/exts/backend/error_handler.py
+++ b/bot/exts/backend/error_handler.py
@@ -85,8 +85,14 @@ async def on_command_error(self, ctx: Context, e: errors.CommandError) -> None:
             else:
                 await self.handle_unexpected_error(ctx, e.original)
             return  # Exit early to avoid logging.
+        elif isinstance(e, errors.ConversionError):
+            if isinstance(e.original, ResponseCodeError):
+                await self.handle_api_error(ctx, e.original)
+            else:
+                await self.handle_unexpected_error(ctx, e.original)
+            return  # Exit early to avoid logging.
         elif not isinstance(e, errors.DisabledCommand):
-            # ConversionError, MaxConcurrencyReached, ExtensionError
+            # MaxConcurrencyReached, ExtensionError
             await self.handle_unexpected_error(ctx, e)
             return  # Exit early to avoid logging.
 


Test patch:
Repository: python-discord/bot

Issue:
Gracefully handle OverflowErrors from ConversionErrors
Sentry Issue: [BOT-9N](https://sentry.io/organizations/python-discord/issues/1927146324/?referrer=github_integration)

It can do a better job than displaying the raw exception message to the user.

```
OverflowError: signed integer is greater than maximum
  File "discord/ext/commands/core.py", line 444, in _actual_conversion
    ret = await instance.convert(ctx, argument)
  File "bot/converters.py", line 352, in convert
    return now + delta
  File "dateutil/relativedelta.py", line 405, in __radd__
    return self.__add__(other)
  File "dateutil/relativedelta.py", line 387, in __add__
    ret = (other.replace(**repl)

ConversionError: (<class 'bot.converters.Duration'>, OverflowError('signed integer is greater than maximum'))
(3 additional frame(s) were not displayed)
...
  File "discord/ext/commands/core.py", line 784, in prepare
    await self._parse_arguments(ctx)
  File "discord/ext/commands/core.py", line 690, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "discord/ext/commands/core.py", line 545, in transform
    return await self.do_conversion(ctx, converter, argument, param)
  File "discord/ext/commands/core.py", line 498, in do_conversion
    return await self._actual_conversion(ctx, converter, argument, param)
  File "discord/ext/commands/core.py", line 457, in _actual_conversion
    raise ConversionError(converter, exc) from exc

Error executing command invoked by <REDACTED>: !remind 1000000000000000y still here?
```


Discussion:
In #1388 I added a new block for handling a `ConversionError`. I was thinking just adding a handler for `OverflowError` to this block. The question I have is, what would we want to display to the user? Something similar to how `BrandingError` is handled might be good. It would look like this:

![image](https://user-images.githubusercontent.com/9753350/106340453-bcaa7600-6291-11eb-837a-a79529cbe19e.png)

I am wondering if its worth overwriting the message content while I'm here, so its not the default `signed integer is greater than maximum`.
The other, possibly better, approach is to add `OverflowError` to the except block at `bot/converters.py:353`. This way it'll behave the same as a `ValueError`:

![image](https://user-images.githubusercontent.com/9753350/106354443-bba53300-62e9-11eb-8d50-b5ab9aad3d06.png)

I prefer the latter solution, it is more consistent with the rest of the code base. 

Resolving patch:
diff --git a/bot/converters.py b/bot/converters.py
--- a/bot/converters.py
+++ b/bot/converters.py
@@ -350,7 +350,7 @@ async def convert(self, ctx: Context, duration: str) -> datetime:
 
         try:
             return now + delta
-        except ValueError:
+        except (ValueError, OverflowError):
             raise BadArgument(f"`{duration}` results in a datetime outside the supported range.")
 
 


Test patch:
Repository: python-discord/bot

Issue:
Command suggester wrongly invoked for commands under cooldown
When a command is under cooldown and is invoked again, the error handler will wrongly try to suggest an alternative as if the command does not exist, when it should not do anything at all.

![image](https://user-images.githubusercontent.com/18114431/105258400-5dae7800-5b92-11eb-9841-c07b06766644.png)



Discussion:
can you mention the file path where i have to make changes?

@rijusougata13 the tag handling and command suggestion starts [here](https://github.com/python-discord/bot/blob/2a31892f2339848e13f3e04fce37e64f5242ab84/bot/exts/backend/error_handler.py#L133), *but* you should do some digging, see how the cooldown on tags work, see what's causing the bug. Once you understand how it works, the fix should be fairly simple.

If you want to take this on let me know and I'll assign it to you.
@rijusougata13 Are you still interested in working on this issue?
> @rijusougata13 Are you still interested in working on this issue?

you can assign others

Resolving patch:
diff --git a/bot/exts/info/tags.py b/bot/exts/info/tags.py
--- a/bot/exts/info/tags.py
+++ b/bot/exts/info/tags.py
@@ -189,7 +189,7 @@ async def display_tag(self, ctx: Context, tag_name: str = None) -> bool:
         If a tag is not specified, display a paginated embed of all tags.
 
         Tags are on cooldowns on a per-tag, per-channel basis. If a tag is on cooldown, display
-        nothing and return False.
+        nothing and return True.
         """
         def _command_on_cooldown(tag_name: str) -> bool:
             """
@@ -217,7 +217,7 @@ def _command_on_cooldown(tag_name: str) -> bool:
                 f"{ctx.author} tried to get the '{tag_name}' tag, but the tag is on cooldown. "
                 f"Cooldown ends in {time_left:.1f} seconds."
             )
-            return False
+            return True
 
         if tag_name is not None:
             temp_founds = self._get_tag(tag_name)
@@ -285,7 +285,8 @@ async def get_command(self, ctx: Context, *, tag_name: TagNameConverter = None)
         """
         Get a specified tag, or a list of all tags if no tag is specified.
 
-        Returns False if a tag is on cooldown, or if no matches are found.
+        Returns True if something can be sent, or if the tag is on cooldown.
+        Returns False if no matches are found.
         """
         return await self.display_tag(ctx, tag_name)
 


Test patch: