From 9a47e8ce5ec11bbc75b89c2939a31f112042b592 Mon Sep 17 00:00:00 2001 From: EdVraz <88881326+EdVraz@users.noreply.github.com> Date: Wed, 9 Nov 2022 20:08:41 +0100 Subject: [PATCH] refactor: Sourcery AI refactor holy fuck thats a lot --- interactions/api/gateway/client.py | 3 +- interactions/api/models/channel.py | 7 +-- interactions/api/models/guild.py | 4 +- interactions/api/models/gw.py | 5 +-- interactions/api/models/member.py | 14 ++---- interactions/api/models/message.py | 7 ++- interactions/api/models/webhook.py | 7 +-- interactions/client/bot.py | 32 +++++++------- interactions/client/context.py | 55 +++++++++--------------- interactions/client/models/command.py | 7 ++- interactions/client/models/component.py | 5 +-- interactions/client/models/misc.py | 5 +-- interactions/ext/version.py | 2 +- interactions/utils/abc/base_iterators.py | 8 ++-- interactions/utils/attrs_utils.py | 9 ++-- interactions/utils/get.py | 33 +++++++------- interactions/utils/utils.py | 4 +- 17 files changed, 90 insertions(+), 117 deletions(-) diff --git a/interactions/api/gateway/client.py b/interactions/api/gateway/client.py index 008f2b06f..27216ef41 100644 --- a/interactions/api/gateway/client.py +++ b/interactions/api/gateway/client.py @@ -291,8 +291,7 @@ async def _handle_stream(self, stream: Dict[str, Any]): event: Optional[str] = stream.get("t") data: Optional[Dict[str, Any]] = stream.get("d") - seq: Optional[str] = stream.get("s") - if seq: + if seq := stream.get("s"): self.sequence = seq if op != OpCodeType.DISPATCH: diff --git a/interactions/api/models/channel.py b/interactions/api/models/channel.py index 400560f3a..d988d81d6 100644 --- a/interactions/api/models/channel.py +++ b/interactions/api/models/channel.py @@ -235,8 +235,8 @@ async def __anext__(self) -> "Message": if not self.__stop and len(self.objects) < 5 and self.object_count <= self.maximum: await self.get_objects() - except IndexError: - raise StopAsyncIteration + except IndexError as e: + raise StopAsyncIteration from e else: return obj @@ -260,7 +260,8 @@ def __init__( except RuntimeError as e: raise RuntimeError("No running event loop detected!") from e - self.object_id = None if not obj else int(obj) if not hasattr(obj, "id") else int(obj.id) + self.object_id = (int(obj.id) if hasattr(obj, "id") else int(obj)) if obj else None + self._client = _client self.__task: Optional[Task] = None diff --git a/interactions/api/models/guild.py b/interactions/api/models/guild.py index 7216cb635..8f0a3cc7d 100644 --- a/interactions/api/models/guild.py +++ b/interactions/api/models/guild.py @@ -310,8 +310,8 @@ async def __anext__(self) -> Member: if not self.__stop and len(self.objects) < 5 and self.object_count <= self.maximum: await self.get_objects() - except IndexError: - raise StopAsyncIteration + except IndexError as e: + raise StopAsyncIteration from e else: return obj diff --git a/interactions/api/models/gw.py b/interactions/api/models/gw.py index 0bc79e935..a4c65e5c2 100644 --- a/interactions/api/models/gw.py +++ b/interactions/api/models/gw.py @@ -494,9 +494,8 @@ class MessageReaction(ClientSerializerMixin): emoji: Optional[Emoji] = field(converter=Emoji, default=None) def __attrs_post_init__(self): - if self.member: - if self.guild_id: - self.member._extras["guild_id"] = self.guild_id + if self.member and self.guild_id: + self.member._extras["guild_id"] = self.guild_id class MessageReactionRemove(MessageReaction): diff --git a/interactions/api/models/member.py b/interactions/api/models/member.py index 57a7bd596..4ebcf9946 100644 --- a/interactions/api/models/member.py +++ b/interactions/api/models/member.py @@ -129,7 +129,7 @@ def check(_member: Member): self._extras["guild_id"] = int(possible_guilds[0].id) return possible_guilds[0].id - elif len(possible_guilds) == 0: + elif not possible_guilds: possible_guilds = list(self._client.cache[Guild].values.values()) for guild in possible_guilds: @@ -548,7 +548,7 @@ async def get_guild_permissions( raise _guild_id else: - _guild_id = int(guild_id) if not isinstance(guild_id, Guild) else int(guild_id.id) + _guild_id = int(guild_id.id) if isinstance(guild_id, Guild) else int(guild_id) guild = Guild(**await self._client.get_guild(int(_guild_id)), _client=self._client) @@ -595,12 +595,6 @@ async def has_permissions( ) if operator == "and": - for perm in permissions: - if perm not in perms: - return False - return True + return all(perm in perms for perm in permissions) else: - for perm in permissions: - if perm in perms: - return True - return False + return any(perm in perms for perm in permissions) diff --git a/interactions/api/models/message.py b/interactions/api/models/message.py index 84806dc04..4f83e0f0d 100644 --- a/interactions/api/models/message.py +++ b/interactions/api/models/message.py @@ -798,9 +798,8 @@ class Message(ClientSerializerMixin, IDMixin): position: Optional[int] = field(default=None, repr=False) def __attrs_post_init__(self): - if self.member: - if self.guild_id: - self.member._extras["guild_id"] = self.guild_id + if self.member and self.guild_id: + self.member._extras["guild_id"] = self.guild_id if self.author and self.member: self.member.user = self.author @@ -862,7 +861,7 @@ async def edit( List["SelectMenu"], ] ] = MISSING, - ) -> "Message": + ) -> "Message": # sourcery skip: low-code-quality """ This method edits a message. Only available for messages sent by the bot. diff --git a/interactions/api/models/webhook.py b/interactions/api/models/webhook.py index b8ffb9fb0..d7addba97 100644 --- a/interactions/api/models/webhook.py +++ b/interactions/api/models/webhook.py @@ -185,7 +185,7 @@ async def execute( ] = MISSING, files: Optional[Union[File, List[File]]] = MISSING, thread_id: Optional[int] = MISSING, - ) -> Optional["Message"]: + ) -> Optional["Message"]: # sourcery skip: low-code-quality """ Executes the webhook. All parameters to this function are optional. @@ -267,10 +267,7 @@ async def execute( thread_id=thread_id if thread_id is not MISSING else None, ) - if not isinstance(res, dict): - return res - - return Message(**res, _client=self._client) + return Message(**res, _client=self._client) if isinstance(res, dict) else res async def delete(self) -> None: """ diff --git a/interactions/client/bot.py b/interactions/client/bot.py index 6286dda99..6c38e00a0 100644 --- a/interactions/client/bot.py +++ b/interactions/client/bot.py @@ -116,9 +116,7 @@ def __init__( presence=self._presence, ) - _logging = kwargs.get("logging", _logging) - if _logging: - + if _logging := kwargs.get("logging", _logging): # thx i0 for posting this on the retux Discord if _logging is True: @@ -378,30 +376,32 @@ async def _ready(self) -> None: | |___ CALLBACK LOOP """ - ready: bool = False - if isinstance(self._http, str): self._http = HTTPClient(self._http, self._cache) data = await self._http.get_current_bot_information() self.me = Application(**data, _client=self._http) + ready: bool = False try: if self.me.flags is not None: # This can be None. - if self._intents.GUILD_PRESENCES in self._intents and not ( - self.me.flags.GATEWAY_PRESENCE in self.me.flags - or self.me.flags.GATEWAY_PRESENCE_LIMITED in self.me.flags + if ( + self._intents.GUILD_PRESENCES in self._intents + and self.me.flags.GATEWAY_PRESENCE not in self.me.flags + and self.me.flags.GATEWAY_PRESENCE_LIMITED not in self.me.flags ): raise RuntimeError("Client not authorised for the GUILD_PRESENCES intent.") - if self._intents.GUILD_MEMBERS in self._intents and not ( - self.me.flags.GATEWAY_GUILD_MEMBERS in self.me.flags - or self.me.flags.GATEWAY_GUILD_MEMBERS_LIMITED in self.me.flags + if ( + self._intents.GUILD_MEMBERS in self._intents + and self.me.flags.GATEWAY_GUILD_MEMBERS not in self.me.flags + and self.me.flags.GATEWAY_GUILD_MEMBERS_LIMITED not in self.me.flags ): raise RuntimeError("Client not authorised for the GUILD_MEMBERS intent.") - if self._intents.GUILD_MESSAGES in self._intents and not ( - self.me.flags.GATEWAY_MESSAGE_CONTENT in self.me.flags - or self.me.flags.GATEWAY_MESSAGE_CONTENT_LIMITED in self.me.flags + if ( + self._intents.GUILD_MESSAGES in self._intents + and self.me.flags.GATEWAY_MESSAGE_CONTENT not in self.me.flags + and self.me.flags.GATEWAY_MESSAGE_CONTENT_LIMITED not in self.me.flags ): log.critical("Client not authorised for the MESSAGE_CONTENT intent.") elif self._intents.value != Intents.DEFAULT.value: @@ -494,7 +494,7 @@ async def __get_all_commands(self) -> None: ) except LibraryException as e: if int(e.code) != 50001: - raise LibraryException(code=e.code, message=e.message) + raise LibraryException(code=e.code, message=e.message) from e log.warning( f"Your bot is missing access to guild with corresponding id {_id}! " @@ -510,7 +510,7 @@ async def __get_all_commands(self) -> None: self.__guild_commands[_id] = {"commands": _cmds, "clean": True} - def __resolve_commands(self) -> None: + def __resolve_commands(self) -> None: # sourcery skip: low-code-quality """ Resolves all commands to the command coroutines. diff --git a/interactions/client/context.py b/interactions/client/context.py index b4b479255..4d43c16f8 100644 --- a/interactions/client/context.py +++ b/interactions/client/context.py @@ -68,9 +68,8 @@ class _Context(ClientSerializerMixin): app_permissions: Permissions = field(converter=convert_int(Permissions), default=None) def __attrs_post_init__(self) -> None: - if self.member: - if self.guild_id: - self.member._extras["guild_id"] = self.guild_id + if self.member and self.guild_id: + self.member._extras["guild_id"] = self.guild_id self.author = self.member @@ -211,7 +210,7 @@ async def edit( components: Optional[ Union[ActionRow, Button, SelectMenu, List[ActionRow], List[Button], List[SelectMenu]] ] = MISSING, - ) -> dict: + ) -> dict: # sourcery skip: low-code-quality """ This allows the invocation state described in the "context" to send an interaction response. This inherits the arguments @@ -317,15 +316,9 @@ async def has_permissions( :rtype: bool """ if operator == "and": - for perm in permissions: - if perm not in self.author.permissions: - return False - return True + return all(perm in self.author.permissions for perm in permissions) else: - for perm in permissions: - if perm in self.author.permissions: - return True - return False + return any(perm in self.author.permissions for perm in permissions) @define() @@ -377,7 +370,9 @@ def __attrs_post_init__(self) -> None: self.target._client = self._client - async def edit(self, content: Optional[str] = MISSING, **kwargs) -> Message: + async def edit( + self, content: Optional[str] = MISSING, **kwargs + ) -> Message: # sourcery skip: low-code-quality payload = await super().edit(content, **kwargs) msg = None @@ -432,9 +427,7 @@ async def edit(self, content: Optional[str] = MISSING, **kwargs) -> Message: else: self.message = msg = Message(**res, _client=self._client) - if msg is not None: - return msg - return Message(**payload, _client=self._client) + return msg if msg is not None else Message(**payload, _client=self._client) async def defer(self, ephemeral: Optional[bool] = False) -> None: """ @@ -614,10 +607,7 @@ async def edit(self, content: Optional[str] = MISSING, **kwargs) -> Message: self.responded = True self.message = msg = Message(**res, _client=self._client) - if msg is not None: - return msg - - return Message(**payload, _client=self._client) + return msg if msg is not None else Message(**payload, _client=self._client) async def send(self, content: Optional[str] = MISSING, **kwargs) -> Message: payload = await super().send(content, **kwargs) @@ -653,9 +643,7 @@ async def send(self, content: Optional[str] = MISSING, **kwargs) -> Message: self.responded = True - if msg is not None: - return msg - return Message(**payload, _client=self._client) + return msg if msg is not None else Message(**payload, _client=self._client) async def defer( self, ephemeral: Optional[bool] = False, edit_origin: Optional[bool] = False @@ -702,18 +690,17 @@ async def disable_all_components( if not respond_to_interaction: return await self.message.disable_all_components() - else: - for components in self.message.components: - for component in components.components: - component.disabled = True + for components in self.message.components: + for component in components.components: + component.disabled = True - if other_kwargs.get("components"): - raise LibraryException( - 12, "You must not specify the `components` argument in this method." - ) + if other_kwargs.get("components"): + raise LibraryException( + 12, "You must not specify the `components` argument in this method." + ) - other_kwargs["components"] = self.message.components - return await self.edit(**other_kwargs) + other_kwargs["components"] = self.message.components + return await self.edit(**other_kwargs) @property def custom_id(self) -> Optional[str]: @@ -731,7 +718,7 @@ def label(self) -> Optional[str]: :rtype: Optional[str] """ - if not self.data.component_type == ComponentType.BUTTON: + if self.data.component_type != ComponentType.BUTTON: return if self.message is None: return diff --git a/interactions/client/models/command.py b/interactions/client/models/command.py index e221a59c2..e6e7ff110 100644 --- a/interactions/client/models/command.py +++ b/interactions/client/models/command.py @@ -1,3 +1,4 @@ +import contextlib from asyncio import CancelledError from functools import wraps from inspect import getdoc, signature @@ -784,7 +785,7 @@ async def __call( _name: Optional[str] = None, _res: Optional[Union[BaseResult, GroupResult]] = None, **kwargs, - ) -> Optional[Any]: + ) -> Optional[Any]: # sourcery skip: low-code-quality """Handles calling the coroutine based on parameter count.""" params = signature(coro).parameters param_len = len(params) @@ -802,7 +803,7 @@ async def __call( ] # parameters that are before *args and **kwargs keyword_only_args = list(params.keys())[index_of_var_pos:] # parameters after *args - try: + with contextlib.suppress(CancelledError): _coro = coro if hasattr(coro, "_wrapped") else self.__wrap_coro(coro) if last.kind == last.VAR_KEYWORD: # foo(ctx, ..., **kwargs) @@ -848,8 +849,6 @@ async def __call( return await _coro(ctx, _res, *args, **kwargs) return await _coro(ctx, *args, **kwargs) - except CancelledError: - pass def __check_command(self, command_type: str) -> None: """Checks if subcommands, groups, or autocompletions are created on context menus.""" diff --git a/interactions/client/models/component.py b/interactions/client/models/component.py index 26026c24c..0978c21fd 100644 --- a/interactions/client/models/component.py +++ b/interactions/client/models/component.py @@ -455,7 +455,4 @@ def __check_components(): _components = __check_action_row() - if _components: - return _components - else: - return __check_components() + return _components or __check_components() diff --git a/interactions/client/models/misc.py b/interactions/client/models/misc.py index 6bff71fb0..3599d6df2 100644 --- a/interactions/client/models/misc.py +++ b/interactions/client/models/misc.py @@ -104,6 +104,5 @@ class Interaction(DictSerializerMixin): message: Optional[Message] = field(converter=Message, default=None, add_client=True) def __attrs_post_init__(self): - if self.member: - if self.guild_id: - self.member._extras["guild_id"] = self.guild_id + if self.member and self.guild_id: + self.member._extras["guild_id"] = self.guild_id diff --git a/interactions/ext/version.py b/interactions/ext/version.py index f37b2f161..2b363dc8f 100644 --- a/interactions/ext/version.py +++ b/interactions/ext/version.py @@ -193,7 +193,7 @@ def extend_version(cls, **kwargs) -> Union[Exception, str]: VersionAlphanumericType.RELEASE_CANDIDATE, ) amount: int = 0 - for key, value in kwargs: + for key, value in kwargs.items(): if key in identifiers and len(value) == 1: amount += 1 cls.__version = f"{cls.__version}-{key}.{value}" diff --git a/interactions/utils/abc/base_iterators.py b/interactions/utils/abc/base_iterators.py index c17d65846..e2fe63b16 100644 --- a/interactions/utils/abc/base_iterators.py +++ b/interactions/utils/abc/base_iterators.py @@ -44,7 +44,8 @@ def __init__( check: Optional[Callable[[_O], bool]] = None, ): - self.object_id = None if not obj else int(obj) if not hasattr(obj, "id") else int(obj.id) + self.object_id = (int(obj.id) if hasattr(obj, "id") else int(obj)) if obj else None + self.maximum = maximum self.check = check self._client = _client @@ -52,10 +53,11 @@ def __init__( self.start_at = ( None if start_at is MISSING - else int(start_at) - if not hasattr(start_at, "id") else int(start_at.id) + if hasattr(start_at, "id") + else int(start_at) ) + self.objects: Optional[List[_O]] = None diff --git a/interactions/utils/attrs_utils.py b/interactions/utils/attrs_utils.py index d1dd9e75f..adc5b97c6 100644 --- a/interactions/utils/attrs_utils.py +++ b/interactions/utils/attrs_utils.py @@ -57,11 +57,10 @@ def __init__(self, kwargs_dict: dict = None, /, **other_kwargs): item["_client"] = client elif isinstance(item, DictSerializerMixin): item._client = client - else: - if isinstance(value, dict): - value["_client"] = client - elif isinstance(value, DictSerializerMixin): - value._client = client + elif isinstance(value, dict): + value["_client"] = client + elif isinstance(value, DictSerializerMixin): + value._client = client # make sure json is recursively handled if isinstance(value, list): diff --git a/interactions/utils/get.py b/interactions/utils/get.py index 857038725..d3458f778 100644 --- a/interactions/utils/get.py +++ b/interactions/utils/get.py @@ -253,22 +253,23 @@ async def _http_request( _name: str = None, **kwargs, ) -> Union[_T, List[_T]]: - if not request: - if obj in (Role, Emoji): - from ..api.models.guild import Guild - - _guild = Guild(**await http.get_guild(kwargs.pop("guild_id")), _client=http) - _func = getattr(_guild, _name) - return await _func(**kwargs) - - _func = getattr(http, _name) - _obj = await _func(**kwargs) - return obj(**_obj, _client=http) - - if not isinstance(request, list): - return obj(**await request, _client=http) - - return [obj(**await req, _client=http) if isawaitable(req) else req for req in request] + if request: + return ( + [obj(**await req, _client=http) if isawaitable(req) else req for req in request] + if isinstance(request, list) + else obj(**await request, _client=http) + ) + + if obj in (Role, Emoji): + from ..api.models.guild import Guild + + _guild = Guild(**await http.get_guild(kwargs.pop("guild_id")), _client=http) + _func = getattr(_guild, _name) + return await _func(**kwargs) + + _func = getattr(http, _name) + _obj = await _func(**kwargs) + return obj(**_obj, _client=http) async def _return_cache( diff --git a/interactions/utils/utils.py b/interactions/utils/utils.py index fb76217ea..359776e5f 100644 --- a/interactions/utils/utils.py +++ b/interactions/utils/utils.py @@ -264,7 +264,7 @@ def get_channel_history( from ..api.models.channel import AsyncHistoryIterator return AsyncHistoryIterator( - http if not hasattr(http, "_http") else http._http, + http._http if hasattr(http, "_http") else http, channel, start_at=start_at, reverse=reverse, @@ -295,7 +295,7 @@ def get_guild_members( from ..api.models.guild import AsyncMembersIterator return AsyncMembersIterator( - http if not hasattr(http, "_http") else http._http, + http._http if hasattr(http, "_http") else http, guild, start_at=start_at, maximum=maximum,