Skip to content

Commit

Permalink
Add a parent() method to the Message class.
Browse files Browse the repository at this point in the history
(cherry picked from commit praw-dev/praw@89eb8b0)
  • Loading branch information
zacc authored and LilSpazJoekp committed Jun 12, 2022
1 parent 96ee3c4 commit 8439e61
Show file tree
Hide file tree
Showing 7 changed files with 592 additions and 7 deletions.
1 change: 1 addition & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,5 @@ Source Contributors
- Dio Brando `@isFakeAccount <https://github.com/isFakeAccount>`_
- Josh Kim `@jsk56143 <https://github.com/jsk56143>`_
- Rolf Campbell `@endlisnis <https://github.com/endlisnis>`_
- zacc `@zacc <https://github.com/zacc>`_
- Add "Name <email (optional)> and github profile link" above this line.
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Unreleased
:class:`.Collection`.
- :meth:`.SubredditCollectionsModeration.create` keyword argument ``display_layout`` for
specifying a display layout when creating a :class:`.Collection`.
- :attr:`~.Message.parent` to get the parent of a :class:`.Message`.

**Changed**

Expand Down
13 changes: 7 additions & 6 deletions asyncpraw/models/inbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,11 +194,12 @@ async def message(self, message_id: str) -> "asyncpraw.models.Message":
"""
listing = await self._reddit.get(API_PATH["message"].format(id=message_id))
messages = [listing[0]] + listing[0].replies
while messages:
message = messages.pop(0)
if message.id == message_id:
return message
messages = {
message.fullname: message for message in [listing[0]] + listing[0].replies
}
for fullname, message in messages.items():
message.parent = messages.get(message.parent_id, None)
return messages[f"t4_{message_id.lower()}"]

def messages(
self, **generator_kwargs: Union[str, int, Dict[str, str]]
Expand Down Expand Up @@ -308,7 +309,7 @@ async def uncollapse(self, items: List["asyncpraw.models.Message"]):
def unread(
self,
mark_read: bool = False,
**generator_kwargs: Union[str, int, Dict[str, str]]
**generator_kwargs: Union[str, int, Dict[str, str]],
) -> AsyncIterator[Union["asyncpraw.models.Comment", "asyncpraw.models.Message"]]:
"""Return a :class:`.ListingGenerator` for unread comments and messages.
Expand Down
44 changes: 43 additions & 1 deletion asyncpraw/models/reddit/message.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""Provide the Message class."""
from typing import TYPE_CHECKING, Any, Dict
from typing import TYPE_CHECKING, Any, Dict, Optional

from ...const import API_PATH
from .base import RedditBase
Expand Down Expand Up @@ -70,9 +70,51 @@ def _kind(self) -> str:
"""Return the class's kind."""
return self._reddit.config.kinds["message"]

@property
def parent(self) -> Optional["asyncpraw.models.Message"]:
"""Return the parent of the message if it exists.
.. note::
If the message is from an inbox listing, the returned parent will be lazy
and must be fetched manually. For example:
.. code-block:: python
async for message in reddit.inbox.all(limit=1):
parent = message.parent
await parent.load()
print(parent.body)
"""
if not self._parent:
if not self._fetched:
raise AttributeError(
"Message must be fetched with `.load()` before accessing the parent."
)
if self.parent_id:
self._parent = Message(
self._reddit, {"id": self.parent_id.split("_")[1]}
)
self._parent._fetched = False
return self._parent

@parent.setter
def parent(self, value):
self._parent = value

def __init__(self, reddit: "asyncpraw.Reddit", _data: Dict[str, Any]):
"""Initialize a :class:`.Message` instance."""
super().__init__(reddit, _data=_data, _fetched=True)
self._parent = None
for reply in _data.get("replies", []):
if reply.parent_id == self.fullname:
reply.parent = self

async def _fetch(self):
message = await self._reddit.inbox.message(self.id)
self.__dict__.update(message.__dict__)
self._fetched = True

async def delete(self):
"""Delete the message.
Expand Down
207 changes: 207 additions & 0 deletions tests/integration/cassettes/TestMessage.test_parent.json

Large diffs are not rendered by default.

Loading

0 comments on commit 8439e61

Please sign in to comment.