From 4b474404115f838d2e370a29c438e70b455157c3 Mon Sep 17 00:00:00 2001 From: Sydney Date: Thu, 4 May 2023 15:25:17 -0400 Subject: [PATCH] Black reformat. --- .github/workflows/black-checker.yml | 2 +- confession/confession.py | 2 - costmanager/manager.py | 1 - economytrickle/activity.py | 6 - economytrickle/converters.py | 1 - economytrickle/core.py | 2 - imagemagic/imagemagic.py | 33 ++-- isolate/isolate.py | 3 - memeify/memeify.py | 1 - moreadmin/moreadmin.py | 1 - moreadmin/utils.py | 1 - pony/pony.py | 5 +- punish/punish.py | 3 - rolemanagement/converters.py | 3 - rolemanagement/core.py | 230 +++++++--------------------- rolemanagement/events.py | 12 +- rolemanagement/massmanager.py | 1 - scheduler/checks.py | 1 - scheduler/converters.py | 2 - scheduler/scheduler.py | 2 - scheduler/tasks.py | 5 - sfx/utils.py | 1 + suggestion/suggestion.py | 3 +- 23 files changed, 75 insertions(+), 246 deletions(-) diff --git a/.github/workflows/black-checker.yml b/.github/workflows/black-checker.yml index 6f4a41c..4d61793 100644 --- a/.github/workflows/black-checker.yml +++ b/.github/workflows/black-checker.yml @@ -10,4 +10,4 @@ jobs: - name: Black Code Formatter uses: lgeiger/black-action@v1.0.1 with: - args: "--line-length 120 --target-version py38 --check ." + args: "--line-length 120 --target-version py310 --check ." diff --git a/confession/confession.py b/confession/confession.py index 23df0e2..53ea9c3 100644 --- a/confession/confession.py +++ b/confession/confession.py @@ -145,12 +145,10 @@ class Confession(commands.Cog): await menu(ctx, pages=embeds, controls=SELECT_CONTROLS, message=None, page=0, timeout=20) async def selected_guild(self, ctx, user_guilds, confession, page): - confession_guild = user_guilds[page] await self.send_confession(ctx, confession_guild, confession) async def send_confession(self, ctx, confession_guild: discord.Guild, confession: str): - confession_room = await self.config.guild(confession_guild).confession_room() confession_room = confession_guild.get_channel(confession_room) diff --git a/costmanager/manager.py b/costmanager/manager.py index a0577d4..a3cf86f 100644 --- a/costmanager/manager.py +++ b/costmanager/manager.py @@ -47,7 +47,6 @@ class CostManager(commands.Cog): # permission hook checker for cost of command async def cost_checker(self, ctx): - cost = await self.get_cost(ctx) if cost == 0: diff --git a/economytrickle/activity.py b/economytrickle/activity.py index 34dcff7..d6edb90 100644 --- a/economytrickle/activity.py +++ b/economytrickle/activity.py @@ -10,7 +10,6 @@ MessagePredicate = Callable[[discord.Message], bool] class RecentActivityRecord: - __slots__ = ("activities", "messages") def __init__(self): @@ -32,7 +31,6 @@ class RecentActivityRecord: after: Optional[datetime] = None, message_check: Optional[MessagePredicate] = None, ) -> List[Union[datetime, discord.Message]]: - ret: List[Union[datetime, discord.Message]] = [] for a in self.activities: @@ -57,7 +55,6 @@ class RecentActivityRecord: after: Optional[datetime] = None, message_check: Optional[MessagePredicate] = None, ) -> int: - ret = len(self._filter(after=after, message_check=message_check)) return ret @@ -84,14 +81,12 @@ RecordDict = Dict[discord.Guild, Dict[discord.Member, RecentActivityRecord]] class RecordHandler: - __slots__ = ("records",) def __init__(self): self.records: RecordDict = {} def proccess_message(self, message): - try: member = message.author guild = member.guild @@ -115,7 +110,6 @@ class RecordHandler: after: datetime, message_check: Optional[MessagePredicate] = None, ) -> Iterator[discord.Member]: - with contextlib.suppress(KeyError): for member, rec in self.records[guild].items(): if rec.conditional_count(after=after, message_check=message_check): diff --git a/economytrickle/converters.py b/economytrickle/converters.py index fb03e23..ed316ae 100644 --- a/economytrickle/converters.py +++ b/economytrickle/converters.py @@ -19,7 +19,6 @@ configable_guild_defaults = { def settings_converter(user_input: str) -> dict: - if user_input.startswith("```") and user_input.endswith("```"): user_input = "\n".join(user_input.split("\n")[1:-1]) diff --git a/economytrickle/core.py b/economytrickle/core.py index 1f55de6..c83d135 100644 --- a/economytrickle/core.py +++ b/economytrickle/core.py @@ -56,7 +56,6 @@ class EconomyTrickle(commands.Cog): self.recordhandler.proccess_message(message) async def main_loop(self): - minutes = defaultdict(int) while self is self.bot.get_cog(self.__class__.__name__): @@ -74,7 +73,6 @@ class EconomyTrickle(commands.Cog): self.extra_tasks.append(tsk) async def do_rewards_for(self, guild: discord.Guild, now: datetime, data: dict): - after = now - timedelta(minutes=data["interval"], seconds=10) voice_mem = await self.config.guild(guild).min_voice_members() if data["mode"] == "blacklist": diff --git a/imagemagic/imagemagic.py b/imagemagic/imagemagic.py index b77cf0f..1340322 100644 --- a/imagemagic/imagemagic.py +++ b/imagemagic/imagemagic.py @@ -8,6 +8,7 @@ from PIL import Image as PILImage MAX_SIZE = 8 * 1024 * 1024 + # by Flame442 class ImageFindError(Exception): """Generic error for the __get_image function.""" @@ -19,9 +20,7 @@ class ImageMagic(commands.Cog): def __init__(self, bot): super().__init__() - self.config = Config.get_conf( - self, identifier=4928034571, force_registration=True - ) + self.config = Config.get_conf(self, identifier=4928034571, force_registration=True) self.bot = bot async def _get_image(self, ctx, link: str = None) -> Image: @@ -36,9 +35,7 @@ class ImageMagic(commands.Cog): if ctx.message.reference: msg = ctx.message.reference.resolved if msg is None: - msg = await ctx.channel.fetch_message( - ctx.message.reference.message_id - ) + msg = await ctx.channel.fetch_message(ctx.message.reference.message_id) if msg and msg.attachments: for a in msg.attachments: path = urllib.parse.urlparse(a.url).path @@ -66,9 +63,7 @@ class ImageMagic(commands.Cog): except: raise ImageFindError("Invalid filetype") except (OSError, aiohttp.ClientError): - raise ImageFindError( - "An image could not be found. Make sure you provide a direct link." - ) + raise ImageFindError("An image could not be found. Make sure you provide a direct link.") else: # attached image path = urllib.parse.urlparse(ctx.message.attachments[0].url).path if ctx.message.attachments[0].size > max_filesize: @@ -165,9 +160,7 @@ class ImageMagic(commands.Cog): return try: - await ctx.reply( - file=discord.File(BytesIO(img.make_blob()), name), mention_author=False - ) + await ctx.reply(file=discord.File(BytesIO(img.make_blob()), name), mention_author=False) except discord.errors.HTTPException: await ctx.reply("That image is too large.", mention_author=False) return @@ -236,9 +229,7 @@ class ImageMagic(commands.Cog): except ImageFindError as e: return await ctx.reply(e, mention_author=False) - await self._command_body( - ctx, args=(self._distortion, img, "implode", (amount * intensity,)) - ) + await self._command_body(ctx, args=(self._distortion, img, "implode", (amount * intensity,))) @distort.command() async def swirl(self, ctx, intensity: Optional[float] = 10, *, link: str = None): @@ -267,9 +258,7 @@ class ImageMagic(commands.Cog): except ImageFindError as e: return await ctx.reply(e, mention_author=False) - await self._command_body( - ctx, args=(self._distortion, img, "swirl", (intensity,)) - ) + await self._command_body(ctx, args=(self._distortion, img, "swirl", (intensity,))) @distort.command() async def charcoal(self, ctx, intensity: Optional[float], *, link: str = None): @@ -283,9 +272,7 @@ class ImageMagic(commands.Cog): except ImageFindError as e: return await ctx.reply(e, mention_author=False) - await self._command_body( - ctx, args=(self._distortion, img, "charcoal", (1.5, 0.5)) - ) + await self._command_body(ctx, args=(self._distortion, img, "charcoal", (1.5, 0.5))) @distort.command() async def sketch(self, ctx, intensity: Optional[float], *, link: str = None): @@ -299,9 +286,7 @@ class ImageMagic(commands.Cog): except ImageFindError as e: return await ctx.reply(e, mention_author=False) - await self._command_body( - ctx, args=(self._distortion, img, "sketch", (0.5, 0.0, 98.0)) - ) + await self._command_body(ctx, args=(self._distortion, img, "sketch", (0.5, 0.0, 98.0))) @distort.command() async def zoom(self, ctx, intensity: Optional[float], *, link: str = None): diff --git a/isolate/isolate.py b/isolate/isolate.py index e152d7e..9e19dfd 100644 --- a/isolate/isolate.py +++ b/isolate/isolate.py @@ -432,7 +432,6 @@ class Isolate(commands.Cog): await self.bot.request_offline_members(guild) for member_id, member_data in isolated.items(): - member = guild.get_member(member_id) if not member: @@ -859,7 +858,6 @@ class Isolate(commands.Cog): isolated = await self.config.guild(guild).ISOLATED() for member_id, data in isolated.items(): - until = data["until"] member = guild.get_member(int(member_id)) @@ -1252,7 +1250,6 @@ class Isolate(commands.Cog): await self.cancel_queue_event(member.guild.id, member.id) if apply_roles: - # readd removed roles from user, by replacing user's roles with all of their roles plus the ones that # were removed (and can be re-added), minus the isolate role user_roles = set(member.roles) diff --git a/memeify/memeify.py b/memeify/memeify.py index 987da54..7870e34 100644 --- a/memeify/memeify.py +++ b/memeify/memeify.py @@ -175,7 +175,6 @@ class Memeify(commands.Cog): text_arr = text.split(" ") for key, word in enumerate(text_arr): - if self.__compare_format(word) == "hello": text_arr[key] = "'allo 'allo" elif self.__compare_format(word) == "hi": diff --git a/moreadmin/moreadmin.py b/moreadmin/moreadmin.py index 07370d6..651188a 100644 --- a/moreadmin/moreadmin.py +++ b/moreadmin/moreadmin.py @@ -1261,7 +1261,6 @@ class MoreAdmin(commands.Cog): await channel.send(embed=data) elif sus_kick_threshold and age < sus_kick_threshold: - data = discord.Embed(title="NEW ACCOUNT KICKED", colour=member.colour) data.add_field(name="Account Age", value=parse_seconds(age)) data.add_field(name="Kick Threshold", value=parse_seconds(sus_kick_threshold)) diff --git a/moreadmin/utils.py b/moreadmin/utils.py index 0d1352b..2778b35 100644 --- a/moreadmin/utils.py +++ b/moreadmin/utils.py @@ -56,7 +56,6 @@ def parse_seconds(seconds: int) -> str: def role_from_string(guild, role_name): - role = discord.utils.find(lambda r: r.name == role_name, guild.roles) # if couldnt find by role name, try to find by role id if role is None: diff --git a/pony/pony.py b/pony/pony.py index fc0ae09..ba6a7e9 100644 --- a/pony/pony.py +++ b/pony/pony.py @@ -186,7 +186,8 @@ class Pony(commands.Cog): Leave blank to get current max filters. - Gives an error when a user tries to add a filter while the server's filter list contains a certain amount of tags""" + Gives an error when a user tries to add a filter while the server's filter list contains a certain amount of tags + """ if new_max_filters is None: max_filters = self.config.maxfilters() await ctx.send("Current filter limit: {} filters.".format(max_filters)) @@ -214,7 +215,6 @@ class Pony(commands.Cog): import_settings = json.load(raw_settings) for json_guild_id, json_guild_verbose in import_settings.items(): if json_guild_id != "maxfilters": - guild = bot.get_guild(int(json_guild_id)) if guild is None: continue @@ -234,7 +234,6 @@ class Pony(commands.Cog): msg = "Filters import successful for these guilds:\n" for json_guild_id, json_guild_filters in import_filters.items(): if json_guild_id != "default": - guild = bot.get_guild(int(json_guild_id)) # returns None if guild is not found if guild is None: continue diff --git a/punish/punish.py b/punish/punish.py index 53d35d3..334e39b 100644 --- a/punish/punish.py +++ b/punish/punish.py @@ -526,7 +526,6 @@ class Punish(commands.Cog): guild_remove_roles = set(role_memo.filter(remove_roles, skip_nulls=True)) for member_id, member_data in punished.items(): - member = guild.get_member(int(member_id)) if not member: @@ -951,7 +950,6 @@ class Punish(commands.Cog): punished = await self.config.guild(guild).PUNISHED() for member_id, data in punished.items(): - until = data["until"] member = guild.get_member(int(member_id)) @@ -1381,7 +1379,6 @@ class Punish(commands.Cog): await self.cancel_queue_event(member.guild.id, member.id) if apply_roles: - # readd removed roles from user, by replacing user's roles with all of their roles plus the ones that # were removed (and can be re-added), minus the punish role user_roles = set(member.roles) diff --git a/rolemanagement/converters.py b/rolemanagement/converters.py index c5a1da0..31a48f5 100644 --- a/rolemanagement/converters.py +++ b/rolemanagement/converters.py @@ -61,7 +61,6 @@ class ComplexActionConverter(NamedTuple): @classmethod async def convert(cls, ctx: Context, argument: str): - parser = NoExitParser(description="Role management syntax help", add_help=False) parser.add_argument("--has-any", nargs="*", dest="any", default=[]) parser.add_argument("--has-all", nargs="*", dest="all", default=[]) @@ -120,7 +119,6 @@ class ComplexActionConverter(NamedTuple): vals[attr] = await _RoleConverter.convert(ctx, vals[attr]) for attr in ("hasperm", "anyperm", "notperm"): - vals[attr] = [i.replace("_", " ").lower().replace(" ", "_").replace("server", "guild") for i in vals[attr]] if any(perm not in dir(discord.Permissions) for perm in vals[attr]): raise BadArgument("You gave an invalid permission") @@ -205,7 +203,6 @@ class ComplexSearchConverter(NamedTuple): vals[attr] = await _RoleConverter.convert(ctx, vals[attr]) for attr in ("hasperm", "anyperm", "notperm"): - vals[attr] = [i.replace("_", " ").lower().replace(" ", "_").replace("server", "guild") for i in vals[attr]] if any(perm not in dir(discord.Permissions) for perm in vals[attr]): raise BadArgument("You gave an invalid permission") diff --git a/rolemanagement/core.py b/rolemanagement/core.py index 84b5bbf..9598066 100644 --- a/rolemanagement/core.py +++ b/rolemanagement/core.py @@ -38,6 +38,7 @@ try: except ImportError: from redbot.core.commands import Context as GuildContext # type: ignore + # This previously used ``(type(commands.Cog), type(ABC))`` # This was changed to be explicit so that mypy # would be slightly happier about it. @@ -79,12 +80,8 @@ class RoleManagement( def __init__(self, bot): self.bot = bot - self.config = Config.get_conf( - self, identifier=78631113035100160, force_registration=True - ) - self.config.register_global( - handled_variation=False, handled_full_str_emoji=False - ) + self.config = Config.get_conf(self, identifier=78631113035100160, force_registration=True) + self.config.register_global(handled_variation=False, handled_full_str_emoji=False) self.config.register_role( exclusive_to={}, requires_any=[], @@ -106,9 +103,7 @@ class RoleManagement( self.config.register_custom( "REACTROLE", roleid=None, channelid=None, guildid=None ) # ID : Message.id, str(React) - self.config.register_guild( - notify_channel=None, s_roles=[], free_roles=[], join_roles=[], age_log=False - ) + self.config.register_guild(notify_channel=None, s_roles=[], free_roles=[], join_roles=[], age_log=False) self._ready = asyncio.Event() self._start_task: Optional[asyncio.Task] = None self.loop = asyncio.get_event_loop() @@ -266,9 +261,7 @@ class RoleManagement( role_data = await self.sub_helper(guild, role, role_data) - await self.config.role(role).subscribed_users.set( - role_data["subscribed_users"] - ) + await self.config.role(role).subscribed_users.set(role_data["subscribed_users"]) if len(role_data["subscribed_users"]) == 0: s_roles.remove(role_id) @@ -299,9 +292,7 @@ class RoleManagement( if dob.year == datetime.now().year: await ctx.send( - error( - f"Invalid date format, please make sure to include your birth year." - ), + error(f"Invalid date format, please make sure to include your birth year."), delete_after=30, ) return @@ -319,16 +310,13 @@ class RoleManagement( """ if not await self.all_are_valid_roles(ctx, role): - return await ctx.maybe_send_embed( - "Can't do that. Discord role heirarchy applies here." - ) + return await ctx.maybe_send_embed("Can't do that. Discord role heirarchy applies here.") if not await self.config.role(role).sticky(): return await ctx.send("This only works on sticky roles.") member = ctx.guild.get_member(user_id) if member: - try: await self.update_roles_atomically(who=member, give=[role]) except PermissionOrHierarchyException: @@ -336,10 +324,7 @@ class RoleManagement( else: await ctx.maybe_send_embed("They are in the guild...assigned anyway.") else: - - async with self.config.member_from_ids( - ctx.guild.id, user_id - ).roles() as sticky: + async with self.config.member_from_ids(ctx.guild.id, user_id).roles() as sticky: if role.id not in sticky: sticky.append(role.id) @@ -400,9 +385,7 @@ class RoleManagement( """ if not await self.all_are_valid_roles(ctx, role): - return await ctx.maybe_send_embed( - "Can't do that. Discord role heirarchy applies here." - ) + return await ctx.maybe_send_embed("Can't do that. Discord role heirarchy applies here.") try: message = await channel.fetch_message(msgid) @@ -427,9 +410,7 @@ class RoleManagement( try: await message.add_reaction(_emoji) except discord.HTTPException: - return await ctx.maybe_send_embed( - "Hmm, that message couldn't be reacted to" - ) + return await ctx.maybe_send_embed("Hmm, that message couldn't be reacted to") cfg = self.config.custom("REACTROLE", str(message.id), eid) await cfg.set( @@ -449,21 +430,15 @@ class RoleManagement( @commands.bot_has_permissions(manage_roles=True) @checks.admin_or_permissions(manage_guild=True) @commands.command(name="roleunbind") - async def unbind_role_from_reactions( - self, ctx: commands.Context, role: discord.Role, msgid: int, emoji: str - ): + async def unbind_role_from_reactions(self, ctx: commands.Context, role: discord.Role, msgid: int, emoji: str): """ unbinds a role from a reaction on a message """ if not await self.all_are_valid_roles(ctx, role): - return await ctx.maybe_send_embed( - "Can't do that. Discord role heirarchy applies here." - ) + return await ctx.maybe_send_embed("Can't do that. Discord role heirarchy applies here.") - await self.config.custom( - "REACTROLE", f"{msgid}", self.strip_variations(emoji) - ).clear() + await self.config.custom("REACTROLE", f"{msgid}", self.strip_variations(emoji)).clear() await ctx.tick() @commands.guild_only() @@ -504,9 +479,7 @@ class RoleManagement( await ctx.tick() @rgroup.command(name="addwith") - async def rg_addwith( - self, ctx: GuildContext, add_role: discord.Role, *roles: discord.Role - ): + async def rg_addwith(self, ctx: GuildContext, add_role: discord.Role, *roles: discord.Role): """ Sets a list of roles to add to a user when they receive the role specifed by `add_role` @@ -538,12 +511,7 @@ class RoleManagement( use_embeds = await ctx.embed_requested() react_roles = "\n".join( - [ - msg - async for msg in self.build_messages_for_react_roles( - *ctx.guild.roles, use_embeds=use_embeds - ) - ] + [msg async for msg in self.build_messages_for_react_roles(*ctx.guild.roles, use_embeds=use_embeds)] ) if not react_roles: @@ -554,9 +522,7 @@ class RoleManagement( color = await ctx.embed_colour() if use_embeds else None - for page in pagify( - react_roles, escape_mass_mentions=False, page_length=1800, shorten_by=0 - ): + for page in pagify(react_roles, escape_mass_mentions=False, page_length=1800, shorten_by=0): # unrolling iterative calling of ctx.maybe_send_embed if use_embeds: await ctx.send(embed=discord.Embed(description=page, color=color)) @@ -564,9 +530,7 @@ class RoleManagement( await ctx.send(page) @rgroup.command(name="dm-message") - async def rg_dm_message( - self, ctx: GuildContext, role: discord.Role, *, msg: str = None - ): + async def rg_dm_message(self, ctx: GuildContext, role: discord.Role, *, msg: str = None): """ Set message to DM to user when they obtain the role. Will send it in the channel they ran the command if DM fails to send. @@ -632,9 +596,7 @@ class RoleManagement( return roles = [ctx.guild.get_role(role) for role in roles] missing = len([role for role in roles if role is None]) - roles = [ - f"{i+1}.{role.name}" for i, role in enumerate(roles) if role is not None - ] + roles = [f"{i+1}.{role.name}" for i, role in enumerate(roles) if role is not None] msg = "\n".join(sorted(roles)) msg = pagify(msg) @@ -655,19 +617,13 @@ class RoleManagement( f"\n{'is' if rsets['sticky'] else 'is not'} sticky." ) if rsets["requires_any"]: - rstring = ", ".join( - r.name for r in ctx.guild.roles if r.id in rsets["requires_any"] - ) + rstring = ", ".join(r.name for r in ctx.guild.roles if r.id in rsets["requires_any"]) output += f"\nThis role requires any of the following roles: {rstring}" if rsets["requires_all"]: - rstring = ", ".join( - r.name for r in ctx.guild.roles if r.id in rsets["requires_all"] - ) + rstring = ", ".join(r.name for r in ctx.guild.roles if r.id in rsets["requires_all"]) output += f"\nThis role requires all of the following roles: {rstring}" if rsets["add_with"]: - rstring = ", ".join( - r.name for r in ctx.guild.roles if r.id in rsets["add_with"] - ) + rstring = ", ".join(r.name for r in ctx.guild.roles if r.id in rsets["add_with"]) output += f"\nThis role when added will also be added with the following roles: {rstring}" if rsets["exclusive_to"]: rstring = "" @@ -699,9 +655,7 @@ class RoleManagement( await ctx.send(page) @rgroup.command(name="cost") - async def make_purchasable( - self, ctx: GuildContext, cost: int, *, role: discord.Role - ): + async def make_purchasable(self, ctx: GuildContext, cost: int, *, role: discord.Role): """ Makes a role purchasable for a specified cost. Cost must be a number greater than 0. @@ -714,9 +668,7 @@ class RoleManagement( """ if not await self.all_are_valid_roles(ctx, role): - return await ctx.maybe_send_embed( - "Can't do that. Discord role heirarchy applies here." - ) + return await ctx.maybe_send_embed("Can't do that. Discord role heirarchy applies here.") if cost < 0: return await ctx.send_help() @@ -744,9 +696,7 @@ class RoleManagement( (etc) """ if not await self.all_are_valid_roles(ctx, role): - return await ctx.maybe_send_embed( - "Can't do that. Discord role heirarchy applies here." - ) + return await ctx.maybe_send_embed("Can't do that. Discord role heirarchy applies here.") role_cost = await self.config.role(role).cost() if role_cost == 0: @@ -769,9 +719,7 @@ class RoleManagement( await ctx.send(f"Subscription set to {parse_seconds(time.total_seconds())}.") @rgroup.command(name="forbid") - async def forbid_role( - self, ctx: GuildContext, role: discord.Role, *, user: discord.Member - ): + async def forbid_role(self, ctx: GuildContext, role: discord.Role, *, user: discord.Member): """ Forbids a user from gaining a specific role. """ @@ -783,9 +731,7 @@ class RoleManagement( await ctx.tick() @rgroup.command(name="unforbid") - async def unforbid_role( - self, ctx: GuildContext, role: discord.Role, *, user: discord.Member - ): + async def unforbid_role(self, ctx: GuildContext, role: discord.Role, *, user: discord.Member): """ Unforbids a user from gaining a specific role. """ @@ -797,9 +743,7 @@ class RoleManagement( await ctx.tick() @rgroup.command(name="exclusive") - async def set_exclusivity( - self, ctx: GuildContext, group: str, *roles: discord.Role - ): + async def set_exclusivity(self, ctx: GuildContext, group: str, *roles: discord.Role): """ Set exclusive roles for group Takes 2 or more roles and sets them as exclusive to eachother @@ -817,16 +761,12 @@ class RoleManagement( async with self.config.role(role).exclusive_to() as ex_list: if group not in ex_list.keys(): ex_list[group] = [] - ex_list[group].extend( - [r.id for r in _roles if r != role and r.id not in ex_list[group]] - ) + ex_list[group].extend([r.id for r in _roles if r != role and r.id not in ex_list[group]]) await ctx.tick() @rgroup.command(name="unexclusive") - async def unset_exclusivity( - self, ctx: GuildContext, group: str, *roles: discord.Role - ): + async def unset_exclusivity(self, ctx: GuildContext, group: str, *roles: discord.Role): """ Remove exclusive roles for group Takes any number of roles, and removes their exclusivity settings @@ -844,29 +784,21 @@ class RoleManagement( ex_list = await self.config.role(role).exclusive_to() if group not in ex_list.keys(): continue - ex_list[group] = [ - idx for idx in ex_list if idx not in [r.id for r in _roles] - ] + ex_list[group] = [idx for idx in ex_list if idx not in [r.id for r in _roles]] if not ex_list[group]: del ex_list[group] await self.config.role(role).exclusive_to.set(ex_list) await ctx.tick() @rgroup.command(name="sticky") - async def setsticky( - self, ctx: GuildContext, role: discord.Role, sticky: bool = None - ): + async def setsticky(self, ctx: GuildContext, role: discord.Role, sticky: bool = None): """ sets a role as sticky if used without a settings, gets the current ones """ if sticky is None: is_sticky = await self.config.role(role).sticky() - return await ctx.send( - "{role} {verb} sticky".format( - role=role.name, verb=("is" if is_sticky else "is not") - ) - ) + return await ctx.send("{role} {verb} sticky".format(role=role.name, verb=("is" if is_sticky else "is not"))) await self.config.role(role).sticky.set(sticky) if sticky: @@ -902,9 +834,7 @@ class RoleManagement( await ctx.tick() @rgroup.command(name="selfrem") - async def selfrem( - self, ctx: GuildContext, role: discord.Role, removable: bool = None - ): + async def selfrem(self, ctx: GuildContext, role: discord.Role, removable: bool = None): """ Sets if a role is self-removable (default False) @@ -914,18 +844,14 @@ class RoleManagement( if removable is None: is_removable = await self.config.role(role).self_removable() return await ctx.send( - "{role} {verb} self-removable".format( - role=role.name, verb=("is" if is_removable else "is not") - ) + "{role} {verb} self-removable".format(role=role.name, verb=("is" if is_removable else "is not")) ) await self.config.role(role).self_removable.set(removable) await ctx.tick() @rgroup.command(name="selfadd") - async def selfadd( - self, ctx: GuildContext, role: discord.Role, assignable: bool = None - ): + async def selfadd(self, ctx: GuildContext, role: discord.Role, assignable: bool = None): """ Sets if a role is self-assignable via command @@ -937,9 +863,7 @@ class RoleManagement( if assignable is None: is_assignable = await self.config.role(role).self_role() return await ctx.send( - "{role} {verb} self-assignable".format( - role=role.name, verb=("is" if is_assignable else "is not") - ) + "{role} {verb} self-assignable".format(role=role.name, verb=("is" if is_assignable else "is not")) ) await self.config.role(role).self_role.set(assignable) @@ -988,9 +912,7 @@ class RoleManagement( return roles = [ctx.guild.get_role(role) for role in roles] missing = len([role for role in roles if role is None]) - roles = [ - f"{i+1}.{role.name}" for i, role in enumerate(roles) if role is not None - ] + roles = [f"{i+1}.{role.name}" for i, role in enumerate(roles) if role is not None] msg = "\n".join(sorted(roles)) msg = pagify(msg) @@ -1035,9 +957,7 @@ class RoleManagement( embed = discord.Embed(title="Roles", colour=ctx.guild.me.colour) embed.set_footer(text="You can only have one role in the same unique group!") i = 0 - for role, (cost, sub, ex_groups) in sorted( - data.items(), key=lambda kv: kv[1][0] - ): + for role, (cost, sub, ex_groups) in sorted(data.items(), key=lambda kv: kv[1][0]): if ex_groups: groups = humanize_list(list(ex_groups.keys())) else: @@ -1073,9 +993,7 @@ class RoleManagement( cost = await self.config.role(role).cost() subscription = await self.config.role(role).subscription() except PermissionOrHierarchyException: - await ctx.send( - "I cannot assign roles which I can not manage. (Discord Hierarchy)" - ) + await ctx.send("I cannot assign roles which I can not manage. (Discord Hierarchy)") except MissingRequirementsException as e: msg = "" if e.miss_all: @@ -1093,14 +1011,10 @@ class RoleManagement( ) else: if not eligible: - return await ctx.send( - f"You aren't allowed to add `{role}` to yourself {ctx.author.mention}!" - ) + return await ctx.send(f"You aren't allowed to add `{role}` to yourself {ctx.author.mention}!") if not cost: - return await ctx.send( - "This role doesn't have a cost. Please try again using `[p]selfrole add`." - ) + return await ctx.send("This role doesn't have a cost. Please try again using `[p]selfrole add`.") if not await self.verify_age(role, ctx=ctx): return await ctx.send( @@ -1111,9 +1025,7 @@ class RoleManagement( currency_name = await bank.get_currency_name(ctx.guild) for m_role in ctx.author.roles: if m_role.id in free_roles: - await ctx.send( - f"You're special, no {currency_name} will be deducted from your account." - ) + await ctx.send(f"You're special, no {currency_name} will be deducted from your account.") cost = 0 # await self.update_roles_atomically(who=ctx.author, give=[role], remove=remove) # await ctx.tick() @@ -1123,15 +1035,11 @@ class RoleManagement( if cost > 0: await bank.withdraw_credits(ctx.author, cost) except ValueError: - return await ctx.send( - f"You don't have enough {currency_name} (Cost: {cost} {currency_name})" - ) + return await ctx.send(f"You don't have enough {currency_name} (Cost: {cost} {currency_name})") else: if subscription > 0: if cost > 0: - await ctx.send( - f"{role.name} will be renewed every {parse_seconds(subscription)}" - ) + await ctx.send(f"{role.name} will be renewed every {parse_seconds(subscription)}") async with self.config.role(role).subscribed_users() as s: s[str(ctx.author.id)] = time.time() + subscription async with self.config.guild(ctx.guild).s_roles() as s: @@ -1143,9 +1051,7 @@ class RoleManagement( await ctx.send( f"Removed `{humanize_list([r.name for r in remove])}` role{plural} since they are exclusive to the role you added." ) - await self.update_roles_atomically( - who=ctx.author, give=[role], remove=remove - ) + await self.update_roles_atomically(who=ctx.author, give=[role], remove=remove) await self.dm_user(ctx, role) await ctx.tick() @@ -1162,9 +1068,7 @@ class RoleManagement( eligible = await self.config.role(role).self_role() cost = await self.config.role(role).cost() except PermissionOrHierarchyException: - await ctx.send( - "I cannot assign roles which I can not manage. (Discord Hierarchy)" - ) + await ctx.send("I cannot assign roles which I can not manage. (Discord Hierarchy)") except MissingRequirementsException as e: msg = "" if e.miss_all: @@ -1182,9 +1086,7 @@ class RoleManagement( ) else: if not eligible: - await ctx.send( - f"You aren't allowed to add `{role}` to yourself {ctx.author.mention}!" - ) + await ctx.send(f"You aren't allowed to add `{role}` to yourself {ctx.author.mention}!") elif not await self.verify_age(role, ctx=ctx): return await ctx.send( @@ -1193,8 +1095,7 @@ class RoleManagement( elif cost: await ctx.send( - "This role is not free. " - "Please use `[p]selfrole buy` if you would like to purchase it." + "This role is not free. " "Please use `[p]selfrole buy` if you would like to purchase it." ) else: if remove: @@ -1202,9 +1103,7 @@ class RoleManagement( await ctx.send( f"Removed `{humanize_list([r.name for r in remove])}` role{plural} since they are exclusive to the role you added." ) - await self.update_roles_atomically( - who=ctx.author, give=[role], remove=remove - ) + await self.update_roles_atomically(who=ctx.author, give=[role], remove=remove) await self.dm_user(ctx, role) await ctx.tick() @@ -1225,15 +1124,11 @@ class RoleManagement( pass await ctx.tick() else: - await ctx.send( - f"You aren't allowed to remove `{role}` from yourself {ctx.author.mention}!`" - ) + await ctx.send(f"You aren't allowed to remove `{role}` from yourself {ctx.author.mention}!`") # Stuff for clean interaction with react role entries - async def build_messages_for_react_roles( - self, *roles: discord.Role, use_embeds=True - ) -> AsyncIterator[str]: + async def build_messages_for_react_roles(self, *roles: discord.Role, use_embeds=True) -> AsyncIterator[str]: """ Builds info. @@ -1249,7 +1144,6 @@ class RoleManagement( for role in roles: # pylint: disable=E1133 async for message_id, emoji_info, data in self.get_react_role_entries(role): - channel_id = data.get("channelid", None) if channel_id: link = linkfmt.format( @@ -1259,15 +1153,13 @@ class RoleManagement( ) else: link = ( - f"unknown message with id {message_id}" - f" (use `roleset fixup` to find missing data for this)" + f"unknown message with id {message_id}" f" (use `roleset fixup` to find missing data for this)" ) emoji: Union[discord.Emoji, str] if emoji_info.isdigit(): emoji = ( - discord.utils.get(self.bot.emojis, id=int(emoji_info)) - or f"A custom enoji with id {emoji_info}" + discord.utils.get(self.bot.emojis, id=int(emoji_info)) or f"A custom enoji with id {emoji_info}" ) else: emoji = emoji_info @@ -1312,9 +1204,7 @@ class RoleManagement( if ctx is not None: await ctx.send( - info( - "Please check your DMs with me in order to continue getting this role!" - ), + info("Please check your DMs with me in order to continue getting this role!"), delete_after=30, ) @@ -1330,9 +1220,7 @@ class RoleManagement( return False except asyncio.TimeoutError: await member.send( - error( - f"Took too long, the {role} role has not been added to you in {guild}!\nPlease try again." - ), + error(f"Took too long, the {role} role has not been added to you in {guild}!\nPlease try again."), delete_after=30, ) return False @@ -1341,9 +1229,7 @@ class RoleManagement( dob = parser.parse(msg.content.strip()) except: await member.send( - error( - f"Invalid date format, the {role} role has not been added to you in {guild}!\nPlease try again." - ), + error(f"Invalid date format, the {role} role has not been added to you in {guild}!\nPlease try again."), delete_after=30, ) return False @@ -1403,9 +1289,7 @@ class RoleManagement( ) await ctx.send(dm_msg) - async def get_react_role_entries( - self, role: discord.Role - ) -> AsyncIterator[Tuple[str, str, dict]]: + async def get_react_role_entries(self, role: discord.Role) -> AsyncIterator[Tuple[str, str, dict]]: """ yields: str, str, dict diff --git a/rolemanagement/events.py b/rolemanagement/events.py index 72a1752..1f99121 100644 --- a/rolemanagement/events.py +++ b/rolemanagement/events.py @@ -68,9 +68,7 @@ class EventMixin(MixinMeta): for r in gained: add_with = await self.config.role_from_id(r).add_with() if add_with: - to_add = [ - discord.utils.get(after.guild.roles, id=add) for add in add_with - ] + to_add = [discord.utils.get(after.guild.roles, id=add) for add in add_with] await after.add_roles(*to_add, reason=f"add with role {r}") for r in sym_diff: @@ -119,9 +117,7 @@ class EventMixin(MixinMeta): await member.add_roles(*to_add) @commands.Cog.listener() - async def on_raw_reaction_add( - self, payload: discord.raw_models.RawReactionActionEvent - ): + async def on_raw_reaction_add(self, payload: discord.raw_models.RawReactionActionEvent): await self.wait_for_ready() if not payload.guild_id: return @@ -180,9 +176,7 @@ class EventMixin(MixinMeta): await self.update_roles_atomically(who=member, give=[role], remove=remove) @commands.Cog.listener() - async def on_raw_reaction_remove( - self, payload: discord.raw_models.RawReactionActionEvent - ): + async def on_raw_reaction_remove(self, payload: discord.raw_models.RawReactionActionEvent): await self.wait_for_ready() if not payload.guild_id: return diff --git a/rolemanagement/massmanager.py b/rolemanagement/massmanager.py index e57916d..cb811d0 100644 --- a/rolemanagement/massmanager.py +++ b/rolemanagement/massmanager.py @@ -221,7 +221,6 @@ class MassManagementMixin(MixinMeta): chunks = [members[i : (i + chunk_size)] for i in range(0, len(members), chunk_size)] for part, chunk in enumerate(chunks, 1): - csvf = io.StringIO() fieldnames = [ "ID", diff --git a/scheduler/checks.py b/scheduler/checks.py index e90bc8c..daf91dd 100644 --- a/scheduler/checks.py +++ b/scheduler/checks.py @@ -5,7 +5,6 @@ from redbot.core import commands def can_run_command(command_name: str): async def predicate(ctx): - command = ctx.bot.get_command(command_name) if not command: return False diff --git a/scheduler/converters.py b/scheduler/converters.py index 0d92ace..b8c93fb 100644 --- a/scheduler/converters.py +++ b/scheduler/converters.py @@ -37,7 +37,6 @@ class Schedule: @classmethod async def convert(cls, ctx: Context, argument: str): - start: datetime command: Optional[str] = None recur: Optional[timedelta] = None @@ -100,7 +99,6 @@ class TempMute(NamedTuple): @classmethod async def convert(cls, ctx: Context, argument: str): - start: datetime reason: str diff --git a/scheduler/scheduler.py b/scheduler/scheduler.py index 7176cec..4082219 100644 --- a/scheduler/scheduler.py +++ b/scheduler/scheduler.py @@ -325,7 +325,6 @@ class Scheduler(commands.Cog): return [t for t in self.tasks if pred(t)] async def fetch_tasks_by_guild(self, guild: discord.Guild) -> List[Task]: - async with self._iter_lock: return [t for t in self.tasks if t.channel in guild.text_channels] @@ -472,7 +471,6 @@ class Scheduler(commands.Cog): tasks: List[Task], message: Optional[discord.Message] = None, ): - color = await ctx.embed_color() async def task_killer( diff --git a/scheduler/tasks.py b/scheduler/tasks.py index acbc606..3126d45 100644 --- a/scheduler/tasks.py +++ b/scheduler/tasks.py @@ -30,13 +30,11 @@ class Task: return hash(self.uid) async def get_message(self, bot): - pfx = (await bot.get_prefix(self.channel))[0] content = f"{pfx}{self.content}" return SchedulerMessage(content=content, author=self.author, channel=self.channel) def to_config(self): - return { self.uid: { "nicename": self.nicename, @@ -51,7 +49,6 @@ class Task: @classmethod def bulk_from_config(cls, bot: discord.Client, **entries): - for uid, data in entries.items(): cid = data.pop("channel", 0) aid = data.pop("author", 0) @@ -80,7 +77,6 @@ class Task: @property def next_call_delay(self) -> float: - now = datetime.now(timezone.utc) if self.recur and now >= self.initial: @@ -90,7 +86,6 @@ class Task: return (self.initial - now).total_seconds() def to_embed(self, index: int, page_count: int, color: discord.Color): - now = datetime.now(timezone.utc) next_run_at = now + timedelta(seconds=self.next_call_delay) embed = discord.Embed(color=color, timestamp=next_run_at) diff --git a/sfx/utils.py b/sfx/utils.py index 7a5638f..0a63282 100644 --- a/sfx/utils.py +++ b/sfx/utils.py @@ -1,6 +1,7 @@ import inspect from pathlib import Path + # defines a saysound dictionary def saysound(name: str, added_by: str, cost: int = 0, volume: int = 100, url: str = None, filepath: str = None) -> dict: saysound = {"name": name, "added_by": added_by, "cost": cost, "volume": volume, "url": url, "filepath": filepath} diff --git a/suggestion/suggestion.py b/suggestion/suggestion.py index 893b894..c72e9b2 100644 --- a/suggestion/suggestion.py +++ b/suggestion/suggestion.py @@ -645,7 +645,8 @@ class Suggestion(commands.Cog): async def setglobal(self, ctx: commands.Context): """Global suggestions settings. - There is nothing like approved or rejected channels because global suggestions are meant to be for the bot only and will only work if it is sent in a server where normal suggestions are disabled.""" + There is nothing like approved or rejected channels because global suggestions are meant to be for the bot only and will only work if it is sent in a server where normal suggestions are disabled. + """ pass @setglobal.command(name="toggle")