Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature - Raw Presence Updates #10048

Open
wants to merge 31 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
467bca4
Add client docs.
EvieePy Dec 20, 2024
21c0bd0
Fix is_on_mobile docs
EvieePy Dec 20, 2024
9697fca
Add RawPresenceUpdateEvent model
EvieePy Dec 20, 2024
c058ff6
Add raw_presence flags and event dispatch to state
EvieePy Dec 20, 2024
646e800
Add docs.
EvieePy Dec 20, 2024
c3639a7
Run black
EvieePy Dec 20, 2024
dd22731
Simplify presence model
EvieePy Dec 20, 2024
e1bd692
Move presences models around
EvieePy Dec 20, 2024
a1ef8f4
Dispatch copy to raw event
EvieePy Dec 21, 2024
c7e34e6
Expose ClientStatus and make it available on Member
EvieePy Dec 21, 2024
e8d1a10
Add missing raw from parse_guild_members_chunk
EvieePy Dec 21, 2024
9c2a4f1
Run black
EvieePy Dec 21, 2024
db2b038
Add ClientStatus to all
EvieePy Dec 21, 2024
887a3a0
ClientStatus docs
EvieePy Dec 21, 2024
1552846
Change flag name
EvieePy Dec 21, 2024
ccad797
Small cleanup to state
EvieePy Dec 21, 2024
5f20270
Change some docs
EvieePy Dec 21, 2024
01d249f
Run black
EvieePy Dec 21, 2024
17b760b
Fix some docs
EvieePy Dec 21, 2024
158122d
Un-property client_status
EvieePy Dec 21, 2024
a292c02
Update docs
EvieePy Dec 21, 2024
b91c1fd
Remove copy in Member._copy
EvieePy Dec 21, 2024
863836f
Run black
EvieePy Dec 21, 2024
53802e6
Remove raw copy
EvieePy Dec 21, 2024
eeb349c
Use old style Union
EvieePy Dec 21, 2024
430d8e6
Update docs
EvieePy Dec 21, 2024
abfd31b
Add original presence update function for chunking
EvieePy Dec 21, 2024
39708ef
Remove raw object creation guild.py
EvieePy Dec 21, 2024
b0f4330
Remove unused import
EvieePy Dec 21, 2024
80bb10e
Docs - Add missing backticks
EvieePy Dec 21, 2024
c572c36
Apply requested changes.
EvieePy Dec 21, 2024
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
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
3 changes: 2 additions & 1 deletion discord/guild.py
Original file line number Diff line number Diff line change
Expand Up @@ -538,8 +538,9 @@ def _from_data(self, guild: GuildPayload) -> None:
for presence in guild.get('presences', []):
user_id = int(presence['user']['id'])
member = self.get_member(user_id)

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

if 'threads' in guild:
threads = guild['threads']
Expand Down
101 changes: 40 additions & 61 deletions discord/member.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,14 @@
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
from .activity import create_activity

__all__ = (
'VoiceState',
Expand All @@ -57,16 +58,14 @@
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,
UserWithMember as UserWithMemberPayload,
)
from .types.gateway import GuildMemberUpdateEvent
from .types.gateway import GuildMemberUpdateEvent, PartialPresenceUpdate
from .types.user import User as UserPayload, AvatarDecorationData
from .abc import Snowflake
from .state import ConnectionState
Expand Down Expand Up @@ -168,46 +167,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 +265,10 @@ class Member(discord.abc.Messageable, _UserTag):
This will be set to ``None`` 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 +281,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 +317,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 +393,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 +436,24 @@ 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]]:
def _presence_update(
self, data: PartialPresenceUpdate, raw: RawPresenceUpdateEvent, user: UserPayload
) -> Optional[Tuple[User, User]]:
if raw._activities is None:
raw._create_activities(data, self._state)

self.activities = raw.activities
self.client_status = raw.client_status

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

def _perf_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'])
self.client_status._update(data['status'], data['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 +492,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`
"""
EvieePy marked this conversation as resolved.
Show resolved Hide resolved
return self.client_status.mobile is not None
EvieePy marked this conversation as resolved.
Show resolved Hide resolved

@property
def colour(self) -> Colour:
Expand Down
Loading
Loading