diff --git a/cogs/automod/__init__.py b/cogs/automod/__init__.py index a259ef2b..517a6e40 100644 --- a/cogs/automod/__init__.py +++ b/cogs/automod/__init__.py @@ -250,8 +250,8 @@ async def automod_add(self, ctx: Context, *, rule: str) -> None: "trigger": view.triggers, "condition": view.conditions, "action": view.actions, - } - } + }, + }, }, upsert=True, ) @@ -283,8 +283,8 @@ async def automod_edit(self, ctx: Context, *, rule: str) -> None: "trigger": view.triggers, "condition": view.conditions, "action": view.actions, - } - } + }, + }, }, ) await self.refresh_cache_specific(ctx.guild.id) diff --git a/cogs/config/config.py b/cogs/config/config.py index 42810aa9..4540732a 100644 --- a/cogs/config/config.py +++ b/cogs/config/config.py @@ -386,19 +386,19 @@ async def telephone(self, ctx: Context): """To set the telephone phone line, in the server to call and receive the call from other server.""" if not ctx.invoked_subcommand: data = await self.bot.guild_configurations.find_one({"_id": ctx.guild.id}) - if data: - role = str(ctx.guild.get_role(data["pingrole"])) if data.get("pingrole") else None - channel = str(ctx.guild.get_channel(data["channel"])) if data.get("channel") else None - member = ( - await self.bot.get_or_fetch_member(ctx.guild, data["memberping"]) if data.get("memberping") else None - ) - await ctx.reply( - f"Configuration of this server [telsetup]\n\n" - f"`Channel :` **{channel}**\n" - f"`Pingrole :` **{role} ({data['pingrole'] or None})**\n" - f"`MemberPing:` **{member} ({data['memberping'] or None})**\n" - f"`Blocked :` **{', '.join(data['blocked']) or None}**", - ) + if data is None: + return + + role = str(ctx.guild.get_role(data["pingrole"])) if data.get("pingrole") else None + channel = str(ctx.guild.get_channel(data["channel"])) if data.get("channel") else None + member = await self.bot.get_or_fetch_member(ctx.guild, data["memberping"]) if data.get("memberping") else None + await ctx.reply( + f"Configuration of this server [telsetup]\n\n" + f"`Channel :` **{channel}**\n" + f"`Pingrole :` **{role} ({data['pingrole'] or None})**\n" + f"`MemberPing:` **{member} ({data['memberping'] or None})**\n" + f"`Blocked :` **{', '.join(data['blocked']) or None}**", + ) @telephone.command(name="channel") @commands.has_permissions(administrator=True) diff --git a/cogs/defcon/defcon.py b/cogs/defcon/defcon.py index 8dee4ec8..891e1764 100644 --- a/cogs/defcon/defcon.py +++ b/cogs/defcon/defcon.py @@ -419,7 +419,7 @@ async def defcon_broadcast(self, ctx: Context, channel: discord.TextChannel = No "$set": { "default_defcon.broadcast.enabled": True, "default_defcon.broadcast.channel": channel.id, - } + }, }, upsert=True, ) diff --git a/cogs/mod/mod.py b/cogs/mod/mod.py index 0ecfd51b..0005d9fc 100644 --- a/cogs/mod/mod.py +++ b/cogs/mod/mod.py @@ -10,12 +10,7 @@ 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 diff --git a/cogs/nasa/nasa.py b/cogs/nasa/nasa.py index f9008592..c6586433 100644 --- a/cogs/nasa/nasa.py +++ b/cogs/nasa/nasa.py @@ -200,7 +200,8 @@ async def apod_loop(self) -> None: await channel.send(embed=embed) await self.bot.guild_configurations.update_one( - {"_id": data["_id"]}, {"$set": {"apod_last": discord.utils.utcnow()}} + {"_id": data["_id"]}, + {"$set": {"apod_last": discord.utils.utcnow()}}, ) @commands.command() diff --git a/cogs/reminder/__init__.py b/cogs/reminder/__init__.py index a7d5afac..7054a2ae 100644 --- a/cogs/reminder/__init__.py +++ b/cogs/reminder/__init__.py @@ -148,10 +148,7 @@ async def _list(self, ctx: Context) -> None: @remindme.command(name="info", aliases=["details", "detail", "i"]) async def info(self, ctx: Context, *, id: str) -> None: """Shows the details of the reminder.""" - if not id.isdigit(): - message = str_to_snowflake(id) - else: - message = int(id) + message = int(id) if id.isdigit() else str_to_snowflake(id) data = await self.collection.find_one({"messageAuthor": ctx.author.id, "_id": message}) if not data: await ctx.reply(f"{ctx.author.mention} reminder of ID: **{id}** not found. ID is case sensitive") @@ -172,10 +169,7 @@ async def info(self, ctx: Context, *, id: str) -> None: @remindme.command(name="del", aliases=["delete", "remove", "rm"]) async def delremind(self, ctx: Context, *, id: str) -> None: """To delete the reminder.""" - if not id.isdigit(): - message = str_to_snowflake(id) - else: - message = int(id) + message = int(id) if id.isdigit() else str_to_snowflake(id) timer = await self.bot.get_timer(_id=message) if not timer: await ctx.reply(f"{ctx.author.mention} reminder of ID: **{id}** not found. ID is case sensitive") diff --git a/cogs/rtfm/rtfm.py b/cogs/rtfm/rtfm.py index 7126bd0f..9c87f301 100644 --- a/cogs/rtfm/rtfm.py +++ b/cogs/rtfm/rtfm.py @@ -31,7 +31,7 @@ from utilities.converters import WrappedMessageConverter from . import _doc, _ref -from ._kontests import AtCoder, CodeChef, CodeForces, CSAcademy, HackerEarth, HackerRank +from ._kontests import AtCoder, CodeForces, CSAcademy, HackerEarth, HackerRank from ._used import execute_run, get_raw, prepare_payload from ._utils import ( ANSI_RE, diff --git a/cogs/suggestion/__init__.py b/cogs/suggestion/__init__.py index 854f5356..3b003ffa 100644 --- a/cogs/suggestion/__init__.py +++ b/cogs/suggestion/__init__.py @@ -158,7 +158,7 @@ async def __notify_on_suggestion(self, ctx: Context, *, message: discord.Message _id: int = message.id content = ( f"{ctx.author.mention} your suggestion being posted.\n" - f"To delete the suggestion type: `{ctx.clean_prefix or await ctx.bot.get_guild_prefixes(ctx.guild.id)}suggest delete {_id}`\n" + f"To delete the suggestion type: `{ctx.clean_prefix or await ctx.bot.get_guild_prefixes(ctx.guild)}suggest delete {_id}`\n" f"> {jump_url}" ) try: diff --git a/core/Parrot.py b/core/Parrot.py index 0ba57c74..bb3c55bb 100644 --- a/core/Parrot.py +++ b/core/Parrot.py @@ -11,15 +11,7 @@ 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 @@ -129,7 +121,7 @@ class Parrot(commands.AutoShardedBot): help_command: commands.HelpCommand | None http_session: ClientSession - mongo: AsyncMongoClient + mongo: AsyncMongoClient[dict] sql: aiosqlite.Connection redis: aioredis.Redis @@ -242,7 +234,7 @@ async def init_db(self) -> None: # MongoDB Database variables # Main DB self.main_db: MongoDatabase = self.mongo["mainDB"] - self.guild_configurations: MongoCollection = self.main_db["guildConfigurations"] + self.guild_configurations: MongoCollection[PostType] = self.main_db["guildConfigurations"] self.game_collections: MongoCollection = self.main_db["gameCollections"] self.command_collections: MongoCollection = self.main_db["commandCollections"] self.timers: MongoCollection = self.main_db["timers"] @@ -277,17 +269,6 @@ async def init_db(self) -> None: def __repr__(self) -> str: return f"" - def __getattribute__(self, __item) -> Any: - try: - return super().__getattribute__(__item) - except AttributeError: - cog = self.get_cog(__item) - if cog is not None: - return cog - - msg = f"'{self.__class__.__name__}' object has no attribute {__item!r}" - raise AttributeError(msg) - @property def config(self) -> Cache[int, PostType]: return cast(Cache[int, PostType], self.guild_configurations_cache) @@ -497,7 +478,7 @@ async def _execute_webhook( _CONTENT = content _FILE = kwargs.pop("file", discord.utils.MISSING) - if content and len(content) > 1990 or force_file: + if content is not None and len(content) > 1990 or force_file: _FILE: discord.File = discord.File( io.BytesIO(content.encode("utf-8") if isinstance(content, str) else content), filename=filename or "content.txt", @@ -512,7 +493,7 @@ async def _execute_webhook( content, ) return await webhook.send( - content=_CONTENT, + _CONTENT, file=_FILE, avatar_url=kwargs.pop("avatar_url", self.user.display_avatar.url), username=kwargs.pop("username", self.user.name), @@ -911,10 +892,7 @@ async def get_prefix(self, message: discord.Message) -> list[str]: prefix = match[1] return commands.when_mentioned_or(prefix)(self, message) - async def get_guild_prefixes(self, guild: discord.Guild | int) -> str: - if isinstance(guild, int): - guild: discord.Object = discord.Object(id=guild) - + async def get_guild_prefixes(self, guild: discord.Guild) -> str: try: return self.guild_configurations_cache[guild.id]["prefix"] except KeyError: @@ -1543,9 +1521,9 @@ async def wait_and_delete( timestamp: float | None = None, channel_id: int | None = None, message_id: int | None = None, - message: discord.Message = None, + message: discord.Message | None = None, ) -> None: - if message and delay: + if message is not None and delay: await message.delete(delay=delay) return @@ -1565,72 +1543,3 @@ async def wait_and_delete( }, }, ) - - # CREATE TABLE IF NOT EXISTS logs ( - # id INTEGER PRIMARY KEY AUTOINCREMENT, - # level INT NOT NULL, - # message TEXT NOT NULL, - # created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - # extra TEXT, - # UNIQUE(message, created_at) - # ); - - @overload - def log( - level: int | str, - message: str, - extra: dict[str, Any] | None = None, - ) -> None: - ... - - @overload - def log( - *, - level: int | str, - message: str, - extra: dict[str, Any] | None = None, - ) -> None: - ... - - @overload - def log( - level: int | str, - *, - message: str, - extra: dict[str, Any] | None = None, - ) -> None: - ... - - @staticmethod - def log( - *args: Any, - **kwargs: Any, - ) -> None: - mapping = { - "debug": "DEBUG", - "info": "INFO", - "warning": "WARNING", - "error": "ERROR", - "critical": "CRITICAL", - "0": "DEBUG", - "1": "INFO", - "2": "WARNING", - "3": "ERROR", - "4": "CRITICAL", - } - level = kwargs.get("level") or args[0] - message = kwargs.get("message") or args[1] - extra = kwargs.get("extra") or args[2] - level = mapping.get(str(level).lower(), "INFO") - Parrot.recieved_logs.append([level, message or "None", extra]) - - async def _log(self) -> None: - if self.recieved_logs: - query = """ - INSERT INTO logs (level, message, extra) VALUES (?, ?, ?) ON CONFLICT DO NOTHING; - """ - await self.sql.executemany(query, self.recieved_logs) - - @tasks.loop(minutes=1) - async def log_loop(self): - await self._log() diff --git a/core/types.py b/core/types.py index d1043661..6dfdb994 100644 --- a/core/types.py +++ b/core/types.py @@ -23,13 +23,7 @@ _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 @@ -179,7 +173,7 @@ async def delete_many( ) -> DeleteResult: ... - async def find_one(self, filter: Any | None = None, *args: Any, **kwargs: Any) -> Any: # noqa: A002 + async def find_one(self, filter: Any | None = None, *args: Any, **kwargs: Any) -> _DocumentType: # noqa: A002 ... def find(self, *args: Any, **kwargs: Any) -> AsyncIterator[Cursor[_DocumentType] | dict]: diff --git a/interactions/buttons/__aki.py b/interactions/buttons/__aki.py index f8c86bfb..7a4e5ebe 100644 --- a/interactions/buttons/__aki.py +++ b/interactions/buttons/__aki.py @@ -6,13 +6,7 @@ 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/__number_slider.py b/interactions/buttons/__number_slider.py index c900194b..a284ce8f 100644 --- a/interactions/buttons/__number_slider.py +++ b/interactions/buttons/__number_slider.py @@ -17,14 +17,7 @@ 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/games.py b/interactions/buttons/games.py index 1f938f30..37f1b525 100644 --- a/interactions/buttons/games.py +++ b/interactions/buttons/games.py @@ -32,16 +32,7 @@ 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, diff --git a/utilities/checks.py b/utilities/checks.py index 362536fa..6ce10015 100644 --- a/utilities/checks.py +++ b/utilities/checks.py @@ -4,14 +4,7 @@ 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