r/redditdev•
SJS830

How to get parent comment from message?

PRAW

I have a bot that responds to user mentions. I need to load the parent comment of the comment that mentioned my bot. How can I do this?

This is the error I get:

'Message' object has no attribute 'parent'

Posted Feb 28, 2020, 12:29 AM UTC

68
Watchful1RemindMeBot & UpdateMeBot•

Parent should be a function rather than an attribute. Try parent().

3
SJS830OPBot Developer•

I still get the error

1
Watchful1RemindMeBot & UpdateMeBot•

Please post your code

2
SJS830OPBot Developer•

This is the relevant code

​

for i in reddit.inbox.stream():

try:

comment = i.parent()

comment.refresh()

1
Watchful1RemindMeBot & UpdateMeBot•

If you're streaming the entire inbox, you'll be getting both username mentions as well as regular messages. But messages don't have a parent. You need to either fetch only mentions or check whether the object is a comment or message before calling parent.

4
Aidgigiprofanitycounter Developer•

From the code you posted, it looks like you’re trying to get a parent from an inbox message. First, you need to get an actual comment object, this can be done by parsing the id of the message object as a comment, and capturing that object. That’s what I had to do for my bot.

1
_jaypatelBot Developer•

from praw.models import Comment

parent = comment.parent()

comment above this is the mentioned comment

You can also check whether the mention has a parent comment or not using the following code

if isinstance(parent, Comment):

#do something with parent comment

else:

#there is no parent comment, mention itself is the parent comment

1