Skip to content

Commit

Permalink
feat: implement remaining forum channel features (#726)
Browse files Browse the repository at this point in the history
Co-authored-by: onerandomusername <[email protected]>
  • Loading branch information
shiftinv and onerandomusername authored Sep 24, 2022
1 parent 62ad564 commit 1860aa7
Show file tree
Hide file tree
Showing 14 changed files with 856 additions and 75 deletions.
7 changes: 7 additions & 0 deletions changelog/724.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Implement remaining forum channel features.
- Add :class:`ForumTag` dataclass.
- Add :attr:`ForumChannel.available_tags` and :attr:`Thread.applied_tags`.
- Add :func:`ForumChannel.get_tag`, :func:`ForumChannel.get_tag_by_name`, :func:`Thread.add_tags` and :func:`Thread.remove_tags`.
- Add :attr:`ForumChannel.default_thread_slowmode_delay`, :attr:`ForumChannel.default_reaction`, and :attr:`ForumChannel.default_sort_order`.
- Add :attr:`ChannelFlags.require_tag` and :attr:`ForumChannel.requires_tag`.
- New audit log fields for the above features.
38 changes: 36 additions & 2 deletions disnake/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,13 @@

from . import utils
from .context_managers import Typing
from .enums import ChannelType, PartyType, VideoQualityMode, try_enum_to_int
from .enums import ChannelType, PartyType, ThreadSortOrder, VideoQualityMode, try_enum_to_int
from .errors import ClientException
from .file import File
from .flags import ChannelFlags, MessageFlags
from .invite import Invite
from .mentions import AllowedMentions
from .partial_emoji import PartialEmoji
from .permissions import PermissionOverwrite, Permissions
from .role import Role
from .sticker import GuildSticker, StickerItem
Expand Down Expand Up @@ -58,20 +59,23 @@
from .channel import CategoryChannel, DMChannel, PartialMessageable
from .client import Client
from .embeds import Embed
from .emoji import Emoji
from .enums import InviteTarget
from .guild import Guild, GuildMessageable
from .guild_scheduled_event import GuildScheduledEvent
from .iterators import HistoryIterator
from .member import Member
from .message import Message, MessageReference, PartialMessage
from .state import ConnectionState
from .threads import AnyThreadArchiveDuration
from .threads import AnyThreadArchiveDuration, ForumTag
from .types.channel import (
Channel as ChannelPayload,
DefaultReaction as DefaultReactionPayload,
GuildChannel as GuildChannelPayload,
OverwriteType,
PermissionOverwrite as PermissionOverwritePayload,
)
from .types.threads import PartialForumTag as PartialForumTagPayload
from .ui.action_row import Components, MessageUIComponent
from .ui.view import View
from .user import ClientUser
Expand Down Expand Up @@ -295,6 +299,7 @@ async def _edit(
sync_permissions: bool = MISSING,
category: Optional[Snowflake] = MISSING,
slowmode_delay: Optional[int] = MISSING,
default_thread_slowmode_delay: Optional[int] = MISSING,
default_auto_archive_duration: Optional[AnyThreadArchiveDuration] = MISSING,
type: ChannelType = MISSING,
overwrites: Mapping[Union[Role, Member], PermissionOverwrite] = MISSING,
Expand All @@ -303,6 +308,9 @@ async def _edit(
rtc_region: Optional[Union[str, VoiceRegion]] = MISSING,
video_quality_mode: VideoQualityMode = MISSING,
flags: ChannelFlags = MISSING,
available_tags: Sequence[ForumTag] = MISSING,
default_reaction: Optional[Union[str, Emoji, PartialEmoji]] = MISSING,
default_sort_order: Optional[ThreadSortOrder] = MISSING,
reason: Optional[str] = None,
) -> Optional[ChannelPayload]:
parent_id: Optional[int]
Expand Down Expand Up @@ -378,13 +386,35 @@ async def _edit(
else:
type_payload = MISSING

flags_payload: int
if flags is not MISSING:
if not isinstance(flags, ChannelFlags):
raise TypeError("flags field must be of type ChannelFlags")
flags_payload = flags.value
else:
flags_payload = MISSING

available_tags_payload: List[PartialForumTagPayload] = MISSING
if available_tags is not MISSING:
available_tags_payload = [tag.to_dict() for tag in available_tags]

default_reaction_emoji_payload: Optional[DefaultReactionPayload] = MISSING
if default_reaction is not MISSING:
if default_reaction is not None:
emoji_name, emoji_id = PartialEmoji._emoji_to_name_id(default_reaction)
default_reaction_emoji_payload = {
"emoji_name": emoji_name,
"emoji_id": emoji_id,
}
else:
default_reaction_emoji_payload = None

default_sort_order_payload: Optional[int] = MISSING
if default_sort_order is not MISSING:
default_sort_order_payload = (
try_enum_to_int(default_sort_order) if default_sort_order is not None else None
)

options: Dict[str, Any] = {
"name": name,
"parent_id": parent_id,
Expand All @@ -395,11 +425,15 @@ async def _edit(
# note: not passing `position` as it already got updated before, if passed
"permission_overwrites": overwrites_payload,
"rate_limit_per_user": slowmode_delay,
"default_thread_rate_limit_per_user": default_thread_slowmode_delay,
"type": type_payload,
"rtc_region": rtc_region_payload,
"video_quality_mode": video_quality_mode_payload,
"default_auto_archive_duration": default_auto_archive_duration_payload,
"flags": flags_payload,
"available_tags": available_tags_payload,
"default_reaction_emoji": default_reaction_emoji_payload,
"default_sort_order": default_sort_order_payload,
}
options = {k: v for k, v in options.items() if v is not MISSING}

Expand Down
142 changes: 96 additions & 46 deletions disnake/audit_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@
from .invite import Invite
from .mixins import Hashable
from .object import Object
from .partial_emoji import PartialEmoji
from .permissions import PermissionOverwrite, Permissions
from .threads import ForumTag, Thread

__all__ = (
"AuditLogDiff",
Expand All @@ -48,7 +50,6 @@
from .role import Role
from .stage_instance import StageInstance
from .sticker import GuildSticker
from .threads import Thread
from .types.audit_log import (
AuditLogChange as AuditLogChangePayload,
AuditLogEntry as AuditLogEntryPayload,
Expand All @@ -58,9 +59,13 @@
AutoModAction as AutoModActionPayload,
AutoModTriggerMetadata as AutoModTriggerMetadataPayload,
)
from .types.channel import PermissionOverwrite as PermissionOverwritePayload
from .types.channel import (
DefaultReaction as DefaultReactionPayload,
PermissionOverwrite as PermissionOverwritePayload,
)
from .types.role import Role as RolePayload
from .types.snowflake import Snowflake
from .types.threads import ForumTag as ForumTagPayload
from .user import User
from .webhook import Webhook

Expand Down Expand Up @@ -157,6 +162,36 @@ def _transform(entry: AuditLogEntry, data: Optional[str]) -> Optional[Asset]:
return _transform


def _transform_tag(entry: AuditLogEntry, data: Optional[ForumTagPayload]) -> Optional[ForumTag]:
if data is None:
return None
return ForumTag._from_data(data=data, state=entry._state)


def _transform_tag_id(
entry: AuditLogEntry, data: Optional[str]
) -> Optional[Union[ForumTag, Object]]:
if data is None:
return None

# cyclic imports
from .channel import ForumChannel

tag: Optional[ForumTag] = None
tag_id = int(data)
thread = entry.target
# try thread parent first
if isinstance(thread, Thread) and isinstance(thread.parent, ForumChannel):
tag = thread.parent.get_tag(tag_id)
else:
# if not found (possibly deleted thread), search all forum channels
for forum in entry.guild.forum_channels:
if tag := forum.get_tag(tag_id):
break

return tag or Object(id=tag_id)


T = TypeVar("T")
EnumT = TypeVar("EnumT", bound=enums.Enum)
FlagsT = TypeVar("FlagsT", bound=flags.BaseFlags)
Expand Down Expand Up @@ -242,6 +277,16 @@ def _transform_automod_trigger_metadata(
return AutoModTriggerMetadata._from_dict(data)


def _transform_default_reaction(
entry: AuditLogEntry, data: Optional[DefaultReactionPayload]
) -> Optional[Union[Emoji, PartialEmoji]]:
if data is None:
return None
return PartialEmoji._emoji_from_name_id(
data.get("emoji_name"), utils._get_as_snowflake(data, "emoji_id"), state=entry._state
)


class AuditLogDiff:
def __len__(self) -> int:
return len(self.__dict__)
Expand All @@ -268,50 +313,55 @@ def __setattr__(self, key: str, value: Any) -> Any:
class AuditLogChanges:
# fmt: off
TRANSFORMERS: ClassVar[Dict[str, Tuple[Optional[str], Optional[Transformer]]]] = {
"verification_level": (None, _enum_transformer(enums.VerificationLevel)),
"explicit_content_filter": (None, _enum_transformer(enums.ContentFilter)),
"allow": (None, _transform_permissions),
"deny": (None, _transform_permissions),
"permissions": (None, _transform_permissions),
"id": (None, _transform_snowflake),
"application_id": (None, _transform_snowflake),
"color": ("colour", _transform_color),
"owner_id": ("owner", _transform_member_id),
"inviter_id": ("inviter", _transform_member_id),
"channel_id": ("channel", _transform_channel),
"afk_channel_id": ("afk_channel", _transform_channel),
"system_channel_id": ("system_channel", _transform_channel),
"widget_channel_id": ("widget_channel", _transform_channel),
"rules_channel_id": ("rules_channel", _transform_channel),
"public_updates_channel_id": ("public_updates_channel", _transform_channel),
"permission_overwrites": ("overwrites", _transform_overwrites),
"splash_hash": ("splash", _guild_hash_transformer("splashes")),
"banner_hash": ("banner", _guild_hash_transformer("banners")),
"discovery_splash_hash": ("discovery_splash", _guild_hash_transformer("discovery-splashes")),
"icon_hash": ("icon", _transform_icon),
"avatar_hash": ("avatar", _transform_avatar),
"rate_limit_per_user": ("slowmode_delay", None),
"guild_id": ("guild", _transform_guild_id),
"tags": ("emoji", None),
"unicode_emoji": ("emoji", None),
"default_message_notifications": ("default_notifications", _enum_transformer(enums.NotificationLevel)),
"communication_disabled_until": ("timeout", _transform_datetime),
"image_hash": ("image", _transform_guild_scheduled_event_image),
"video_quality_mode": (None, _enum_transformer(enums.VideoQualityMode)),
"preferred_locale": (None, _enum_transformer(enums.Locale)),
"privacy_level": (None, _transform_privacy_level),
"format_type": (None, _enum_transformer(enums.StickerFormatType)),
"entity_type": (None, _enum_transformer(enums.GuildScheduledEventEntityType)),
"status": (None, _enum_transformer(enums.GuildScheduledEventStatus)),
"type": (None, _transform_type),
"flags": (None, _flags_transformer(flags.ChannelFlags)),
"system_channel_flags": (None, _flags_transformer(flags.SystemChannelFlags)),
"trigger_type": (None, _enum_transformer(enums.AutoModTriggerType)),
"event_type": (None, _enum_transformer(enums.AutoModEventType)),
"actions": (None, _list_transformer(_transform_automod_action)),
"trigger_metadata": (None, _transform_automod_trigger_metadata),
"exempt_roles": (None, _list_transformer(_transform_role)),
"exempt_channels": (None, _list_transformer(_transform_channel)),
"verification_level": (None, _enum_transformer(enums.VerificationLevel)),
"explicit_content_filter": (None, _enum_transformer(enums.ContentFilter)),
"allow": (None, _transform_permissions),
"deny": (None, _transform_permissions),
"permissions": (None, _transform_permissions),
"id": (None, _transform_snowflake),
"application_id": (None, _transform_snowflake),
"color": ("colour", _transform_color),
"owner_id": ("owner", _transform_member_id),
"inviter_id": ("inviter", _transform_member_id),
"channel_id": ("channel", _transform_channel),
"afk_channel_id": ("afk_channel", _transform_channel),
"system_channel_id": ("system_channel", _transform_channel),
"widget_channel_id": ("widget_channel", _transform_channel),
"rules_channel_id": ("rules_channel", _transform_channel),
"public_updates_channel_id": ("public_updates_channel", _transform_channel),
"permission_overwrites": ("overwrites", _transform_overwrites),
"splash_hash": ("splash", _guild_hash_transformer("splashes")),
"banner_hash": ("banner", _guild_hash_transformer("banners")),
"discovery_splash_hash": ("discovery_splash", _guild_hash_transformer("discovery-splashes")),
"icon_hash": ("icon", _transform_icon),
"avatar_hash": ("avatar", _transform_avatar),
"rate_limit_per_user": ("slowmode_delay", None),
"default_thread_rate_limit_per_user": ("default_thread_slowmode_delay", None),
"guild_id": ("guild", _transform_guild_id),
"tags": ("emoji", None),
"unicode_emoji": ("emoji", None),
"default_message_notifications": ("default_notifications", _enum_transformer(enums.NotificationLevel)),
"communication_disabled_until": ("timeout", _transform_datetime),
"image_hash": ("image", _transform_guild_scheduled_event_image),
"video_quality_mode": (None, _enum_transformer(enums.VideoQualityMode)),
"preferred_locale": (None, _enum_transformer(enums.Locale)),
"privacy_level": (None, _transform_privacy_level),
"format_type": (None, _enum_transformer(enums.StickerFormatType)),
"entity_type": (None, _enum_transformer(enums.GuildScheduledEventEntityType)),
"status": (None, _enum_transformer(enums.GuildScheduledEventStatus)),
"type": (None, _transform_type),
"flags": (None, _flags_transformer(flags.ChannelFlags)),
"system_channel_flags": (None, _flags_transformer(flags.SystemChannelFlags)),
"trigger_type": (None, _enum_transformer(enums.AutoModTriggerType)),
"event_type": (None, _enum_transformer(enums.AutoModEventType)),
"actions": (None, _list_transformer(_transform_automod_action)),
"trigger_metadata": (None, _transform_automod_trigger_metadata),
"exempt_roles": (None, _list_transformer(_transform_role)),
"exempt_channels": (None, _list_transformer(_transform_channel)),
"applied_tags": (None, _list_transformer(_transform_tag_id)),
"available_tags": (None, _list_transformer(_transform_tag)),
"default_reaction_emoji": ("default_reaction", _transform_default_reaction),
"default_sort_order": (None, _enum_transformer(enums.ThreadSortOrder)),
}
# fmt: on

Expand Down
Loading

0 comments on commit 1860aa7

Please sign in to comment.