Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions interactions/api/gateway/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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 = ""
Expand Down Expand Up @@ -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:
Expand Down
9 changes: 4 additions & 5 deletions interactions/api/models/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
)


Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
22 changes: 12 additions & 10 deletions interactions/api/models/guild.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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]:
Expand All @@ -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):
Expand Down
4 changes: 1 addition & 3 deletions interactions/api/models/gw.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
32 changes: 14 additions & 18 deletions interactions/api/models/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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:
Expand All @@ -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))
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
)
Expand All @@ -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
)
Expand All @@ -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
Expand Down Expand Up @@ -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}"


Expand Down
8 changes: 2 additions & 6 deletions interactions/api/models/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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()
Expand Down
66 changes: 4 additions & 62 deletions interactions/base.py
Original file line number Diff line number Diff line change
@@ -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)
10 changes: 7 additions & 3 deletions interactions/client/models/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand 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,
Expand Down Expand Up @@ -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,
Expand All @@ -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")
Expand Down
1 change: 0 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
aiohttp >= 3.8.1
colorama
orjson
3 changes: 1 addition & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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,
Expand Down