diff --git a/cogs/afk/afk.py b/cogs/afk/afk.py index e11d0491..37403148 100644 --- a/cogs/afk/afk.py +++ b/cogs/afk/afk.py @@ -83,7 +83,13 @@ async def _global(self, ctx: Context, *, text: Annotated[str, commands.clean_con self.bot.afk_users.add(ctx.author.id) @afk.command(name="for") - async def afk_till(self, ctx: Context, till: ShortTime, *, text: Annotated[str, commands.clean_content] = "AFK"): + async def afk_till( + self, + ctx: Context, + till: ShortTime, + *, + text: Annotated[str, commands.clean_content] = "AFK", + ): """To set the AFK time.""" if till.dt.timestamp() - ctx.message.created_at.timestamp() <= 120: return await ctx.send(f"{ctx.author.mention} time must be above 120s") @@ -106,7 +112,13 @@ async def afk_till(self, ctx: Context, till: ShortTime, *, text: Annotated[str, ) @afk.command(name="after") - async def afk_after(self, ctx: Context, after: ShortTime, *, text: Annotated[str, commands.clean_content] = "AFK"): + async def afk_after( + self, + ctx: Context, + after: ShortTime, + *, + text: Annotated[str, commands.clean_content] = "AFK", + ): """To set the AFK future time.""" if after.dt.timestamp() - ctx.message.created_at.timestamp() <= 120: return await ctx.send(f"{ctx.author.mention} time must be above 120s") diff --git a/cogs/automod/__init__.py b/cogs/automod/__init__.py index 66c566b6..a259ef2b 100644 --- a/cogs/automod/__init__.py +++ b/cogs/automod/__init__.py @@ -244,7 +244,15 @@ async def automod_add(self, ctx: Context, *, rule: str) -> None: await self.bot.automod_configurations.update_one( {"guild_id": ctx.guild.id}, - {"$set": {rule: {"trigger": view.triggers, "condition": view.conditions, "action": view.actions}}}, + { + "$set": { + rule: { + "trigger": view.triggers, + "condition": view.conditions, + "action": view.actions, + } + } + }, upsert=True, ) await self.refresh_cache_specific(ctx.guild.id) @@ -269,7 +277,15 @@ async def automod_edit(self, ctx: Context, *, rule: str) -> None: await self.bot.automod_configurations.update_one( {"guild_id": ctx.guild.id}, - {"$set": {rule: {"trigger": view.triggers, "condition": view.conditions, "action": view.actions}}}, + { + "$set": { + rule: { + "trigger": view.triggers, + "condition": view.conditions, + "action": view.actions, + } + } + }, ) await self.refresh_cache_specific(ctx.guild.id) await ctx.reply(f"Rule `{rule}` has been updated.") diff --git a/cogs/automod/parsers/action.py b/cogs/automod/parsers/action.py index d0bbc222..69cbac30 100644 --- a/cogs/automod/parsers/action.py +++ b/cogs/automod/parsers/action.py @@ -53,7 +53,7 @@ async def warn( "warning_name": warning_name, "reason": reason, "moderator_id": moderator_id, - "expires_at": expires_at.timestamp() if expires_at is not None else None, + "expires_at": (expires_at.timestamp() if expires_at is not None else None), }, }, } @@ -100,7 +100,10 @@ async def count_during(self, *, before: datetime | None = None, after: datetime) query = { "guild_id": self.guild_id, - "warnings.timestamp": {"$gte": after.timestamp(), "$lte": before.timestamp()}, + "warnings.timestamp": { + "$gte": after.timestamp(), + "$lte": before.timestamp(), + }, } return await self.bot.automod_voilations.count_documents(query) diff --git a/cogs/autoresponder/__init__.py b/cogs/autoresponder/__init__.py index 65a735c3..9b53e31b 100644 --- a/cogs/autoresponder/__init__.py +++ b/cogs/autoresponder/__init__.py @@ -395,12 +395,21 @@ async def execute_jinja( template = await asyncio.to_thread(self.jinja_env.from_string, response) return_data = await template.render_async(**variables) if len(return_data) > 1990: - return f"Gave up executing {executing_what} - `{trigger}`.\nReason: `Response is too long`", True + return ( + f"Gave up executing {executing_what} - `{trigger}`.\nReason: `Response is too long`", + True, + ) return return_data, False except Exception as e: - return f"Gave up executing {executing_what}.\nReason: `{e.__class__.__name__}: {e}`", True + return ( + f"Gave up executing {executing_what}.\nReason: `{e.__class__.__name__}: {e}`", + True, + ) except Exception as e: - return f"Gave up executing {executing_what} - `{trigger}`.\nReason: `{e.__class__.__name__}: {e}`", True + return ( + f"Gave up executing {executing_what} - `{trigger}`.\nReason: `{e.__class__.__name__}: {e}`", + True, + ) @commands.command(name="jinja", aliases=["j2", "jinja2"]) async def jinja(self, ctx: Context, *, code: str) -> None: diff --git a/cogs/autoresponder/variables/guild.py b/cogs/autoresponder/variables/guild.py index fbe9b30f..ae9461a2 100644 --- a/cogs/autoresponder/variables/guild.py +++ b/cogs/autoresponder/variables/guild.py @@ -121,7 +121,13 @@ async def _check_perms(self, **perms: bool) -> bool: permissions = discord.Permissions(**perms) return self.__guild.me.guild_permissions >= permissions - async def ban(self, member: JinjaMember, *, reason: str = None, delete_message_days: int = discord.utils.MISSING): + async def ban( + self, + member: JinjaMember, + *, + reason: str = None, + delete_message_days: int = discord.utils.MISSING, + ): """Ban member from guild.""" if not await self._check_perms(ban_members=True): return diff --git a/cogs/config/config.py b/cogs/config/config.py index a4a2c876..42810aa9 100644 --- a/cogs/config/config.py +++ b/cogs/config/config.py @@ -452,7 +452,7 @@ async def tel_config_block(self, ctx: Context, *, server: discord.Guild | int): await self.bot.guild_configurations.update_one( {"_id": ctx.guild.id}, - {"$addToSet": {"telephone.blocked": server.id if isinstance(server, discord.Guild) else server}}, + {"$addToSet": {"telephone.blocked": (server.id if isinstance(server, discord.Guild) else server)}}, upsert=True, ) await ctx.reply(f"{ctx.author.mention} success! blocked: **{server.name}**") @@ -487,7 +487,7 @@ async def enable( ctx: Context, command: Annotated[str, commands.clean_content], *, - target: discord.TextChannel | discord.VoiceChannel | discord.Thread | discord.Role | None = None, + target: (discord.TextChannel | discord.VoiceChannel | discord.Thread | discord.Role | None) = None, ): """To enable the command.""" cmd = self.bot.get_command(command) @@ -509,7 +509,7 @@ async def disable( ctx: Context, command: Annotated[str, commands.clean_content], *, - target: discord.TextChannel | discord.VoiceChannel | discord.Thread | discord.Role | None = None, + target: (discord.TextChannel | discord.VoiceChannel | discord.Thread | discord.Role | None) = None, ): """To disable the command.""" cmd = self.bot.get_command(command) @@ -545,42 +545,50 @@ async def cmd_config_list(self, ctx: Context, *, cmd: str): ) .add_field( name="Role Enable", - value="<@&" + ">, <@&".join(data.get(CMD_ROLE_ENABLE_, [0])) + ">" if data.get(CMD_ROLE_ENABLE_) else "N/A", + value=( + "<@&" + ">, <@&".join(data.get(CMD_ROLE_ENABLE_, [0])) + ">" if data.get(CMD_ROLE_ENABLE_) else "N/A" + ), inline=False, ) .add_field( name="Role Disable", - value="<@&" + ">, <@&".join(data.get(CMD_ROLE_DISABLE_, [0])) + ">" - if data.get(CMD_ROLE_DISABLE_) - else "N/A", + value=( + "<@&" + ">, <@&".join(data.get(CMD_ROLE_DISABLE_, [0])) + ">" if data.get(CMD_ROLE_DISABLE_) else "N/A" + ), inline=False, ) .add_field( name="Channel Enable", - value="<#" + ">, <#".join(data.get(CMD_CHANNEL_ENABLE_, [0])) + ">" - if data.get(CMD_CHANNEL_ENABLE_) - else "N/A", + value=( + "<#" + ">, <#".join(data.get(CMD_CHANNEL_ENABLE_, [0])) + ">" if data.get(CMD_CHANNEL_ENABLE_) else "N/A" + ), inline=False, ) .add_field( name="Channel Disable", - value="<#" + ">, <#".join(data.get(CMD_CHANNEL_DISABLE_, [0])) + ">" - if data.get(CMD_CHANNEL_DISABLE_) - else "N/A", + value=( + "<#" + ">, <#".join(data.get(CMD_CHANNEL_DISABLE_, [0])) + ">" + if data.get(CMD_CHANNEL_DISABLE_) + else "N/A" + ), inline=False, ) .add_field( name="Category Enable", - value="<#" + ">, <#".join(data.get(CMD_CATEGORY_ENABLE_, [0])) + ">" - if data.get(CMD_CATEGORY_ENABLE_) - else "N/A", + value=( + "<#" + ">, <#".join(data.get(CMD_CATEGORY_ENABLE_, [0])) + ">" + if data.get(CMD_CATEGORY_ENABLE_) + else "N/A" + ), inline=False, ) .add_field( name="Category Disable", - value="<#" + ">, <#".join(data.get(CMD_CATEGORY_DISABLE_, [0])) + ">" - if data.get(CMD_CATEGORY_DISABLE_) - else "N/A", + value=( + "<#" + ">, <#".join(data.get(CMD_CATEGORY_DISABLE_, [0])) + ">" + if data.get(CMD_CATEGORY_DISABLE_) + else "N/A" + ), inline=False, ) .add_field( @@ -760,9 +768,11 @@ def check(m: discord.Message) -> bool: await self.bot.guild_configurations.update_one( {"_id": ctx.guild.id}, { - OP: {f"stats_channels.{k}": v for k, v in PAYLOAD.items()} - if counter != "role" - else {"stats_channels.role": PAYLOAD_R}, + OP: ( + {f"stats_channels.{k}": v for k, v in PAYLOAD.items()} + if counter != "role" + else {"stats_channels.role": PAYLOAD_R} + ), }, upsert=True, ) diff --git a/cogs/config/method.py b/cogs/config/method.py index 3376588d..f1f9dcb3 100644 --- a/cogs/config/method.py +++ b/cogs/config/method.py @@ -44,7 +44,13 @@ async def _enable( await update_db(ctx=ctx, key="CMD_GLOBAL_ENABLE", cmd=cmd_cog, value=True, op="$set") elif isinstance(target, discord.TextChannel): - await update_db(ctx=ctx, key="CMD_CHANNEL_DISABLE", cmd=cmd_cog, value=ctx.channel.id, op="$pull") + await update_db( + ctx=ctx, + key="CMD_CHANNEL_DISABLE", + cmd=cmd_cog, + value=ctx.channel.id, + op="$pull", + ) elif isinstance(target, discord.Role): await update_db(ctx=ctx, key="CMD_ROLE_DISABLE", cmd=cmd_cog, value=target.id, op="$pull") @@ -61,9 +67,21 @@ async def _disable( await update_db(ctx=ctx, key="CMD_GLOBAL_ENABLE", cmd=cmd_cog, value=False, op="$set") elif isinstance(target, discord.TextChannel): - await update_db(ctx=ctx, key="CMD_CHANNEL_DISABLE", cmd=cmd_cog, value=ctx.channel.id, op="$addToSet") + await update_db( + ctx=ctx, + key="CMD_CHANNEL_DISABLE", + cmd=cmd_cog, + value=ctx.channel.id, + op="$addToSet", + ) elif isinstance(target, discord.Role): - await update_db(ctx=ctx, key="CMD_ROLE_DISABLE", cmd=cmd_cog, value=target.id, op="$addToSet") + await update_db( + ctx=ctx, + key="CMD_ROLE_DISABLE", + cmd=cmd_cog, + value=target.id, + op="$addToSet", + ) await ctx.send(get_text(ctx=ctx, cmd_cog=cmd_cog, target=target, tp="disable")) diff --git a/cogs/defcon/defcon.py b/cogs/defcon/defcon.py index b6bb5b15..8dee4ec8 100644 --- a/cogs/defcon/defcon.py +++ b/cogs/defcon/defcon.py @@ -110,7 +110,11 @@ async def defcon_set(self, ctx: Context, level: int) -> None: ) channel_hidded.append(channel.id) except discord.Forbidden: - log.warning("failed to hide channel %s in guild %s", channel.id, ctx.guild.id) + log.warning( + "failed to hide channel %s in guild %s", + channel.id, + ctx.guild.id, + ) if channel_hidded: await self.bot.guild_configurations.update_one( @@ -134,7 +138,11 @@ async def defcon_set(self, ctx: Context, level: int) -> None: ) channel_locked.append(channel.id) except discord.Forbidden: - log.warning("failed to lock channel %s in guild %s", channel.id, ctx.guild.id) + log.warning( + "failed to lock channel %s in guild %s", + channel.id, + ctx.guild.id, + ) if settings.get("LOCK_TEXT_CHANNELS"): for channel in ctx.guild.text_channels: @@ -150,7 +158,11 @@ async def defcon_set(self, ctx: Context, level: int) -> None: ) channel_locked.append(channel.id) except discord.Forbidden: - log.warning("failed to lock channel %s in guild %s", channel.id, ctx.guild.id) + log.warning( + "failed to lock channel %s in guild %s", + channel.id, + ctx.guild.id, + ) if channel_locked: await self.bot.guild_configurations.update_one( @@ -171,7 +183,11 @@ async def defcon_set(self, ctx: Context, level: int) -> None: ) count += 1 except discord.Forbidden: - log.warning("failed to set slowmode in channel %s in guild %s", channel.id, ctx.guild.id) + log.warning( + "failed to set slowmode in channel %s in guild %s", + channel.id, + ctx.guild.id, + ) cog: DefconListeners = self.bot.DefconListeners if cog: @@ -211,7 +227,11 @@ async def defcon_reset(self, ctx: Context, level: int) -> None: ) except discord.Forbidden: - log.warning("failed to reset channel %s in guild %s", channel.id, ctx.guild.id) + log.warning( + "failed to reset channel %s in guild %s", + channel.id, + ctx.guild.id, + ) count = 0 if settings.get("LOCK_VOICE_CHANNELS"): @@ -228,7 +248,11 @@ async def defcon_reset(self, ctx: Context, level: int) -> None: ) count += 1 except discord.Forbidden: - log.warning("failed to reset channel %s in guild %s", channel.id, ctx.guild.id) + log.warning( + "failed to reset channel %s in guild %s", + channel.id, + ctx.guild.id, + ) if settings.get("LOCK_TEXT_CHANNELS"): for channel_id in guild_config["default_defcon"].get("locked_channels", []): @@ -244,7 +268,11 @@ async def defcon_reset(self, ctx: Context, level: int) -> None: ) count += 1 except discord.Forbidden: - log.warning("failed to reset channel %s in guild %s", channel.id, ctx.guild.id) + log.warning( + "failed to reset channel %s in guild %s", + channel.id, + ctx.guild.id, + ) await self.bot.guild_configurations.update_one( {"_id": ctx.guild.id}, @@ -269,7 +297,11 @@ async def defcon_reset(self, ctx: Context, level: int) -> None: ) slow_mode_count += 1 except discord.Forbidden: - log.warning("failed to reset slowmode in channel %s in guild %s", channel.id, ctx.guild.id) + log.warning( + "failed to reset slowmode in channel %s in guild %s", + channel.id, + ctx.guild.id, + ) if cog := self.bot.DefconListeners: embed = discord.Embed(title=f"DEFCON {level}", color=self.bot.color).set_footer( @@ -383,7 +415,12 @@ async def defcon_broadcast(self, ctx: Context, channel: discord.TextChannel = No await self.bot.guild_configurations.update_one( {"_id": ctx.guild.id}, - {"$set": {"default_defcon.broadcast.enabled": True, "default_defcon.broadcast.channel": channel.id}}, + { + "$set": { + "default_defcon.broadcast.enabled": True, + "default_defcon.broadcast.channel": channel.id, + } + }, upsert=True, ) await ctx.reply(f"Broadcast enabled in {channel.mention}.") @@ -447,7 +484,10 @@ async def defcon_trustables_add(self, ctx: Context, *roles_or_members: discord.R await ctx.reply("No defcon settings found.") return - trustables = guild_config["default_defcon"].get("trustables", {}) or {"roles": [], "members": []} + trustables = guild_config["default_defcon"].get("trustables", {}) or { + "roles": [], + "members": [], + } for role_or_member in roles_or_members: if isinstance(role_or_member, discord.Role): diff --git a/cogs/defcon/events.py b/cogs/defcon/events.py index ece2bd1f..febb70e7 100644 --- a/cogs/defcon/events.py +++ b/cogs/defcon/events.py @@ -18,7 +18,10 @@ async def defcon_broadcast(self, message: str | discord.Embed, *, guild: discord {"$set": {"default_defcon.level": level}}, upsert=True, ) - self.settings[guild.id]["default_defcon"] = {"level": level, "broadcast": {"enabled": True, "channel": None}} + self.settings[guild.id]["default_defcon"] = { + "level": level, + "broadcast": {"enabled": True, "channel": None}, + } if "broadcast" not in self.settings[guild.id]["default_defcon"]: return diff --git a/cogs/fun/fun.py b/cogs/fun/fun.py index 2adb50b2..b3d2485b 100644 --- a/cogs/fun/fun.py +++ b/cogs/fun/fun.py @@ -807,7 +807,7 @@ async def quiz_game( if "dynamic_id" not in question_dict: quiz_entry = QuizEntry( question_dict["question"], - quiz_answers if isinstance(quiz_answers := question_dict["answer"], list) else [quiz_answers], + (quiz_answers if isinstance(quiz_answers := question_dict["answer"], list) else [quiz_answers]), STANDARD_VARIATION_TOLERANCE, ) else: @@ -1249,7 +1249,10 @@ async def hsv(self, ctx: Context, hue: int, saturation: int, value: int) -> None message="Hue can only be from 0 to 360. Saturation and Value can only be from 0 to 100. " f"User input was: `{hue, saturation, value}`.", ) - hsv_tuple = cast(tuple[int, int, int], ImageColor.getrgb(f"hsv({hue}, {saturation}%, {value}%)")) + hsv_tuple = cast( + tuple[int, int, int], + ImageColor.getrgb(f"hsv({hue}, {saturation}%, {value}%)"), + ) await self.send_colour_response(ctx, hsv_tuple) @colour.command() @@ -1260,7 +1263,10 @@ async def hsl(self, ctx: Context, hue: int, saturation: int, lightness: int) -> message="Hue can only be from 0 to 360. Saturation and Lightness can only be from 0 to 100. " f"User input was: `{hue, saturation, lightness}`.", ) - hsl_tuple = cast(tuple[int, int, int], ImageColor.getrgb(f"hsl({hue}, {saturation}%, {lightness}%)")) + hsl_tuple = cast( + tuple[int, int, int], + ImageColor.getrgb(f"hsl({hue}, {saturation}%, {lightness}%)"), + ) await self.send_colour_response(ctx, hsl_tuple) @colour.command() @@ -2500,10 +2506,16 @@ def check(m: discord.Message) -> bool: return if guess < number: - await ctx.reply(f"{ctx.author.mention} Your guess is **too low**. Try again", delete_after=4) + await ctx.reply( + f"{ctx.author.mention} Your guess is **too low**. Try again", + delete_after=4, + ) else: - await ctx.reply(f"{ctx.author.mention} Your guess is **too high**. Try again", delete_after=4) + await ctx.reply( + f"{ctx.author.mention} Your guess is **too high**. Try again", + delete_after=4, + ) if count >= number_of_chances: await ctx.reply(f"{ctx.author.mention} The number is **{number}**. Better luck next time") diff --git a/cogs/highlight/highlight.py b/cogs/highlight/highlight.py index 1398d7aa..558e7aed 100644 --- a/cogs/highlight/highlight.py +++ b/cogs/highlight/highlight.py @@ -55,7 +55,12 @@ def display_emoji(self) -> discord.PartialEmoji: return discord.PartialEmoji(name="\N{ELECTRIC TORCH}") def _partial_settings(self, user_id: int) -> dict: - return {"user_id": user_id, "disabled": False, "blocked_users": [], "blocked_channels": []} + return { + "user_id": user_id, + "disabled": False, + "blocked_users": [], + "blocked_channels": [], + } async def get_user_settings(self, user_id: int) -> _CACHED_SETTINGS_HINT: try: @@ -334,7 +339,10 @@ async def highlight_history(self, ctx: Context): await ctx.paginate(entries=entries, module="JishakuPaginatorEmbedInterface") - @highlight.command(name="delete-history", aliases=["delete_history", "dh", "clear-history", "clear_history", "ch"]) + @highlight.command( + name="delete-history", + aliases=["delete_history", "dh", "clear-history", "clear_history", "ch"], + ) async def delete_history(self, ctx: Context): """Delete your highlight history.""" col = self.bot.user_collections_ind diff --git a/cogs/meta/meta.py b/cogs/meta/meta.py index 20be8ade..6b8e06df 100644 --- a/cogs/meta/meta.py +++ b/cogs/meta/meta.py @@ -187,7 +187,7 @@ async def server_info(self, ctx: Context): guild = ctx.guild embed: discord.Embed = discord.Embed( title=f"Server Info: {ctx.guild.name}", - colour=ctx.guild.owner.colour if ctx.guild.owner else discord.Colour.blurple(), + colour=(ctx.guild.owner.colour if ctx.guild.owner else discord.Colour.blurple()), timestamp=discord.utils.utcnow(), ) if ctx.guild.icon: @@ -354,7 +354,10 @@ async def member_count(self, ctx: Context): humans = len(list(filter(lambda m: not m.bot, ctx.guild.members))) embed = ( - discord.Embed(description=f"Total Members: {ctx.guild.member_count}", color=ctx.author.color) + discord.Embed( + description=f"Total Members: {ctx.guild.member_count}", + color=ctx.author.color, + ) .add_field(name="Humans", value=humans) .add_field(name="Bots", value=bots) ) @@ -401,7 +404,10 @@ async def show_bot_stats(self, ctx: Context): ) .set_author(name=str(owner), icon_url=owner.display_avatar.url) .add_field(name="Members", value=f"{total_members} total\n{total_unique} unique") - .add_field(name="Channels", value=f"{text + voice} total\n{text} text\n{voice} voice") + .add_field( + name="Channels", + value=f"{text + voice} total\n{text} text\n{voice} voice", + ) .add_field(name="Process", value=f"{memory_usage:.2f} MiB\n{cpu_usage:.2f}% CPU") .add_field(name="Guilds", value=guilds) .add_field(name="Bot Version", value=VERSION) @@ -445,7 +451,11 @@ async def user_info(self, ctx: Context, *, member: discord.Member = None): f"{str(target.activity.type).split('.')[-1].title() if target.activity else 'N/A'} {target.activity.name if target.activity else ''} [Blame Discord]", True, ), - ("Joined at", f"{discord.utils.format_dt(target.joined_at)}" if target.joined_at else "N/A", True), + ( + "Joined at", + (f"{discord.utils.format_dt(target.joined_at)}" if target.joined_at else "N/A"), + True, + ), ("Boosted", bool(target.premium_since), True), ("Bot?", target.bot, True), ("Nickname", target.display_name, True), @@ -571,7 +581,7 @@ async def channel_info( self, ctx: Context, *, - channel: discord.TextChannel | discord.VoiceChannel | discord.CategoryChannel | discord.StageChannel = None, + channel: (discord.TextChannel | discord.VoiceChannel | discord.CategoryChannel | discord.StageChannel) = None, ): channel = channel or ctx.channel _id = channel.id @@ -656,7 +666,10 @@ async def announcement(self, ctx: Context): color=ctx.author.color, description=f"{change_log.content}", ).set_footer(text=f"Message by: {ctx.author}") - await ctx.reply(embed=embed, view=ctx.link_view(url=change_log.jump_url, label="Click to Jump")) + await ctx.reply( + embed=embed, + view=ctx.link_view(url=change_log.jump_url, label="Click to Jump"), + ) @commands.command() @Context.with_type @@ -691,22 +704,22 @@ async def inviteinfo(self, ctx: Context, code: str): ("Channel", f"<#{invite.channel.id}>" if invite.channel else "N/A", True), ( "Created At", - discord.utils.format_dt(invite.created_at, "R") if invite.created_at is not None else "Can not determine", + (discord.utils.format_dt(invite.created_at, "R") if invite.created_at is not None else "Can not determine"), True, ), ( "Expires At", - discord.utils.format_dt(invite.expires_at, "R") if invite.expires_at is not None else "Can not determine", + (discord.utils.format_dt(invite.expires_at, "R") if invite.expires_at is not None else "Can not determine"), True, ), ( "Temporary?", - invite.temporary if invite.temporary is not None else "Can not determine", + (invite.temporary if invite.temporary is not None else "Can not determine"), True, ), ( "Max Age", - invite.max_age or "Infinite" if invite.max_age is not None else "Can not determine", + (invite.max_age or "Infinite" if invite.max_age is not None else "Can not determine"), True, ), ("Link", invite.url, True), @@ -790,8 +803,15 @@ async def on_audit_log_entry(self, entry: discord.AuditLogEntry) -> None: .add_field(name="Performed by", value=by, inline=True) .add_field(name="Target", value=target, inline=True) .add_field(name="Reason", value=entry.reason, inline=False) - .add_field(name="Category", value=f"{action_name} (Type: {target_type})", inline=False) - .set_footer(text=f"Log: [{entry.id}]", icon_url=entry.user.display_avatar.url if entry.user else None) + .add_field( + name="Category", + value=f"{action_name} (Type: {target_type})", + inline=False, + ) + .set_footer( + text=f"Log: [{entry.id}]", + icon_url=entry.user.display_avatar.url if entry.user else None, + ) ) embed.timestamp = entry.created_at diff --git a/cogs/mis/__flags.py b/cogs/mis/__flags.py index 3fd479b2..98ad746a 100644 --- a/cogs/mis/__flags.py +++ b/cogs/mis/__flags.py @@ -27,72 +27,81 @@ class SearchFlag(commands.FlagConverter, case_insensitive=True, prefix="--", del hl: str | None = None hq: str | None = None img_color_type: Literal["color", "gray", "mono", "trans"] | None = None - img_dominant_color: Literal[ - "black", - "blue", - "brown", - "gray", - "green", - "orange", - "ping", - "purple", - "red", - "teal", - "white", - "yellow", - ] | None = None - img_size: Literal["huge", "icon", "large", "medium", "small", "xlarge", "xxlarge"] | None = None - img_type: Literal["face", "photo", "clipart", "lineart", "stock", "animated"] | None = None + img_dominant_color: ( + Literal[ + "black", + "blue", + "brown", + "gray", + "green", + "orange", + "ping", + "purple", + "red", + "teal", + "white", + "yellow", + ] + | None + ) = None + img_size: (Literal["huge", "icon", "large", "medium", "small", "xlarge", "xxlarge"] | None) = None + img_type: (Literal["face", "photo", "clipart", "lineart", "stock", "animated"] | None) = None link_site: str | None = None low_range: str | None = None - lr: Literal[ - "lang_ar", - "lang_bg", - "lang_cs", - "lang_da", - "lang_de", - "lang_ca", - "lang_el", - "lang_en", - "lang_es", - "lang_et", - "lang_fi", - "lang_fr", - "lang_hr", - "lang_hu", - "lang_id", - "lang_is", - "lang_it", - "lang_iw", - "lang_ja", - "lang_ko", - "lang_lt", - "lang_lv", - "lang_nl", - "lang_no", - "lang_pl", - "lang_pt", - "lang_ro", - "lang_ru", - "lang_sk", - "lang_sl", - "lang_sr", - "lang_sv", - "lang_tr", - "lang_zh-CN", - "lang_zh-TW", - ] | None = None + lr: ( + Literal[ + "lang_ar", + "lang_bg", + "lang_cs", + "lang_da", + "lang_de", + "lang_ca", + "lang_el", + "lang_en", + "lang_es", + "lang_et", + "lang_fi", + "lang_fr", + "lang_hr", + "lang_hu", + "lang_id", + "lang_is", + "lang_it", + "lang_iw", + "lang_ja", + "lang_ko", + "lang_lt", + "lang_lv", + "lang_nl", + "lang_no", + "lang_pl", + "lang_pt", + "lang_ro", + "lang_ru", + "lang_sk", + "lang_sl", + "lang_sr", + "lang_sv", + "lang_tr", + "lang_zh-CN", + "lang_zh-TW", + ] + | None + ) = None num: Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | None = None or_terms: str | None = None q: str related_site: str | None = None - rights: Literal[ - "cc_publicdomain", - "cc_attribute", - "cc_sharealike", - "cc_noncommercial", - "cc_nonderived", - ] | None = None + rights: ( + Literal[ + "cc_publicdomain", + "cc_attribute", + "cc_sharealike", + "cc_noncommercial", + "cc_nonderived", + ] + | None + ) = None safe: Literal["active", "off"] | None = None search_type: Literal["image"] | None = None site_search: str | None = None diff --git a/cogs/mis/mis.py b/cogs/mis/mis.py index 8e868a80..d7940eb3 100644 --- a/cogs/mis/mis.py +++ b/cogs/mis/mis.py @@ -832,21 +832,23 @@ async def snowflakeid( self, ctx: Context, *, - target: discord.User - | discord.Member - | discord.Role - | discord.Thread - | discord.TextChannel - | discord.VoiceChannel - | discord.StageChannel - | discord.Guild - | discord.Emoji - | discord.Invite - | discord.Template - | discord.CategoryChannel - | discord.DMChannel - | discord.GroupChannel - | discord.Object, + target: ( + discord.User + | discord.Member + | discord.Role + | discord.Thread + | discord.TextChannel + | discord.VoiceChannel + | discord.StageChannel + | discord.Guild + | discord.Emoji + | discord.Invite + | discord.Template + | discord.CategoryChannel + | discord.DMChannel + | discord.GroupChannel + | discord.Object + ), ): """To get the ID of discord models.""" embed = discord.Embed( @@ -857,7 +859,7 @@ async def snowflakeid( embed.add_field(name="Type", value=f"`{target.__class__.__name__}`", inline=True) embed.add_field( name="Created At", - value=f"{discord.utils.format_dt(target.created_at)}" if target.created_at is not None else "None", + value=(f"{discord.utils.format_dt(target.created_at)}" if target.created_at is not None else "None"), inline=True, ) embed.add_field(name="ID", value=f"`{getattr(target, 'id', 'NA')}`", inline=True) @@ -983,7 +985,12 @@ async def qrcode(self, ctx: Context, text: str, *, flags: QRCodeFlags): @commands.cooldown(1, 5, commands.BucketType.member) @commands.max_concurrency(1, per=commands.BucketType.user) @Context.with_type - async def mine_server_status(self, ctx: Context, address: str, bedrock: Annotated[bool | None, convert_bool] = False): + async def mine_server_status( + self, + ctx: Context, + address: str, + bedrock: Annotated[bool | None, convert_bool] = False, + ): """If you are minecraft fan, then you must be know about servers. Check server status with thi command.""" if bedrock: link = f"https://api.mcsrvstat.us/bedrock/2/{address}" diff --git a/cogs/mod/mod.py b/cogs/mod/mod.py index 31961547..0ecfd51b 100644 --- a/cogs/mod/mod.py +++ b/cogs/mod/mod.py @@ -10,7 +10,12 @@ import discord from cogs.mod import method as mod_method -from cogs.mod.embeds import MEMBER_EMBED, ROLE_EMBED, TEXT_CHANNEL_EMBED, VOICE_CHANNEL_EMBED +from cogs.mod.embeds import ( + MEMBER_EMBED, + ROLE_EMBED, + TEXT_CHANNEL_EMBED, + VOICE_CHANNEL_EMBED, +) from core import Cog, Context, Parrot from discord.ext import commands from utilities.checks import in_temp_channel, is_mod @@ -1711,7 +1716,8 @@ async def get_response(self, ctx: Context, *, convert=None): timeout=60, ) except asyncio.TimeoutError as e: - raise commands.BadArgument("You took too long to respond.") from e + error_message = "You took too long to respond." + raise commands.BadArgument(error_message) from e else: if convert: return await discord.utils.maybe_coroutine(convert, msg.content) @@ -1781,7 +1787,7 @@ def _fmt_embed( async def mod( self, ctx: Context, - target: discord.Member | discord.TextChannel | discord.VoiceChannel | discord.Role, + target: (discord.Member | discord.TextChannel | discord.VoiceChannel | discord.Role), *, reason: Annotated[str, ActionReason | None] = None, ): @@ -1867,9 +1873,11 @@ async def _mod_action_text_channel(self, *, ctx: Context, target: discord.TextCh if str(reaction.emoji) in {"\N{MEMO}", "\N{LOWER LEFT FOUNTAIN PEN}"}: await ctx.send( - f"{ctx.author.mention} Enter the Channel Topic" - if str(reaction.emoji) == "\N{MEMO}" - else f"{ctx.author.mention} Enter the Channel Name", + ( + f"{ctx.author.mention} Enter the Channel Topic" + if str(reaction.emoji) == "\N{MEMO}" + else f"{ctx.author.mention} Enter the Channel Name" + ), ) return await func( guild=ctx.guild, diff --git a/cogs/nasa/nasa.py b/cogs/nasa/nasa.py index 07f9589f..6c9c83e9 100644 --- a/cogs/nasa/nasa.py +++ b/cogs/nasa/nasa.py @@ -10,7 +10,7 @@ import discord from core import Cog, Context, Parrot -from discord.ext import commands +from discord.ext import commands, tasks from utilities.paginator import PaginationView NASA_KEY = os.environ["NASA_KEY"] @@ -70,7 +70,13 @@ def display_emoji(self) -> discord.PartialEmoji: @commands.command(aliases=["sat", "satelite"]) @commands.max_concurrency(1, commands.BucketType.user) @Context.with_type - async def earth(self, ctx: Context, longitute: float, latitude: float, date: Annotated[str, date_parser]): + async def earth( + self, + ctx: Context, + longitute: float, + latitude: float, + date: Annotated[str, date_parser], + ): """Satelite Imagery - NASA. Date must be in "YYYY-MM-DD" format.""" if not -90 <= latitude <= 90: return await ctx.reply(f"{ctx.author.mention} Invalid latitude range, must be between -90 to 90") @@ -103,10 +109,13 @@ async def earth(self, ctx: Context, longitute: float, latitude: float, date: Ann await ctx.reply(embed=embed, file=file) - @commands.command() + @commands.group() @Context.with_type async def apod(self, ctx: Context): """Asteroid Picture of the Day.""" + if ctx.invoked_subcommand is not None: + return + link = ENDPOINTS.APOD r = await self.bot.http_session.get(link, params=self._api_params, headers=self.bot.GLOBAL_HEADERS) @@ -134,6 +143,64 @@ async def apod(self, ctx: Context): await ctx.reply(embed=embed) + @apod.command(name="set") + @commands.has_permissions(administrator=True) + @Context.with_type + async def apod_set(self, ctx: Context, *, channel: discord.TextChannel) -> None: + """Set an automatic APOD in a channel.""" + await self.bot.guild_configurations.update_one({"_id": ctx.guild.id}, {"$set": {"apod_channel": channel.id}}) + self.bot.guild_configurations_cache[ctx.guild.id]["apod_channel"] = channel.id + await ctx.tick() + + @apod.command(name="remove") + @commands.has_permissions(administrator=True) + @Context.with_type + async def apod_remove(self, ctx: Context) -> None: + """Remove the automatic APOD in a channel.""" + await self.bot.guild_configurations.update_one({"_id": ctx.guild.id}, {"$set": {"apod_channel": None}}) + self.bot.guild_configurations_cache[ctx.guild.id]["apod_channel"] = None + await ctx.tick() + + @tasks.loop(hours=24) + async def apod_loop(self) -> None: + async for data in self.bot.guild_configurations.find({"apod_channel": {"$exists": True}}): + if not data["apod_channel"]: + continue + + if data.get("apod_last") and arrow.get(data["apod_last"]).shift(days=1) > arrow.utcnow(): + continue + + channel = self.bot.get_channel(data["apod_channel"]) + if not channel: + continue + link = ENDPOINTS.APOD + + r = await self.bot.http_session.get(link, params=self._api_params, headers=self.bot.GLOBAL_HEADERS) + if r.status == 200: + res = await r.json() + else: + continue + + title = res["title"] + expln = res["explanation"] + date_ = res["date"] + if res["media_type"] == "image": + image = res["url"] + + embed = discord.Embed( + title=f"Astronomy Picture of the Day: {title} | At: {date_}", + description=f"{expln}", + timestamp=discord.utils.utcnow(), + ) + if res["media_type"] == "image": + embed.set_image(url=f"{image}") + embed.set_thumbnail(url=ENDPOINTS.NASA_LOGO) + + await channel.send(embed=embed) + await self.bot.guild_configurations.update_one( + {"_id": data["_id"]}, {"$set": {"apod_last": discord.utils.utcnow()}} + ) + @commands.command() @commands.max_concurrency(1, commands.BucketType.user) @Context.with_type @@ -173,7 +240,12 @@ async def epic(self, ctx: Context, date: Annotated[str, date_parser]): @commands.command(aliases=["finda", "asteroid", "neo"]) @commands.max_concurrency(1, commands.BucketType.user) @Context.with_type - async def findasteroid(self, ctx: Context, start: Annotated[str, date_parser], end: Annotated[str, date_parser]): + async def findasteroid( + self, + ctx: Context, + start: Annotated[str, date_parser], + end: Annotated[str, date_parser], + ): """You can literally find any asteroid in the space by date. Date must be in "YYYY-MM-DD" format.""" r = await self.bot.http_session.get( @@ -214,7 +286,11 @@ async def findasteroid(self, ctx: Context, start: Annotated[str, date_parser], e .add_field(name="Estimated Diameter:", value=f"{dia} M", inline=True) .add_field(name="Is Danger?", value=f"{danger}", inline=True) .add_field(name="Approach Date:", value=f"{approach_date}", inline=True) - .add_field(name="Relative velocity:", value=f"{velocity} KM/hr", inline=True) + .add_field( + name="Relative velocity:", + value=f"{velocity} KM/hr", + inline=True, + ) .add_field(name="Miss Distance:", value=f"{miss_dist} KM", inline=True) .add_field(name="Orbiting:", value=f"{orbiting}", inline=True) .add_field(name="Is sentry?", value=f"{is_sentry_object}", inline=True) @@ -382,7 +458,12 @@ async def donki(self, ctx: Context): await self.bot.invoke_help_command(ctx) @donki.command(name="cme") - async def donki_cme(self, ctx: Context, start: Annotated[str, date_parser], end: Annotated[str, date_parser]): + async def donki_cme( + self, + ctx: Context, + start: Annotated[str, date_parser], + end: Annotated[str, date_parser], + ): """Coronal Mass Ejection.""" AGENT = self.random_agent(USER_AGENTS) r = await self.bot.http_session.get( @@ -428,7 +509,12 @@ async def donki_cme(self, ctx: Context, start: Annotated[str, date_parser], end: await PaginationView(em_list).start(ctx=ctx) @donki.command(name="gst") - async def donki_gst(self, ctx: Context, start: Annotated[str, date_parser], end: Annotated[str, date_parser]): + async def donki_gst( + self, + ctx: Context, + start: Annotated[str, date_parser], + end: Annotated[str, date_parser], + ): """Geomagnetic Storm.""" AGENT = self.random_agent(USER_AGENTS) r = await self.bot.http_session.get( @@ -461,7 +547,12 @@ async def donki_gst(self, ctx: Context, start: Annotated[str, date_parser], end: await PaginationView(em_list).start(ctx=ctx) @donki.command(name="ips") - async def donki_ips(self, ctx: Context, start: Annotated[str, date_parser], end: Annotated[str, date_parser]): + async def donki_ips( + self, + ctx: Context, + start: Annotated[str, date_parser], + end: Annotated[str, date_parser], + ): """Interplanetary Shock.""" AGENT = self.random_agent(USER_AGENTS) r = await self.bot.http_session.get( @@ -502,7 +593,12 @@ async def donki_ips(self, ctx: Context, start: Annotated[str, date_parser], end: await PaginationView(em_list).start(ctx=ctx) @donki.command(name="flr") - async def donki_flr(self, ctx: Context, start: Annotated[str, date_parser], end: Annotated[str, date_parser]): + async def donki_flr( + self, + ctx: Context, + start: Annotated[str, date_parser], + end: Annotated[str, date_parser], + ): """Solar Flare.""" AGENT = self.random_agent(USER_AGENTS) r = await self.bot.http_session.get( @@ -551,7 +647,12 @@ async def donki_flr(self, ctx: Context, start: Annotated[str, date_parser], end: await PaginationView(em_list).start(ctx=ctx) @donki.command(name="sep") - async def donki_sep(self, ctx: Context, start: Annotated[str, date_parser], end: Annotated[str, date_parser]): + async def donki_sep( + self, + ctx: Context, + start: Annotated[str, date_parser], + end: Annotated[str, date_parser], + ): """Solar Energetic Particle.""" AGENT = self.random_agent(USER_AGENTS) r = await self.bot.http_session.get( @@ -589,7 +690,12 @@ async def donki_sep(self, ctx: Context, start: Annotated[str, date_parser], end: await PaginationView(em_list).start(ctx=ctx) @donki.command(name="mpc") - async def donki_mpc(self, ctx: Context, start: Annotated[str, date_parser], end: Annotated[str, date_parser]): + async def donki_mpc( + self, + ctx: Context, + start: Annotated[str, date_parser], + end: Annotated[str, date_parser], + ): """Magnetopause Crossing.""" AGENT = self.random_agent(USER_AGENTS) r = await self.bot.http_session.get( @@ -626,7 +732,12 @@ async def donki_mpc(self, ctx: Context, start: Annotated[str, date_parser], end: await PaginationView(em_list).start(ctx=ctx) @donki.command(name="rbe") - async def donki_rbe(self, ctx: Context, start: Annotated[str, date_parser], end: Annotated[str, date_parser]): + async def donki_rbe( + self, + ctx: Context, + start: Annotated[str, date_parser], + end: Annotated[str, date_parser], + ): """Radiation Belt Enhancement.""" AGENT = self.random_agent(USER_AGENTS) r = await self.bot.http_session.get( @@ -663,7 +774,12 @@ async def donki_rbe(self, ctx: Context, start: Annotated[str, date_parser], end: await PaginationView(em_list).start(ctx=ctx) @donki.command(name="hhs") - async def donki_hhs(self, ctx: Context, start: Annotated[str, date_parser], end: Annotated[str, date_parser]): + async def donki_hhs( + self, + ctx: Context, + start: Annotated[str, date_parser], + end: Annotated[str, date_parser], + ): """Hight Speed Stream.""" AGENT = self.random_agent(USER_AGENTS) r = await self.bot.http_session.get( diff --git a/cogs/nsfw/nsfw.py b/cogs/nsfw/nsfw.py index 896b9a30..56a309ab 100644 --- a/cogs/nsfw/nsfw.py +++ b/cogs/nsfw/nsfw.py @@ -167,7 +167,8 @@ async def check_user_age(self, ctx: Context) -> bool: async def adult(self, ctx: Context) -> None: """To tell bot that you are 18+. This is required to use NSFW commands. DO NOT FAKE IT. - If you are caught faking it, you will be blacklisted from using NSFW commands forever.""" + If you are caught faking it, you will be blacklisted from using NSFW commands forever. + """ if await self.check_user_age(ctx): await ctx.reply("You are already 18+", delete_after=5) return @@ -181,7 +182,8 @@ async def adult(self, ctx: Context) -> None: async def not_adult(self, ctx: Context) -> None: """To tell bot that you are not 18+. This is required to use NSFW commands. DO NOT FAKE IT. - If you are caught faking it, you will be blacklisted from using NSFW commands forever.""" + If you are caught faking it, you will be blacklisted from using NSFW commands forever. + """ if not await self.check_user_age(ctx): await ctx.reply("You are already not 18+", delete_after=5) return diff --git a/cogs/owner/owner.py b/cogs/owner/owner.py index aec96b4c..7c094e72 100644 --- a/cogs/owner/owner.py +++ b/cogs/owner/owner.py @@ -330,7 +330,13 @@ async def command_lookup(self, ctx: Context, _id: int, tp: str = "user"): table.append([cmd_name, count]) table = tabulate(table, headers="firstrow", tablefmt="psql") - await ctx.paginate(table, module="JishakuPaginatorInterface", max_size=1000, prefix="```sql", suffix="```") + await ctx.paginate( + table, + module="JishakuPaginatorInterface", + max_size=1000, + prefix="```sql", + suffix="```", + ) @commands.command(alises=["direct-message"]) async def dm(self, ctx: Context, user: discord.User, *, reply: str): @@ -506,7 +512,12 @@ async def playing( await ctx.tick() @commands.command() - async def toggle_testing(self, ctx: Context, cog: str, toggle: Annotated[bool | None, convert_bool] = None) -> None: + async def toggle_testing( + self, + ctx: Context, + cog: str, + toggle: Annotated[bool | None, convert_bool] = None, + ) -> None: """Update the cog setting to toggle testing mode. ```py @@ -649,7 +660,12 @@ def _join_values(values: list[str] | list[list[str]]) -> str: val.append(value) return "\n".join(val) - async def add_page(interface: PaginatorEmbedInterface, *, title: str, data: list[str] | list[list[str]]) -> None: + async def add_page( + interface: PaginatorEmbedInterface, + *, + title: str, + data: list[str] | list[list[str]], + ) -> None: if not data: return await interface.add_line(f"# {title}") @@ -659,7 +675,11 @@ async def add_page(interface: PaginatorEmbedInterface, *, title: str, data: list await interface.add_line(f"- {d}") if real.get("Things You Should Know"): - await add_page(interface, title="Things You Should Know", data=real["Things You Should Know"].values()) + await add_page( + interface, + title="Things You Should Know", + data=real["Things You Should Know"].values(), + ) wiki_steps: dict[ str, @@ -690,13 +710,21 @@ async def add_page(interface: PaginatorEmbedInterface, *, title: str, data: list await add_page(interface, title="Warnings", data=real["Warnings"].values()) if real.get("Test Your Knowledge"): - await add_page(interface, title="Test Your Knowledge", data=real["Test Your Knowledge"].values()) + await add_page( + interface, + title="Test Your Knowledge", + data=real["Test Your Knowledge"].values(), + ) if real.get("Video"): await add_page(interface, title="Video", data=real["Video"].values()) if real.get("Related wikiHows"): - await add_page(interface, title="Related wikiHows", data=real["Related wikiHows"].values()) + await add_page( + interface, + title="Related wikiHows", + data=real["Related wikiHows"].values(), + ) if real.get("References"): await add_page(interface, title="References", data=real["References"].values()) diff --git a/cogs/reminder/__init__.py b/cogs/reminder/__init__.py index 2c68ef41..a7d5afac 100644 --- a/cogs/reminder/__init__.py +++ b/cogs/reminder/__init__.py @@ -82,7 +82,11 @@ async def notify_reminder_msg(self, ctx: Context, *, timestamp: int | float) -> except discord.Forbidden: await ctx.reply(msg, embed=embed) - @commands.group(name="remindme", aliases=["remind", "reminder", "remind-me"], invoke_without_command=True) + @commands.group( + name="remindme", + aliases=["remind", "reminder", "remind-me"], + invoke_without_command=True, + ) async def remindme( self, ctx: Context[Parrot], @@ -113,7 +117,11 @@ async def remindme( content=when.arg, message=ctx.message, ) - log.info("Created a reminder for %s. reminder exipres at %s", ctx.author, timestamp) + log.info( + "Created a reminder for %s. reminder exipres at %s", + ctx.author, + timestamp, + ) @remindme.command(name="list", aliases=["all", "ls", "showall"]) async def _list(self, ctx: Context) -> None: diff --git a/cogs/rss/rss.py b/cogs/rss/rss.py index a6dc11cb..8aa1abef 100644 --- a/cogs/rss/rss.py +++ b/cogs/rss/rss.py @@ -115,7 +115,11 @@ async def add(self, _id: int) -> None: {"_id": _id}, { "$addToSet": { - "rss": {"channel_id": self.channel_id, "webhook_url": self.webhook_url, "link": self.link}, + "rss": { + "channel_id": self.channel_id, + "webhook_url": self.webhook_url, + "link": self.link, + }, }, }, upsert=True, @@ -220,7 +224,13 @@ async def rss_list(self, ctx: Context): return await ctx.reply(f"{ctx.author.mention} No RSS Feeds found.") if ls := [f"**Channel:** <#{feed['channel_id']}> | **Link:** {feed['link']}" for feed in data["rss"]]: - await ctx.paginate(ls, module="JishakuPaginatorEmbedInterface", max_size=1000, prefix="", suffix="") + await ctx.paginate( + ls, + module="JishakuPaginatorEmbedInterface", + max_size=1000, + prefix="", + suffix="", + ) else: await ctx.reply(f"{ctx.author.mention} No RSS Feeds found.") diff --git a/cogs/rtfm/_kontests/codeforces.py b/cogs/rtfm/_kontests/codeforces.py index d4ec7c98..ee0d0c92 100644 --- a/cogs/rtfm/_kontests/codeforces.py +++ b/cogs/rtfm/_kontests/codeforces.py @@ -11,7 +11,12 @@ class Tree: - def __init__(self, data: CodeForcesContestData, left: Tree | None = None, right: Tree | None = None) -> None: + def __init__( + self, + data: CodeForcesContestData, + left: Tree | None = None, + right: Tree | None = None, + ) -> None: self.left = left self.right = right self.data = data @@ -34,7 +39,9 @@ def type(self) -> Literal["CF", "IOI", "ICPC"]: return self.__data["type"] @property - def phase(self) -> Literal["BEFORE", "CODING", "PENDING_SYSTEM_TEST", "SYSTEM_TEST", "FINISHED"]: + def phase( + self, + ) -> Literal["BEFORE", "CODING", "PENDING_SYSTEM_TEST", "SYSTEM_TEST", "FINISHED"]: return self.__data["phase"] @property @@ -142,7 +149,11 @@ def __build_tree(self, contests: list[CodeForcesContestData]) -> Tree | None: if not contests: return None mid = len(contests) // 2 - return Tree(contests[mid], self.__build_tree(contests[:mid]), self.__build_tree(contests[mid + 1 :])) + return Tree( + contests[mid], + self.__build_tree(contests[:mid]), + self.__build_tree(contests[mid + 1 :]), + ) def search(self, contest_id: int) -> CodeForcesContestData | None: return self.__search(self.__node, contest_id) diff --git a/cogs/rtfm/rtfm.py b/cogs/rtfm/rtfm.py index 8ea37ecb..7126bd0f 100644 --- a/cogs/rtfm/rtfm.py +++ b/cogs/rtfm/rtfm.py @@ -803,7 +803,7 @@ async def github_user_info(self, ctx: Context, username: str) -> None: embed = ( discord.Embed( title=f"`{user_data['login']}`'s GitHub profile info", - description=f"```\n{user_data['bio']}\n```\n" if user_data["bio"] else "", + description=(f"```\n{user_data['bio']}\n```\n" if user_data["bio"] else ""), colour=discord.Colour.og_blurple(), url=user_data["html_url"], timestamp=arrow.get(user_data["created_at"]).datetime, @@ -1416,7 +1416,13 @@ async def kontests(self, ctx: Context, platform: str | None = None) -> None: if random() < 0.1: await ctx.send("From Owner: This command is still in development. Please be patient.") - available_platforms = {"hackerearth", "hackerrank", "codeforces", "atcoder", "csacademy"} + available_platforms = { + "hackerearth", + "hackerrank", + "codeforces", + "atcoder", + "csacademy", + } if platform is None: msg = "Please provide a platform to get the upcoming contests for." msg += f"\n\nAvailable platforms: {', '.join(available_platforms)}" diff --git a/cogs/sports/__init__.py b/cogs/sports/__init__.py deleted file mode 100644 index f6c61cec..00000000 --- a/cogs/sports/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -from __future__ import annotations - -from core import Parrot - -from .sports import Sports - - -async def setup(bot: Parrot) -> None: - await bot.add_cog(Sports(bot)) diff --git a/cogs/sports/sports.py b/cogs/sports/sports.py deleted file mode 100644 index 35043867..00000000 --- a/cogs/sports/sports.py +++ /dev/null @@ -1,154 +0,0 @@ -from __future__ import annotations - -from typing import Any - -from tabulate import tabulate - -import discord -from core import Cog, Context, Parrot -from discord.ext import commands, tasks -from utilities.deco import with_role - -STAFF_ROLES = [771025632184369152, 793531029184708639] - - -class Sports(Cog): - """Sports related commands. This category is only for requested servers.""" - - def __init__(self, bot: Parrot) -> None: - self.bot = bot - - # ipl url - the url to the ipl score page. - # to my localhost to be honest. - self.url = None - self.ON_TESTING = False - # list of channels - self.channels: list[discord.TextChannel] = [] - self.annouce_task.start() - - self.data = None - - @property - def display_emoji(self) -> discord.PartialEmoji: - return discord.PartialEmoji(name="\N{CRICKET BAT AND BALL}") - - def create_embed_ipl( - self, - *, - data: dict[str, Any], - ) -> discord.Embed: - """To create the embed for the ipl score. For more detailed information, see https://github.com/rtk-rnjn/cricbuzz_scraper.""" - embed = discord.Embed(timestamp=discord.utils.utcnow()) - if data["title"]: - embed = discord.Embed(title=data["title"], timestamp=discord.utils.utcnow()) - embed.set_footer(text=data["status"]) - - table1 = tabulate(data["batting"], headers="keys") - table2 = tabulate(data["bowling"], headers="keys") - extra = "" - if extra_ := data.get("extra"): - for temp in extra_: - extra += "".join(temp) + "\n" - if crr := "\n".join(data["crr"]): - embed.description = f""" -> `{data['team_one']} | {data['team_two']}` -``` -{crr} -``` -{extra} -""" - if data.get("batting"): - embed.add_field(name="Batting - Stats", value=f"```\n{table1}```", inline=False) - - if data.get("bowling"): - embed.add_field(name="Bowling - Stats", value=f"```\n{table2}```", inline=False) - - embed.add_field( - name="Recent Commentry", - value="- " + "\n - ".join(i for i in data["commentry"][:2] if i), - inline=False, - ) - return embed - - @commands.group(name="ipl", invoke_without_command=True) - async def ipl(self, ctx: Context) -> None: - """To get the IPL score.""" - if ctx.invoked_subcommand is not None: - return - if not self.url: - await ctx.send(f"{ctx.author.mention} No IPL score page set | Ask for it in support server") - return - - if self.data is None: - url = f"http://127.0.0.1:1729/cricket_api?url={self.url}" - response = await self.bot.http_session.get(url) - if response.status != 200: - return await ctx.send( - f"{ctx.author.mention} Could not get IPL score | Ask for it in support server | Status code: {response.status}", - ) - self.data = await response.json() - - embed = self.create_embed_ipl(data=self.data) - await ctx.send(embed=embed) - - @with_role(*STAFF_ROLES) - @ipl.command(name="set") - async def set_ipl_url(self, ctx: Context, *, url: str) -> None: - """Set the IPL score page url.""" - if url.startswith(("<", "[")) and url.endswith((">", "]")): - url = url[1:-1] - - self.url = url - await ctx.send(f"Set IPL score page to <{url}>") - - @ipl.command(name="add") - @commands.is_owner() - async def add_channel(self, ctx: Context, *, channel: discord.TextChannel): - """To add the channel to the list of channels to get IPL score.""" - if channel.id in self.channels: - return await ctx.send(f"{ctx.author.mention} Channel already added") - - self.channels.append(channel) - await ctx.send(f"{ctx.author.mention} Channel added") - - @ipl.command(name="remove") - @commands.is_owner() - async def remove_channel(self, ctx: Context, *, channel: discord.TextChannel): - """To remove the channel from the list of channels to get IPL score.""" - if channel.id not in self.channels: - return await ctx.send(f"{ctx.author.mention} Channel not added") - - self.channels.remove(channel) - await ctx.send(f"{ctx.author.mention} Channel removed") - - @tasks.loop(seconds=90) - async def annouce_task( - self, - ): - if self.url is None: - return - - url = f"http://127.0.0.1:1729/cricket_api?url={self.url}" - response = await self.bot.http_session.get(url) - - if response.status != 200: - return - - data = await response.json() - - if data == self.data: - return - - if self.data is None: - self.data = data - - embed = self.create_embed_ipl(data=data) - - for channel in self.channels: - await channel.send(embed=embed) - self.data = data - - async def cog_unload( - self, - ): - self.annouce_task.cancel() diff --git a/cogs/suggestion/__init__.py b/cogs/suggestion/__init__.py index a9cf700e..854f5356 100644 --- a/cogs/suggestion/__init__.py +++ b/cogs/suggestion/__init__.py @@ -309,7 +309,10 @@ async def suggest_resolved(self, ctx: Context, *, message_id: int): f"{ctx.author.mention} Can not find message of ID `{thread_id}`. Probably already deleted, or `{thread_id}` is invalid", ) if thread.locked and thread.archived: - await ctx.send(f"{ctx.author.mention} This suggestion is already resolved", delete_after=5) + await ctx.send( + f"{ctx.author.mention} This suggestion is already resolved", + delete_after=5, + ) return await thread.send("This suggestion has been resolved") diff --git a/cogs/tags/method.py b/cogs/tags/method.py index 472c9b24..e0f5dee9 100644 --- a/cogs/tags/method.py +++ b/cogs/tags/method.py @@ -128,7 +128,10 @@ async def _claim_owner(bot: Parrot, ctx: Context, tag: str): return await ctx.error( f"{ctx.author.mention} you can not claim the tag ownership as the member is still in the server", ) - await collection.update_one({"tag_id": tag, "guild_id": ctx.guild.id}, {"$set": {"owner": ctx.author.id}}) + await collection.update_one( + {"tag_id": tag, "guild_id": ctx.guild.id}, + {"$set": {"owner": ctx.author.id}}, + ) await ctx.reply(f"{ctx.author.mention} ownership of tag `{tag}` claimed!") else: await ctx.error(f"{ctx.author.mention} No tag with named `{tag}`") @@ -145,7 +148,10 @@ async def _transfer_owner(bot: Parrot, ctx: Context, tag: str, member: discord.M if val is None: await ctx.error(f"{ctx.author.mention} you did not responds on time") elif val: - await collection.update_one({"tag_id": tag, "guild_id": ctx.guild.id}, {"$set": {"owner": member.id}}) + await collection.update_one( + {"tag_id": tag, "guild_id": ctx.guild.id}, + {"$set": {"owner": member.id}}, + ) await ctx.reply(f"{ctx.author.mention} tag ownership successfully transfered to **{member}**") else: await ctx.error(f"{ctx.author.mention} ok! reverting the process!") diff --git a/cogs/todo/__init__.py b/cogs/todo/__init__.py index 764aeb14..42034d34 100644 --- a/cogs/todo/__init__.py +++ b/cogs/todo/__init__.py @@ -345,7 +345,11 @@ async def sync_with_reminders(self) -> None: class EditDueDateModal(ui.Modal, title="Edit Due Date"): - due_date = ui.TextInput(label="Due Date", placeholder="e.g. 5m, 2022-12-31, tomorrow, etc.", max_length=100) + due_date = ui.TextInput( + label="Due Date", + placeholder="e.g. 5m, 2022-12-31, tomorrow, etc.", + max_length=100, + ) def __init__(self, item: TodoItem, *, required: bool = False) -> None: super().__init__() @@ -413,7 +417,12 @@ def __init__(self, todos: list[TodoItem]) -> None: class AddTodoModal(ui.Modal, title="Add Todo"): - content = ui.TextInput(label="Content (optional)", max_length=1024, required=False, style=discord.TextStyle.long) + content = ui.TextInput( + label="Content (optional)", + max_length=1024, + required=False, + style=discord.TextStyle.long, + ) due_date = ui.TextInput( label="Due Date (optional)", @@ -785,7 +794,11 @@ async def add_todo( collection = self.bot.user_db[f"{user_id}"] payload = {} if message: - payload = {**payload, "message_id": message.id, "channel_id": message.channel.id} + payload = { + **payload, + "message_id": message.id, + "channel_id": message.channel.id, + } if message.guild: payload["guild_id"] = message.guild.id else: diff --git a/core/Context.py b/core/Context.py index 87fb3d12..c7e97854 100644 --- a/core/Context.py +++ b/core/Context.py @@ -48,7 +48,12 @@ Callback = MaybeAwaitable VOTER_ROLE_ID = 1139439408723013672 -MODULE_ANNOTATIONS = Literal["SimplePages", "PaginationView", "JishakuPaginatorInterface", "JishakuPaginatorEmbedInterface"] +MODULE_ANNOTATIONS = Literal[ + "SimplePages", + "PaginationView", + "JishakuPaginatorInterface", + "JishakuPaginatorEmbedInterface", +] log = logging.getLogger("core.context") diff --git a/core/Parrot.py b/core/Parrot.py index 05c4b3fb..0ba57c74 100644 --- a/core/Parrot.py +++ b/core/Parrot.py @@ -11,7 +11,15 @@ import traceback import types from collections import Counter, defaultdict, deque -from collections.abc import AsyncGenerator, Awaitable, Callable, Collection, Iterable, Mapping, Sequence +from collections.abc import ( + AsyncGenerator, + Awaitable, + Callable, + Collection, + Iterable, + Mapping, + Sequence, +) from typing import TYPE_CHECKING, Any, Literal, TypeVar, cast, overload import aiohttp @@ -645,7 +653,7 @@ async def __bot_under_maintenance_message(self, ctx: Context) -> None: ) .add_field( name="ETA?", - value=discord.utils.format_dt(self.UNDER_MAINTENANCE_OVER, "R") if self.UNDER_MAINTENANCE_OVER else "N/A", + value=(discord.utils.format_dt(self.UNDER_MAINTENANCE_OVER, "R") if self.UNDER_MAINTENANCE_OVER else "N/A"), ) .add_field(name="Message From?", value=self.author_name) .add_field( @@ -676,7 +684,12 @@ async def process_commands(self, message: discord.Message) -> None: if bucket.update_rate_limit(message.created_at.timestamp()): self._auto_spam_count[message.author.id] += 1 if self._auto_spam_count[message.author.id] >= 5: - await self.ban_user(user_id=message.author.id, reason="**Spamming commands.**", command=True, send=True) + await self.ban_user( + user_id=message.author.id, + reason="**Spamming commands.**", + command=True, + send=True, + ) return if self._auto_spam_count[message.author.id] >= 3: @@ -1446,7 +1459,15 @@ async def set_user_timezone(self, user_id: int, timezone: str) -> None: await self.user_collections_ind.update_one({"_id": user_id}, {"$set": {"timezone": timezone}}, upsert=True) self.__user_timezone_cache[user_id] = timezone - async def ban_user(self, *, user_id: int, reason: str, command: bool = True, send: bool = False, **kw: bool): + async def ban_user( + self, + *, + user_id: int, + reason: str, + command: bool = True, + send: bool = False, + **kw: bool, + ): # sourcery skip: use-contextlib-suppress collection = self.extra_collections diff --git a/core/__template.py b/core/__template.py index d7ec85c1..2d98edb9 100644 --- a/core/__template.py +++ b/core/__template.py @@ -13,6 +13,7 @@ "warn_count": 0, "suggestion_channel": None, "auditlog": None, + "apod_channel": None, "global_chat": { "enable": False, "channel_id": None, diff --git a/core/types.py b/core/types.py index 532cf803..d1043661 100644 --- a/core/types.py +++ b/core/types.py @@ -23,7 +23,13 @@ _IndexList, ) from pymongo.read_concern import ReadConcern -from pymongo.results import BulkWriteResult, DeleteResult, InsertManyResult, InsertOneResult, UpdateResult +from pymongo.results import ( + BulkWriteResult, + DeleteResult, + InsertManyResult, + InsertOneResult, + UpdateResult, +) from pymongo.typings import _CollationIn, _DocumentType, _Pipeline _WriteOp = Union[ # noqa: UP007 @@ -205,7 +211,12 @@ async def create_indexes( ) -> Sequence[str]: ... - async def drop_index(self, index_or_name: _IndexKeyHint, session: ClientSession | None = None, **kwargs: Any) -> None: + async def drop_index( + self, + index_or_name: _IndexKeyHint, + session: ClientSession | None = None, + **kwargs: Any, + ) -> None: ... async def drop_indexes(self, session: ClientSession | None = None, **kwargs: Any) -> None: @@ -472,6 +483,7 @@ class PostType(TypedDict): premium: bool dj_role: int | None warn_expiry: int | None + apod_channel: int | None muted: list[int] warn_count: int suggestion_channel: int | None diff --git a/core/view.py b/core/view.py index 3189bc94..eabcaba8 100644 --- a/core/view.py +++ b/core/view.py @@ -11,7 +11,13 @@ if TYPE_CHECKING: from . import Context, Parrot -__all__ = ("ParrotView", "ParrotButton", "ParrotSelect", "ParrotLinkView", "ParrotModal") +__all__ = ( + "ParrotView", + "ParrotButton", + "ParrotSelect", + "ParrotLinkView", + "ParrotModal", +) class ParrotItem(discord.ui.Item): @@ -104,7 +110,15 @@ def __init__( row: int = None, **kwargs, ) -> None: - super().__init__(style=style, label=label, disabled=disabled, custom_id=custom_id, url=url, emoji=emoji, row=row) + super().__init__( + style=style, + label=label, + disabled=disabled, + custom_id=custom_id, + url=url, + emoji=emoji, + row=row, + ) self.callback_function = kwargs.pop("callback", None) diff --git a/custom_commands/sector_17_29/__init__.py b/custom_commands/sector_17_29/__init__.py index 9e54a81a..f30f4bbe 100644 --- a/custom_commands/sector_17_29/__init__.py +++ b/custom_commands/sector_17_29/__init__.py @@ -427,7 +427,10 @@ async def sector_17_29_general_chat(self, ctx: Context, name: str): if general_chat is None: return await ctx.error("General chat channel not found", delete_after=5) - await general_chat.edit(name=channel_name, reason=f"{ctx.author} ({ctx.author.id}) changed the name of general chat") + await general_chat.edit( + name=channel_name, + reason=f"{ctx.author} ({ctx.author.id}) changed the name of general chat", + ) await ctx.tick() @sector_17_29.command(name="rainbow", aliases=["rainbowrole", "rainbow_role", "rr"]) @@ -451,7 +454,10 @@ async def sector_17_29_rainbow_role(self, ctx: Context, *, color: str): except ValueError: return await ctx.error("Invalid color", delete_after=5) - await role.edit(color=clr, reason=f"{ctx.author} ({ctx.author.id}) changed the color of rainbow role") + await role.edit( + color=clr, + reason=f"{ctx.author} ({ctx.author.id}) changed the color of rainbow role", + ) @Cog.listener("on_message") async def extra_parser_on_message(self, message: discord.Message) -> None: @@ -601,7 +607,11 @@ async def sector_17_29_add_adj(self, ctx: Context, *adjs: str): table = tabulate({"Adjectives": adjs}, headers="keys", tablefmt="github") if cog is not None: author = tabulate( - {"Author": [f"{ctx.author}"], "ID": [ctx.author.id], "Is Mod?": ["Yes"]}, + { + "Author": [f"{ctx.author}"], + "ID": [ctx.author.id], + "Is Mod?": ["Yes"], + }, headers="keys", tablefmt="github", ) diff --git a/emojis/db/db.py b/emojis/db/db.py index f820c474..a375b613 100644 --- a/emojis/db/db.py +++ b/emojis/db/db.py @@ -10,7 +10,13 @@ EMOJI_DB = [ Emoji(["grinning"], "๐Ÿ˜€", ["smile", "happy"], "Smileys & Emotion", "6.1"), Emoji(["smiley"], "๐Ÿ˜ƒ", ["happy", "joy", "haha"], "Smileys & Emotion", "6.0"), - Emoji(["smile"], "๐Ÿ˜„", ["happy", "joy", "laugh", "pleased"], "Smileys & Emotion", "6.0"), + Emoji( + ["smile"], + "๐Ÿ˜„", + ["happy", "joy", "laugh", "pleased"], + "Smileys & Emotion", + "6.0", + ), Emoji(["grin"], "๐Ÿ˜", [], "Smileys & Emotion", "6.0"), Emoji(["laughing", "satisfied"], "๐Ÿ˜†", ["happy", "haha"], "Smileys & Emotion", "6.0"), Emoji(["sweat_smile"], "๐Ÿ˜…", ["hot"], "Smileys & Emotion", "6.0"), @@ -79,7 +85,13 @@ Emoji(["dizzy_face"], "๐Ÿ˜ต", [], "Smileys & Emotion", "6.0"), Emoji(["exploding_head"], "๐Ÿคฏ", ["mind", "blown"], "Smileys & Emotion", "11.0"), Emoji(["cowboy_hat_face"], "๐Ÿค ", [], "Smileys & Emotion", "9.0"), - Emoji(["partying_face"], "๐Ÿฅณ", ["celebration", "birthday"], "Smileys & Emotion", "11.0"), + Emoji( + ["partying_face"], + "๐Ÿฅณ", + ["celebration", "birthday"], + "Smileys & Emotion", + "11.0", + ), Emoji(["disguised_face"], "๐Ÿฅธ", [], "Smileys & Emotion", "13.0"), Emoji(["sunglasses"], "๐Ÿ˜Ž", ["cool"], "Smileys & Emotion", "6.0"), Emoji(["nerd_face"], "๐Ÿค“", ["geek", "glasses"], "Smileys & Emotion", "8.0"), @@ -205,7 +217,13 @@ Emoji(["+1", "thumbsup"], "๐Ÿ‘", ["approve", "ok"], "People & Body", "6.0"), Emoji(["-1", "thumbsdown"], "๐Ÿ‘Ž", ["disapprove", "bury"], "People & Body", "6.0"), Emoji(["fist_raised", "fist"], "โœŠ", ["power"], "People & Body", "6.0"), - Emoji(["fist_oncoming", "facepunch", "punch"], "๐Ÿ‘Š", ["attack"], "People & Body", "6.0"), + Emoji( + ["fist_oncoming", "facepunch", "punch"], + "๐Ÿ‘Š", + ["attack"], + "People & Body", + "6.0", + ), Emoji(["fist_left"], "๐Ÿค›", [], "People & Body", "9.0"), Emoji(["fist_right"], "๐Ÿคœ", [], "People & Body", "9.0"), Emoji(["clap"], "๐Ÿ‘", ["praise", "applause"], "People & Body", "6.0"), @@ -581,7 +599,13 @@ Emoji(["family_woman_girl_girl"], "๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ง", [], "People & Body", "6.0"), Emoji(["speaking_head"], "๐Ÿ—ฃ๏ธ", [], "People & Body", "7.0"), Emoji(["bust_in_silhouette"], "๐Ÿ‘ค", ["user"], "People & Body", "6.0"), - Emoji(["busts_in_silhouette"], "๐Ÿ‘ฅ", ["users", "group", "team"], "People & Body", "6.0"), + Emoji( + ["busts_in_silhouette"], + "๐Ÿ‘ฅ", + ["users", "group", "team"], + "People & Body", + "6.0", + ), Emoji(["people_hugging"], "๐Ÿซ‚", [], "People & Body", "13.0"), Emoji(["footprints"], "๐Ÿ‘ฃ", ["feet", "tracks"], "People & Body", "6.0"), Emoji(["monkey_face"], "๐Ÿต", [], "Animals & Nature", "6.0"), diff --git a/events/on_cmd.py b/events/on_cmd.py index 95c9a59a..a9f05fc7 100644 --- a/events/on_cmd.py +++ b/events/on_cmd.py @@ -17,7 +17,10 @@ if TYPE_CHECKING: from core import Context, Parrot -T = TypeVar("T", bound=discord.Member | discord.Emoji | discord.TextChannel | discord.Role | discord.VoiceChannel) +T = TypeVar( + "T", + bound=discord.Member | discord.Emoji | discord.TextChannel | discord.Role | discord.VoiceChannel, +) quote_ = pathlib.Path("extra/quote.txt").read_text() quote = quote_.split("\n") diff --git a/events/on_msg.py b/events/on_msg.py index e76dffaa..d2be2133 100644 --- a/events/on_msg.py +++ b/events/on_msg.py @@ -66,7 +66,10 @@ re.IGNORECASE, ) -GITHUB_HEADERS = {"Accept": "application/vnd.github.v3.raw", "Authorization": f"token {os.environ['GITHUB_TOKEN']}"} +GITHUB_HEADERS = { + "Accept": "application/vnd.github.v3.raw", + "Authorization": f"token {os.environ['GITHUB_TOKEN']}", +} DISCORD_PY_ID = 336642139381301249 @@ -672,7 +675,10 @@ async def _on_message_passive_afk_user_message(self, message: discord.Message): "$and": [ { "$or": [ - {"messageAuthor": interacted_user.id, "guild": message.guild.id}, + { + "messageAuthor": interacted_user.id, + "guild": message.guild.id, + }, {"messageAuthor": interacted_user.id, "global": True}, ], }, @@ -707,7 +713,10 @@ async def _on_message_passive_afk_user_mention(self, message: discord.Message): "$and": [ { "$or": [ - {"messageAuthor": user.id, "guild": message.guild.id}, + { + "messageAuthor": user.id, + "guild": message.guild.id, + }, {"messageAuthor": user.id, "global": True}, ], }, diff --git a/interactions/buttons/__aki.py b/interactions/buttons/__aki.py index 7a4e5ebe..f8c86bfb 100644 --- a/interactions/buttons/__aki.py +++ b/interactions/buttons/__aki.py @@ -6,7 +6,13 @@ from enum import Enum from typing import TYPE_CHECKING, Any, ClassVar, Final -from akinator import Answer, AsyncAkinator as AkinatorGame, CantGoBackAnyFurther, Language, Theme +from akinator import ( + Answer, + AsyncAkinator as AkinatorGame, + CantGoBackAnyFurther, + Language, + Theme, +) import discord from core import Context, Parrot diff --git a/interactions/buttons/__chess.py b/interactions/buttons/__chess.py index b0fb624c..88a7d80a 100644 --- a/interactions/buttons/__chess.py +++ b/interactions/buttons/__chess.py @@ -217,7 +217,7 @@ async def start(self): if msg.content.lower() == "draw": value = await self.ctx.prompt( f"**{msg.author}** offered draw! **{self.turn if self.turn.id != msg.author.id else self.alternate_turn}** to accept the draw click `Confirm`", - author_id=self.turn.id if self.turn.id != msg.author.id else self.alternate_turn.id, + author_id=(self.turn.id if self.turn.id != msg.author.id else self.alternate_turn.id), ) if value: msg_ = await self.ctx.send( @@ -252,8 +252,8 @@ async def add_db(self, **kwargs): "$push": { "game_chess_stat": { "game_chess_winner": kwargs["winner"], - "game_chess_player_1": _id if _id == self.white.id else self.black.id, - "game_chess_player_2": _id if _id == self.black.id else self.white.id, + "game_chess_player_1": (_id if _id == self.white.id else self.black.id), + "game_chess_player_2": (_id if _id == self.black.id else self.white.id), }, }, }, diff --git a/interactions/buttons/__games_utils.py b/interactions/buttons/__games_utils.py index a11011f0..822e6da2 100644 --- a/interactions/buttons/__games_utils.py +++ b/interactions/buttons/__games_utils.py @@ -559,8 +559,8 @@ async def start_game(self) -> None: if not coords: await self.game_over( "draw", - self.bot.user if isinstance(self.player_active, AI_C4) else self.player_active, - self.bot.user if isinstance(self.player_inactive, AI_C4) else self.player_inactive, + (self.bot.user if isinstance(self.player_active, AI_C4) else self.player_active), + (self.bot.user if isinstance(self.player_inactive, AI_C4) else self.player_inactive), ) else: coords = await self.player_turn() @@ -571,8 +571,8 @@ async def start_game(self) -> None: if self.check_win(coords, 1 if self.player_active == self.player1 else 2): await self.game_over( "win", - self.bot.user if isinstance(self.player_active, AI_C4) else self.player_active, - self.bot.user if isinstance(self.player_inactive, AI_C4) else self.player_inactive, + (self.bot.user if isinstance(self.player_active, AI_C4) else self.player_active), + (self.bot.user if isinstance(self.player_inactive, AI_C4) else self.player_inactive), ) return diff --git a/interactions/buttons/__number_slider.py b/interactions/buttons/__number_slider.py index a284ce8f..c900194b 100644 --- a/interactions/buttons/__number_slider.py +++ b/interactions/buttons/__number_slider.py @@ -17,7 +17,14 @@ Board: TypeAlias = list[list[int | None]] -from .utils import DEFAULT_COLOR, BaseView, DiscordColor, chunk, double_wait, wait_for_delete +from .utils import ( + DEFAULT_COLOR, + BaseView, + DiscordColor, + chunk, + double_wait, + wait_for_delete, +) class SlideButton(discord.ui.Button["SlideView"]): diff --git a/interactions/buttons/__wordle.py b/interactions/buttons/__wordle.py index 808e6799..7be244fc 100644 --- a/interactions/buttons/__wordle.py +++ b/interactions/buttons/__wordle.py @@ -201,7 +201,7 @@ class WordInputButton(discord.ui.Button["WordleView"]): def __init__(self, *, cancel_button: bool = False) -> None: super().__init__( label="Cancel" if cancel_button else "Make a guess!", - style=discord.ButtonStyle.red if cancel_button else discord.ButtonStyle.blurple, + style=(discord.ButtonStyle.red if cancel_button else discord.ButtonStyle.blurple), ) async def callback(self, interaction: discord.Interaction) -> None: diff --git a/interactions/buttons/games.py b/interactions/buttons/games.py index 821abfa9..1f938f30 100644 --- a/interactions/buttons/games.py +++ b/interactions/buttons/games.py @@ -32,7 +32,16 @@ from .__black_jack import BlackJackView from .__chess import Chess from .__chimp import ChimpTest -from .__constants import _2048_GAME, CHOICES, CROSS_EMOJI, EMOJI_CHECK, HAND_RAISED_EMOJI, SHORT_CHOICES, WINNER_DICT, Emojis +from .__constants import ( + _2048_GAME, + CHOICES, + CROSS_EMOJI, + EMOJI_CHECK, + HAND_RAISED_EMOJI, + SHORT_CHOICES, + WINNER_DICT, + Emojis, +) from .__country_guess import BetaCountryGuesser from .__duckgame import ( ANSWER_REGEX, @@ -984,7 +993,7 @@ async def end_game(self, channel: discord.TextChannel, game: DuckGame, end_messa title=end_message, color=discord.Color.dark_purple(), ) - scores: list[discord.Member, int] = sorted( + scores: list[discord.Member, int] = sorted( # type: ignore game.scores.items(), key=lambda item: item[1], reverse=True, diff --git a/tests/test_time.py b/tests/test_time.py index a530d650..515b320c 100644 --- a/tests/test_time.py +++ b/tests/test_time.py @@ -16,14 +16,20 @@ def setUp(self) -> None: ("2d3h", timedelta(days=2, hours=3)), ("1w", timedelta(weeks=1)), ("2w3d", timedelta(weeks=2, days=3)), - ("3w4d5h40m30s", timedelta(weeks=3, days=4, hours=5, minutes=40, seconds=30)), + ( + "3w4d5h40m30s", + timedelta(weeks=3, days=4, hours=5, minutes=40, seconds=30), + ), ] def test_shorttime(self): # sourcery skip: no-loop-in-tests for argument, expected in self.arguments: with self.subTest(argument=argument, expected=expected): - self.assertEqual(ShortTime(argument).dt.timestamp(), (datetime.now(timezone.utc) + expected).timestamp()) + self.assertEqual( + ShortTime(argument).dt.timestamp(), + (datetime.now(timezone.utc) + expected).timestamp(), + ) if __name__ == "__main__": diff --git a/utilities/checks.py b/utilities/checks.py index 6ce10015..362536fa 100644 --- a/utilities/checks.py +++ b/utilities/checks.py @@ -4,7 +4,14 @@ from collections.abc import Callable, Container, Iterable from typing import TYPE_CHECKING, TypeAlias -from discord.ext.commands import BucketType, Cog, Command, CommandOnCooldown, Cooldown, CooldownMapping +from discord.ext.commands import ( + BucketType, + Cog, + Command, + CommandOnCooldown, + Cooldown, + CooldownMapping, +) from pymongo.collection import Collection import discord diff --git a/utilities/converters.py b/utilities/converters.py index ccfdeaf3..6c121ee0 100644 --- a/utilities/converters.py +++ b/utilities/converters.py @@ -26,7 +26,21 @@ def convert_bool(text: Any) -> bool: """True/False converter.""" - return str(text).lower() in {"yes", "y", "true", "t", "1", "enable", "on", "o", "ok", "sure", "yeah", "yup", "right"} + return str(text).lower() in { + "yes", + "y", + "true", + "t", + "1", + "enable", + "on", + "o", + "ok", + "sure", + "yeah", + "yup", + "right", + } class ActionReason(commands.Converter): diff --git a/utilities/paginator.py b/utilities/paginator.py index 14333c0f..d882b726 100644 --- a/utilities/paginator.py +++ b/utilities/paginator.py @@ -461,7 +461,12 @@ async def paginate_embed(cls, ctx: Context, embed_list: list[PageT]): paginator = cls(embed_list) await paginator.start(ctx) - async def on_error(self, interaction: discord.Interaction[Parrot], exception: Exception, item: discord.ui.Item) -> None: + async def on_error( + self, + interaction: discord.Interaction[Parrot], + exception: Exception, + item: discord.ui.Item, + ) -> None: bot: Parrot = self.ctx.bot if isinstance(self.ctx, Context) else self.ctx.client bot.dispatch("error", interaction, exception) diff --git a/utilities/robopages.py b/utilities/robopages.py index d0de8608..6a26cb61 100644 --- a/utilities/robopages.py +++ b/utilities/robopages.py @@ -124,7 +124,10 @@ async def show_checked_page(self, interaction: discord.Interaction, page_number: pass async def interaction_check(self, interaction: discord.Interaction) -> bool: - if interaction.user and interaction.user.id in (self.ctx.bot.owner_id, self.ctx.author.id): + if interaction.user and interaction.user.id in ( + self.ctx.bot.owner_id, + self.ctx.author.id, + ): return True await interaction.response.send_message("This pagination menu cannot be controlled by you, sorry!", ephemeral=True) return False @@ -133,7 +136,12 @@ async def on_timeout(self) -> None: if self.message: await self.message.edit(view=None) - async def on_error(self, interaction: discord.Interaction[Parrot], error: Exception, item: discord.ui.Item) -> None: + async def on_error( + self, + interaction: discord.Interaction[Parrot], + error: Exception, + item: discord.ui.Item, + ) -> None: if await interaction.client.is_owner(interaction.user): raise error if interaction.response.is_done(): @@ -145,7 +153,10 @@ async def on_error(self, interaction: discord.Interaction[Parrot], error: Except async def start(self, *, content: str | None = None, ephemeral: bool = False) -> None: if self.check_embeds and not self.ctx.channel.permissions_for(self.ctx.me).embed_links: - await self.ctx.send("Bot does not have embed links permission in this channel.", ephemeral=True) + await self.ctx.send( + "Bot does not have embed links permission in this channel.", + ephemeral=True, + ) return await self.source._prepare_once()