From 2733c84724afdbb8e97f6ddce1daa9edd3023cf7 Mon Sep 17 00:00:00 2001 From: EdVraz <88881326+EdVraz@users.noreply.github.com> Date: Thu, 21 Apr 2022 22:00:50 +0200 Subject: [PATCH 1/2] refactor: cleanup base.py & sourcery-AI-refactor --- interactions/api/gateway/client.py | 12 ++--- interactions/api/models/channel.py | 9 ++-- interactions/api/models/guild.py | 22 +++++---- interactions/api/models/gw.py | 4 +- interactions/api/models/message.py | 32 ++++++------ interactions/api/models/misc.py | 8 +-- interactions/base.py | 66 ++----------------------- interactions/client/models/component.py | 10 ++-- setup.py | 3 +- 9 files changed, 51 insertions(+), 115 deletions(-) diff --git a/interactions/api/gateway/client.py b/interactions/api/gateway/client.py index 5b1b84388..7d12c4624 100644 --- a/interactions/api/gateway/client.py +++ b/interactions/api/gateway/client.py @@ -239,7 +239,7 @@ async def _handle_connection( # self.sequence = None # self._closed = True - if bool(data) is False and op == OpCodeType.INVALIDATE_SESSION: + if not bool(data) and op == OpCodeType.INVALIDATE_SESSION: self.session_id = None await self.__restart() @@ -272,11 +272,7 @@ def _dispatch_event(self, event: str, data: dict) -> None: # sourcery no-metric path: str = "interactions" path += ".models" if event == "INTERACTION_CREATE" else ".api.models" if event == "INTERACTION_CREATE": - if not data.get("type"): - log.warning( - "Context is being created for the interaction, but no type is specified. Skipping..." - ) - else: + if data.get("type"): # sourcery skip: extract-method _context = self.__contextualize(data) _name: str = "" @@ -339,6 +335,10 @@ def _dispatch_event(self, event: str, data: dict) -> None: # sourcery no-metric self._dispatch.dispatch(_name, *__args, **__kwargs) self._dispatch.dispatch("on_interaction", _context) self._dispatch.dispatch("on_interaction_create", _context) + else: + log.warning( + "Context is being created for the interaction, but no type is specified. Skipping..." + ) elif event != "TYPING_START": name: str = event.lower() try: diff --git a/interactions/api/models/channel.py b/interactions/api/models/channel.py index f814df670..363c2e159 100644 --- a/interactions/api/models/channel.py +++ b/interactions/api/models/channel.py @@ -50,7 +50,7 @@ def __init__(self, **kwargs): self.archive_timestamp = ( datetime.fromisoformat(self._json.get("archive_timestamp")) if self._json.get("archive_timestamp") - else datetime.utcnow() + else datetime.now(timezone.utc) ) @@ -675,9 +675,8 @@ async def publish_message( raise AttributeError("HTTPClient not found!") from .message import Message - res = await self._client.publish_message( - channel_id=int(self.id), message_id=int(message_id) - ) + res = await self._client.publish_message(channel_id=int(self.id), message_id=message_id) + return Message(**res, _client=self._client) async def get_pinned_messages(self) -> List["Message"]: # noqa @@ -966,7 +965,7 @@ async def create_thread( @property def url(self) -> str: - _guild_id = "@me" if not isinstance(self.guild_id, int) else self.guild_id + _guild_id = self.guild_id if isinstance(self.guild_id, int) else "@me" return f"https://discord.com/channels/{_guild_id}/{self.id}" async def create_invite( diff --git a/interactions/api/models/guild.py b/interactions/api/models/guild.py index 30994e457..aa360eae1 100644 --- a/interactions/api/models/guild.py +++ b/interactions/api/models/guild.py @@ -666,7 +666,7 @@ async def create_thread( _message_id = None if message_id is MISSING else message_id res = await self._client.create_thread( channel_id=channel_id, - thread_type=type.value if not isinstance(type, int) else type, + thread_type=type if isinstance(type, int) else type.value, name=name, auto_archive_duration=_auto_archive_duration, invitable=_invitable, @@ -1808,7 +1808,7 @@ async def get_list_of_members( if not self._client: raise AttributeError("HTTPClient not found!") if after is not MISSING: - _after = int(after.id) if not isinstance(after, int) else after + _after = after if isinstance(after, int) else int(after.id) else: _after = None res = await self._client.get_list_of_members( @@ -1897,10 +1897,11 @@ def splash_url(self) -> Optional[str]: :return: URL of the guild's invite splash banner (None will be returned if no banner is set) :rtype: str """ - if not self.banner: - return None - - return f"https://cdn.discordapp.com/splashes/{int(self.id)}/{self.splash}.png" + return ( + f"https://cdn.discordapp.com/splashes/{int(self.id)}/{self.splash}.png" + if self.banner + else None + ) @property def discovery_splash_url(self) -> Optional[str]: @@ -1909,10 +1910,11 @@ def discovery_splash_url(self) -> Optional[str]: :return: URL of the guild's discovery splash banner (None will be returned if no banner is set) :rtype: str """ - if not self.banner: - return None - - return f"https://cdn.discordapp.com/discovery-splashes/{int(self.id)}/{self.discovery_splash}.png" + return ( + f"https://cdn.discordapp.com/discovery-splashes/{int(self.id)}/{self.discovery_splash}.png" + if self.banner + else None + ) class GuildPreview(DictSerializerMixin): diff --git a/interactions/api/models/gw.py b/interactions/api/models/gw.py index 5fa182ad0..24f31a9cd 100644 --- a/interactions/api/models/gw.py +++ b/interactions/api/models/gw.py @@ -230,9 +230,7 @@ def mention(self) -> str: :return: The string of the mentioned member. :rtype: str """ - if self.nick: - return f"<@!{self.user.id}>" - return f"<@{self.user.id}>" + return f"<@!{self.user.id}>" if self.nick else f"<@{self.user.id}>" async def ban( self, diff --git a/interactions/api/models/message.py b/interactions/api/models/message.py index 3fa51ba64..31bf46812 100644 --- a/interactions/api/models/message.py +++ b/interactions/api/models/message.py @@ -380,7 +380,7 @@ async def edit( if not self._client: raise AttributeError("HTTPClient not found!") if self.flags == 64: - raise Exception("You cannot edit a hidden message!") + raise TypeError("You cannot edit a hidden message!") from ...client.models.component import _build_components @@ -398,10 +398,11 @@ async def edit( if embeds is MISSING: embeds = self.embeds _embeds: list = ( - [] - if not embeds - else ([embed._json for embed in embeds] if isinstance(embeds, list) else [embeds._json]) + ([embed._json for embed in embeds] if isinstance(embeds, list) else [embeds._json]) + if embeds + else [] ) + _allowed_mentions: dict = {} if allowed_mentions is MISSING else allowed_mentions _message_reference: dict = {} if message_reference is MISSING else message_reference._json if not components: @@ -428,7 +429,7 @@ async def edit( files=files, ) - msg = Message(**_dct) if not _dct.get("code") else payload + msg = payload if _dct.get("code") else Message(**_dct) for attr in self.__slots__: setattr(self, attr, getattr(msg, attr)) @@ -591,9 +592,7 @@ async def create_reaction( if not self._client: raise AttributeError("HTTPClient not found!") - _emoji = ( - emoji if not isinstance(emoji, Emoji) else f":{emoji.name.replace(':', '')}:{emoji.id}" - ) + _emoji = f":{emoji.name.replace(':', '')}:{emoji.id}" if isinstance(emoji, Emoji) else emoji return await self._client.create_reaction( channel_id=int(self.channel_id), message_id=int(self.id), emoji=_emoji @@ -623,9 +622,8 @@ async def remove_all_reactions_of( if not self._client: raise AttributeError("HTTPClient not found!") - _emoji = ( - emoji if not isinstance(emoji, Emoji) else f":{emoji.name.replace(':', '')}:{emoji.id}" - ) + _emoji = f":{emoji.name.replace(':', '')}:{emoji.id}" if isinstance(emoji, Emoji) else emoji + return await self._client.remove_all_reactions_of_emoji( channel_id=int(self.channel_id), message_id=int(self.id), emoji=_emoji ) @@ -643,9 +641,8 @@ async def remove_own_reaction_of( if not self._client: raise AttributeError("HTTPClient not found!") - _emoji = ( - emoji if not isinstance(emoji, Emoji) else f"{emoji.name.replace(':', '')}:{emoji.id}" - ) + _emoji = f"{emoji.name.replace(':', '')}:{emoji.id}" if isinstance(emoji, Emoji) else emoji + return await self._client.remove_self_reaction( channel_id=int(self.channel_id), message_id=int(self.id), emoji=_emoji ) @@ -661,9 +658,8 @@ async def remove_reaction_from( :param user: The user or user_id to remove the reaction of :type user: Union[Member, user, int] """ - _emoji = ( - emoji if not isinstance(emoji, Emoji) else f":{emoji.name.replace(':', '')}:{emoji.id}" - ) + _emoji = f":{emoji.name.replace(':', '')}:{emoji.id}" if isinstance(emoji, Emoji) else emoji + _user_id = user if isinstance(user, int) else user.id return await self._client.remove_user_reaction( channel_id=int(self.channel_id), message_id=int(self.id), user_id=_user_id, emoji=_emoji @@ -699,7 +695,7 @@ def url(self) -> str: :return: The URL of said message :rtype: str """ - guild = self.guild_id if self.guild_id else "@me" + guild = self.guild_id or "@me" return f"https://discord.com/channels/{guild}/{self.channel_id}/{self.id}" diff --git a/interactions/api/models/misc.py b/interactions/api/models/misc.py index aea4a3c15..d7a208628 100644 --- a/interactions/api/models/misc.py +++ b/interactions/api/models/misc.py @@ -259,11 +259,7 @@ def __init__( "File's first parameter 'filename' must be a string, not " + str(type(filename)) ) - if not fp or fp is MISSING: - self._fp = open(filename, "rb") - else: - self._fp = fp - + self._fp = open(filename, "rb") if not fp or fp is MISSING else fp self._filename = basename(filename) if not description or description is MISSING: @@ -288,7 +284,7 @@ def __init__(self, file: Union[str, FileIO], fp: Optional[IOBase] = MISSING): self._URI = "data:image/" if fp is MISSING or isinstance(file, FileIO): - file: FileIO = FileIO(file) if not isinstance(file, FileIO) else file + file: FileIO = file if isinstance(file, FileIO) else FileIO(file) self._name = file.name _file = file.read() diff --git a/interactions/base.py b/interactions/base.py index 972aee87d..24c3fa045 100644 --- a/interactions/base.py +++ b/interactions/base.py @@ -1,77 +1,19 @@ import logging -from typing import ClassVar, List - -from colorama import Fore, Style, init __version__ = "4.1.1-rc.1" __authors__ = { "current": [ - {"name": "James Walston<@goverfl0w>", "status": "Project Maintainer"}, - {"name": "DeltaX<@DeltaXWizard>", "status": "Project Lead"}, + {"name": "DeltaX<@DeltaXWizard>", "status": "Project Maintainer"}, {"name": "EdVraz<@EdVraz>", "status": "Developer"}, + {"name": "Astrea<@Astrea49>", "status": "Developer"}, + {"name": "Toricane<@Toricane>", "status": "Developer"}, ], "old": [ + {"name": "James Walston<@jameswalston>"}, {"name": "Daniel Allen<@LordOfPolls>"}, {"name": "eunwoo1104<@eunwoo1104>"}, ], } -class Data: - """A class representing constants for the library. - - :ivar LOG_LEVEL ClassVar[int]: The default level of logging as an integer - :ivar LOGGERS List[str]: A list of all loggers registered from this library - """ - - LOG_LEVEL: ClassVar[int] = logging.ERROR - LOGGERS: List[str] = [] - - -# def get_logger( -# logger: Optional[Union[logging.Logger, str]] = None, -# handler: Optional[logging.Handler] = logging.StreamHandler(), -# ) -> logging.Logger: -# _logger = logging.getLogger(logger) if isinstance(logger, str) else logger -# _logger_name = logger if isinstance(logger, str) else logger.name -# if len(_logger.handlers) > 1: -# _logger.removeHandler(_logger.handlers[0]) -# _handler = handler -# _handler.setFormatter(CustomFormatter) -# _handler.setLevel(Data.LOG_LEVEL) -# _logger.addHandler(_handler) -# _logger.propagate = True - -# Data.LOGGERS.append(_logger_name) -# return _logger - get_logger = logging.getLogger - -# TODO: clean up base.py - - -class CustomFormatter(logging.Formatter): - """A class that allows for customized logged outputs from the library.""" - - format_str: str = "%(levelname)s:%(name)s:(ln.%(lineno)d):%(message)s" - formats: dict = { - logging.DEBUG: Fore.CYAN + format_str + Fore.RESET, - logging.INFO: Fore.GREEN + format_str + Fore.RESET, - logging.WARNING: Fore.YELLOW + format_str + Fore.RESET, - logging.ERROR: Fore.RED + format_str + Fore.RESET, - logging.CRITICAL: Style.BRIGHT + Fore.RED + format_str + Fore.RESET + Style.NORMAL, - } - - def __init__(self): - super().__init__() - init(autoreset=True) - - def format(self, record): - # reference - # https://github.com/python/cpython/blob/3.10/Lib/logging/__init__.py#L420 - # https://github.com/python/cpython/blob/3.10/Lib/logging/__init__.py#L665-L695 - - # set format for the style class - self._style._fmt = self.formats.get(record.levelno) - # call the default formatting fuction - return logging.Formatter.format(self, record) diff --git a/interactions/client/models/component.py b/interactions/client/models/component.py index dbf5707e4..fa1b72e2e 100644 --- a/interactions/client/models/component.py +++ b/interactions/client/models/component.py @@ -429,6 +429,7 @@ def __setattr__(self, key, value) -> None: def _build_components(components) -> List[dict]: + # sourcery no-metrics def __check_action_row(): if isinstance(components, list) and all( @@ -441,9 +442,10 @@ def __check_action_row(): ): if isinstance(component, SelectMenu): component._json["options"] = [ - option._json if not isinstance(option, dict) else option + option if isinstance(option, dict) else option._json for option in component.options ] + _components.append( { "type": 1, @@ -484,9 +486,10 @@ def __check_components(): for component in components: if isinstance(component, SelectMenu): component._json["options"] = [ - options._json if not isinstance(options, dict) else options + options if isinstance(options, dict) else options._json for options in component._json["options"] ] + _components = [ { "type": 1, @@ -513,9 +516,10 @@ def __check_components(): elif isinstance(components, SelectMenu): _components: List[dict] = [{"type": 1, "components": []}] components._json["options"] = [ - options._json if not isinstance(options, dict) else options + options if isinstance(options, dict) else options._json for options in components._json["options"] ] + _components[0]["components"] = ( [components._json] if components._json.get("custom_id") or components._json.get("url") diff --git a/setup.py b/setup.py index f80f48e9c..35017c4cb 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ with open("README.rst", "r", encoding="UTF-8") as f: README = f.read() with open(path.join(HERE, PACKAGE_NAME, "base.py"), encoding="utf-8") as fp: - VERSION = re.search('__version__ = "([^"]+)"', fp.read()).group(1) + VERSION = re.search('__version__ = "([^"]+)"', fp.read())[1] def read_requirements(filename): @@ -24,7 +24,6 @@ def read_requirements(filename): } extras["dev"] = extras["lint"] + extras["readthedocs"] requirements = read_requirements("requirements.txt") - setup( name="discord-py-interactions", version=VERSION, From 869723f6580fc0e77cd1bc9ac7f722ed5ce3ee3c Mon Sep 17 00:00:00 2001 From: EdVraz <88881326+EdVraz@users.noreply.github.com> Date: Thu, 21 Apr 2022 22:03:19 +0200 Subject: [PATCH 2/2] revert: remove colorama from requirements.txt --- requirements.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index dd89d40fd..e394e23b5 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,2 @@ aiohttp >= 3.8.1 -colorama orjson