Skip to content

Commit

Permalink
Add support for guild scheduled events (#211)
Browse files Browse the repository at this point in the history
Co-authored-by: Izhar Ahmad <[email protected]>
  • Loading branch information
Middledot and izxxr authored Jan 1, 2022
1 parent 4ddf450 commit 7ca9d17
Show file tree
Hide file tree
Showing 21 changed files with 1,399 additions and 138 deletions.
1 change: 1 addition & 0 deletions discord/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
from .commands import *
from .cog import Cog
from .welcome_screen import *
from .scheduled_events import ScheduledEvent, ScheduledEventLocation


class VersionInfo(NamedTuple):
Expand Down
18 changes: 16 additions & 2 deletions discord/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
runtime_checkable,
)

from .scheduled_events import ScheduledEvent
from .iterators import HistoryIterator
from .context_managers import Typing
from .enums import ChannelType
Expand Down Expand Up @@ -1035,6 +1036,7 @@ async def create_invite(
max_uses: int = 0,
temporary: bool = False,
unique: bool = True,
target_event: Optional[ScheduledEvent] = None,
target_type: Optional[InviteTarget] = None,
target_user: Optional[User] = None,
target_application_id: Optional[int] = None,
Expand Down Expand Up @@ -1073,11 +1075,20 @@ async def create_invite(
.. versionadded:: 2.0
target_application_id:: Optional[:class:`int`]
target_application_id: Optional[:class:`int`]
The id of the embedded application for the invite, required if `target_type` is `TargetType.embedded_application`.
.. versionadded:: 2.0
target_event: Optional[:class:`ScheduledEvent`]
The scheduled event object to link to the event.
Shortcut to :meth:`Invite.set_scheduled_event`
See :meth:`Invite.set_scheduled_event` for more
info on event invite linking.
.. versionadded:: 2.0
Raises
-------
~discord.HTTPException
Expand All @@ -1103,7 +1114,10 @@ async def create_invite(
target_user_id=target_user.id if target_user else None,
target_application_id=target_application_id,
)
return Invite.from_incomplete(data=data, state=self._state)
invite = Invite.from_incomplete(data=data, state=self._state)
if target_event:
invite.set_scheduled_event(target_event)
return invite

async def invites(self) -> List[Invite]:
"""|coro|
Expand Down
31 changes: 27 additions & 4 deletions discord/audit_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@
from .stage_instance import StageInstance
from .sticker import GuildSticker
from .threads import Thread
from .scheduled_events import ScheduledEvent
from .state import ConnectionState


def _transform_permissions(entry: AuditLogEntry, data: str) -> Permissions:
Expand Down Expand Up @@ -147,7 +149,7 @@ def _transform(entry: AuditLogEntry, data: int) -> T:

return _transform

def _transform_type(entry: AuditLogEntry, data: Union[int]) -> Union[enums.ChannelType, enums.StickerType]:
def _transform_type(entry: AuditLogEntry, data: int) -> Union[enums.ChannelType, enums.StickerType]:
if entry.action.name.startswith('sticker_'):
return enums.try_enum(enums.StickerType, data)
else:
Expand Down Expand Up @@ -210,14 +212,16 @@ class AuditLogChanges:
'privacy_level': (None, _enum_transformer(enums.StagePrivacyLevel)),
'format_type': (None, _enum_transformer(enums.StickerFormatType)),
'type': (None, _transform_type),
'status': (None, _enum_transformer(enums.ScheduledEventStatus)),
'entity_type': ('location_type', _enum_transformer(enums.ScheduledEventLocationType)),
}
# fmt: on

def __init__(self, entry: AuditLogEntry, data: List[AuditLogChangePayload]):
def __init__(self, entry: AuditLogEntry, data: List[AuditLogChangePayload], *, state: ConnectionState):
self.before = AuditLogDiff()
self.after = AuditLogDiff()

for elem in data:
for elem in sorted(data, key=lambda i: i['key']):
attr = elem['key']

# special cases for role add/remove
Expand Down Expand Up @@ -246,6 +250,14 @@ def __init__(self, entry: AuditLogEntry, data: List[AuditLogChangePayload]):
if transformer:
before = transformer(entry, before)

if attr == 'location':
if hasattr(self.before, 'location_type'):
from .scheduled_events import ScheduledEventLocation
if self.before.location_type is enums.ScheduledEventLocationType.external:
before = ScheduledEventLocation(state=state, location=before)
elif hasattr(self.before, 'channel'):
before = ScheduledEventLocation(state=state, location=self.before.channel)

setattr(self.before, attr, before)

try:
Expand All @@ -256,6 +268,14 @@ def __init__(self, entry: AuditLogEntry, data: List[AuditLogChangePayload]):
if transformer:
after = transformer(entry, after)

if attr == 'location':
if hasattr(self.after, 'location_type'):
from .scheduled_events import ScheduledEventLocation
if self.after.location_type is enums.ScheduledEventLocationType.external:
after = ScheduledEventLocation(state=state, location=after)
elif hasattr(self.after, 'channel'):
after = ScheduledEventLocation(state=state, location=self.after.channel)

setattr(self.after, attr, after)

# add an alias
Expand Down Expand Up @@ -463,7 +483,7 @@ def category(self) -> enums.AuditLogActionCategory:
@utils.cached_property
def changes(self) -> AuditLogChanges:
""":class:`AuditLogChanges`: The list of changes this entry has."""
obj = AuditLogChanges(self, self._changes)
obj = AuditLogChanges(self, self._changes, state=self._state)
del self._changes
return obj

Expand Down Expand Up @@ -523,3 +543,6 @@ def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]

def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]:
return self.guild.get_thread(target_id) or Object(id=target_id)

def _convert_target_scheduled_event(self, target_id: int) -> Union[ScheduledEvent, None]:
return self.guild.get_scheduled_event(target_id) or Object(id=target_id)
11 changes: 9 additions & 2 deletions discord/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1337,7 +1337,7 @@ async def fetch_stage_instance(self, channel_id: int, /) -> StageInstance:

# Invite management

async def fetch_invite(self, url: Union[Invite, str], *, with_counts: bool = True, with_expiration: bool = True) -> Invite:
async def fetch_invite(self, url: Union[Invite, str], *, with_counts: bool = True, with_expiration: bool = True, event_id: Snowflake = None) -> Invite:
"""|coro|
Gets an :class:`.Invite` from a discord.gg URL or ID.
Expand All @@ -1361,6 +1361,13 @@ async def fetch_invite(self, url: Union[Invite, str], *, with_counts: bool = Tru
:attr:`.Invite.expires_at` field.
.. versionadded:: 2.0
event_id: :class:`int`
The ID of the scheduled event to be associated with the event.
See :meth:`Invite.set_scheduled_event` for more
info on event invite linking.
..versionadded:: 2.0
Raises
-------
Expand All @@ -1376,7 +1383,7 @@ async def fetch_invite(self, url: Union[Invite, str], *, with_counts: bool = Tru
"""

invite_id = utils.resolve_invite(url)
data = await self.http.get_invite(invite_id, with_counts=with_counts, with_expiration=with_expiration)
data = await self.http.get_invite(invite_id, with_counts=with_counts, with_expiration=with_expiration, guild_scheduled_event_id=event_id)
return Invite.from_incomplete(state=self._connection, data=data)

async def delete_invite(self, invite: Union[Invite, str]) -> None:
Expand Down
128 changes: 64 additions & 64 deletions discord/commands/errors.py
Original file line number Diff line number Diff line change
@@ -1,64 +1,64 @@
"""
The MIT License (MIT)
Copyright (c) 2021-present Pycord Development
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""

from ..errors import DiscordException

__all__ = (
"ApplicationCommandError",
"CheckFailure",
"ApplicationCommandInvokeError",
)

class ApplicationCommandError(DiscordException):
r"""The base exception type for all application command related errors.
This inherits from :exc:`discord.DiscordException`.
This exception and exceptions inherited from it are handled
in a special way as they are caught and passed into a special event
from :class:`.Bot`\, :func:`.on_command_error`.
"""
pass

class CheckFailure(ApplicationCommandError):
"""Exception raised when the predicates in :attr:`.Command.checks` have failed.
This inherits from :exc:`ApplicationCommandError`
"""
pass

class ApplicationCommandInvokeError(ApplicationCommandError):
"""Exception raised when the command being invoked raised an exception.
This inherits from :exc:`ApplicationCommandError`
Attributes
-----------
original: :exc:`Exception`
The original exception that was raised. You can also get this via
the ``__cause__`` attribute.
"""
def __init__(self, e: Exception) -> None:
self.original: Exception = e
super().__init__(f'Application Command raised an exception: {e.__class__.__name__}: {e}')
"""
The MIT License (MIT)
Copyright (c) 2021-present Pycord Development
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""

from ..errors import DiscordException

__all__ = (
"ApplicationCommandError",
"CheckFailure",
"ApplicationCommandInvokeError",
)

class ApplicationCommandError(DiscordException):
r"""The base exception type for all application command related errors.
This inherits from :exc:`discord.DiscordException`.
This exception and exceptions inherited from it are handled
in a special way as they are caught and passed into a special event
from :class:`.Bot`\, :func:`.on_command_error`.
"""
pass

class CheckFailure(ApplicationCommandError):
"""Exception raised when the predicates in :attr:`.Command.checks` have failed.
This inherits from :exc:`ApplicationCommandError`
"""
pass

class ApplicationCommandInvokeError(ApplicationCommandError):
"""Exception raised when the command being invoked raised an exception.
This inherits from :exc:`ApplicationCommandError`
Attributes
-----------
original: :exc:`Exception`
The original exception that was raised. You can also get this via
the ``__cause__`` attribute.
"""
def __init__(self, e: Exception) -> None:
self.original: Exception = e
super().__init__(f'Application Command raised an exception: {e.__class__.__name__}: {e}')
Loading

0 comments on commit 7ca9d17

Please sign in to comment.