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

Issue:
Move `bot_in_a_guild` from `redbot.core.checks` to `redbot.core.commands`
As the title says.

`bot_in_a_guild()` should also get imported from `commands` in `checks` to avoid breakage


Discussion:

Resolving patch:
diff --git a/redbot/core/checks.py b/redbot/core/checks.py
--- a/redbot/core/checks.py
+++ b/redbot/core/checks.py
@@ -5,6 +5,7 @@
 
 from .commands import (
     bot_has_permissions,
+    bot_in_a_guild,
     has_permissions,
     is_owner,
     guildowner,
@@ -13,7 +14,6 @@
     admin_or_permissions,
     mod,
     mod_or_permissions,
-    check as _check_decorator,
 )
 from .utils.mod import (
     is_mod_or_superior as _is_mod_or_superior,
@@ -27,6 +27,7 @@
 
 __all__ = [
     "bot_has_permissions",
+    "bot_in_a_guild",
     "has_permissions",
     "is_owner",
     "guildowner",
@@ -37,20 +38,10 @@
     "mod_or_permissions",
     "is_mod_or_superior",
     "is_admin_or_superior",
-    "bot_in_a_guild",
     "check_permissions",
 ]
 
 
-def bot_in_a_guild():
-    """Deny the command if the bot is not in a guild."""
-
-    async def predicate(ctx):
-        return len(ctx.bot.guilds) > 0
-
-    return _check_decorator(predicate)
-
-
 def is_mod_or_superior(ctx: "Context") -> Awaitable[bool]:
     warnings.warn(
         "`redbot.core.checks.is_mod_or_superior` is deprecated and will be removed in a future "
diff --git a/redbot/core/commands/__init__.py b/redbot/core/commands/__init__.py
--- a/redbot/core/commands/__init__.py
+++ b/redbot/core/commands/__init__.py
@@ -52,6 +52,7 @@
     Requires as Requires,
     permissions_check as permissions_check,
     bot_has_permissions as bot_has_permissions,
+    bot_in_a_guild as bot_in_a_guild,
     has_permissions as has_permissions,
     has_guild_permissions as has_guild_permissions,
     is_owner as is_owner,
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
@@ -11,22 +11,23 @@
 import inspect
 from collections import ChainMap
 from typing import (
-    Union,
-    Optional,
-    List,
-    Callable,
-    Awaitable,
-    Dict,
-    Any,
     TYPE_CHECKING,
-    TypeVar,
-    Tuple,
+    Any,
+    Awaitable,
+    Callable,
     ClassVar,
+    Dict,
+    List,
     Mapping,
+    Optional,
+    Tuple,
+    TypeVar,
+    Union,
 )
 
 import discord
 
+from discord.ext.commands import check
 from .converter import GuildConverter
 from .errors import BotMissingPermissions
 
@@ -47,6 +48,7 @@
     "Requires",
     "permissions_check",
     "bot_has_permissions",
+    "bot_in_a_guild",
     "has_permissions",
     "has_guild_permissions",
     "is_owner",
@@ -705,6 +707,15 @@ def decorator(func: "_CommandOrCoro") -> "_CommandOrCoro":
     return decorator
 
 
+def bot_in_a_guild():
+    """Deny the command if the bot is not in a guild."""
+
+    async def predicate(ctx):
+        return len(ctx.bot.guilds) > 0
+
+    return check(predicate)
+
+
 def has_permissions(**perms: bool):
     """Restrict the command to users with these permissions.
 


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

Issue:
Channel mute data is only cleared in cache on error
I was waiting for the automatic unmute to trigger and once it did, it sent the error:
```
I am unable to unmute KslibLivxud#1317 in #bhc-casual for the following reason:
Failed to mute or unmute user. I need the Manage Permissions permission.
```
I then waited for next loop cycle and the message was NOT sent again.
However, after I restarted the bot, it sent the same error again.

It seems that channel mute data is only cleared in the cache if the automatic unmute errors and therefore the error message gets resent on each bot restart.
Channel mute data is only cleared in cache on error
I was waiting for the automatic unmute to trigger and once it did, it sent the error:
```
I am unable to unmute KslibLivxud#1317 in #bhc-casual for the following reason:
Failed to mute or unmute user. I need the Manage Permissions permission.
```
I then waited for next loop cycle and the message was NOT sent again.
However, after I restarted the bot, it sent the same error again.

It seems that channel mute data is only cleared in the cache if the automatic unmute errors and therefore the error message gets resent on each bot restart.


Discussion:

Resolving patch:
diff --git a/redbot/cogs/mutes/mutes.py b/redbot/cogs/mutes/mutes.py
--- a/redbot/cogs/mutes/mutes.py
+++ b/redbot/cogs/mutes/mutes.py
@@ -404,6 +404,9 @@ async def _auto_channel_unmute_user(
         success = await self.channel_unmute_user(
             channel.guild, channel, author, member, _("Automatic unmute")
         )
+        async with self.config.channel(channel).muted_users() as muted_users:
+            if str(member.id) in muted_users:
+                del muted_users[str(member.id)]
         if success["success"]:
             if create_case:
                 if isinstance(channel, discord.VoiceChannel):
@@ -421,9 +424,6 @@ async def _auto_channel_unmute_user(
                     until=None,
                     channel=channel,
                 )
-            async with self.config.channel(channel).muted_users() as muted_users:
-                if str(member.id) in muted_users:
-                    del muted_users[str(member.id)]
             return None
         else:
             error_msg = _(


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

Issue:
massban not banning ids
# Command bugs

I found a bug.

#### Command name

massban

#### What cog is this command from?

Mod

#### What were you expecting to happen?

The mass ban to ban all 3 members I pinged.

#### What actually happened?

2 members were banned, but on one I got the following error:
https://cdn.discordapp.com/attachments/133251234164375552/770791292468068362/unknown.png
![image](https://user-images.githubusercontent.com/34169552/97373353-38a8b280-188c-11eb-8df6-d49593b7a88f.png)

#### How can we reproduce this issue?

1. attempt to massban a member by pinging them
2. it doesn't work
From my experience it only happens when trying to massban this id: `651931638409986049`
https://cdn.discordapp.com/attachments/133251234164375552/770792689323081738/unknown.png
![image](https://user-images.githubusercontent.com/34169552/97373361-3e05fd00-188c-11eb-88fc-59339bef0038.png)


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
@@ -460,7 +460,7 @@ def remove_processed(ids):
             to_query = to_query[100:]
 
         # Call `ban_user()` method for all users that turned out to be guild members.
-        for member in members:
+        for user_id, member in members.items():
             try:
                 success, reason = await self.ban_user(
                     user=member, ctx=ctx, days=days, reason=reason, create_modlog_case=True


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

Issue:
Modlog API raises when trying to get a case if bot can't read message history in modlog channel
# Other bugs

#### What were you trying to do?

Get a case with `[p]case` command.

#### What were you expecting to happen?

Get a case.

#### What actually happened?

I got an error:
```py
Exception in command 'case'
Traceback (most recent call last):
  File "/home/ubuntu/red-venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/ubuntu/red-venv/lib/python3.8/site-packages/redbot/cogs/modlog/modlog.py", line 112, in case
    case = await modlog.get_case(number, ctx.guild, self.bot)
  File "/home/ubuntu/red-venv/lib/python3.8/site-packages/redbot/core/modlog.py", line 725, in get_case
    return await Case.from_json(mod_channel, bot, case_number, case)
  File "/home/ubuntu/red-venv/lib/python3.8/site-packages/redbot/core/modlog.py", line 556, in from_json
    message = await mod_channel.fetch_message(message_id)
  File "/home/ubuntu/red-venv/lib/python3.8/site-packages/discord/abc.py", line 970, in fetch_message
    data = await self._state.http.get_message(channel.id, id)
  File "/home/ubuntu/red-venv/lib/python3.8/site-packages/discord/http.py", line 241, in request
    raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
```

#### How can we reproduce this issue?

1. Set modlog channel
2. Make a case (either manually through API or by using some moderation command)
3. Change modlog channel's permissions and forbid the bot from reading messages (or at least reading message history)
4. Try getting the case with `[p]case` command.

---

This can be fixed by adding `discord.Forbidden` to catched errors in the code that fetches the message here:
https://github.com/Cog-Creators/Red-DiscordBot/blob/48ec2dfee0d806f31cf4eada75de3226829b10eb/redbot/core/modlog.py#L555-L558





Discussion:

Resolving patch:
diff --git a/redbot/core/modlog.py b/redbot/core/modlog.py
--- a/redbot/core/modlog.py
+++ b/redbot/core/modlog.py
@@ -554,7 +554,7 @@ async def from_json(
                 if message is None:
                     try:
                         message = await mod_channel.fetch_message(message_id)
-                    except (discord.NotFound, AttributeError):
+                    except (discord.HTTPException, AttributeError):
                         message = None
             else:
                 message = None


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

Issue:
[Core] Add "competing" as a status that can be used.
# Feature request


#### Select the type of feature you are requesting:

- [ ] Cog
- [X] Command 
- [ ] API functionality

#### Describe your requested feature

d.py 1.5 include a new kind of activity called "Competing". Since `[p]set` already have all kind of activity that can be set on Red, this option should be added. (Maybe as `[p]set competition` or simply `competing`)


Discussion:
Makes sense to me, should be added under `[p]set competing` command name to be consistent with the rest of the command names for setting statuses.

PRs welcome! ❤️ 

---

We also need to add this new type of activity to the `[p]userinfo` command. This can either be done in same PR or a separate one. Please don't mark your PR as fixing this issue if you only do one of these things so that it's not forgotten about because of issue closing automatically, thanks!

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
@@ -1896,6 +1896,25 @@ async def _watching(self, ctx: commands.Context, *, watching: str = None):
         else:
             await ctx.send(_("Watching cleared."))
 
+    @_set.command(name="competing")
+    @checks.bot_in_a_guild()
+    @checks.is_owner()
+    async def _competing(self, ctx: commands.Context, *, competing: str = None):
+        """Sets [botname]'s competing status."""
+
+        status = ctx.bot.guilds[0].me.status if len(ctx.bot.guilds) > 0 else discord.Status.online
+        if competing:
+            activity = discord.Activity(name=competing, type=discord.ActivityType.competing)
+        else:
+            activity = None
+        await ctx.bot.change_presence(status=status, activity=activity)
+        if activity:
+            await ctx.send(
+                _("Status set to ``Competing in {competing}``.").format(competing=competing)
+            )
+        else:
+            await ctx.send(_("Competing cleared."))
+
     @_set.command()
     @checks.bot_in_a_guild()
     @checks.is_owner()


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

Issue:
`[p]userinfo` doesn't show the new `competing` activity type
# Command bugs

#### Command name

`[p]userinfo`

#### What cog is this command from?

Mod

#### What were you expecting to happen?

I expected `[p]userinfo` to show competing activity when using it on user with competing activity set.

#### What actually happened?

Command didn't show any activity.

#### How can we reproduce this issue?

1. Set "Competing in" activity on bot user with `[p]set competing` command.
2. Use `[p]userinfo` command on bot user.
3. See the issue.



Discussion:

Resolving patch:
diff --git a/redbot/cogs/mod/names.py b/redbot/cogs/mod/names.py
--- a/redbot/cogs/mod/names.py
+++ b/redbot/cogs/mod/names.py
@@ -133,6 +133,14 @@ def handle_watching(self, user):
         act = _("Watching: {name}").format(name=w_act.name)
         return act, discord.ActivityType.watching
 
+    def handle_competing(self, user):
+        w_acts = [c for c in user.activities if c.type == discord.ActivityType.competing]
+        if not w_acts:
+            return None, discord.ActivityType.competing
+        w_act = w_acts[0]
+        act = _("Competing in: {competing}").format(competing=w_act.name)
+        return act, discord.ActivityType.competing
+
     def get_status_string(self, user):
         string = ""
         for a in [
@@ -141,6 +149,7 @@ def get_status_string(self, user):
             self.handle_listening(user),
             self.handle_streaming(user),
             self.handle_watching(user),
+            self.handle_competing(user),
         ]:
             status_string, status_type = a
             if status_string is None:


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

Issue:
[Audio] Error when changing Java path
# Command bugs

<!-- 
Did you find a bug with a command? Fill out the following:
-->

#### Command name

`llset java`

#### What cog is this command from?

Audio

#### What were you expecting to happen?

To set a custom java path

#### What actually happened?

No response in Discord, traceback in the console

#### How can we reproduce this issue?

`llset java /usr/bin/java` or any other executable path (I get the expected error message in Discord if provided path is not a valid executable)

```
[2020-11-18 18:44:58] [ERROR] red: TypeError
Traceback (most recent call last):
File "/home/red/envs/eevee/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
File "/home/red/envs/eevee/lib/python3.8/site-packages/redbot/cogs/audio/core/commands/llset.py", line 58, in command_llsetup_java
    await self.config.java_exc_path.set(exc_absolute)
File "/home/red/envs/eevee/lib/python3.8/site-packages/redbot/core/config.py", line 257, in set
    await self.driver.set(self.identifier_data, value=value)
File "/home/red/envs/eevee/lib/python3.8/site-packages/redbot/core/drivers/json.py", line 146, in set
    value_copy = json.loads(json.dumps(value))
File "/usr/lib/python3.8/json/init.py", line 231, in dumps
    return _default_encoder.encode(obj)
File "/usr/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
File "/usr/lib/python3.8/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.class.name} '
TypeError: Object of type PosixPath is not JSON serializable
```


Discussion:

Resolving patch:
diff --git a/redbot/cogs/audio/core/commands/llset.py b/redbot/cogs/audio/core/commands/llset.py
--- a/redbot/cogs/audio/core/commands/llset.py
+++ b/redbot/cogs/audio/core/commands/llset.py
@@ -55,7 +55,7 @@ async def command_llsetup_java(self, ctx: commands.Context, *, java_path: str =
                         java_path=exc_absolute
                     ),
                 )
-            await self.config.java_exc_path.set(exc_absolute)
+            await self.config.java_exc_path.set(str(exc_absolute))
             await self.send_embed_msg(
                 ctx,
                 title=_("Java Executable Changed"),


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

Issue:
`[p]streamalert youtube` raises an error
# Command bugs

#### Command name

`[p]streamalert youtube`

#### What cog is this command from?

Streams

#### What were you expecting to happen?

I expected it to work.

#### What actually happened?

I got an error:
```
Exception in command 'streamalert youtube'
Traceback (most recent call last):
  File "/home/ubuntu/red-venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/ubuntu/red-venv/lib/python3.8/site-packages/redbot/cogs/streams/streams.py", line 322, in youtube_alert
    await self.stream_alert(ctx, YoutubeStream, channel_name_or_id)
  File "/home/ubuntu/red-venv/lib/python3.8/site-packages/redbot/cogs/streams/streams.py", line 411, in stream_alert
    stream = _class(name=channel_name, token=token)
  File "/home/ubuntu/red-venv/lib/python3.8/site-packages/redbot/cogs/streams/streamtypes.py", line 92, in __init__
    self._config = kwargs.pop("config")
KeyError: 'config'
```

#### How can we reproduce this issue?

Just try calling `[p]streamalert youtube` with some YouTube channel.



Discussion:
Gonna work on a fix myself for that one

Resolving patch:
diff --git a/redbot/cogs/streams/streams.py b/redbot/cogs/streams/streams.py
--- a/redbot/cogs/streams/streams.py
+++ b/redbot/cogs/streams/streams.py
@@ -408,7 +408,10 @@ async def stream_alert(self, ctx: commands.Context, _class, channel_name):
                     bearer=self.ttv_bearer_cache.get("access_token", None),
                 )
             else:
-                stream = _class(name=channel_name, token=token)
+                if is_yt:
+                    stream = _class(name=channel_name, token=token, config=self.config)
+                else:
+                    stream = _class(name=channel_name, token=token)
             try:
                 exists = await self.check_exists(stream)
             except InvalidTwitchCredentials:


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

Issue:
Cleanup self inconsistent with other commands in the cog
# Command bugs

An inconsistency with a command (self) on the cleanup cog

#### Command name

[p]cleanup self

#### What cog is this command from?

It is from the cleanup cog.

#### What were you expecting to happen?

I expected the command to delete my message which  invoked the command, like any other command in the cog

#### What actually happened?

It didn't delete the invoked command.

#### How can we reproduce this issue?

Have some bot messages 
cleanup self 1



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
@@ -579,6 +579,8 @@ def check(m):
             before=ctx.message,
             delete_pinned=delete_pinned,
         )
+        if can_mass_purge:
+            to_delete.append(ctx.message)
 
         if ctx.guild:
             channel_name = "channel " + channel.name


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

Issue:
[Streams] Mismatched stream start times in embed
# Other bugs

#### What were you trying to do?
Receive YouTube scheduled streams

#### What were you expecting to happen?
An embed with some information pertaining to upcoming stream

#### What actually happened?
Received aforementioned embed, but times are off in the description versus the footer. The footer start time is correct, the one in the description is off by 8 hours, so this seems related to time zones.

#### How can we reproduce this issue?
In my instance and on my Discord client, my time zone is America/Vancouver (PST/GMT-8). Configure a YouTube channel and wait.
![image](https://user-images.githubusercontent.com/6710854/103105845-38573a00-45e5-11eb-821f-d533ebd36cdd.png)


Discussion:

Resolving patch:
diff --git a/redbot/cogs/streams/streamtypes.py b/redbot/cogs/streams/streamtypes.py
--- a/redbot/cogs/streams/streamtypes.py
+++ b/redbot/cogs/streams/streamtypes.py
@@ -4,7 +4,7 @@
 from dateutil.parser import parse as parse_time
 from random import choice
 from string import ascii_letters
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta, timezone
 import xml.etree.ElementTree as ET
 from typing import ClassVar, Optional, List, Tuple
 
@@ -138,9 +138,7 @@ async def is_online(self):
                         scheduled = stream_data.get("scheduledStartTime", None)
                         if scheduled is not None and actual_start_time is None:
                             scheduled = parse_time(scheduled)
-                            if (
-                                scheduled.replace(tzinfo=None) - datetime.now()
-                            ).total_seconds() < -3600:
+                            if (scheduled - datetime.now(timezone.utc)).total_seconds() < -3600:
                                 continue
                         elif actual_start_time is None:
                             continue
@@ -178,7 +176,7 @@ async def make_embed(self, data):
         if vid_data["liveStreamingDetails"].get("scheduledStartTime", None) is not None:
             if "actualStartTime" not in vid_data["liveStreamingDetails"]:
                 start_time = parse_time(vid_data["liveStreamingDetails"]["scheduledStartTime"])
-                start_in = start_time.replace(tzinfo=None) - datetime.now()
+                start_in = start_time - datetime.now(timezone.utc)
                 if start_in.total_seconds() > 0:
                     embed.description = _("This stream will start in {time}").format(
                         time=humanize_timedelta(


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

Issue:
Properly rotate logging
# Other bugs

<!-- 
Did you find a bug with something other than a command? Fill out the following:
-->

#### What were you trying to do?

Check log files due to no disk space. 12gb for 2 of reds files. The logs are only labelled as part 1 and 9 with nothing in between.

#### What were you expecting to happen?

Log files to correctly rotate and not be just labelled as 1 and 9

#### What actually happened?

<!-- Replace this line with a description of what actually happened. Include any error messages -->

#### How can we reproduce this issue?

Just running red with ~100 cogs.


![](https://i.flaree.xyz/WindowsTerminal_0UK1SRb72M.png)




Discussion:

Resolving patch:
diff --git a/redbot/logging.py b/redbot/logging.py
--- a/redbot/logging.py
+++ b/redbot/logging.py
@@ -58,7 +58,7 @@ def __init__(
         self.baseStem = stem
         self.directory = directory.resolve()
         # Scan for existing files in directory, append to last part of existing log
-        log_part_re = re.compile(rf"{stem}-part(?P<partnum>\d+).log")
+        log_part_re = re.compile(rf"{stem}-part(?P<partnum>\d)\.log")
         highest_part = 0
         for path in directory.iterdir():
             match = log_part_re.match(path.name)
@@ -86,7 +86,7 @@ def doRollover(self):
             initial_path.replace(self.directory / f"{self.baseStem}-part1.log")
 
         match = re.match(
-            rf"{self.baseStem}(?:-part(?P<part>\d+)?)?.log", pathlib.Path(self.baseFilename).name
+            rf"{self.baseStem}(?:-part(?P<part>\d))?\.log", pathlib.Path(self.baseFilename).name
         )
         latest_part_num = int(match.groupdict(default="1").get("part", "1"))
         if self.backupCount < 1:
@@ -95,7 +95,7 @@ def doRollover(self):
         elif latest_part_num > self.backupCount:
             # Rotate files down one
             # red-part2.log becomes red-part1.log etc, a new log is added at the end.
-            for i in range(1, self.backupCount):
+            for i in range(1, self.backupCount + 1):
                 next_log = self.directory / f"{self.baseStem}-part{i + 1}.log"
                 if next_log.exists():
                     prev_log = self.directory / f"{self.baseStem}-part{i}.log"


Test patch: