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
3 changes: 1 addition & 2 deletions interactions/api/gateway/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
7 changes: 4 additions & 3 deletions interactions/api/models/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down
4 changes: 2 additions & 2 deletions interactions/api/models/guild.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
5 changes: 2 additions & 3 deletions interactions/api/models/gw.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
14 changes: 4 additions & 10 deletions interactions/api/models/member.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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)
7 changes: 3 additions & 4 deletions interactions/api/models/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down
7 changes: 2 additions & 5 deletions interactions/api/models/webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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:
"""
Expand Down
32 changes: 16 additions & 16 deletions interactions/client/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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}! "
Expand All @@ -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.

Expand Down
55 changes: 21 additions & 34 deletions interactions/client/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
"""
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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]:
Expand All @@ -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
Expand Down
7 changes: 3 additions & 4 deletions interactions/client/models/command.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import contextlib
from asyncio import CancelledError
from functools import wraps
from inspect import getdoc, signature
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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."""
Expand Down
5 changes: 1 addition & 4 deletions interactions/client/models/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,4 @@ def __check_components():

_components = __check_action_row()

if _components:
return _components
else:
return __check_components()
return _components or __check_components()
5 changes: 2 additions & 3 deletions interactions/client/models/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion interactions/ext/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
Expand Down
Loading