### Install Pre-commit Hooks Source: https://github.com/praw-dev/praw/blob/main/docs/package_info/contributing.rst Install the pre-commit hooks to automatically enforce code style and other checks upon committing. ```bash pre-commit install ``` -------------------------------- ### Install PRAW from GitHub repository using git clone Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/installation.rst Install PRAW by cloning the repository directly using git. This is useful for testing the latest unreleased changes. ```bash pip install --upgrade git+https://github.com/praw-dev/praw.git ``` -------------------------------- ### Install Linting Dependencies Source: https://github.com/praw-dev/praw/blob/main/docs/package_info/contributing.rst Install PRAW and linting-specific development dependencies in an editable state. This is an alternative to installing all development dependencies. ```bash pip install -e .[lint] ``` -------------------------------- ### Install PRAW using pip Source: https://github.com/praw-dev/praw/blob/main/README.rst Install the latest stable version of PRAW using pip. Ensure you have Python 3.9+. ```bash pip install praw ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/praw-dev/praw/blob/main/docs/package_info/contributing.rst Install PRAW and its development dependencies in an editable state using pip. The '[dev]' extra installs all necessary packages for linting and testing. ```bash pip install -e .[dev] ``` -------------------------------- ### Define Additional Sites in praw.ini Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/configuration/prawini.rst Example of defining multiple custom sites (e.g., for different bots) in a praw.ini file, inheriting from DEFAULT. ```ini [bot1] client_id=revokedpDQy3xZ client_secret=revokedoqsMk5nHCJTHLrwgvHpr password=invalidht4wd50gk username=fakebot1 [bot2] client_id=revokedcIqbclb client_secret=revokedCClyu4FjVO77MYlTynfj password=invalidzpiq8s59j username=fakebot2 [bot3] client_id=revokedSbt0zor client_secret=revokedNh8kwg8e5t4m6KvSrbTI password=invalidlfo00esyy username=fakebot3 ``` -------------------------------- ### Keyword-Only Arguments Example Source: https://github.com/praw-dev/praw/blob/main/docs/package_info/contributing.rst Demonstrates PRAW's style for methods with multiple arguments, where optional arguments are keyword-only and sorted alphabetically after a '*' marker. ```python class ExampleClass: def example_method( self, *, arg1, arg2, optional_arg1=None, ): ... ``` -------------------------------- ### Mixed Positional and Keyword-Only Arguments Example Source: https://github.com/praw-dev/praw/blob/main/docs/package_info/contributing.rst Shows an example where one or two mandatory arguments can be positional, while optional arguments are keyword-only and sorted alphabetically. ```python class Subreddit: def submit( self, title, *, collection_id=None, discussion_type=None, draft_id=None, flair_id=None, flair_text=None, inline_media=None, nsfw=False, resubmit=True, selftext=None, send_replies=True, spoiler=False, ): ... ``` -------------------------------- ### PRAW praw.ini with Basic Interpolation Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/configuration/prawini.rst Example of using basic interpolation in praw.ini to define dynamic configuration values, such as for a user agent. ```ini [bot1] bot_name=MyBot bot_version=1.2.3 bot_author=MyUser user_agent=script:%(bot_name)s:v%(bot_version)s (by u/%(bot_author)s) ``` -------------------------------- ### Example HTTP Request Log Output Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/logging.rst This is an example of the output you can expect in your logs when PRAW issues an HTTP request. It shows the request method, URL, timestamp, data, parameters, and response status. ```text Fetching: GET https://oauth.reddit.com/api/v1/me at 1691743155.4952002 Data: None Params: {'raw_json': 1} Response: 200 (876 bytes) (rst-45:rem-892:used-104 ratelimit) at 1691743156.3847592 ``` -------------------------------- ### Install Latest Development Version of PRAW Source: https://github.com/praw-dev/praw/blob/main/README.rst Install the latest development version of PRAW directly from its GitHub repository using pip. ```bash pip install --upgrade https://github.com/praw-dev/praw/archive/main.zip ``` -------------------------------- ### Install Development Dependencies (zsh) Source: https://github.com/praw-dev/praw/blob/main/docs/package_info/contributing.rst When using zsh, development dependencies must be installed with the '[dev]' extra enclosed in double quotes. ```zsh pip install -e ".[dev]" ``` -------------------------------- ### Example Rate Limit Log Output Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/logging.rst This log entry indicates that an API rate limit was encountered during a POST action and shows the duration the script will sleep before retrying. ```text Rate limit hit, sleeping for 5.5 seconds ``` -------------------------------- ### Positional Arguments Exception Example Source: https://github.com/praw-dev/praw/blob/main/docs/package_info/contributing.rst Illustrates an exception to the keyword-only argument rule, where simple, clear mandatory positional arguments are permitted. ```python class ExampleClass: def pair(self, left, right): ... ``` -------------------------------- ### Accessing a Redditor Profile with PRAW Source: https://context7.com/praw-dev/praw/llms.txt Demonstrates how to retrieve a Redditor's profile information and iterate through their submissions and comments. Includes examples for social actions and sending private messages. ```python import praw reddit = praw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", user_agent="MyBot/1.0 by u/you", ) redditor = reddit.redditor("spez") print(redditor.name) print(redditor.link_karma) print(redditor.comment_karma) print(redditor.created_utc) print(redditor.is_employee) print(redditor.icon_img) # By fullname (t2_ prefix) redditor2 = reddit.redditor(fullname="t2_abc123") # Iterate user's submissions for submission in redditor.submissions.new(limit=5): print(submission.title, submission.subreddit) # Iterate user's comments for comment in redditor.comments.new(limit=5): print(comment.body[:60]) # Iterate user's top submissions for submission in redditor.submissions.top(time_filter="month", limit=5): print(submission.title, submission.score) # Social actions (authenticated) redditor.friend() redditor.friend(note="Met at PyCon") # Requires Reddit Premium redditor.unfriend() redditor.block() redditor.trust() redditor.distrust() # Send private message (authenticated) redditor.message(subject="Hello!", message="Hi from PRAW!") # Check friend info friend_data = redditor.friend_info() print(friend_data.date) # When friendship was created ``` -------------------------------- ### Authorize Code and Get User Info Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/authentication.rst Exchange the authorization code for a refresh token and retrieve the authenticated user's information. The first line of output is the refresh token. ```python print(reddit.auth.authorize(code)) print(reddit.user.me()) ``` -------------------------------- ### Obtain Submission Object from URL Source: https://github.com/praw-dev/praw/blob/main/docs/tutorials/comments.rst Get a submission object by providing the full URL of the Reddit submission. This is one way to start processing comments for a specific thread. ```python url = "https://www.reddit.com/r/funny/comments/3g1jfi/buttons/" submission = reddit.submission(url=url) ``` -------------------------------- ### Initialize PRAW for Moderation Source: https://context7.com/praw-dev/praw/llms.txt Set up a PRAW instance with necessary credentials for moderation tasks. Ensure your user agent is descriptive and includes your username. ```python import praw reddit = praw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", username="mod_username", password="mod_password", user_agent="ModBot/1.0 by u/mod_username", ) subreddit = reddit.subreddit("my_subreddit") ``` -------------------------------- ### Install a specific older version of PRAW Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/installation.rst To install a particular older version of PRAW, specify the version number after '==' in the pip install command. ```bash pip install praw==3.6.0 ``` -------------------------------- ### Initialize PRAW with a Specific Site Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/configuration/prawini.rst Demonstrates how to initialize the PRAW Reddit instance using a specific site name defined in praw.ini. ```python reddit = praw.Reddit("bot2", user_agent="bot2 user agent") ``` -------------------------------- ### Initialize Reddit with Keyword Arguments Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/configuration/reddit_initialization.rst Pass configuration options like client ID, secret, user agent, and credentials directly as keyword arguments when creating a `praw.Reddit` instance. This is an alternative to using a `praw.ini` file. ```python reddit = praw.Reddit( client_id="SI8pN3DSbt0zor", client_secret="xaxkj7HNh8kwg8e5t4m6KvSrbTI", password="1guiwevlfo00esyy", user_agent="testscript by u/fakebot3", username="fakebot3", ) ``` -------------------------------- ### Configure PRAW with praw.ini Source: https://context7.com/praw-dev/praw/llms.txt Shows how to configure PRAW using a praw.ini file for different profiles, including default settings and specific bot credentials. Environment variables can also be used for configuration. ```ini # praw.ini — place in current directory, home directory, or XDG_CONFIG_HOME [DEFAULT] # Fallback settings for all profiles check_for_updates=True ratelimit_seconds=5 [bot1] client_id=BOT1_CLIENT_ID client_secret=BOT1_CLIENT_SECRET username=bot1_username password=bot1_password user_agent=Bot1/1.0 by u/bot1_username [bot2] client_id=BOT2_CLIENT_ID client_secret=BOT2_CLIENT_SECRET refresh_token=BOT2_REFRESH_TOKEN user_agent=Bot2/1.0 by u/bot2_username [read_only_app] client_id=APP_CLIENT_ID client_secret=APP_CLIENT_SECRET user_agent=ReadOnlyApp/1.0 by u/app_author ``` ```python import praw # Use the DEFAULT profile reddit = praw.Reddit() # Use a named profile reddit = praw.Reddit("bot1") # Use a different profile per environment import os profile = os.getenv("PRAW_PROFILE", "bot1") reddit = praw.Reddit(profile) # Environment variables also work (prefix: praw_) ``` -------------------------------- ### praw.Reddit - Creating a Reddit Instance Source: https://context7.com/praw-dev/praw/llms.txt Demonstrates how to create a `Reddit` instance for read-only access, authorized script applications, and using saved refresh tokens. It also shows how to toggle read-only mode and check username availability. ```APIDOC ## `praw.Reddit` — Creating a Reddit Instance The `Reddit` class is the single entry point for all API interactions. It accepts OAuth2 credentials directly or via a `praw.ini` configuration file and exposes top-level helpers for every Reddit resource. ```python import praw from praw.exceptions import RedditAPIException # --- Read-only instance (no username/password required) --- reddit = praw.Reddit( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", user_agent="MyBot/1.0 by u/your_username", ) print(reddit.read_only) # True # --- Authorized script-app instance (password flow) --- reddit = praw.Reddit( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", username="your_username", password="your_password", user_agent="MyBot/1.0 by u/your_username", ) print(reddit.read_only) # False print(reddit.user.me()) # Output: your_username # --- Using a saved refresh token (code flow) --- reddit = praw.Reddit( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", refresh_token="SAVED_REFRESH_TOKEN", user_agent="MyBot/1.0 by u/your_username", ) print(reddit.auth.scopes()) # {'identity', 'submit', ...} # --- Toggle read-only mode at runtime --- reddit.read_only = True # switch to read-only reddit.read_only = False # re-enable write access (requires valid auth) # --- Check username availability --- available = reddit.username_available("potential_username") print(available) # True or False ``` ``` -------------------------------- ### Initialize PRAW with Interpolation Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/configuration/prawini.rst Shows how to initialize PRAW when using interpolation in the praw.ini file, specifying the interpolation type. ```python reddit = praw.Reddit("bot1", config_interpolation="basic") ``` -------------------------------- ### Activate Virtual Environment (MacOS/Linux) Source: https://github.com/praw-dev/praw/blob/main/docs/package_info/contributing.rst Activate the virtual environment on MacOS or Linux systems using the source command. ```bash source .venv/bin/activate ``` -------------------------------- ### Subreddit Rules Source: https://context7.com/praw-dev/praw/llms.txt Manage subreddit rules, including getting, adding, updating, reordering, and deleting them. ```APIDOC ## Subreddit Rules ### Get a single rule by short name ```python rule = subreddit.rules["Be Nice"] print(rule.violation_reason) ``` ### Add a rule (mod only) ```python new_rule = subreddit.rules.mod.add( short_name="No spam", kind="all", description="Spam of any kind is not allowed.", violation_reason="Spam", ) ``` ### Update a rule ```python rule.mod.update( short_name="Be Respectful", description="Treat all members with respect.", ) ``` ### Reorder rules ```python subreddit.rules.mod.reorder([rule1, rule2, rule3]) ``` ### Delete a rule ```python rule.mod.delete() ``` ``` -------------------------------- ### Get Modmail Unread Counts Source: https://context7.com/praw-dev/praw/llms.txt Fetches the counts of unread modmail conversations categorized by state (e.g., new, in-progress). ```python counts = subreddit.modmail.unread_count() print(f"New: {counts['new']}, In-progress: {counts['inprogress']}") ``` -------------------------------- ### Initialize Subreddit with Multiple Subreddits Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/faq.rst Concatenate subreddit names with '+' to create a Subreddit instance for fetching logs from multiple subreddits simultaneously, potentially avoiding timeouts. ```python reddit.subreddit("pics+LifeProTips") ``` -------------------------------- ### Run Pre-push Checks Source: https://github.com/praw-dev/praw/blob/main/docs/package_info/contributing.rst Execute the pre_push.py script to run all necessary checks, including the full pre-commit suite and documentation build, before submitting a pull request. ```bash ./pre_push.py ``` -------------------------------- ### Check Environment Variables in Bash/PowerShell Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/configuration/prawini.rst Demonstrates how to check environment variable values in different operating systems' terminals. ```bash echo "$" ``` ```bat echo "%%" ``` ```powershell Write-Output "$env:" ``` -------------------------------- ### Subreddit.mod.removal_reasons Source: https://context7.com/praw-dev/praw/llms.txt Define and use custom removal reasons when removing content. This includes listing, getting, adding, updating, and deleting removal reasons. ```APIDOC ## `Subreddit.mod.removal_reasons` — Removal Reasons Define and use custom removal reasons when removing content. ### List all removal reasons ```python for reason in subreddit.mod.removal_reasons: print(reason.id, reason.title) ``` ### Get a specific removal reason ```python reason = subreddit.mod.removal_reasons["REASON_ID"] print(reason.title, reason.message) ``` ### Add a removal reason ```python new_reason = subreddit.mod.removal_reasons.add( title="Off-topic", message="Your post has been removed because it is off-topic for this subreddit.", ) ``` ### Update a removal reason ```python reason.update(title="Off-Topic Post", message="Updated message text.") ``` ### Delete a removal reason ```python reason.delete() ``` ### Remove a submission with a removal reason ```python submission = reddit.submission("abc123") submission.mod.remove() submission.mod.send_removal_message( message="Your post was removed because it violates our off-topic rule.", title="Removed: Off-topic", type="public", # "public", "private", or "private_exposed" ) ``` ``` -------------------------------- ### Obtain Submission Object from ID Source: https://github.com/praw-dev/praw/blob/main/docs/tutorials/comments.rst Get a submission object using only the submission ID, which can be extracted from the submission's URL. This is an alternative to using the full URL. ```python submission = reddit.submission("3g1jfi") ``` -------------------------------- ### Initialize PRAW Reddit Instance Source: https://github.com/praw-dev/praw/blob/main/docs/tutorials/reply_bot.rst Create an instance of the Reddit class to interact with the Reddit API. Ensure you have obtained OAuth2 credentials. ```python import praw reddit = praw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", password="PASSWORD", user_agent="LMGTFY (by u/USERNAME)", username="USERNAME", ) ``` -------------------------------- ### Check Environment Variables in Python Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/configuration/prawini.rst Shows how to retrieve environment variable values using Python's os module. ```python import os print(os.environ.get("", "")) ``` -------------------------------- ### Iterate Through All Comments on a Submission Source: https://github.com/praw-dev/praw/blob/main/docs/tutorials/comments.rst Use `submission.comments.list()` to get a list of all comments, including replies, in a breadth-first order. Ensure `submission.comments.replace_more(limit=None)` is called first to fetch all comments. ```python comment_queue = submission.comments[:] while comment_queue: comment = comment_queue.pop(0) print(comment.body) comment_queue.extend(comment.replies) ``` ```python submission.comments.replace_more(limit=None) for comment in submission.comments.list(): print(comment.body) ``` -------------------------------- ### Initialize Reddit with Refresh Token Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/authentication.rst Initialize a Reddit instance using a saved refresh token to immediately obtain an authorized instance. ```python reddit = praw.Reddit( client_id="SI8pN3DSbt0zor", client_secret="xaxkj7HNh8kwg8e5t4m6KvSrbTI", refresh_token="WeheY7PwgeCZj4S3QgUcLhKE5S2s4eAYdxM", ``` -------------------------------- ### Accessing a Comment Directly with PRAW Source: https://context7.com/praw-dev/praw/llms.txt Shows how to fetch a specific comment using its ID or permalink URL. Includes examples for accessing comment attributes, voting, saving, editing, and deleting. ```python import praw reddit = praw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", user_agent="MyBot/1.0 by u/you", ) comment = reddit.comment("cklhv0f") print(comment.body) print(comment.author) print(comment.score) print(comment.created_utc) print(comment.permalink) print(comment.subreddit.display_name) # By permalink URL comment = reddit.comment(url="https://www.reddit.com/r/test/comments/abc123/_/cklhv0f/") # Vote (authenticated) comment.upvote() comment.downvote() # Save comment.save() comment.unsave() # Edit own comment (authenticated) comment.edit("Updated text for my comment.") # Delete own comment (authenticated) comment.delete() ``` -------------------------------- ### Set Environment Variables for Integration Tests Source: https://github.com/praw-dev/praw/blob/main/docs/package_info/contributing.rst Configure environment variables required for recording and updating Betamax cassettes in integration tests. These variables are replaced with placeholders in recorded cassettes to protect credentials. ```bash export prawtest_client_id=myclientid export prawtest_client_secret=myclientsecret export prawtest_password=mypassword export prawtest_test_subreddit=test export prawtest_username=myusername export prawtest_user_agent=praw_pytest ``` -------------------------------- ### Initialize PRAW Reddit Instance Source: https://github.com/praw-dev/praw/blob/main/docs/tutorials/comments.rst Create an instance of the Reddit class to interact with the Reddit API. Provide your client ID, client secret, username, password, and a user agent string. Username and password are optional for analyzing public comments. ```python import praw reddit = praw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", password="PASSWORD", user_agent="Comment Extraction (by u/USERNAME)", username="USERNAME", ) ``` -------------------------------- ### Reddit.auth — OAuth2 Authorization Source: https://context7.com/praw-dev/praw/llms.txt Details on using the `Auth` helper for managing code-flow OAuth2, including building authorization URLs, exchanging codes for tokens, and handling the implicit flow for installed apps. ```APIDOC ## `Reddit.auth` — OAuth2 Authorization The `Auth` helper manages code-flow OAuth2: generating authorization URLs, exchanging codes for tokens, and handling the implicit flow for installed apps. ```python import praw # Step 1 — build the authorization URL to redirect users to reddit = praw.Reddit( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", redirect_uri="http://localhost:8080", user_agent="MyApp/1.0 by u/your_username", ) url = reddit.auth.url(scopes=["identity", "submit", "read"], state="random_csrf_token", duration="permanent") print(url) # https://www.reddit.com/api/v1/authorize?... # Step 2 — after the user is redirected back, exchange the `code` param refresh_token = reddit.auth.authorize("CODE_FROM_REDIRECT") print(refresh_token) # Save this for future use print(reddit.user.me()) # Now authenticated # Implicit flow (installed apps only — returns access_token directly) implicit_url = reddit.auth.url(scopes=["identity"], state="csrf_token", implicit=True) reddit.auth.implicit(access_token="TOKEN_FROM_REDIRECT", expires_in=3600, scope="identity") # Inspect currently authorized scopes print(reddit.auth.scopes()) # frozenset({'identity', 'submit', ...}) ``` ``` -------------------------------- ### Obtain Comment Instances Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/quick_start.rst Access top-level comments from a Submission's comments attribute, or get all comments as a flattened list using the .list() method. The comment sort order can be changed before accessing comments. ```python # assume you have a praw.Reddit instance bound to variable `reddit` top_level_comments = list(submission.comments) all_comments = submission.comments.list() ``` -------------------------------- ### Activate Virtual Environment (Windows) Source: https://github.com/praw-dev/praw/blob/main/docs/package_info/contributing.rst Activate the virtual environment on Windows Command Prompt using the provided batch script. ```bat .venv\Scripts\activate.bat ``` -------------------------------- ### PRAW OAuth2 Authorization Source: https://context7.com/praw-dev/praw/llms.txt Manage OAuth2 authorization using the `Auth` helper. Build authorization URLs for users to grant permissions, exchange codes for tokens, and handle the implicit flow for installed apps. Inspect authorized scopes. ```python import praw # Step 1 — build the authorization URL to redirect users to reddit = praw.Reddit( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", redirect_uri="http://localhost:8080", user_agent="MyApp/1.0 by u/your_username", ) url = reddit.auth.url(scopes=["identity", "submit", "read"], state="random_csrf_token", duration="permanent") print(url) # https://www.reddit.com/api/v1/authorize?... # Step 2 — after the user is redirected back, exchange the `code` param refresh_token = reddit.auth.authorize("CODE_FROM_REDIRECT") print(refresh_token) # Save this for future use print(reddit.user.me()) # Now authenticated # Implicit flow (installed apps only — returns access_token directly) implicit_url = reddit.auth.url(scopes=["identity"], state="csrf_token", implicit=True) reddit.auth.implicit(access_token="TOKEN_FROM_REDIRECT", expires_in=3600, scope="identity") # Inspect currently authorized scopes print(reddit.auth.scopes()) # frozenset({'identity', 'submit', ...}) ``` -------------------------------- ### Access PRAW Subreddit Instance Source: https://context7.com/praw-dev/praw/llms.txt Get a lazy `Subreddit` instance to interact with a specific subreddit. Accessing attributes like `display_name`, `title`, `subscribers`, or `public_description` fetches data from Reddit. Supports combining multiple subreddits or filtering r/all. ```python import praw reddit = praw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", user_agent="MyBot/1.0 by u/you", ) subreddit = reddit.subreddit("python") print(subreddit.display_name) # python print(subreddit.title) # Python print(subreddit.subscribers) # e.g., 1200000 print(subreddit.public_description) # Combine multiple subreddits multi = reddit.subreddit("python+learnpython+django") for submission in multi.hot(limit=5): print(submission.title) # Filter r/all filtered = reddit.subreddit("all-python-learnpython") for submission in filtered.new(limit=3): print(submission.subreddit, submission.title) ``` -------------------------------- ### Instantiate PRAW Reddit Instance Source: https://github.com/praw-dev/praw/blob/main/README.rst Instantiate a PRAW Reddit object using your script-type OAuth application credentials. Ensure your user agent is descriptive. ```python import praw reddit = praw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", password="PASSWORD", user_agent="USERAGENT", username="USERNAME", ) ``` -------------------------------- ### Discover Subreddits using `Reddit.subreddits` Source: https://context7.com/praw-dev/praw/llms.txt Discover subreddits via default, popular, new, gold, and search methods. Requires PRAW initialization. ```python import praw reddit = praw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", user_agent="MyBot/1.0 by u/you", ) # Default subreddits for sub in reddit.subreddits.default(limit=10): print(sub.display_name, sub.subscribers) # Popular subreddits for sub in reddit.subreddits.popular(limit=10): print(sub.display_name) # Newest subreddits for sub in reddit.subreddits.new(limit=5): print(sub.display_name, sub.created_utc) # Search subreddits for sub in reddit.subreddits.search("programming", limit=10): print(sub.display_name, sub.public_description[:80]) # Search by name prefix for sub in reddit.subreddits.search_by_name("learn", include_nsfw=False): print(sub.display_name) # User's subscribed subreddits (authenticated) for sub in reddit.user.subreddits(limit=None): print(sub.display_name) ``` -------------------------------- ### Obtain a Reddit Refresh Token Source: https://github.com/praw-dev/praw/blob/main/docs/tutorials/refresh_token.rst This script guides you through the OAuth2 authorization flow to obtain a refresh token. Ensure your application's redirect URI is configured to 'localhost:8080'. The script will prompt for scopes, provide an authorization URL, and print the obtained refresh token. ```python import praw r = praw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", redirect_uri="http://localhost:8080", user_agent="MyRefreshApp by u/MyUsername", ) scopes = input("Enter comma-separated scopes: ") auth_url = r.auth.url(scopes.split(','), "state", "permanent") print(f"Go to this URL: {auth_url}") response_url = input("Paste the full redirect URL here: ") r.auth.authorize(response_url) print(f"Refresh token: {r.auth.refresh_token}") ``` -------------------------------- ### Display Available Scopes Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/authentication.rst Instantiate a Reddit instance with a user agent and then print the available scopes. This is useful for understanding the permissions associated with your API client. ```python import praw reddit = praw.Reddit( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", user_agent="testscript by u/fakebot3", ) print(reddit.auth.scopes()) ``` -------------------------------- ### Create a New Subreddit Source: https://context7.com/praw-dev/praw/llms.txt Use this method to create a new subreddit. Requires authentication. ```python new_sub = reddit.subreddit.create( name="mycoolsubreddit", title="My Cool Subreddit", public_description="A place for cool things", subreddit_type="public", wikimode="modonly", ) ``` -------------------------------- ### Accept Mod Invite with PRAW Source: https://context7.com/praw-dev/praw/llms.txt Programmatically accept an invitation to moderate a subreddit using the `accept_invite` method. ```python subreddit.mod.accept_invite() ``` -------------------------------- ### Create Virtual Environment Source: https://github.com/praw-dev/praw/blob/main/docs/package_info/contributing.rst Use this command to create a virtual environment named .venv in your project directory. This helps isolate PRAW's dependencies. ```bash python3 -m venv .venv ``` -------------------------------- ### Main Function Source: https://github.com/praw-dev/praw/blob/main/docs/tutorials/reply_bot.rst Organize the main execution logic within a `main` function. This is good practice for making scripts importable as modules. ```python def main(): """Main function to run the bot.""" reddit = Reddit( "lmgtfy_bot", user_agent="LMGTFY Bot by u/your_username", ) for submission in stream_generator(reddit.subreddit(subreddit_to_monitor).stream(["new"])): process_submission(submission) ``` -------------------------------- ### Retrieve Subreddit Settings with PRAW Source: https://context7.com/praw-dev/praw/llms.txt Fetch the current settings of a subreddit as a dictionary. ```python settings = subreddit.mod.settings() print(settings["title"], settings["public_description"]) ``` -------------------------------- ### Real-time Content Streams with PRAW Source: https://context7.com/praw-dev/praw/llms.txt Explains how to use `SubredditStream` to monitor new submissions and comments in real-time. Shows how to stream from multiple subreddits and optionally skip existing backlog. ```python import praw reddit = praw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", username="your_username", password="your_password", user_agent="MyBot/1.0 by u/your_username", ) # Stream new submissions to a subreddit subreddit = reddit.subreddit("learnpython") for submission in subreddit.stream.submissions(): print(f"New submission: {submission.title}") if "help" in submission.title.lower(): submission.reply("Looks like you need help! Check the sidebar for resources.") # Stream new comments (skip historical backlog) for comment in subreddit.stream.comments(skip_existing=True): print(f"{comment.author}: {comment.body[:80]}") # Stream multiple subreddits for submission in reddit.subreddit("python+learnpython+django").stream.submissions(): print(submission.subreddit, submission.title) ``` -------------------------------- ### Manage User Flair Templates Source: https://context7.com/praw-dev/praw/llms.txt Lists all available user flair templates, including their ID, text, and CSS class. Requires subreddit permissions. ```python import praw reddit = praw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", username="mod_username", password="mod_password", user_agent="ModBot/1.0 by u/mod_username", ) subreddit = reddit.subreddit("my_subreddit") # List all user flair templates for template in subreddit.flair.templates: print(template["id"], template["flair_text"], template["flair_css_class"]) ``` -------------------------------- ### Update PRAW with pip Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/installation.rst Run this command to upgrade to the latest stable release of PRAW. ```bash pip install --upgrade praw ``` -------------------------------- ### Import Statements Source: https://github.com/praw-dev/praw/blob/main/docs/tutorials/reply_bot.rst Place all import statements at the top of the file, listing built-in packages before third-party ones. ```python from praw import Reddit from praw.models import Submission from praw.models.util import stream_generator from urllib.parse import quote_plus ``` -------------------------------- ### Create Authorized Reddit Instance Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/quick_start.rst Instantiate an authorized PRAW Reddit object by including username and password along with client ID, client secret, and user agent. This allows for actions requiring authentication. ```python import praw reddit = praw.Reddit( client_id="my client id", client_secret="my client secret", password="my password", user_agent="my user agent", username="my username", ) ``` ```python print(reddit.read_only) # Output: False ``` -------------------------------- ### Iterate All Subreddit Wiki Pages Source: https://context7.com/praw-dev/praw/llms.txt Lists the names of all available wiki pages within a subreddit. Useful for discovering existing content. ```python for page in subreddit.wiki: print(page.name) ``` -------------------------------- ### Log PRAW and PRAWCORE to File and Console Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/logging.rst Configure logging to write to both a rotating file and the console. This is useful for longer-running bots or scripts where you need to review past activity. The file handler rotates logs when they reach 16MB, keeping up to 5 backup files. ```python import logging 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) ``` -------------------------------- ### Generate Authorization URL (Code Flow) Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/authentication.rst Use this to generate the authorization URL for the code flow. Ensure your redirect_uri is set correctly. ```python reddit = praw.Reddit( client_id="SI8pN3DSbt0zor", client_secret="xaxkj7HNh8kwg8e5t4m6KvSrbTI", redirect_uri="http://localhost:8080", user_agent="testscript by u/fakebot3", ) print(reddit.auth.url(scopes=["identity"], state="...", duration="permanent")) ``` -------------------------------- ### Add New User Flair Template Source: https://context7.com/praw-dev/praw/llms.txt Creates a new user flair template with specified text, CSS class, and appearance settings. Requires subreddit flair permissions. ```python subreddit.flair.templates.add( text="Moderator", css_class="mod", text_editable=False, background_color="#ff4500", text_color="light", ) ``` -------------------------------- ### Subreddit.submit() - Creating Submissions Source: https://context7.com/praw-dev/praw/llms.txt An authenticated method to create various types of posts (text, link, image, video, gallery, poll) within a subreddit. Supports options for flair, NSFW, spoilers, and reply notifications. ```APIDOC ## `Subreddit.submit()` — Creating Submissions Authenticated method to create text, link, image, video, gallery, or poll posts in a subreddit. ### Text (self) post ```python text_submission = subreddit.submit( title="Hello from PRAW", selftext="This is the body of my self post.\n\nFormatted in **Markdown**.", send_replies=True, flair_id="FLAIR_TEMPLATE_ID", # optional ) print(text_submission.id, text_submission.shortlink) ``` ### Link post ```python link_submission = subreddit.submit( title="Check out this link", url="https://www.python.org", nsfw=False, spoiler=False, ) print(link_submission.permalink) ``` ### Image post ```python image_submission = subreddit.submit_image( title="My cool image", image_path="/path/to/image.jpg", flair_id="FLAIR_TEMPLATE_ID", ) ``` ### Video post ```python video_submission = subreddit.submit_video( title="My video post", video_path="/path/to/video.mp4", thumbnail_path="/path/to/thumbnail.jpg", # optional ) ``` ### Gallery post (multiple images) ```python gallery_submission = subreddit.submit_gallery( title="My photo gallery", images=[ {"image_path": "/path/to/image1.jpg", "caption": "First image", "outbound_url": "https://example.com"}, {"image_path": "/path/to/image2.jpg", "caption": "Second image"}, ], ) ``` ### Poll post ```python poll_submission = subreddit.submit_poll( title="What is your favorite Python version?", selftext="Vote below!", options=["Python 3.11", "Python 3.12", "Python 3.13"], duration=3, # days: 1–7 ) ``` ``` -------------------------------- ### Create Submissions in a Subreddit Source: https://context7.com/praw-dev/praw/llms.txt Authenticated method to create text, link, image, video, gallery, or poll posts. Ensure you have the necessary authentication credentials. ```python import praw reddit = praw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", username="your_username", password="your_password", user_agent="MyBot/1.0 by u/your_username", ) subreddit = reddit.subreddit("test") # Text (self) post text_submission = subreddit.submit( title="Hello from PRAW", selftext="This is the body of my self post.\n\nFormatted in **Markdown**.", send_replies=True, flair_id="FLAIR_TEMPLATE_ID", # optional ) print(text_submission.id, text_submission.shortlink) # Link post link_submission = subreddit.submit( title="Check out this link", url="https://www.python.org", nsfw=False, spoiler=False, ) print(link_submission.permalink) # Image post image_submission = subreddit.submit_image( title="My cool image", image_path="/path/to/image.jpg", flair_id="FLAIR_TEMPLATE_ID", ) # Video post video_submission = subreddit.submit_video( title="My video post", video_path="/path/to/video.mp4", thumbnail_path="/path/to/thumbnail.jpg", # optional ) # Gallery post (multiple images) gallery_submission = subreddit.submit_gallery( title="My photo gallery", images=[ {"image_path": "/path/to/image1.jpg", "caption": "First image", "outbound_url": "https://example.com"}, {"image_path": "/path/to/image2.jpg", "caption": "Second image"}, ], ) # Poll post poll_submission = subreddit.submit_poll( title="What is your favorite Python version?", selftext="Vote below!", options=["Python 3.11", "Python 3.12", "Python 3.13"], duration=3, # days: 1–7 ) ``` -------------------------------- ### Create a Submission Source: https://github.com/praw-dev/praw/blob/main/README.rst Create a new submission to a specified subreddit using the PRAW Reddit instance. ```python # Create a submission to r/test reddit.subreddit("test").submit("Test Submission", url="https://reddit.com") ``` -------------------------------- ### Access and Manage Multireddits Source: https://context7.com/praw-dev/praw/llms.txt Demonstrates how to access, browse, create, modify, and delete multireddits using PRAW. Requires authentication for creation and modification. ```python import praw reddit = praw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", username="your_username", password="your_password", user_agent="MyBot/1.0 by u/your_username", ) # Access a public multireddit multi = reddit.multireddit(redditor="samuraisam", name="programming") print(multi.display_name) for subreddit in multi.subreddits: print(subreddit.display_name) # Browse a multireddit for submission in multi.hot(limit=10): print(submission.title) # Create a multireddit (authenticated) new_multi = reddit.multireddit.create( display_name="My Python Feed", subreddits=["python", "learnpython", "django"], description_md="My curated Python content feed.", visibility="private", # "public", "private", "hidden" ) # Add/remove subreddits new_multi.add("flask") new_multi.remove("django") # Delete multireddit new_multi.delete() # User's own multireddits for multi in reddit.user.multireddits(): print(multi.name, len(multi.subreddits)) ``` -------------------------------- ### Fetch Reddit Items by Fullname or URL using `Reddit.info()` Source: https://context7.com/praw-dev/praw/llms.txt Efficiently fetch multiple items (submissions, comments, subreddits) in batches of 100 using their fullnames or a URL. Requires PRAW initialization. ```python import praw reddit = praw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", user_agent="MyBot/1.0 by u/you", ) # Fetch items by fullname (t1_ = comment, t3_ = submission, t5_ = subreddit) fullnames = ["t3_abc123", "t3_def456", "t1_xyz789"] for item in reddit.info(fullnames=fullnames): print(type(item).__name__, item) # Fetch subreddits by name for sub in reddit.info(subreddits=["python", "learnpython", "django"]): print(sub.display_name, sub.subscribers) # Find submissions pointing to a URL for submission in reddit.info(url="https://www.python.org"): print(submission.title, submission.subreddit, submission.score) ``` -------------------------------- ### Retrieve a Subreddit Wiki Page Source: https://context7.com/praw-dev/praw/llms.txt Fetches the content, revision date, and author of a specific subreddit wiki page. Requires read access to the wiki. ```python import praw reddit = praw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", username="your_username", password="your_password", user_agent="MyBot/1.0 by u/your_username", ) subreddit = reddit.subreddit("learnpython") # Retrieve a wiki page wiki_page = subreddit.wiki["rules"] print(wiki_page.content_md) print(wiki_page.revision_date) print(wiki_page.revision_by) ``` -------------------------------- ### Obtain a Subreddit Instance Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/quick_start.rst Obtain a Subreddit instance by passing the subreddit's name to the subreddit() method of a PRAW Reddit instance. ```python subreddit = reddit.subreddit("redditdev") print(subreddit.display_name) # Output: redditdev print(subreddit.title) # Output: reddit development print(subreddit.description) # Output: a subreddit for discussion of ... ``` -------------------------------- ### LiveThread Source: https://context7.com/praw-dev/praw/llms.txt Create and manage Reddit live threads with real-time updates. Includes creating threads, accessing existing ones, posting updates, editing updates, and streaming updates. ```APIDOC ## `LiveThread` — Reddit Live Threads Create and manage live event threads with real-time updates. ### Create a live thread ```python live_thread = reddit.live.create( title="Live Coverage: PyCon 2024", description="Real-time updates from PyCon 2024.", nsfw=False, resources="Check out #pycon for more!", ) print(live_thread.id) ``` ### Access an existing live thread ```python thread = reddit.live("LiveThreadID12345") print(thread.title) print(thread.viewer_count) ``` ### Post an update ```python thread.contrib.add(body="The keynote just started!") ``` ### Edit an update ```python update = next(iter(thread)) thread.updates[update.id].contrib.strike() # strike through an update ``` ### Stream live updates ```python for update in thread.stream.updates(): print(update.author, update.body) ``` ``` -------------------------------- ### Edit Special Config Wiki Pages (e.g., Sidebar) Source: https://context7.com/praw-dev/praw/llms.txt Allows editing of special configuration wiki pages, such as the subreddit sidebar. Requires appropriate permissions. ```python sidebar = subreddit.wiki["config/sidebar"] sidebar.edit(content="Welcome to our subreddit!") ``` -------------------------------- ### Generate Authorization URL (Implicit Flow) Source: https://github.com/praw-dev/praw/blob/main/docs/getting_started/authentication.rst Generate the authorization URL for the implicit flow. The token is returned directly as part of the redirect. ```python print(reddit.auth.url(scopes=["identity"], state="...", implicit=True)) ```