Skip to content

Commit 129a6b3

Browse files
authored
refactor: cleanup base.py & sourcery-AI-refactor (#748)
* refactor: cleanup base.py & sourcery-AI-refactor * revert: remove colorama from requirements.txt
1 parent 6b49261 commit 129a6b3

File tree

10 files changed

+51
-116
lines changed

10 files changed

+51
-116
lines changed

interactions/api/gateway/client.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ async def _handle_connection(
239239
# self.sequence = None
240240
# self._closed = True
241241

242-
if bool(data) is False and op == OpCodeType.INVALIDATE_SESSION:
242+
if not bool(data) and op == OpCodeType.INVALIDATE_SESSION:
243243
self.session_id = None
244244

245245
await self.__restart()
@@ -272,11 +272,7 @@ def _dispatch_event(self, event: str, data: dict) -> None: # sourcery no-metric
272272
path: str = "interactions"
273273
path += ".models" if event == "INTERACTION_CREATE" else ".api.models"
274274
if event == "INTERACTION_CREATE":
275-
if not data.get("type"):
276-
log.warning(
277-
"Context is being created for the interaction, but no type is specified. Skipping..."
278-
)
279-
else:
275+
if data.get("type"):
280276
# sourcery skip: extract-method
281277
_context = self.__contextualize(data)
282278
_name: str = ""
@@ -339,6 +335,10 @@ def _dispatch_event(self, event: str, data: dict) -> None: # sourcery no-metric
339335
self._dispatch.dispatch(_name, *__args, **__kwargs)
340336
self._dispatch.dispatch("on_interaction", _context)
341337
self._dispatch.dispatch("on_interaction_create", _context)
338+
else:
339+
log.warning(
340+
"Context is being created for the interaction, but no type is specified. Skipping..."
341+
)
342342
elif event != "TYPING_START":
343343
name: str = event.lower()
344344
try:

interactions/api/models/channel.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def __init__(self, **kwargs):
5050
self.archive_timestamp = (
5151
datetime.fromisoformat(self._json.get("archive_timestamp"))
5252
if self._json.get("archive_timestamp")
53-
else datetime.utcnow()
53+
else datetime.now(timezone.utc)
5454
)
5555

5656

@@ -675,9 +675,8 @@ async def publish_message(
675675
raise AttributeError("HTTPClient not found!")
676676
from .message import Message
677677

678-
res = await self._client.publish_message(
679-
channel_id=int(self.id), message_id=int(message_id)
680-
)
678+
res = await self._client.publish_message(channel_id=int(self.id), message_id=message_id)
679+
681680
return Message(**res, _client=self._client)
682681

683682
async def get_pinned_messages(self) -> List["Message"]: # noqa
@@ -966,7 +965,7 @@ async def create_thread(
966965

967966
@property
968967
def url(self) -> str:
969-
_guild_id = "@me" if not isinstance(self.guild_id, int) else self.guild_id
968+
_guild_id = self.guild_id if isinstance(self.guild_id, int) else "@me"
970969
return f"https://discord.com/channels/{_guild_id}/{self.id}"
971970

972971
async def create_invite(

interactions/api/models/guild.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -666,7 +666,7 @@ async def create_thread(
666666
_message_id = None if message_id is MISSING else message_id
667667
res = await self._client.create_thread(
668668
channel_id=channel_id,
669-
thread_type=type.value if not isinstance(type, int) else type,
669+
thread_type=type if isinstance(type, int) else type.value,
670670
name=name,
671671
auto_archive_duration=_auto_archive_duration,
672672
invitable=_invitable,
@@ -1808,7 +1808,7 @@ async def get_list_of_members(
18081808
if not self._client:
18091809
raise AttributeError("HTTPClient not found!")
18101810
if after is not MISSING:
1811-
_after = int(after.id) if not isinstance(after, int) else after
1811+
_after = after if isinstance(after, int) else int(after.id)
18121812
else:
18131813
_after = None
18141814
res = await self._client.get_list_of_members(
@@ -1897,10 +1897,11 @@ def splash_url(self) -> Optional[str]:
18971897
:return: URL of the guild's invite splash banner (None will be returned if no banner is set)
18981898
:rtype: str
18991899
"""
1900-
if not self.banner:
1901-
return None
1902-
1903-
return f"https://cdn.discordapp.com/splashes/{int(self.id)}/{self.splash}.png"
1900+
return (
1901+
f"https://cdn.discordapp.com/splashes/{int(self.id)}/{self.splash}.png"
1902+
if self.banner
1903+
else None
1904+
)
19041905

19051906
@property
19061907
def discovery_splash_url(self) -> Optional[str]:
@@ -1909,10 +1910,11 @@ def discovery_splash_url(self) -> Optional[str]:
19091910
:return: URL of the guild's discovery splash banner (None will be returned if no banner is set)
19101911
:rtype: str
19111912
"""
1912-
if not self.banner:
1913-
return None
1914-
1915-
return f"https://cdn.discordapp.com/discovery-splashes/{int(self.id)}/{self.discovery_splash}.png"
1913+
return (
1914+
f"https://cdn.discordapp.com/discovery-splashes/{int(self.id)}/{self.discovery_splash}.png"
1915+
if self.banner
1916+
else None
1917+
)
19161918

19171919

19181920
class GuildPreview(DictSerializerMixin):

interactions/api/models/gw.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -230,9 +230,7 @@ def mention(self) -> str:
230230
:return: The string of the mentioned member.
231231
:rtype: str
232232
"""
233-
if self.nick:
234-
return f"<@!{self.user.id}>"
235-
return f"<@{self.user.id}>"
233+
return f"<@!{self.user.id}>" if self.nick else f"<@{self.user.id}>"
236234

237235
async def ban(
238236
self,

interactions/api/models/message.py

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -380,7 +380,7 @@ async def edit(
380380
if not self._client:
381381
raise AttributeError("HTTPClient not found!")
382382
if self.flags == 64:
383-
raise Exception("You cannot edit a hidden message!")
383+
raise TypeError("You cannot edit a hidden message!")
384384

385385
from ...client.models.component import _build_components
386386

@@ -398,10 +398,11 @@ async def edit(
398398
if embeds is MISSING:
399399
embeds = self.embeds
400400
_embeds: list = (
401-
[]
402-
if not embeds
403-
else ([embed._json for embed in embeds] if isinstance(embeds, list) else [embeds._json])
401+
([embed._json for embed in embeds] if isinstance(embeds, list) else [embeds._json])
402+
if embeds
403+
else []
404404
)
405+
405406
_allowed_mentions: dict = {} if allowed_mentions is MISSING else allowed_mentions
406407
_message_reference: dict = {} if message_reference is MISSING else message_reference._json
407408
if not components:
@@ -428,7 +429,7 @@ async def edit(
428429
files=files,
429430
)
430431

431-
msg = Message(**_dct) if not _dct.get("code") else payload
432+
msg = payload if _dct.get("code") else Message(**_dct)
432433

433434
for attr in self.__slots__:
434435
setattr(self, attr, getattr(msg, attr))
@@ -591,9 +592,7 @@ async def create_reaction(
591592
if not self._client:
592593
raise AttributeError("HTTPClient not found!")
593594

594-
_emoji = (
595-
emoji if not isinstance(emoji, Emoji) else f":{emoji.name.replace(':', '')}:{emoji.id}"
596-
)
595+
_emoji = f":{emoji.name.replace(':', '')}:{emoji.id}" if isinstance(emoji, Emoji) else emoji
597596

598597
return await self._client.create_reaction(
599598
channel_id=int(self.channel_id), message_id=int(self.id), emoji=_emoji
@@ -623,9 +622,8 @@ async def remove_all_reactions_of(
623622
if not self._client:
624623
raise AttributeError("HTTPClient not found!")
625624

626-
_emoji = (
627-
emoji if not isinstance(emoji, Emoji) else f":{emoji.name.replace(':', '')}:{emoji.id}"
628-
)
625+
_emoji = f":{emoji.name.replace(':', '')}:{emoji.id}" if isinstance(emoji, Emoji) else emoji
626+
629627
return await self._client.remove_all_reactions_of_emoji(
630628
channel_id=int(self.channel_id), message_id=int(self.id), emoji=_emoji
631629
)
@@ -643,9 +641,8 @@ async def remove_own_reaction_of(
643641
if not self._client:
644642
raise AttributeError("HTTPClient not found!")
645643

646-
_emoji = (
647-
emoji if not isinstance(emoji, Emoji) else f"{emoji.name.replace(':', '')}:{emoji.id}"
648-
)
644+
_emoji = f"{emoji.name.replace(':', '')}:{emoji.id}" if isinstance(emoji, Emoji) else emoji
645+
649646
return await self._client.remove_self_reaction(
650647
channel_id=int(self.channel_id), message_id=int(self.id), emoji=_emoji
651648
)
@@ -661,9 +658,8 @@ async def remove_reaction_from(
661658
:param user: The user or user_id to remove the reaction of
662659
:type user: Union[Member, user, int]
663660
"""
664-
_emoji = (
665-
emoji if not isinstance(emoji, Emoji) else f":{emoji.name.replace(':', '')}:{emoji.id}"
666-
)
661+
_emoji = f":{emoji.name.replace(':', '')}:{emoji.id}" if isinstance(emoji, Emoji) else emoji
662+
667663
_user_id = user if isinstance(user, int) else user.id
668664
return await self._client.remove_user_reaction(
669665
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:
699695
:return: The URL of said message
700696
:rtype: str
701697
"""
702-
guild = self.guild_id if self.guild_id else "@me"
698+
guild = self.guild_id or "@me"
703699
return f"https://discord.com/channels/{guild}/{self.channel_id}/{self.id}"
704700

705701

interactions/api/models/misc.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -259,11 +259,7 @@ def __init__(
259259
"File's first parameter 'filename' must be a string, not " + str(type(filename))
260260
)
261261

262-
if not fp or fp is MISSING:
263-
self._fp = open(filename, "rb")
264-
else:
265-
self._fp = fp
266-
262+
self._fp = open(filename, "rb") if not fp or fp is MISSING else fp
267263
self._filename = basename(filename)
268264

269265
if not description or description is MISSING:
@@ -288,7 +284,7 @@ def __init__(self, file: Union[str, FileIO], fp: Optional[IOBase] = MISSING):
288284
self._URI = "data:image/"
289285

290286
if fp is MISSING or isinstance(file, FileIO):
291-
file: FileIO = FileIO(file) if not isinstance(file, FileIO) else file
287+
file: FileIO = file if isinstance(file, FileIO) else FileIO(file)
292288

293289
self._name = file.name
294290
_file = file.read()

interactions/base.py

Lines changed: 4 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,77 +1,19 @@
11
import logging
2-
from typing import ClassVar, List
3-
4-
from colorama import Fore, Style, init
52

63
__version__ = "4.1.1-rc.1"
74
__authors__ = {
85
"current": [
9-
{"name": "James Walston<@goverfl0w>", "status": "Project Maintainer"},
10-
{"name": "DeltaX<@DeltaXWizard>", "status": "Project Lead"},
6+
{"name": "DeltaX<@DeltaXWizard>", "status": "Project Maintainer"},
117
{"name": "EdVraz<@EdVraz>", "status": "Developer"},
8+
{"name": "Astrea<@Astrea49>", "status": "Developer"},
9+
{"name": "Toricane<@Toricane>", "status": "Developer"},
1210
],
1311
"old": [
12+
{"name": "James Walston<@jameswalston>"},
1413
{"name": "Daniel Allen<@LordOfPolls>"},
1514
{"name": "eunwoo1104<@eunwoo1104>"},
1615
],
1716
}
1817

1918

20-
class Data:
21-
"""A class representing constants for the library.
22-
23-
:ivar LOG_LEVEL ClassVar[int]: The default level of logging as an integer
24-
:ivar LOGGERS List[str]: A list of all loggers registered from this library
25-
"""
26-
27-
LOG_LEVEL: ClassVar[int] = logging.ERROR
28-
LOGGERS: List[str] = []
29-
30-
31-
# def get_logger(
32-
# logger: Optional[Union[logging.Logger, str]] = None,
33-
# handler: Optional[logging.Handler] = logging.StreamHandler(),
34-
# ) -> logging.Logger:
35-
# _logger = logging.getLogger(logger) if isinstance(logger, str) else logger
36-
# _logger_name = logger if isinstance(logger, str) else logger.name
37-
# if len(_logger.handlers) > 1:
38-
# _logger.removeHandler(_logger.handlers[0])
39-
# _handler = handler
40-
# _handler.setFormatter(CustomFormatter)
41-
# _handler.setLevel(Data.LOG_LEVEL)
42-
# _logger.addHandler(_handler)
43-
# _logger.propagate = True
44-
45-
# Data.LOGGERS.append(_logger_name)
46-
# return _logger
47-
4819
get_logger = logging.getLogger
49-
50-
# TODO: clean up base.py
51-
52-
53-
class CustomFormatter(logging.Formatter):
54-
"""A class that allows for customized logged outputs from the library."""
55-
56-
format_str: str = "%(levelname)s:%(name)s:(ln.%(lineno)d):%(message)s"
57-
formats: dict = {
58-
logging.DEBUG: Fore.CYAN + format_str + Fore.RESET,
59-
logging.INFO: Fore.GREEN + format_str + Fore.RESET,
60-
logging.WARNING: Fore.YELLOW + format_str + Fore.RESET,
61-
logging.ERROR: Fore.RED + format_str + Fore.RESET,
62-
logging.CRITICAL: Style.BRIGHT + Fore.RED + format_str + Fore.RESET + Style.NORMAL,
63-
}
64-
65-
def __init__(self):
66-
super().__init__()
67-
init(autoreset=True)
68-
69-
def format(self, record):
70-
# reference
71-
# https://github.com/python/cpython/blob/3.10/Lib/logging/__init__.py#L420
72-
# https://github.com/python/cpython/blob/3.10/Lib/logging/__init__.py#L665-L695
73-
74-
# set format for the style class
75-
self._style._fmt = self.formats.get(record.levelno)
76-
# call the default formatting fuction
77-
return logging.Formatter.format(self, record)

interactions/client/models/component.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,7 @@ def __setattr__(self, key, value) -> None:
429429

430430

431431
def _build_components(components) -> List[dict]:
432+
# sourcery no-metrics
432433
def __check_action_row():
433434

434435
if isinstance(components, list) and all(
@@ -441,9 +442,10 @@ def __check_action_row():
441442
):
442443
if isinstance(component, SelectMenu):
443444
component._json["options"] = [
444-
option._json if not isinstance(option, dict) else option
445+
option if isinstance(option, dict) else option._json
445446
for option in component.options
446447
]
448+
447449
_components.append(
448450
{
449451
"type": 1,
@@ -484,9 +486,10 @@ def __check_components():
484486
for component in components:
485487
if isinstance(component, SelectMenu):
486488
component._json["options"] = [
487-
options._json if not isinstance(options, dict) else options
489+
options if isinstance(options, dict) else options._json
488490
for options in component._json["options"]
489491
]
492+
490493
_components = [
491494
{
492495
"type": 1,
@@ -513,9 +516,10 @@ def __check_components():
513516
elif isinstance(components, SelectMenu):
514517
_components: List[dict] = [{"type": 1, "components": []}]
515518
components._json["options"] = [
516-
options._json if not isinstance(options, dict) else options
519+
options if isinstance(options, dict) else options._json
517520
for options in components._json["options"]
518521
]
522+
519523
_components[0]["components"] = (
520524
[components._json]
521525
if components._json.get("custom_id") or components._json.get("url")

requirements.txt

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
11
aiohttp >= 3.8.1
2-
colorama
32
orjson

setup.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
with open("README.rst", "r", encoding="UTF-8") as f:
1111
README = f.read()
1212
with open(path.join(HERE, PACKAGE_NAME, "base.py"), encoding="utf-8") as fp:
13-
VERSION = re.search('__version__ = "([^"]+)"', fp.read()).group(1)
13+
VERSION = re.search('__version__ = "([^"]+)"', fp.read())[1]
1414

1515

1616
def read_requirements(filename):
@@ -24,7 +24,6 @@ def read_requirements(filename):
2424
}
2525
extras["dev"] = extras["lint"] + extras["readthedocs"]
2626
requirements = read_requirements("requirements.txt")
27-
2827
setup(
2928
name="discord-py-interactions",
3029
version=VERSION,

0 commit comments

Comments
 (0)