CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-praw

Python Reddit API Wrapper - simple access to Reddit's API

Pending
Overview
Eval results
Files

messaging-inbox.mddocs/

Messaging and Inbox

PRAW provides comprehensive messaging and inbox management capabilities including private messages, comment replies, username mentions, modmail conversations, and notification handling. These features enable bot communication and user interaction management.

Capabilities

Inbox Management

Access and manage the authenticated user's inbox with various message types and filtering options.

class Inbox:
    def __init__(self, reddit): ...
    
    def all(self, **kwargs):
        """
        Get all inbox items (messages, comments, mentions).
        
        Parameters:
        - limit: Number of items (default: 25, max: 100)
        - mark: Whether to mark as read ("true", "false", or None)
        - params: Additional query parameters
        
        Returns:
        ListingGenerator of Message/Comment instances
        """
    
    def unread(self, **kwargs):
        """
        Get unread inbox items.
        
        Parameters:
        - limit: Number of items (default: 25, max: 100)
        - mark: Whether to mark as read when accessed
        - params: Additional query parameters
        
        Returns:
        ListingGenerator of unread Message/Comment instances
        """
    
    def messages(self, **kwargs):
        """
        Get private messages only.
        
        Parameters:
        - limit: Number of messages (default: 25, max: 100)
        - mark: Whether to mark as read ("true", "false", or None)
        - params: Additional query parameters
        
        Returns:
        ListingGenerator of Message instances
        """
    
    def comment_replies(self, **kwargs):
        """
        Get comment replies to user's comments.
        
        Parameters:
        - limit: Number of replies (default: 25, max: 100)
        - mark: Whether to mark as read ("true", "false", or None)
        - params: Additional query parameters
        
        Returns:
        ListingGenerator of Comment instances
        """
    
    def submission_replies(self, **kwargs):
        """
        Get comment replies to user's submissions.
        
        Parameters:
        - limit: Number of replies (default: 25, max: 100)
        - mark: Whether to mark as read ("true", "false", or None)
        - params: Additional query parameters
        
        Returns:
        ListingGenerator of Comment instances
        """
    
    def mentions(self, **kwargs):
        """
        Get username mentions (/u/username).
        
        Parameters:
        - limit: Number of mentions (default: 25, max: 100)
        - mark: Whether to mark as read ("true", "false", or None)
        - params: Additional query parameters
        
        Returns:
        ListingGenerator of Comment instances containing mentions
        """
    
    def sent(self, **kwargs):
        """
        Get sent private messages.
        
        Parameters:
        - limit: Number of messages (default: 25, max: 100)
        - params: Additional query parameters
        
        Returns:
        ListingGenerator of sent Message instances
        """

Message Management

Manage individual messages with marking, blocking, and reporting capabilities.

def mark_read(self, items: list):
    """
    Mark messages or comments as read.
    
    Parameters:
    - items: List of Message/Comment instances to mark as read
    """

def mark_unread(self, items: list):
    """
    Mark messages or comments as unread.
    
    Parameters:
    - items: List of Message/Comment instances to mark as unread
    """

def collapse(self, items: list):
    """
    Collapse messages in inbox.
    
    Parameters:
    - items: List of Message instances to collapse
    """

def uncollapse(self, items: list):
    """
    Uncollapse messages in inbox.
    
    Parameters:
    - items: List of Message instances to uncollapse
    """

def block(self, user):
    """
    Block a user from sending messages.
    
    Parameters:
    - user: Redditor instance or username to block
    """

def unblock(self, user):
    """
    Unblock a user, allowing them to send messages again.
    
    Parameters:
    - user: Redditor instance or username to unblock
    """

Private Message Classes

Handle private messages between users and subreddit messaging.

class Message:
    """Private message between users."""
    
    def __init__(self, reddit, id: str = None): ...
    
    def reply(self, body: str):
        """
        Reply to the private message.
        
        Parameters:
        - body: Reply message content (markdown supported)
        
        Returns:
        Message instance of the reply
        """
    
    def mark_read(self):
        """Mark this message as read."""
    
    def mark_unread(self):
        """Mark this message as unread."""
    
    def block_user(self):
        """Block the sender of this message."""
    
    def report(self, reason: str):
        """
        Report the message.
        
        Parameters:
        - reason: Report reason
        """

class SubredditMessage:
    """Message sent to/from a subreddit."""
    
    def __init__(self, reddit, id: str = None): ...
    
    def mute(self):
        """Mute the user in modmail (moderator only)."""
    
    def unmute(self):
        """Unmute the user in modmail (moderator only)."""

Message Properties and Data

Access message metadata, content, and threading information.

# Message properties
id: str  # Message ID
subject: str  # Message subject
body: str  # Message content
body_html: str  # Message HTML content
author: Redditor  # Message sender
dest: str  # Message recipient username
created_utc: float  # Creation timestamp (UTC)
context: str  # Thread context (for comment replies)

# Message status
new: bool  # Whether message is unread
was_comment: bool  # Whether from comment reply
first_message: str  # ID of first message in thread
first_message_name: str  # Fullname of first message
parent_id: str  # Parent message ID (for threading)

# Subreddit messages
subreddit: Subreddit  # Associated subreddit (for subreddit messages)

Modmail System

Modern modmail conversations and message management.

class ModmailConversation:
    """Modern modmail conversation."""
    
    def __init__(self, reddit, id: str = None): ...
    
    def reply(
        self,
        body: str,
        *,
        author_hidden: bool = False,
        internal: bool = False
    ):
        """
        Reply to modmail conversation.
        
        Parameters:
        - body: Reply content (markdown supported)
        - author_hidden: Hide moderator name
        - internal: Internal moderator note (not visible to user)
        
        Returns:
        ModmailMessage instance
        """
    
    def archive(self):
        """Archive the conversation."""
    
    def unarchive(self):
        """Unarchive the conversation."""
    
    def highlight(self):
        """Highlight the conversation."""
    
    def unhighlight(self):
        """Remove highlight from conversation."""
    
    def mute(self):
        """Mute the user (prevent further messages)."""
    
    def unmute(self):
        """Unmute the user."""
    
    def read(self):
        """Mark conversation as read."""
    
    def unread(self):
        """Mark conversation as unread."""

class ModmailMessage:
    """Individual message in modmail conversation."""
    
    def __init__(self, reddit, id: str = None): ...

class ModmailAction:
    """Modmail action/event in conversation."""
    
    def __init__(self, reddit, id: str = None): ...

Modmail Properties and Data

Access modmail conversation metadata and message threading.

# Conversation properties
id: str  # Conversation ID
subject: str  # Conversation subject
state: int  # Conversation state (0=new, 1=in_progress, 2=archived, etc.)
last_updated: str  # Last update timestamp
last_user_update: str  # Last user update timestamp
last_mod_update: str  # Last moderator update timestamp
last_unread: str  # Last unread timestamp

# Participants
authors: list  # List of conversation participants
participant: Redditor  # Main user participant (non-moderator)

# Message threading
messages: list  # List of ModmailMessage instances
obj_ids: list  # List of message/action IDs in order

# Conversation metadata
is_auto: bool  # Whether auto-generated
is_repliable: bool  # Whether user can reply
is_highlighted: bool  # Whether highlighted by moderators
num_messages: int  # Total number of messages
owner: Subreddit  # Subreddit that owns the conversation

Inbox Streaming

Stream new inbox items in real-time for immediate notification processing.

def stream(self, **kwargs):
    """
    Stream new inbox items as they arrive.
    
    Parameters:
    - pause_after: Pause after this many requests
    - skip_existing: Skip items created before stream start
    - attribute_name: Specific inbox attribute to stream ("unread", "messages", etc.)
    
    Yields:
    Message/Comment instances as they arrive
    
    Continuously monitors inbox and yields new items immediately.
    """

Message Composition

Send private messages to users and subreddits.

def message(
    self,
    recipient: str,
    subject: str,
    message: str,
    *,
    from_subreddit = None
):
    """
    Send private message.
    
    Parameters:
    - recipient: Username or subreddit name (with /r/ prefix)
    - subject: Message subject
    - message: Message content (markdown supported)
    - from_subreddit: Send from subreddit instead of user account
    
    Returns:
    None (message is queued for delivery)
    """

Usage Examples

Basic Inbox Management

import praw

reddit = praw.Reddit(...)

# Check unread messages
print("Unread messages:")
for item in reddit.inbox.unread(limit=10):
    if hasattr(item, 'subject'):  # It's a private message
        print(f"Message from {item.author}: {item.subject}")
        print(f"Content: {item.body[:100]}...")
    else:  # It's a comment reply
        print(f"Reply from {item.author}: {item.body[:100]}...")
    
    # Mark as read
    item.mark_read()

# Get all inbox items
print("\nAll inbox:")
for item in reddit.inbox.all(limit=20):
    print(f"From: {item.author}, Type: {type(item).__name__}")

Private Message Handling

# Send private message
reddit.redditor("recipient_username").message(
    subject="Hello from my bot",
    message="This is a test message sent using PRAW.\n\nThanks!"
)

# Process incoming messages
for message in reddit.inbox.messages(limit=10):
    print(f"Message from {message.author}: {message.subject}")
    print(f"Content: {message.body}")
    
    # Reply to message
    if "help" in message.body.lower():
        message.reply("Here's some help information...")
    
    # Block problematic users
    if "spam" in message.body.lower():
        message.block_user()
        print(f"Blocked user: {message.author}")

Comment Reply Management

# Process comment replies
print("Comment replies:")
for reply in reddit.inbox.comment_replies(limit=15):
    print(f"Reply to your comment by {reply.author}:")
    print(f"Content: {reply.body}")
    print(f"Parent comment context: {reply.context}")
    
    # Reply to the reply
    if "question" in reply.body.lower():
        reply.reply("Thanks for your question! Here's my answer...")

# Process submission replies
print("\nSubmission replies:")  
for reply in reddit.inbox.submission_replies(limit=10):
    print(f"Reply to your post by {reply.author}:")
    print(f"Content: {reply.body[:100]}...")

Username Mention Handling

# Process username mentions
print("Username mentions:")
for mention in reddit.inbox.mentions(limit=10):
    print(f"Mentioned by {mention.author} in r/{mention.subreddit}:")
    print(f"Context: {mention.body[:200]}...")
    
    # Reply to mention
    mention.reply("Thanks for the mention!")
    
    # Get full submission context
    submission = mention.submission
    print(f"Mentioned in: {submission.title}")

Bulk Message Management

# Mark multiple items as read
unread_items = list(reddit.inbox.unread(limit=50))
if unread_items:
    reddit.inbox.mark_read(unread_items)
    print(f"Marked {len(unread_items)} items as read")

# Mark specific items as unread
recent_messages = list(reddit.inbox.messages(limit=5))
reddit.inbox.mark_unread(recent_messages)
print("Marked recent messages as unread")

# Collapse old messages
old_messages = []
for message in reddit.inbox.messages(limit=100):
    if hasattr(message, 'created_utc'):
        # Messages older than 30 days
        if time.time() - message.created_utc > 30 * 24 * 3600:
            old_messages.append(message)

if old_messages:
    reddit.inbox.collapse(old_messages)
    print(f"Collapsed {len(old_messages)} old messages")

Modmail Conversation Management

# Access subreddit modmail (requires moderation permissions)
subreddit = reddit.subreddit("mysubreddit")

# Get modmail conversations
for conversation in subreddit.modmail.conversations():
    print(f"Conversation: {conversation.subject}")
    print(f"Participant: {conversation.participant}")
    print(f"State: {conversation.state}")
    print(f"Messages: {conversation.num_messages}")
    
    # Reply to conversation
    if conversation.state == 0:  # New conversation
        conversation.reply(
            "Thanks for contacting the moderators. We'll look into this.",
            author_hidden=False
        )
        
    # Archive resolved conversations
    if "resolved" in conversation.subject.lower():
        conversation.archive()

# Create new modmail conversation
subreddit.modmail.create(
    subject="Moderator Notice",
    body="This is an official message from the moderation team.",
    recipient="target_username"
)

Real-time Inbox Monitoring

import time

# Stream new inbox items
print("Monitoring inbox for new items...")
for item in reddit.inbox.stream():
    print(f"\nNew inbox item from {item.author}:")
    
    if hasattr(item, 'subject'):  # Private message
        print(f"Message: {item.subject}")
        print(f"Content: {item.body[:100]}...")
        
        # Auto-reply to messages containing "info"
        if "info" in item.body.lower():
            item.reply("Here's the information you requested...")
            
    else:  # Comment reply or mention
        print(f"Comment: {item.body[:100]}...")
        
        # Check if it's a mention
        if f"/u/{reddit.user.me().name}" in item.body:
            print("This is a username mention!")
            
    # Mark as read automatically
    item.mark_read()

# Stream only unread messages
print("Monitoring only unread messages...")
for message in reddit.inbox.stream(attribute_name="unread"):
    print(f"New unread from {message.author}: {message.subject}")
    # Process unread message
    message.mark_read()

Advanced Message Filtering

# Filter messages by criteria
def process_inbox_with_filters():
    important_keywords = ["urgent", "important", "help"]
    
    for item in reddit.inbox.all(limit=50):
        # Skip if already processed
        if not item.new:
            continue
            
        # Check for important keywords
        is_important = False
        text_to_check = ""
        
        if hasattr(item, 'subject'):  # Private message
            text_to_check = f"{item.subject} {item.body}"
        else:  # Comment
            text_to_check = item.body
            
        for keyword in important_keywords:
            if keyword.lower() in text_to_check.lower():
                is_important = True
                break
        
        if is_important:
            print(f"IMPORTANT: {item.author} - {text_to_check[:100]}...")
            # Process important message immediately
            if hasattr(item, 'reply'):
                item.reply("Thanks for your message. A moderator will respond shortly.")
        
        # Mark as read
        item.mark_read()

process_inbox_with_filters()

Message Threading and Context

# Handle threaded conversations
def process_message_thread(message):
    """Process a message and its thread context."""
    
    print(f"Message from {message.author}: {message.subject}")
    
    # If this is part of a thread, get the original message
    if hasattr(message, 'first_message') and message.first_message:
        print(f"This is part of thread: {message.first_message}")
    
    # If this is a comment reply, get context
    if hasattr(message, 'context') and message.context:
        print(f"Comment context: {message.context}")
        
        # Get the parent submission
        submission = message.submission
        print(f"Reply was on post: {submission.title}")
    
    # Process the message content
    print(f"Content: {message.body}")
    
    return message

# Process messages with threading context
for message in reddit.inbox.messages(limit=20):
    process_message_thread(message)
    print("---")

Types

class InboxableMixin:
    """Mixin for objects that can be in inbox."""
    
    def block_user(self):
        """Block the author of this item."""
    
    def collapse(self):
        """Collapse this inbox item."""
    
    def uncollapse(self):
        """Uncollapse this inbox item."""
    
    def mark_read(self):
        """Mark as read."""
    
    def mark_unread(self):
        """Mark as unread."""

class MessageableMixin:
    """Mixin for objects that can receive messages."""
    
    def message(self, subject: str, message: str, **kwargs):
        """Send message to this entity."""

Install with Tessl CLI

npx tessl i tessl/pypi-praw

docs

authentication.md

content-discovery.md

index.md

live-threads.md

messaging-inbox.md

moderation.md

reddit-client.md

submissions-comments.md

subreddits.md

user-management.md

tile.json