Skip to content

Commit

Permalink
Add raw presence update evemt
Browse files Browse the repository at this point in the history
  • Loading branch information
EvieePy authored Jan 21, 2025
1 parent afbbc07 commit 418a791
Show file tree
Hide file tree
Showing 10 changed files with 262 additions and 86 deletions.
1 change: 1 addition & 0 deletions discord/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
from .poll import *
from .soundboard import *
from .subscription import *
from .presences import *


class VersionInfo(NamedTuple):
Expand Down
9 changes: 9 additions & 0 deletions discord/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,15 @@ class Client:
To enable these events, this must be set to ``True``. Defaults to ``False``.
.. versionadded:: 2.0
enable_raw_presences: :class:`bool`
Whether to manually enable or disable the :func:`on_raw_presence_update` event.
Setting this flag to ``True`` requires :attr:`Intents.presences` to be enabled.
By default, this flag is set to ``True`` only when :attr:`Intents.presences` is enabled and :attr:`Intents.members`
is disabled, otherwise it's set to ``False``.
.. versionadded:: 2.5
http_trace: :class:`aiohttp.TraceConfig`
The trace configuration to use for tracking HTTP requests the library does using ``aiohttp``.
This allows you to check requests the library is using. For more information, check the
Expand Down
9 changes: 5 additions & 4 deletions discord/guild.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@
from .automod import AutoModRule, AutoModTrigger, AutoModRuleAction
from .partial_emoji import _EmojiTag, PartialEmoji
from .soundboard import SoundboardSound

from .presences import RawPresenceUpdateEvent

__all__ = (
'Guild',
Expand Down Expand Up @@ -653,10 +653,11 @@ def _from_data(self, guild: GuildPayload) -> None:

empty_tuple = ()
for presence in guild.get('presences', []):
user_id = int(presence['user']['id'])
member = self.get_member(user_id)
raw_presence = RawPresenceUpdateEvent(data=presence, state=self._state)
member = self.get_member(raw_presence.user_id)

if member is not None:
member._presence_update(presence, empty_tuple) # type: ignore
member._presence_update(raw_presence, empty_tuple) # type: ignore

if 'threads' in guild:
threads = guild['threads']
Expand Down
88 changes: 27 additions & 61 deletions discord/member.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,13 @@
from .asset import Asset
from .utils import MISSING
from .user import BaseUser, ClientUser, User, _UserTag
from .activity import create_activity, ActivityTypes
from .permissions import Permissions
from .enums import Status, try_enum
from .enums import Status
from .errors import ClientException
from .colour import Colour
from .object import Object
from .flags import MemberFlags
from .presences import ClientStatus

__all__ = (
'VoiceState',
Expand All @@ -57,10 +57,8 @@
from .channel import DMChannel, VoiceChannel, StageChannel
from .flags import PublicUserFlags
from .guild import Guild
from .types.activity import (
ClientStatus as ClientStatusPayload,
PartialPresenceUpdate,
)
from .activity import ActivityTypes
from .presences import RawPresenceUpdateEvent
from .types.member import (
MemberWithUser as MemberWithUserPayload,
Member as MemberPayload,
Expand Down Expand Up @@ -168,46 +166,6 @@ def __repr__(self) -> str:
return f'<{self.__class__.__name__} {inner}>'


class _ClientStatus:
__slots__ = ('_status', 'desktop', 'mobile', 'web')

def __init__(self):
self._status: str = 'offline'

self.desktop: Optional[str] = None
self.mobile: Optional[str] = None
self.web: Optional[str] = None

def __repr__(self) -> str:
attrs = [
('_status', self._status),
('desktop', self.desktop),
('mobile', self.mobile),
('web', self.web),
]
inner = ' '.join('%s=%r' % t for t in attrs)
return f'<{self.__class__.__name__} {inner}>'

def _update(self, status: str, data: ClientStatusPayload, /) -> None:
self._status = status

self.desktop = data.get('desktop')
self.mobile = data.get('mobile')
self.web = data.get('web')

@classmethod
def _copy(cls, client_status: Self, /) -> Self:
self = cls.__new__(cls) # bypass __init__

self._status = client_status._status

self.desktop = client_status.desktop
self.mobile = client_status.mobile
self.web = client_status.web

return self


def flatten_user(cls: T) -> T:
for attr, value in itertools.chain(BaseUser.__dict__.items(), User.__dict__.items()):
# ignore private/special methods
Expand Down Expand Up @@ -306,6 +264,10 @@ class Member(discord.abc.Messageable, _UserTag):
This will be set to ``None`` or a time in the past if the user is not timed out.
.. versionadded:: 2.0
client_status: :class:`ClientStatus`
Model which holds information about the status of the member on various clients/platforms via presence updates.
.. versionadded:: 2.5
"""

__slots__ = (
Expand All @@ -318,7 +280,7 @@ class Member(discord.abc.Messageable, _UserTag):
'nick',
'timed_out_until',
'_permissions',
'_client_status',
'client_status',
'_user',
'_state',
'_avatar',
Expand Down Expand Up @@ -354,7 +316,7 @@ def __init__(self, *, data: MemberWithUserPayload, guild: Guild, state: Connecti
self.joined_at: Optional[datetime.datetime] = utils.parse_time(data.get('joined_at'))
self.premium_since: Optional[datetime.datetime] = utils.parse_time(data.get('premium_since'))
self._roles: utils.SnowflakeList = utils.SnowflakeList(map(int, data['roles']))
self._client_status: _ClientStatus = _ClientStatus()
self.client_status: ClientStatus = ClientStatus()
self.activities: Tuple[ActivityTypes, ...] = ()
self.nick: Optional[str] = data.get('nick', None)
self.pending: bool = data.get('pending', False)
Expand Down Expand Up @@ -430,7 +392,7 @@ def _copy(cls, member: Self) -> Self:
self._roles = utils.SnowflakeList(member._roles, is_sorted=True)
self.joined_at = member.joined_at
self.premium_since = member.premium_since
self._client_status = _ClientStatus._copy(member._client_status)
self.client_status = member.client_status
self.guild = member.guild
self.nick = member.nick
self.pending = member.pending
Expand Down Expand Up @@ -473,13 +435,12 @@ def _update(self, data: GuildMemberUpdateEvent) -> None:
self._flags = data.get('flags', 0)
self._avatar_decoration_data = data.get('avatar_decoration_data')

def _presence_update(self, data: PartialPresenceUpdate, user: UserPayload) -> Optional[Tuple[User, User]]:
self.activities = tuple(create_activity(d, self._state) for d in data['activities'])
self._client_status._update(data['status'], data['client_status'])
def _presence_update(self, raw: RawPresenceUpdateEvent, user: UserPayload) -> Optional[Tuple[User, User]]:
self.activities = raw.activities
self.client_status = raw.client_status

if len(user) > 1:
return self._update_inner_user(user)
return None

def _update_inner_user(self, user: UserPayload) -> Optional[Tuple[User, User]]:
u = self._user
Expand Down Expand Up @@ -518,39 +479,44 @@ def _update_inner_user(self, user: UserPayload) -> Optional[Tuple[User, User]]:
@property
def status(self) -> Status:
""":class:`Status`: The member's overall status. If the value is unknown, then it will be a :class:`str` instead."""
return try_enum(Status, self._client_status._status)
return self.client_status.status

@property
def raw_status(self) -> str:
""":class:`str`: The member's overall status as a string value.
.. versionadded:: 1.5
"""
return self._client_status._status
return self.client_status._status

@status.setter
def status(self, value: Status) -> None:
# internal use only
self._client_status._status = str(value)
self.client_status._status = str(value)

@property
def mobile_status(self) -> Status:
""":class:`Status`: The member's status on a mobile device, if applicable."""
return try_enum(Status, self._client_status.mobile or 'offline')
return self.client_status.mobile_status

@property
def desktop_status(self) -> Status:
""":class:`Status`: The member's status on the desktop client, if applicable."""
return try_enum(Status, self._client_status.desktop or 'offline')
return self.client_status.desktop_status

@property
def web_status(self) -> Status:
""":class:`Status`: The member's status on the web client, if applicable."""
return try_enum(Status, self._client_status.web or 'offline')
return self.client_status.web_status

def is_on_mobile(self) -> bool:
""":class:`bool`: A helper function that determines if a member is active on a mobile device."""
return self._client_status.mobile is not None
"""A helper function that determines if a member is active on a mobile device.
Returns
-------
:class:`bool`
"""
return self.client_status.is_on_mobile()

@property
def colour(self) -> Colour:
Expand Down
150 changes: 150 additions & 0 deletions discord/presences.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
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 __future__ import annotations

from typing import TYPE_CHECKING, Optional, Tuple

from .activity import create_activity
from .enums import Status, try_enum
from .utils import MISSING, _get_as_snowflake, _RawReprMixin

if TYPE_CHECKING:
from typing_extensions import Self

from .activity import ActivityTypes
from .guild import Guild
from .state import ConnectionState
from .types.activity import ClientStatus as ClientStatusPayload, PartialPresenceUpdate


__all__ = (
'RawPresenceUpdateEvent',
'ClientStatus',
)


class ClientStatus:
"""Represents the :ddocs:`Client Status Object <events/gateway-events#client-status-object>` from Discord,
which holds information about the status of the user on various clients/platforms, with additional helpers.
.. versionadded:: 2.5
"""

__slots__ = ('_status', 'desktop', 'mobile', 'web')

def __init__(self, *, status: str = MISSING, data: ClientStatusPayload = MISSING) -> None:
self._status: str = status or 'offline'

data = data or {}
self.desktop: Optional[str] = data.get('desktop')
self.mobile: Optional[str] = data.get('mobile')
self.web: Optional[str] = data.get('web')

def __repr__(self) -> str:
attrs = [
('_status', self._status),
('desktop', self.desktop),
('mobile', self.mobile),
('web', self.web),
]
inner = ' '.join('%s=%r' % t for t in attrs)
return f'<{self.__class__.__name__} {inner}>'

def _update(self, status: str, data: ClientStatusPayload, /) -> None:
self._status = status

self.desktop = data.get('desktop')
self.mobile = data.get('mobile')
self.web = data.get('web')

@classmethod
def _copy(cls, client_status: Self, /) -> Self:
self = cls.__new__(cls) # bypass __init__

self._status = client_status._status

self.desktop = client_status.desktop
self.mobile = client_status.mobile
self.web = client_status.web

return self

@property
def status(self) -> Status:
""":class:`Status`: The user's overall status. If the value is unknown, then it will be a :class:`str` instead."""
return try_enum(Status, self._status)

@property
def raw_status(self) -> str:
""":class:`str`: The user's overall status as a string value."""
return self._status

@property
def mobile_status(self) -> Status:
""":class:`Status`: The user's status on a mobile device, if applicable."""
return try_enum(Status, self.mobile or 'offline')

@property
def desktop_status(self) -> Status:
""":class:`Status`: The user's status on the desktop client, if applicable."""
return try_enum(Status, self.desktop or 'offline')

@property
def web_status(self) -> Status:
""":class:`Status`: The user's status on the web client, if applicable."""
return try_enum(Status, self.web or 'offline')

def is_on_mobile(self) -> bool:
""":class:`bool`: A helper function that determines if a user is active on a mobile device."""
return self.mobile is not None


class RawPresenceUpdateEvent(_RawReprMixin):
"""Represents the payload for a :func:`on_raw_presence_update` event.
.. versionadded:: 2.5
Attributes
----------
user_id: :class:`int`
The ID of the user that triggered the presence update.
guild_id: Optional[:class:`int`]
The guild ID for the users presence update. Could be ``None``.
guild: Optional[:class:`Guild`]
The guild associated with the presence update and user. Could be ``None``.
client_status: :class:`ClientStatus`
The :class:`~.ClientStatus` model which holds information about the status of the user on various clients.
activities: Tuple[Union[:class:`BaseActivity`, :class:`Spotify`]]
The activities the user is currently doing. Due to a Discord API limitation, a user's Spotify activity may not appear
if they are listening to a song with a title longer than ``128`` characters. See :issue:`1738` for more information.
"""

__slots__ = ('user_id', 'guild_id', 'guild', 'client_status', 'activities')

def __init__(self, *, data: PartialPresenceUpdate, state: ConnectionState) -> None:
self.user_id: int = int(data['user']['id'])
self.client_status: ClientStatus = ClientStatus(status=data['status'], data=data['client_status'])
self.activities: Tuple[ActivityTypes, ...] = tuple(create_activity(d, state) for d in data['activities'])
self.guild_id: Optional[int] = _get_as_snowflake(data, 'guild_id')
self.guild: Optional[Guild] = state._get_guild(self.guild_id)
Loading

0 comments on commit 418a791

Please sign in to comment.