Skip to content

Commit

Permalink
Merge pull request #1270 from interactions-py/unstable
Browse files Browse the repository at this point in the history
chore: Merge unstable to stable.
  • Loading branch information
FayeDel authored Feb 9, 2023
2 parents 5a76913 + be2ac0e commit 8bc3e1d
Show file tree
Hide file tree
Showing 37 changed files with 483 additions and 262 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ repos:
- id: check-merge-conflict
name: Merge Conflicts
- repo: https://github.com/psf/black
rev: 22.12.0
rev: 23.1.0
hooks:
- id: black
name: Black Formatting
Expand All @@ -45,7 +45,7 @@ repos:
types: [file, python]
args: [--max-line-length=100, --ignore=E203 E301 E302 E501 E402 E704 W503 W504]
- repo: https://github.com/pycqa/isort
rev: 5.11.4
rev: 5.12.0
hooks:
- id: isort
name: isort Formatting
Expand Down
8 changes: 8 additions & 0 deletions docs/events.rst
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ There are several different internal events:

- ``raw_socket_create``
- ``on_start``
- ``on_disconnect``
- ``on_interaction``
- ``on_command``
- ``on_command_error``
Expand Down Expand Up @@ -82,6 +83,13 @@ This function takes no arguments.
.. attention::
Unlike ``on_ready``, this event will never be dispatched more than once.

Event: ``on_disconnect``
^^^^^^^^^^^^^^^^^^^^^^^^^^^
This event fires whenever the connection is invalidated and will often precede an ``on_ready`` event

This function takes no arguments.


Event: ``on_interaction``
^^^^^^^^^^^^^^^^^^^^^^^^^^^
This event fires on any interaction (commands, components, autocomplete and modals).
Expand Down
1 change: 0 additions & 1 deletion interactions/api/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ def merge(self, item: _T, id: Optional["Key"] = None) -> None:
continue
# we can only assume that discord did not provide it, falsely deleting is worse than not deleting
if getattr(old_item, attrib) != getattr(item, attrib):

if isinstance(getattr(item, attrib), list) and not isinstance(
getattr(old_item, attrib), list
): # could be None
Expand Down
1 change: 0 additions & 1 deletion interactions/api/dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ def dispatch(self, name: str, /, *args, **kwargs) -> None:
if converters := getattr(event, "_converters", None):
_kwargs = kwargs.copy()
for key, value in _kwargs.items():

if key in converters.keys():
del kwargs[key]
kwargs[converters[key]] = value
Expand Down
1 change: 0 additions & 1 deletion interactions/api/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,6 @@ def __init__(self, code: int = 0, message: str = None, severity: int = 0, **kwar
self.log(self.message)

if _fmt_error:

_flag: bool = (
self.message.lower() in self.lookup(self.code).lower()
) # creativity is hard
Expand Down
14 changes: 7 additions & 7 deletions interactions/api/gateway/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
wait_for,
)
from contextlib import suppress
from enum import IntEnum
from sys import platform, version_info
from time import perf_counter
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, Union
Expand All @@ -26,7 +25,7 @@
from aiohttp import ClientWebSocketResponse, WSMessage, WSMsgType

from ...base import __version__, get_logger
from ...client.enums import ComponentType, InteractionType, OptionType
from ...client.enums import ComponentType, IntEnum, InteractionType, OptionType
from ...client.models import Option
from ...utils.missing import MISSING
from ..dispatch import Listener
Expand Down Expand Up @@ -242,7 +241,6 @@ async def _manage_heartbeat(self) -> None:
"""Manages the heartbeat loop."""
log.debug(f"Sending heartbeat every {self.__heartbeater.delay / 1000} seconds...")
while not self.__heartbeat_event.is_set():

log.debug("Sending heartbeat...")
if not self.__heartbeater.event.is_set():
log.debug("HEARTBEAT_ACK missing, reconnecting...")
Expand Down Expand Up @@ -404,7 +402,6 @@ def _dispatch_interaction_event(self, data: dict) -> None:
_option = self.__sub_command_context(option, _context)
__kwargs.update(_option)

self._dispatch.dispatch("on_command", _context)
elif data["type"] == InteractionType.MESSAGE_COMPONENT:
_name = f"component_{_context.data.custom_id}"

Expand Down Expand Up @@ -931,6 +928,12 @@ async def _reconnect(self, to_resume: bool, code: Optional[int] = 1012) -> None:
if self.__heartbeat_event.is_set():
self.__heartbeat_event.clear() # Because we're hardresetting the process

self._dispatch.dispatch(
"on_disconnect"
) # will be followed by the on_ready event after reconnection
# reconnection happens whenever it disconnects either with or without a resume prompt
# as this is called whenever the WS client closes

if not to_resume:
url = self.ws_url if self.ws_url else await self._http.get_gateway()
else:
Expand Down Expand Up @@ -963,7 +966,6 @@ async def __receive_packet(self, ignore_lock: bool = False) -> Optional[Dict[str
buffer = bytearray()

while True:

if not ignore_lock:
# meaning if we're reconnecting or something because of tasks
await self.__closed.wait()
Expand Down Expand Up @@ -1003,7 +1005,6 @@ async def __receive_packet(self, ignore_lock: bool = False) -> Optional[Dict[str
await self._reconnect(True)

elif packet.type == WSMsgType.CLOSING:

if ignore_lock:
raise LibraryException(
message="Discord unexpectedly closing on receiving by force.", severity=50
Expand Down Expand Up @@ -1061,7 +1062,6 @@ async def _send_packet(self, data: Dict[str, Any]) -> None:
await self._client.send_str(packet)
else:
async with self.reconnect_lock: # needs to lock while it reconnects.

if data["op"] != OpCodeType.HEARTBEAT.value:
# This is because the ratelimiter limits already accounts for this.
await self._ratelimiter.block()
Expand Down
2 changes: 0 additions & 2 deletions interactions/api/http/interaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,6 @@ async def create_interaction_response(

file_data = None
if files:

file_data = MultipartWriter("form-data")
part = file_data.append_json(data)
part.set_content_disposition("form-data", name="payload_json")
Expand Down Expand Up @@ -295,7 +294,6 @@ async def edit_interaction_response(
# ^ again, I don't know if python will let me
file_data = None
if files:

file_data = MultipartWriter("form-data")
part = file_data.append_json(data)
part.set_content_disposition("form-data", name="payload_json")
Expand Down
2 changes: 0 additions & 2 deletions interactions/api/http/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ async def create_message(

data = None
if files is not MISSING and len(files) > 0:

data = MultipartWriter("form-data")
part = data.append_json(payload)
part.set_content_disposition("form-data", name="payload_json")
Expand Down Expand Up @@ -172,7 +171,6 @@ async def edit_message(
"""
data = None
if files is not MISSING and len(files) > 0:

data = MultipartWriter("form-data")
part = data.append_json(payload)
part.set_content_disposition("form-data", name="payload_json")
Expand Down
2 changes: 1 addition & 1 deletion interactions/api/http/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ async def request(self, route: Route, **kwargs) -> Optional[Any]:
await asyncio.sleep(_limiter.reset_after)
continue
if remaining is not None and int(remaining) == 0:
log.warning(
log.debug(
f"The HTTP client has exhausted a per-route ratelimit. Locking route for {reset_after} seconds."
)
self._loop.call_later(reset_after, _limiter.release_lock)
Expand Down
1 change: 0 additions & 1 deletion interactions/api/http/thread.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,6 @@ async def create_thread_in_forum(

data = None
if files is not MISSING and files and len(files) > 0: # edge case `None`

data = MultipartWriter("form-data")
part = data.append_json(payload)
part.set_content_disposition("form-data", name="payload_json")
Expand Down
1 change: 0 additions & 1 deletion interactions/api/http/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@


class UserRequest:

_req: _Request
cache: Cache

Expand Down
2 changes: 0 additions & 2 deletions interactions/api/http/webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@


class WebhookRequest:

_req: _Request
cache: Cache

Expand Down Expand Up @@ -121,7 +120,6 @@ async def execute_webhook(

data = None
if files is not MISSING and len(files) > 0:

data = MultipartWriter("form-data")
part = data.append_json(payload)
part.set_content_disposition("form-data", name="payload_json")
Expand Down
4 changes: 2 additions & 2 deletions interactions/api/models/audit_log.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# versionadded declared in docs gen file

from enum import IntEnum
from typing import TYPE_CHECKING, List, Optional, TypeVar

from ...client.enums import IntEnum
from ...utils.attrs_utils import DictSerializerMixin, convert_list, define, field
from .channel import Channel
from .misc import Snowflake
Expand Down Expand Up @@ -235,7 +235,7 @@ class AuditLogEntry(DictSerializerMixin):
:ivar Snowflake id: ID of the entry
:ivar AuditLogEvents action_type: Type of action that occurred
:ivar OptionalAuditEntryInfo options: Additional info for certain event types
:ivar str reason: Reason for the change (1-512 characters)
:ivar Optional[str] reason: Reason for the change (1-512 characters)
"""

target_id: Optional[str] = field(default=None)
Expand Down
15 changes: 7 additions & 8 deletions interactions/api/models/channel.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from asyncio import Task, create_task, get_running_loop, sleep
from datetime import datetime, timedelta, timezone
from enum import IntEnum
from inspect import isawaitable
from math import inf
from typing import (
Expand All @@ -17,11 +16,13 @@
)
from warnings import warn

from ...client.enums import IntEnum
from ...utils.abc.base_context_managers import BaseAsyncContextManager
from ...utils.abc.base_iterators import DiscordPaginationIterator
from ...utils.attrs_utils import (
ClientSerializerMixin,
DictSerializerMixin,
convert_int,
convert_list,
define,
field,
Expand Down Expand Up @@ -232,7 +233,6 @@ async def __anext__(self) -> "Message":
obj = self.objects.pop(0)

if self.check:

res = self.check(obj)
_res = await res if isawaitable(res) else res
while not _res:
Expand Down Expand Up @@ -271,7 +271,6 @@ def __init__(
obj: Union[int, str, "Snowflake", "Channel"],
_client: "HTTPClient",
):

try:
self.loop = get_running_loop()
except RuntimeError as e:
Expand Down Expand Up @@ -433,7 +432,7 @@ class Channel(ClientSerializerMixin, IDMixin):
:ivar Optional[ThreadMetadata] thread_metadata: The thread metadata of the channel.
:ivar Optional[ThreadMember] member: The member of the thread in the channel.
:ivar Optional[int] default_auto_archive_duration: The set auto-archive time for all threads to naturally follow in the channel.
:ivar Optional[str] permissions: The permissions of the channel.
:ivar Optional[Permissions] permissions: The permissions of the channel.
:ivar Optional[int] flags: The flags of the channel.
:ivar Optional[int] total_message_sent: Number of messages ever sent in a thread.
:ivar Optional[int] default_thread_slowmode_delay: The default slowmode delay in seconds for threads, if this channel is a forum.
Expand Down Expand Up @@ -484,7 +483,9 @@ class Channel(ClientSerializerMixin, IDMixin):
converter=ThreadMember, default=None, add_client=True, repr=False
)
default_auto_archive_duration: Optional[int] = field(default=None)
permissions: Optional[str] = field(default=None, repr=False)
permissions: Optional[Permissions] = field(
converter=convert_int(Permissions), default=None, repr=False
)
flags: Optional[int] = field(default=None, repr=False)
total_message_sent: Optional[int] = field(default=None, repr=False)
default_thread_slowmode_delay: Optional[int] = field(default=None, repr=False)
Expand Down Expand Up @@ -1322,7 +1323,6 @@ async def bulk_delete():
_allowed_time = datetime.now(tz=timezone.utc) - timedelta(days=14)
_stop = False
while amount > 100:

messages = [
Message(**res)
for res in await self._client.get_channel_messages(
Expand Down Expand Up @@ -1938,7 +1938,6 @@ async def create_forum_post(
_content["attachments"].append(attach._json)

else:

_data = await attach.download()

__files.append(File(attach.filename, _data))
Expand Down Expand Up @@ -2070,7 +2069,7 @@ async def add_permission_overwrite(
_id = int(id)
_type = type

if not _type:
if _type is MISSING:
raise LibraryException(12, "Please set the type of the overwrite!")

overwrites.append(Overwrite(id=_id, type=_type, allow=allow, deny=deny))
Expand Down
34 changes: 31 additions & 3 deletions interactions/api/models/flags.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
from enum import Enum, IntFlag
from enum import IntFlag

__all__ = ("Intents", "AppFlags", "StatusType", "UserFlags", "Permissions", "MessageFlags")
from ...client.enums import StrEnum

__all__ = (
"Intents",
"AppFlags",
"StatusType",
"UserFlags",
"Permissions",
"MessageFlags",
"MemberFlags",
)


class Intents(IntFlag):
Expand Down Expand Up @@ -176,7 +186,7 @@ class AppFlags(IntFlag):
APPLICATION_COMMAND_BADGE = 1 << 23


class StatusType(str, Enum):
class StatusType(StrEnum):
"""
An enumerable object representing Discord status icons that a user may have.
"""
Expand Down Expand Up @@ -214,3 +224,21 @@ class MessageFlags(IntFlag):
EPHEMERAL = 1 << 6
LOADING = 1 << 7
FAILED_TO_MENTION_SOME_ROLES_IN_THREAD = 1 << 8


class MemberFlags(IntFlag):
"""
.. versionadded:: 4.4.0
An integer flag bitshift object representing member flags on the guild.
:ivar int DID_REJOIN: Member has left and rejoined the guild
:ivar int COMPLETED_ONBOARDING: Member has completed onboarding
:ivar int BYPASSES_VERIFICATION: Member bypasses guild verification requirements
:ivar int STARTED_ONBOARDING: Member has started onboarding
"""

DID_REJOIN = 1 << 0
COMPLETED_ONBOARDING = 1 << 1
BYPASSES_VERIFICATION = 1 << 2
STARTED_ONBOARDING = 1 << 3
Loading

0 comments on commit 8bc3e1d

Please sign in to comment.