Move mutes to new cog, add role-based and temporary mutes #3634
No reviewers
Labels
No labels
Automated PR
Blocked
Blocked By: Damage Control
Blocked By: Dependency
Blocked By: Other PR
Breaking Change
Category: CI
Category: Cogs - Admin
Category: Cogs - Alias
Category: Cogs - Audio
Category: Cogs - Bank
Category: Cogs - Cleanup
Category: Cogs - CustomCommands
Category: Cogs - Dev
Category: Cogs - Downloader
Category: Cogs - Economy
Category: Cogs - Filter
Category: Cogs - General
Category: Cogs - Image
Category: Cogs - Mod
Category: Cogs - Modlog
Category: Cogs - Mutes
Category: Cogs - Permissions
Category: Cogs - Reports
Category: Cogs - Streams
Category: Cogs - Trivia
Category: Cogs - Trivia - Lists
Category: Cogs - Warnings
Category: Core - API - App Commands Package
Category: Core - API - Audio
Category: Core - API - Bank
Category: Core - API - Commands Package
Category: Core - API - Config
Category: Core - API - Other
Category: Core - API - Utils Package
Category: Core - Bot Class
Category: Core - Bot Commands
Category: Core - Command-line Interfaces
Category: Core - Downloader
Category: Core - Help
Category: Core - i18n
Category: Core - Modlog
Category: Core - Other Internals
Category: Core - RPC/ZMQ
Category: Docker
Category: Docs - Changelogs
Category: Docs - For Developers
Category: Docs - Install Guides
Category: Docs - Other
Category: Docs - User Guides
Category: Meta
Category: RPC/ZMQ methods
Category: Vendored Packages
Changelog Entry: Added
Changelog Entry: Pending
Changelog Entry: Skipped
Closed: Duplicate
Closed: External
Closed: Invalid
Closed: User Error
Closed: Won't Fix
Complex Issue
Docs-only
Feature Branch
Good First Issue
Help Wanted
High Priority
Needs Backport To stable-docs
No Activity
No Repro
QA: Bypassed
QA: Changes Requested
QA: Passed
Release Blocker
Status: Accepted
Status: Frozen
Status: In Progress
Status: Needs Discussion
Status: Needs Info
Status: Needs Triage
Status: PRs Welcome
Type: Bug
Type: Dependency Update
Type: Deprecation
Type: Enhancement
Type: Feature
Type: Informational
Type: Merge
Type: Optimisation
Type: Question
Type: Removal
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
Mrcoolgamer11/Red-DiscordBot!3634
Loading…
Reference in a new issue
No description provided.
Delete branch "mutes-rewrite"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Type
Description of the changes
This moves mutes outside of the mod cog into its own separate cog.
[p]mutedefaults to serverwide muting and[p]mutechannelmutes in the current channelCouple small things i found when testing
https://media.kstj.us/DarkorangeImaginativeDunlin.png
though i can confirm it adds the person to each channel and revokes perms properly,
though it does remove the overrides properly it just throws an ugly error, i also get a similar traceback when trying it with role mutes too, though the key error changes their ID versus the guild id as it was before
Seems that tempmutes with channel overrides doesn't actually ever unmuted, tested with
[p]mute @user 5mand[p]mute @user 1 minutesand both mute but never seem to unmute, no apparent errors in console either just no unmute[p]channelunmutehas the same issue as unmute doestraceback just for consistency
sense we have mutechannel, i feel unmutechannel works better than channelunmute, but thats just my preference
voicemute and voiceunmute throw the following traceback when trying to mute or unmute someone in voice
If any of this doesn't make sense let me know and i can explain further
I'm not sure what the reasoning behind abandoning the work done on
V3/feature/mutes, but there are issues with this code here which were actually considered in that branch even in an unfinished state@ -0,0 +1,1567 @@import asyncioThis isn't a safe way to determine if someone was muted, data about mutes should be stored upon muting, it also only works if they were role muted instead of overwrites being applied.
@ -0,0 +564,4 @@if await self.bot.cog_disabled_in_guild(self, guild):returnmute_role = await self.config.guild(guild).mute_role()if not mute_role:This also prevents re-applying channel permission based mutes.
@ -0,0 +1423,4 @@}old_overs = {k: getattr(overwrites, k) for k in new_overs}overwrites.update(**new_overs)Storing the old overwrites is an error that could change other permissions upon unmute, this should only store the difference in permissions caused by the mute.
@ -0,0 +1,1567 @@import asyncioThis was intentional when I started on this as I did not want to support permission based muting be applied when a user left and rejoined encouraging people use the role based model instead if they wanted to prevent people leaving and rejoining to avoid a mute.
@ -0,0 +1423,4 @@}old_overs = {k: getattr(overwrites, k) for k in new_overs}overwrites.update(**new_overs)This only stores the old overwrites for specific permissions on that user.
overwritesabove is the channel perms for that user only and the state they were in before they were muted. This was straight from the old mutes in mod.It would be great if this would expose some kind of an API that'd allow 3rd party cogs to apply timed / permanent mutes as well. I have a cog that currently has to do this manually, via creating it's own
Mutedrole and tracking the unmute time on each muted member. It'd be much easier if I could just hook-up to this via an API.@DevilXD that was outside the scope of this PR. I wanted to get the new features in people's hands and get them stable before things are re-arranged as an API which also moves a lot of this outside of a cog and into something core always has available.
This is just a code review, I still have to test any of this.
I marked any instances of datetime usage (I'm sure I missed some) so that someone who better understood #4017 can more easily take a look at them.
Most part of this looks fine to me
@ -0,0 +1,8 @@from redbot.core.bot import RedIs this import and typehint necessary?
@ -0,0 +1,1567 @@import asyncio?
Might want to use tasks.loop here? There won't be a big difference though.
Otherwise this could be handled like tempbans to be more efficient and percise, current handling should be good enough to start with though.
Something something time zone aware datetime objects. I'm not an expert here. Maybe @jack1142 can clarify
@jack1142 is this still correct with what we learned about naive/aware datetime objects?
Same thing with datetime
Datetime
Datetime
This shouldn't fail silently
Yay more datetimes
Does this overwrite "indefinite" mutes?
I'm not a fan of the default time here. How can an indefinite mute still happen with a default time set? If you want to keep this behaviour it definitely needs to be explained in the docstrings for
[p]muteDatetime
Switch the alias and name around here or in mutechannel for consistency
@ -0,0 +19,4 @@T_ = i18n.Translator("Mutes", __file__)_ = lambda s: sWhat purpose does this serve?
@ -0,0 +22,4 @@_ = lambda s: sMUTE_UNMUTE_ISSUES = {"already_muted": _("That user is already muted in this channel."),redgettext will output these as strings to be translated even though _ isn't a translator here
@ -0,0 +66,4 @@def __init__(self, bot: Red):self.bot = botself.config = Config.get_conf(self, 49615220001, force_registration=True)Shouldn't we use this here?
@ -0,0 +688,4 @@role = await ctx.guild.create_role(name=name, permissions=perms, reason=_("Mute role setup"))except discord.errors.Forbidden:This shouldn't fail silently
@ -0,0 +1,235 @@from typing import Optional, TupleThis is obsolete?
@ -0,0 +66,4 @@def __init__(self, bot: Red):self.bot = botself.config = Config.get_conf(self, 49615220001, force_registration=True)In this case no,
get_core_confis for anything inside the core package not cogs distributed with core unless I'm mistaken.@ -0,0 +1,8 @@from redbot.core.bot import RedIt's not necessary but in the essence if typehints it ensures that this cog is meant for Red and not someone elses bot that supports cogs.
@ -0,0 +19,4 @@T_ = i18n.Translator("Mutes", __file__)_ = lambda s: sAfter some digging this and the immediate comment after this was proposed so that redgettext will still grabt the correct strings but it doesn't actually get translated until runtime.
@ -0,0 +1,1567 @@import asyncioThese datetimes don't need to worry about being aware or naive since they represent a timedelta from a naive datetime object in seconds. I believe if this were to cause an issue it might happen if the system time changes but I am not sure entirely. This was the simpler logic to deal with change in time rather than fully implementing timedelta calculations as it sets a single point in time as a timestamp where the mute will be active until. The referenced issue you linked was for converting from datetime to timestamp and back to datetime.
@ -0,0 +1,1567 @@import asyncioThis is handled under the new converter for finding time inside the reason_and_time arg. If no time is detected then this check will return false meaning
untilwill be None allowing for indefinite mutes.@ -0,0 +1,1567 @@import asyncioTimedeltas don't matter as long as you subtract naive datetime objects with same timezone (or just use aware datetime objects) since they are relative, but there are places where the
.timestamp()is used on naive objects created bydatetime.utcnow()which will indeed cause it to save incorrect timestamp. You should instead usedatetime.now()(optionally withtz=timezone.utckwarg) for this to work correctly (same goes for creating case with modlog).Naive datetime objects are evil.
@ -0,0 +1,1567 @@import asyncioYes, but if no
untilis provided it will use the default time set in config. Or am I reading this wrong?@ -0,0 +1,1567 @@import asyncioif duration is supplied which comes from the converter it will use that and override the default. If a guild opts for a default for all mutes they cannot override the default time to be indefinite. Maybe not support a default time for mutes? I can't think of a simple way to allow this to explicitly not have a duration if the server has chosen to set a default. Then again the default is optional entirely so I could just document that better.
@ -0,0 +1,1567 @@import asyncioIf you think the default time is beneficial (I don't really) you should definitely make it clear that that rules out the indefinite mute. That was the point of my first comment but it wasn't worded clearly enough
So, I did some testing.
[p]activemutesuntil(I am UTC+1)Mute expired correctly after 2h
After messing around with mute I have 2 possible requests to try make it easier to use.
muteset makerole should also set that role as the muted roleI've been testing this for a while and am really happy with it. Timestamps are still off by some hours but functionally this works like a charm. Persistence across member rejoins would be nice but is not necessarily within scope here.
I found no other bugs over the past 7 days in prod and would take this over the old mutes any day for the cleaner UI and higher reliability for tempmutes than the scheduler workaround.
Timestamp on the manual modlog cases still off by 2h. Everything else a-ok. Not sure if it's a mute problem or modlog.
Not quite sure what caused this
Your cache no longer having those users? i.e they left the server?
They are still in the server. Some of them even on tempmutes that didn't get cleared I just learned a minute ago
@invalid-user is often caused due to your client being unable to render a mention
I'll take a lookie on the PC later. Maybe android being derpy again. None the less, these 3 are missing timing information if I haven't gone completely insane.
So after a quick investigation it seems that the guild wasn't cached properly. Not sure why the timed mutes keep failing (people are still muted) though
I'll be doing some additional testing tomorrow, but the review comments should contain pretty much everything that I had any concerns about.
List of few review comments that didn't fit into code:
RuntimeErrorformodlog.create_case()doesn't do anything and any suchtry-excepthas been removed in #4095. This PR introduces a few of the oldtry-excepts like this.[p](un)mute voicehas been changed a bit so that it takes action instantly, see: #4064redbot/core/mutessince you'll be the most knowledgeable person when it comes to Mutes cog.I know the comment count seems to be high, but there's plenty of things that I just repeated multiple times so that you don't miss some occurrence of the issue.
This method (as in, the actual method, not the abstract one that I'm commenting on) was also used by
[p]voicekickcommand inkickban.pyfile.@ -0,0 +8,4 @@log = logging.getLogger("red.cogs.mutes")# the following regex is slightly modified from RedWould be nice if this explained how is it different from the linked regex to be more helpful for the code reader.
@ -0,0 +1,1567 @@import asyncioThis cog help docstring could probably be improved a bit.
This comment seems no longer relevant (at least the second part of it) and it seems to also be misplaced.
all_membershas a structure:So
m_idis actually a dict of all members in theg_id.Doing this like that may result in the task not getting canceled if
bot.add_cog()call fails (as an example, this may happen if there are command conflicts and the cog fails to load)Could we remove the user from the muted_users config as part of the task to avoid situations where the bot is being shutdown while someone was supposed to get unmuted or if maybe some other exception in a task occurs?
Cog disabling API needs to be handled here.
Cog disabling API needs to be handled here.
Should we do some logging when
successis false?Logging should not be translated.
Logging should not be translated.
Logging should not be translated.
Logging should not be translated.
Logging should not be translated.
Logging should not be translated.
Logging should not be translated.
Logging should not be translated.
Logging should not be translated.
You probably meant to only include the mute's target, not mute's author in this if:
This makes more sense to be limited to bot's admin role because it involves role-related functionality as well as changes other cog's settings that affect the whole guild.
I think it would be nice if we also applied these to category channels so that creating a new channel in the category automatically makes the appropriate channel overwrite. It is not required, I just think it would be nice.
Here's a code suggestion which works just fine as it is not required to only specify the overwrites that are actually related to the channel type:
pagify()only breaks on newline character by default:Removing the default mute time is a bit weird, because it requires you to pass an input that won't get considered as time by
MuteTime. So just passing a random sequence of characters works, which I don't think is quite good here. This converter also accepts a reason which isn't that good either, but it is what currently allows you to reset default mute time.Could you move the commands out of the translated string (e.g. using
{command_1},{command_2}format fields) so that translators don't try to translate it (which is a real concern and some of the messages in Red have already been adapted for this)?Is this check relevant for channel mutes that use overrides regardless?
Is this check relevant for channel mutes that use overrides regardless?
There's nothing to translate here + you missed a space:
Depending on what was the purpose of clearing this, you might also want to clear config data for these users.
Why not just use
guild.get_channel()here?There's nothing to translate here.
Users argument is not optional.
For better translation support, you should have 2 separate strings for both plural forms.
issuegets replaced on each iteration of the for loop above, so this will only send whatever was the last issue (or even not send anything at all ifissuegets set toNoneon last iteration).Same as in the if above (
if not success_list and issuein L712)This is not true as it depends on the set default duration.
For better translation support, you should have 2 separate strings for both plural forms.
Maybe we should provide granularity here and mute everyone we can and only send errors for users we couldn't mute.
Maybe we should provide granularity here and mute everyone we can and only send errors for users we couldn't mute.
issuegets replaced on each iteration of the for loop above, so this will only send whatever was the last issue (or even not send anything at all ifissuegets set toNoneon last iteration).Depending on what was the purpose of clearing this, you might also want to clear config data for these channels.
Most of the strings here aren't wrapped in
_()and therefore aren't translated.(optional) It could potentially help a future reader, if this had a type hint:
Should we do some logging when
success["success"]is false?Role can't be both removed and added, so we can make this into an
elif:Currently this will save to config any time there are some server mutes in cache, whether it's something that was just added or something that was already in there.
It would be good to only save to Config when we need to here.
Currently this will save to config no matter if there was any new mute or not. It would be nice, if this was changed to only save to Config when needed.
That's not true though, is it (it doesn't seem to from the code and would also seem to be bad to remove such crucial part from overrides-based mutes)?
Users argument is not optional.
With this amount of context, it might be hard for translator to translate this properly, maybe something like this would be better? (I'm not sure)
With this amount of context, it might be hard for translator to translate this properly, maybe something like this would be better? (I'm not sure)
Users argument is required.
Users argument is required.
With this amount of context, it might be hard for translator to translate this properly, maybe something like this would be better? (I'm not sure)
With this amount of context, it might be hard for translator to translate this properly, maybe something like this would be better? (I'm not sure)
Users argument is required.
Users argument is required.
Same as in the if above (
if not success_list and issuein L894)Users argument is required.
Users argument is required.
Can you make this
try-exceptto only wrap the relevant line? It would make it easier to figure out what's going here at a glance.Most of the strings here aren't wrapped in
_()and therefore aren't translated.Since this is a global constant, it should be all uppercase.
This being after the API call means
_tempwill always beNoneinexceptsThis won't work for voice mutes.
What's the benefit of having
removed_usersrather than just checking mutes list for the user ID?I'm asking because in the latter case, we would not skip users that left the server while bot was offline (or for which Discord simply didn't fire an event, because why would Discord guarantee that the event gets fired?) and I don't know if there is a reason why this was done like that.
@ -0,0 +304,4 @@member = guild.get_member(user)self._unmute_tasks[task_name] = asyncio.create_task(self._auto_channel_unmute_user_multi(member, guild, channels))I wanted to just put the same comment as for this line in
_handle_guild_unmutes()but looks like you missed appending toto_removelist completely here :)Either way, the same comment technically still applies:
Could we remove the user from the muted_users config as part of the task to avoid situations where the bot is being shutdown while someone was supposed to get unmuted or if maybe some other exception in a task occurs?
@ -0,0 +447,4 @@"""Used to handle the cache if a member manually has the muted role removed"""guild = before.guildCog disabling API needs to be handled here.
@ -0,0 +754,4 @@))async def _check_for_mute_role(self, ctx: commands.Context) -> bool:Hmm, this instructions may also get sent to a user that has access to
[p]mutebut not to[p]muteset, I don't really know what we should (and whether we should) do about it though 🤔@ -0,0 +1087,4 @@issue_list = []success_list = []for user in users:success = await self.channel_mute_user(It doesn't seem like
old_oversare saved in this command.@ -0,0 +1365,4 @@if not guild.me.guild_permissions.manage_roles or role >= guild.me.top_role:ret["reason"] = _(MUTE_UNMUTE_ISSUES["permissions_issue_role"])return rettry:Can you make this
try-exceptto only wrap the relevant line? It would make it easier to figure out what's going here at a glance.@ -0,0 +1,235 @@from typing import Optional, TupleWhat he said 😄
Tuple unpacking here is incorrect.
@ -0,0 +754,4 @@))async def _check_for_mute_role(self, ctx: commands.Context) -> bool:I think it's fine to leave this, the mod who uses the mute can escalate the problem with setting the role later and continue with the overwrites based mute.
Follow-up review mostly for things that were changed since my last review, but I also found some smaller things I missed.
@ -0,0 +53,4 @@class CompositeMetaClass(type(commands.Cog), type(ABC)):"""This allows the metaclass used for proper type detection tocoexist with discord.py's metaclass@ -0,0 +352,4 @@if any(results):reasons = {}for result in results:if not result:I think it would make more sense for this setting to be available only to people with admin role or those having manage channels permission as I don't think that most administrators would want moderators to have access to this kind of setting and it is a setting that affects all moderators and visibility of these notifications.
There should probably be a way to reset this.
@ -0,0 +503,4 @@await self.config.guild(guild).muted_users.set(self._server_mutes[guild.id])@commands.Cog.listener()async def on_guild_channel_update(Could you add a cog disabling API check in this for the guild?
@ -0,0 +559,4 @@await self.config.channel(after).muted_users.set(self._channel_mutes[after.id])@commands.Cog.listener()async def on_member_join(self, member: discord.Member):Could you add a cog disabling API check in this for the guild?
@ -0,0 +1,235 @@from typing import Optional, TupleLooks like you accidentally reverted your change here and changed it back to
mute_user()when copying the code fromMod. This should be usingchannel_mute_user(). Don't forget thatchannel_mute_user()has different return type :)Looks like you accidentally reverted your change here and changed it back to
unmute_user()when copying the code fromMod. This should be usingchannel_unmute_user(). Don't forget thatchannel_unmute_user()has different return type :)@ -0,0 +81,4 @@is provided the mute will use the set default time or indefinite if not set.Examples:`[p]voicemute @member1 @member2 spam 5 hours`@ -0,0 +122,4 @@author = ctx.authorchannel = user_voice_state.channelaudit_reason = get_audit_reason(author, reason)@ -0,0 +152,4 @@msg = _("{users} has been muted in this channel{time}.")if len(success_list) > 1:msg = _("{users} have been muted in this channel{time}.")await ctx.send(@ -0,0 +216,4 @@until=None,channel=channel,)else:@ -0,0 +63,4 @@).format(perms=format_perms_list(required_perms)),)return True, None_voice_perm_check()sends an error message immediately which doesn't really play that well with how the rest of the command behave (as in, it returns errors at the end for the rest)_voice_perm_check()sends an error message immediately which doesn't really play that well with how the rest of the command behave (as in, it returns errors at the end for the rest)smaller one cause I found a rather unfortunate bug 😄
I'll be continuing with functional review so expect more :)
@ -0,0 +1,1567 @@import asyncioThis string is also used in
channel_unmute_user()methodGotta unindent this for it to work 😬
Automatic unmute spams modlog like hell
Reproduce:
[p]mute @ghost#0000 another one bites the test 45sSettings:
Would be nice to have a
showsettingscommand btw.Got that on Draper's
v3/edgebranch.overrides-based automatic unmutes go brrr (might be similar to the issue that I mentioned in the comment in L213)
Channel unmutes (as well as the bulk channel unmutes that are always called "Server mute") in modlog don't mention the channel(s) they refer to.
the dict format used everywhere in mutes for time storage seems a bit overcomplicated, why not just use
timedelta.total_seconds()?MuteTime converter is quite lax and detects time in the middle of text as well, is that intentional?
@ -0,0 +1,1567 @@import asyncioShouldn't this
try-exceptonly be wrapping the send() at the end of this method?Because the mute is in the cache as well as in the config, this sends a message every 30 seconds.

This should be moved out of
async with ctx.typing()block so that bot doesn't type while waiting for the reaction/messageThis should be moved out of
async with ctx.typing()block so that bot doesn't type while waiting for the message. Also, was there any reason why[p]channelmuteis the only command that usesctx.send_interactive()rather thanself.handle_issues()?This should be moved out of
async with ctx.typing()block so that bot doesn't type while waiting for the reaction/messageThis should be moved out of
async with ctx.typing()block so that bot doesn't type while waiting for the reaction/message@ -0,0 +23,4 @@MUTE_UNMUTE_ISSUES = {"already_muted": _("That user is already muted in this channel."),"already_unmuted": _("That user is not muted in this channel."),These strings aren't used anywhere.
This also means that you can use


[p]channelmuteand[p]channelunmutecommands multiple times in a row and have it "mute" each time you use the command, which I'm not sure was intended. I guess it couldhave been convenient if it allowed making the mute last longer, but what it seems to actually be doing is just adding another mute onto the stack and later just spams with more modlog cases for unmuting:
@ -0,0 +233,4 @@del self._server_mutes[guild.id][data["member"]]returnsuccess = await self.unmute_user(guild, author, member, _("Automatic unmute"))async with self.config.guild(guild).muted_users() as muted_users:Making separate method for basically same things seems overcomplicated. You could just add a
silentkwarg (or possibly a better name:create_casethat defaults toTrue) to_auto_channel_unmute_user()that would make the method not create the case.@ -0,0 +476,4 @@None,_("Manually removed mute role"),)del self._server_mutes[guild.id][after.id]This one doesn't really tell the user much, did you mean to add it or have you added it accidentally?
@ -0,0 +894,4 @@@commands.command(usage="<users...> [time_and_reason]")@commands.guild_only()@checks.mod_or_permissions(manage_roles=True)async def mute([p]mute User1 User2get repeated without any difference, formatting is a bit broken tooExample of what I'm talking about:

@ -0,0 +1,1567 @@import asynciotypo
Message written like that only makes sense for overrides-based mutes, not so much for role-based mutes.
@ -0,0 +23,4 @@MUTE_UNMUTE_ISSUES = {"already_muted": _("That user is already muted in this channel."),"already_unmuted": _("That user is not muted in this channel."),This isn't unique to channel mutes, same can be observed with server mutes, both overrides-based and role-based.
@ -0,0 +416,4 @@member,channel.guild.me,_("Automatic unmute"),until=None,You should pass channel here.
@ -0,0 +894,4 @@@commands.command(usage="<users...> [time_and_reason]")@commands.guild_only()@checks.mod_or_permissions(manage_roles=True)async def mute(To add here, the issue with failure reasons can also be seen with role-based mutes, although role-based mutes tend to have less permission-related issues so it's not as hard to read, but still, in case of different reason it can be non-obvious what reason refers to what:

Grouping reasons still seems like the best idea for addressing it to me, but feel free to figure out something else that makes it more user-friendly.
@ -0,0 +1,235 @@from typing import Optional, TupleI can't imagine a lot of situations where a time delta would be used inside a reason field that isn't meant to be the time itself. It's more lax this way so that users can start with the time or end with it and not have to really think "which goes first again?" when they're trying to just get the mute done. If it's a problem you can specify time as well with
t=2 hoursbut the idea was to be more user friendly.@ -0,0 +254,4 @@returnif not notification_channel.permissions_for(guild.me).send_messages:returnerror_msg = _(This name needs to contain guild id so that tasks for the same user can be spawned in 2 different servers.
_auto_channel_unmute_user()can returnNonein which case this tuple-unpacking will fail.This is some weird blank line.
@ -0,0 +449,4 @@"""guild = before.guildif await self.bot.cog_disabled_in_guild(self, guild):returnerror_msgdoesn't exist in this context@ -0,0 +671,4 @@@muteset.command(name="makerole")@checks.admin_or_permissions(manage_roles=True)@commands.bot_has_guild_permissions(manage_roles=True)First letter uppercase and add space as last char so that the message appended later in this code has proper spacing.
You already have one space below. Judging by next line, I'm also assuming you wanted to have a dot here, not a comma.
And I really like the idea of being more user friendly here, and I think it's really cool that you can start or end with the time. I was just wondering, if allowing to put it in the middle was also intended here or if it's just a bit unfortunate side effect.
Once all changes that were requested so far (including the review comments in this review) are done, this should be in a mergeable state. I know it's easier said than done though, but I just wanted to let you know that I won't add anything else to my reviews than I already have (unless some new issues get introduced of course). And if you will need any help, feel free to ask :)
Now onto this review, aside from code comments, there's one thing that hasn't been included in them as it wasn't referring to one specific code part:
@ -0,0 +1,1567 @@import asyncioThis default needs to be updated, here's one of errors I get due to current default value:
Cog seems to be working fine when
0is set as the default:Argument to
humanize_timedelta()are keyword-only.Alternatively you could just pass seconds directly to
humanize_timedelta()and ditch thedefault_timevariable.This is some weird blank line.
What we actually need to be checking for here is the guild permission, not the channel-specific permission.
This doesn't work properly if override gets set to None state.
I honestly think we should just have set this to
Trueas the default to not encourage new users to use overrides-based mutes, but this might need to be brought up in the server.@ -0,0 +247,4 @@_("Automatic unmute"),until=None,)else:This will keep sending messages infinitely for any errors. As an example of reproduction, you can role mute a user and then remove manage roles perm from the bot which will make the bot send messages infinitely in the notification channel.
@ -0,0 +257,4 @@error_msg = _("I am unable to unmute {user} for the following reason:\n{reason}").format(user=member, reason=success["reason"])try:We should be checking if we can send messages before making an API call using
notification_channel.permissions_for(guild.me).send_messagesand only catch Forbidden as last resort.@ -0,0 +373,4 @@return Noneif not notification_channel.permissions_for(guild.me).send_messages:return Nonetry:We should be checking if we can send messages before making an API call using
notification_channel.permissions_for(guild.me).send_messagesand only catch Forbidden as last resort.@ -0,0 +434,4 @@return Noneif not notification_channel.permissions_for(channel.guild.me).send_messages:return Nonetry:We should be checking if we can send messages before making an API call using
notification_channel.permissions_for(guild.me).send_messagesand only catch Forbidden as last resort.@ -0,0 +575,4 @@if not role:returnuntil = datetime.fromtimestamp(self._server_mutes[guild.id][member.id]["until"])await self.mute_user(mute_user()expectsuntilto be a datetime object.@ -0,0 +725,4 @@overs.send_messages = Falseovers.add_reactions = Falseovers.speak = Falsetry:We should be checking if we can manage permissions in the channel before making an API call using
channel.permissions_for(guild.me).manage_permissionsand only catch Forbidden as last resort.@ -0,0 +1300,4 @@"member": user.id,"until": until.timestamp() if until else None,}try:We should be checking if we can manage roles before making an API call using
guild.me.guild_permissions.manage_rolesand only catch Forbidden as last resort. The same goes for checking whether the role we're trying to assign can be assigned by the bot by checking its position against the bot's top role.By doing both of these things, we could also easily have more specific errors here :)
@ -0,0 +1365,4 @@if not guild.me.guild_permissions.manage_roles or role >= guild.me.top_role:ret["reason"] = _(MUTE_UNMUTE_ISSUES["permissions_issue_role"])return rettry:We should be checking if we can manage roles before making an API call using
guild.me.guild_permissions.manage_rolesand only catch Forbidden as last resort. The same goes for checking whether the role we're trying to assign can be assigned by the bot by checking its position against the bot's top role.By doing both of these things, we could also easily have more specific errors here :)
@ -0,0 +1443,4 @@"member": user.id,"until": until.timestamp() if until else None,}try:We should be checking if we can manage permissions in the channel before making an API call using
channel.permissions_for(guild.me).manage_permissionsand only catch Forbidden as last resort.@ -0,0 +1530,4 @@"channel": channel,"reason": _(MUTE_UNMUTE_ISSUES["permissions_issue_channel"]),}try:We should be checking if we can manage permissions in the channel before making an API call using
channel.permissions_for(guild.me).manage_permissionsand only catch Forbidden as last resort.Aside from the code comments, it looks like there's still one thing that wasn't addressed and/or answered to (quote rephrased to better explain what I meant):
This might be the last review before approval - I still need to do some testing with the newly introduced changes so there is a chance I'll find some bug, but if I don't, it will be time for approval.
@ -0,0 +1,1567 @@import asyncioAs said in the previous review comment
If you want to, you can split this into 2 errors, but I won't require that.
As said in the previous review comment
If you want to, you can split this into 2 errors, but I won't require that.
@ -0,0 +743,4 @@if not time:await self.config.guild(ctx.guild).default_time.clear()await ctx.send(_("Default mute time removed."))else:Missing space
@ -0,0 +1270,4 @@"channels": [],"user": user,}# TODO: This typing is ugly and should probably be an object on its ownUnused variable
@ -0,0 +317,4 @@)async def _auto_channel_unmute_user_multi(self, member: discord.Member, guild: discord.Guild, channels: Dict[int, dict]I would want to propose alternative formatting for this (you can write the code differently, just wanted to present what I mean by using code):
[p]muteand to[p]channelmuteand[p]voicemutecommands)[p]vocemutedoesn't contain the duration/until fieldsWhat can also be seen on the screenshot below is that there's a nice empty line between
AlmostSlimeandJackenmenthat improves readability, but such an empty line doesn't exist betweenJackenmenandKslibLivxud.Besides what I mentioned, I think we could do one more thing improving readability - make the different reasons form a list by preceding each reason with
-:@ -0,0 +1,1567 @@import asyncioThese raise when
user_idisn't inafter_perms.It's that time! LGTM, let's ship it! 😏
Thanks for all the work on this @TrustyJAID and thanks for all the help with testing to our contributors ❤️