PRAW (Python Reddit API Wrapper)

repository·main·Indexed 26 days ago

https://github.com/praw-dev/praw

A Python package that provides simple, easy-to-use access to Reddit's API while internally handling API rules like rate limiting. It includes models for interacting with subreddits, submissions, multireddits, and wiki pages, as well as support for multiple authentication flows including Password, Code, and Implicit flows.

Tokens
17.9K
Snippets
56
Records
119
Agent score
88%

What's inside PRAW

  1. Set up the PRAW development environment

    main

    PRAW uses uv for dependency management. To set up your environment, install uv and run uv sync from the project root. This creates a .venv virtual environment with PRAW installed in an editable state and installs the dev dependency group (including lint and test).

    To run commands within this environment without manual activation, prefix them with uv run.

    uv sync
  2. Handle reddit.user.me() in read-only mode

    main

    In :read_only mode, calling reddit.user.me() no longer returns None with a warning; it now raises a ReadOnlyException. Use a try-except block to handle unauthenticated users.

    from praw.exceptions import ReadOnlyException
    
    try:
        reddit.user.me()
    except ReadOnlyException:
        print("Not authenticated")
  3. Locate and use praw.ini configuration files

    main

    PRAW uses praw.ini files to manage configuration. You can define your own praw.ini to override default settings or store multiple sets of credentials. PRAW searches for these files in the following order:

    1. The current working directory at the time praw.Reddit is initialized.
    2. The user's config directory, detected as follows:
      • On Linux/modern systems: The directory in the XDG_CONFIG_HOME environment variable.
      • On Linux/macOS: The directory in $HOME/.config.
      • On Windows: The directory in the APPDATA environment variable.

    Note: Do not modify the package's internal praw.ini. Instead, create your own file to override DEFAULT settings or define new sites.

  4. Obtain an Authorization URL for Code Flow

    main

    The Code Flow is used to access Reddit via a user's account without handling their raw password. This is ideal for web applications or for avoiding 2FA hassles.

    1. Initialize praw.Reddit with client_id, client_secret, redirect_uri, and user_agent.
    2. Call reddit.auth.url() to generate the URL.
    3. Direct the user to this URL. After they authorize, they will be redirected to your redirect_uri with a code parameter.
    4. Use reddit.auth.authorize(code) to exchange that code for a refresh_token.
  5. Install PRAW

    main

    PRAW requires Python 3.10+. You can install it using uv (recommended), pip, or install the latest development version directly from GitHub.

    To install via uv:

    uv add praw

    To install via pip:

    pip install praw

    To install the latest development version:

    pip install --upgrade https://github.com/praw-dev/praw/archive/main.zip
    uv add praw
  6. Enable debug logging to a file with rotation

    main

    For long-running bots or scripts, you can log PRAW activity to both the console and a file. Using logging.handlers.RotatingFileHandler allows you to manage log file size and keep a history of previous logs.

    import logging
    import logging.handlers
    
    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(logging.DEBUG)
    file_handler = logging.handlers.RotatingFileHandler(
        "praw_log.txt", maxBytes=1024 * 1024 * 16, backupCount=5
    )
    file_handler.setLevel(logging.DEBUG)
    for logger_name in ("praw", "prawcore"):
        logger = logging.getLogger(logger_name)
        logger.setLevel(logging.DEBUG)
        logger.addHandler(stream_handler)
        logger.addHandler(file_handler)
  7. Follow PRAW Python style guidelines

    main

    When contributing code, adhere to these specific PRAW patterns:

    • Sorting: Sort classes alphabetically by name. Within a class, sort methods alphabetically within these groups: Static methods, Class methods, Cached properties, Properties, and Instance Methods.
    • Keyword Arguments: Use descriptive names for catch-all arguments (e.g., **other_options instead of **kwargs).
    • Argument Ordering: For methods with multiple arguments, sort them alphabetically and mark them as keyword-only using the * syntax.

    Exception: Mandatory positional arguments may be used if their purpose is obvious without documentation, or if there are only one or two mandatory arguments followed by optional keyword-only arguments.

    class ExampleClass:
        def example_method(
            self,
            *,
            arg1,
            arg2,
            optional_arg1=None,
        ): ...
  8. Enable debug logging to stdout

    main

    To observe the HTTP requests issued by PRAW, you can configure the praw and prawcore loggers to output DEBUG level messages to the console using a logging.StreamHandler.

    import logging
    
    handler = logging.StreamHandler()
    handler.setLevel(logging.DEBUG)
    for logger_name in ("praw", "prawcore"):
        logger = logging.getLogger(logger_name)
        logger.setLevel(logging.DEBUG)
        logger.addHandler(handler)
  9. Use the new Modmail interface

    main

    The old modmail system has been retired. Subreddit.mod.inbox, Subreddit.mod.unread, Subreddit.mod.stream.unread, SubredditMessage.mute, and SubredditMessage.unmute have been removed.

    Use Subreddit.modmail.conversations(state="new") to fetch conversations. To stream, use SubredditModerationStream.modmail_conversations. Muting/unmuting is now handled via ModmailConversation.mute and ModmailConversation.unmute.

    # Fetching conversations
    for conversation in reddit.subreddit("test").modmail.conversations(state="new"):
        print(conversation.subject)
    
    # Resuming a listing using 'after' via params
    conversations = reddit.subreddit("test").modmail.conversations(params={"after": "2gmz"})