### Install Development Dependencies Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/package_info/contributing.rst Install all necessary development dependencies, including those for linting and testing, in an editable state. ```bash pip install -e .[dev] ``` -------------------------------- ### Install Development Version using Git Clone Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/installation.rst Alternatively, clone the repository using git and install directly. ```bash pip install --upgrade git+https://github.com/praw-dev/asyncpraw.git ``` -------------------------------- ### Install Linting Dependencies Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/package_info/contributing.rst Install only the linting dependencies if you do not need the full development set. ```bash pip install -e .[lint] ``` -------------------------------- ### Install Latest Development Version from GitHub Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/installation.rst Install the most recent development version directly from the main branch on GitHub. ```bash pip install --upgrade https://github.com/praw-dev/asyncpraw/archive/main.zip ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/praw-dev/asyncpraw/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 ``` -------------------------------- ### Example Ratelimit Log Output Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/logging.rst This example shows the log entry generated when an API ratelimit is encountered during a POST action and handled by Async PRAW. ```text Rate limit hit, sleeping for 5.5 seconds ``` -------------------------------- ### Install Async PRAW Source: https://github.com/praw-dev/asyncpraw/blob/main/README.rst Install Async PRAW using pip. For the latest development version, use the provided URL. ```bash pip install asyncpraw ``` ```bash pip install --upgrade https://github.com/praw-dev/asyncpraw/archive/main.zip ``` -------------------------------- ### Install Async PRAW Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/installation.rst Use this command to install the latest stable version of Async PRAW. Ensure you are using Python 3.9+. ```bash pip install asyncpraw ``` -------------------------------- ### Install Specific Older Version of Async PRAW Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/installation.rst To install a specific older version, append the version number to the installation command. ```bash pip install asyncpraw==7.1.0 ``` -------------------------------- ### Example HTTP Request Log Output Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/logging.rst This is an example of the output you can expect in your logs when Async PRAW issues an HTTP request. It shows the request details and response. ```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 ``` -------------------------------- ### Define Additional Sites in praw.ini Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/configuration/prawini.rst Example of defining multiple custom sites in a praw.ini file for different bots or applications. ```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 ``` -------------------------------- ### PRAW Configuration with Interpolation Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/configuration/prawini.rst Example of using basic interpolation in praw.ini to define variables for the user agent string. ```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) ``` -------------------------------- ### Install Development Dependencies (zsh) Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/package_info/contributing.rst When using zsh, development dependencies must be installed with the package name double-quoted. ```zsh pip install -e ".[dev]" ``` -------------------------------- ### Async PRAW Specific Style: Keyword-Only Arguments Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/package_info/contributing.rst Example demonstrating the use of keyword-only arguments for methods with multiple arguments, sorted alphabetically. ```python class ExampleClass: async def example_method( self, *, arg1, arg2, optional_arg1=None, ): ... ``` -------------------------------- ### Complete LMGTFY Bot Example Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/tutorials/reply_bot.rst The complete Python script for the LMGTFY Bot, integrating all previously discussed components for automatic replying to submissions. ```python import praw import asyncpraw from asyncpraw.models import Submission from asyncpraw.models.reddit.subreddit import Subreddit from asyncpraw.models.reddit.user import Redditor from asyncpraw.exceptions import ClientException from configparser import ConfigParser from urllib.parse import quote_plus import asyncio REPLY_TEMPLATE = "[Let me google that for you](https://lmgtfy.com/?q={})" SUBREDDIT_TO_MONITOR = "learnpython" async def process_submission(submission: Submission): """Process a single submission.""" print(f"Processing submission: {submission.id}") if "?" in submission.title: url_title = quote_plus(submission.title) reply_text = REPLY_TEMPLATE.format(url_title) await submission.reply(reply_text) print(f"Replied to submission: {submission.id}") async def main(): """Main function to run the bot.""" try: config = ConfigParser() config.read("praw.ini") reddit = asyncpraw.Reddit( client_id=config.get("reddit", "client_id"), client_secret=config.get("reddit", "client_secret"), user_agent=config.get("reddit", "user_agent"), username=config.get("reddit", "username"), password=config.get("reddit", "password"), ) subreddit: Subreddit = await reddit.subreddit(SUBREDDIT_TO_MONITOR) async for submission in subreddit.stream.submissions(): await process_submission(submission) except ClientException as e: print(f"ClientException: {e}") except Exception as e: print(f"An unexpected error occurred: {e}") finally: await reddit.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Async PRAW Integration Test Examples with Pytest Markers Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/package_info/contributing.rst Demonstrates the use of pytest markers for controlling cassette recording and playback in integration tests. Use these markers to customize placeholder addition, cassette naming, and recorder arguments. ```python @pytest.mark.recorder_kwargs(allow_playback_repeats=True) class TestClass: @pytest.mark.recorder_kwargs(match_on=["uri", "method", "body"]) async def test_example(self): ... @pytest.mark.cassette_name("TestClass.test_example") @pytest.mark.recorder_kwargs(match_on=["uri", "method", "body"]) async def test_example__different_assertion(self): ... @pytest.mark.add_placeholder(generated_data_a=generate_data_a()) @pytest.mark.add_placeholder(generated_data_b=generate_data_b()) async def test_example__with_generated_placeholders(self): ... ``` -------------------------------- ### Log HTTP Requests and Ratelimits to File Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/logging.rst Configure logging to write to a file, which is useful for longer-running bots or scripts. This setup logs to both the console and a rotating file. ```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 ("asyncpraw", "asyncprawcore"): logger = logging.getLogger(logger_name) logger.setLevel(logging.DEBUG) logger.addHandler(stream_handler) logger.addHandler(file_handler) ``` -------------------------------- ### Update Async PRAW Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/installation.rst Run this command to update your Async PRAW installation to the latest version. ```bash pip install --upgrade asyncpraw ``` -------------------------------- ### Async PRAW Specific Style: Mixed Positional and Keyword-Only Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/package_info/contributing.rst Example demonstrating a mix of positional arguments for mandatory inputs and keyword-only for optional arguments, sorted alphabetically. ```python class Subreddit: async 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, ): ... ``` -------------------------------- ### Accessing a Subreddit Source: https://context7.com/praw-dev/asyncpraw/llms.txt Shows how to get a `Subreddit` instance using `reddit.subreddit()`. It covers lazy and fetched instances, combining multiple subreddits, and filtering subreddits. ```APIDOC ## reddit.subreddit — Accessing a Subreddit Returns a lazy or fetched `Subreddit` instance. Subreddits can be combined with `+` for multi-subreddit views, or filtered with `-`. The `r/all` and `r/mod` special subreddits are supported. ```python import asyncio import asyncpraw async def main(): async with asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", user_agent="MyBot/1.0", ) as reddit: # Lazy instance (no network request yet) subreddit = await reddit.subreddit("learnpython") # Fetched instance with full attributes subreddit = await reddit.subreddit("learnpython", fetch=True) print(subreddit.title) # "Learning Python" print(subreddit.subscribers) # e.g. 800000 print(subreddit.public_description) # Combine subreddits multi = await reddit.subreddit("python+learnpython") async for submission in multi.hot(limit=5): print(submission.title) # Filter from r/all filtered = await reddit.subreddit("all-learnpython") async for submission in filtered.new(limit=5): print(submission.title) asyncio.run(main()) ``` ``` -------------------------------- ### Obtain a Subreddit Instance Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/quick_start.rst Get a Subreddit instance by passing the subreddit's name to the `subreddit` method of a Reddit instance. `fetch=True` will immediately retrieve subreddit details. ```python # assume you have a asyncpraw.Reddit instance bound to variable `reddit` subreddit = await reddit.subreddit("redditdev", fetch=True) print(subreddit.display_name) # Output: redditdev print(subreddit.title) # Output: reddit development print(subreddit.description) # Output: a subreddit for discussion of ... ``` -------------------------------- ### Async PRAW Specific Style: Positional Arguments Exception Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/package_info/contributing.rst Example showing an exception to the keyword-only rule where simple, clear positional arguments are permitted. ```python class ExampleClass: def pair(self, left, right): ... ``` -------------------------------- ### Configure Async PRAW with Custom SSL Context Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/configuration.rst Configure Async PRAW to use a custom SSL context, for example, to handle self-signed SSL certificates. This involves creating an aiohttp.TCPConnector with the SSL context and passing it to a ClientSession. ```python import ssl import aiohttp import asyncpraw ssl_ctx = ssl.create_default_context(cafile="/path/to/certfile.pem") conn = aiohttp.TCPConnector(ssl_context=ssl_ctx) session = aiohttp.ClientSession(connector=conn) reddit = asyncpraw.Reddit( client_id="SI8pN3DSbt0zor", client_secret="xaxkj7HNh8kwg8e5t4m6KvSrbTI", password="1guiwevlfo00esyy", requestor_kwargs={"session": session}, # pass the custom Session instance user_agent="testscript by u/fakebot3", username="fakebot3", ) ``` -------------------------------- ### Subreddit Listings Source: https://context7.com/praw-dev/asyncpraw/llms.txt Provides examples for iterating through subreddit submissions using various sorting methods like `hot`, `new`, `top`, `rising`, and `controversial`, with options for time filters and limits. ```APIDOC ## Subreddit Listings — hot, new, top, rising, controversial Async-iterable listing generators for retrieving submissions from a subreddit in various sort orders. ```python import asyncio import asyncpraw async def main(): async with asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", user_agent="MyBot/1.0", ) as reddit: subreddit = await reddit.subreddit("python") # Top 10 hot submissions print("=== HOT ===") async for submission in subreddit.hot(limit=10): print(f"[{submission.score}] {submission.title}") # Top submissions from the past week print("=== TOP (week) ===") async for submission in subreddit.top(time_filter="week", limit=5): print(f"{submission.title} — {submission.url}") # All new submissions (no limit) print("=== NEW (unlimited) ===") async for submission in subreddit.new(limit=None): print(submission.id) # Rising async for submission in subreddit.rising(limit=5): print(submission.title) # Controversial of the day async for submission in subreddit.controversial(time_filter="day", limit=5): print(submission.title) asyncio.run(main()) ``` ``` -------------------------------- ### Subreddit Listing Generators Source: https://context7.com/praw-dev/asyncpraw/llms.txt Provides examples of using async-iterable listing generators to retrieve submissions from a subreddit in various sort orders: hot, top, new, rising, and controversial. Supports time filters for 'top' and 'controversial'. ```python import asyncio import asyncpraw async def main(): async with asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", user_agent="MyBot/1.0", ) as reddit: subreddit = await reddit.subreddit("python") # Top 10 hot submissions print("=== HOT ===") async for submission in subreddit.hot(limit=10): print(f"[{submission.score}] {submission.title}") # Top submissions from the past week print("=== TOP (week) ===") async for submission in subreddit.top(time_filter="week", limit=5): print(f"{submission.title} — {submission.url}") # All new submissions (no limit) print("=== NEW (unlimited) ===") async for submission in subreddit.new(limit=None): print(submission.id) # Rising async for submission in subreddit.rising(limit=5): print(submission.title) # Controversial of the day async for submission in subreddit.controversial(time_filter="day", limit=5): print(submission.title) asyncio.run(main()) ``` -------------------------------- ### Initialize Reddit with Keyword Arguments Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/configuration/reddit_initialization.rst Use keyword arguments to directly provide authentication and user agent details when creating a `Reddit` instance. This is an alternative to using a `praw.ini` file. ```python reddit = asyncpraw.Reddit( client_id="SI8pN3DSbt0zor", client_secret="xaxkj7HNh8kwg8e5t4m6KvSrbTI", password="1guiwevlfo00esyy", user_agent="testscript by u/fakebot3", username="fakebot3", ) ``` -------------------------------- ### Initializing the Reddit Client Source: https://context7.com/praw-dev/asyncpraw/llms.txt Demonstrates how to initialize the `Reddit` client with different authentication methods (script, read-only, refresh token) and how to use it as an async context manager. ```APIDOC ## Reddit — Initializing the Client The `Reddit` class is the entry point for all API calls. It supports script (username/password), read-only, and web/installed app (refresh token) authentication. It can be used as an async context manager to automatically close the underlying `aiohttp` session. ```python import asyncio import asyncpraw async def main(): # Script-type OAuth (authenticated, read/write) async with asyncpraw.Reddit( client_id="MY_CLIENT_ID", client_secret="MY_CLIENT_SECRET", username="MY_USERNAME", password="MY_PASSWORD", user_agent="MyBot/1.0 by u/MY_USERNAME", ) as reddit: print(reddit.read_only) # False # Read-only (no username/password) reddit_ro = asyncpraw.Reddit( client_id="MY_CLIENT_ID", client_secret="MY_CLIENT_SECRET", user_agent="MyBot/1.0", ) print(reddit_ro.read_only) # True await reddit_ro.close() # Refresh-token (web/installed app) reddit_web = asyncpraw.Reddit( client_id="MY_CLIENT_ID", client_secret="MY_CLIENT_SECRET", refresh_token="MY_REFRESH_TOKEN", user_agent="MyBot/1.0 by u/MY_USERNAME", ) me = await reddit_web.user.me() print(me) # Output: MY_USERNAME await reddit_web.close() asyncio.run(main()) ``` ``` -------------------------------- ### Initialize Async PRAW Client Source: https://context7.com/praw-dev/asyncpraw/llms.txt Demonstrates initializing the Async PRAW Reddit client with different authentication methods: script-type, read-only, and refresh-token. The client can be used as an async context manager. ```python import asyncio import asyncpraw async def main(): # Script-type OAuth (authenticated, read/write) async with asyncpraw.Reddit( client_id="MY_CLIENT_ID", client_secret="MY_CLIENT_SECRET", username="MY_USERNAME", password="MY_PASSWORD", user_agent="MyBot/1.0 by u/MY_USERNAME", ) as reddit: print(reddit.read_only) # False # Read-only (no username/password) reddit_ro = asyncpraw.Reddit( client_id="MY_CLIENT_ID", client_secret="MY_CLIENT_SECRET", user_agent="MyBot/1.0", ) print(reddit_ro.read_only) # True await reddit_ro.close() # Refresh-token (web/installed app) reddit_web = asyncpraw.Reddit( client_id="MY_CLIENT_ID", client_secret="MY_CLIENT_SECRET", refresh_token="MY_REFRESH_TOKEN", user_agent="MyBot/1.0 by u/MY_USERNAME", ) me = await reddit_web.user.me() print(me) # Output: MY_USERNAME await reddit_web.close() asyncio.run(main()) ``` -------------------------------- ### Initialize Async PRAW Reddit Instance Source: https://github.com/praw-dev/asyncpraw/blob/main/README.rst Instantiate an Async PRAW Reddit client with your API credentials. Ensure you have a script-type OAuth application. ```python import asyncpraw reddit = asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", password="PASSWORD", user_agent="USERAGENT", username="USERNAME", ) ``` -------------------------------- ### Initialize Reddit with a Specific Site Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/configuration/prawini.rst Demonstrates how to initialize the Async PRAW Reddit instance using a specific site name defined in praw.ini. ```python import asyncpraw reddit = asyncpraw.Reddit("bot2", user_agent="bot2 user agent") ``` -------------------------------- ### Initialize Reddit with Interpolation Enabled Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/configuration/prawini.rst Shows how to initialize Async PRAW with interpolation enabled for configuration values. ```python import asyncpraw reddit = asyncpraw.Reddit("bot1", config_interpolation="basic") ``` -------------------------------- ### Run Pre-push Checks Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/package_info/contributing.rst Execute the full pre-commit suite and documentation build checks before submitting a pull request. ```bash ./pre_push.py ``` -------------------------------- ### Activate Virtual Environment (MacOS/Linux) Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/package_info/contributing.rst Activate the virtual environment on MacOS or Linux systems to begin development. ```bash source .venv/bin/activate ``` -------------------------------- ### Create a Virtual Environment Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/package_info/contributing.rst Use this command to create a virtual environment for development. It isolates project dependencies. ```bash python3 -m venv .venv ``` -------------------------------- ### Authorize Code Flow and Get User Me Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/authentication.rst After obtaining the authorization code from the redirect, use it to authorize the Reddit instance and fetch the authenticated user's information. ```python print(await reddit.auth.authorize(code)) print(await reddit.user.me()) ``` -------------------------------- ### Check Environment Variables (Bash/Batch/Powershell) Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/configuration/prawini.rst Demonstrates how to check the values of environment variables in different shells to locate configuration directories. ```bash echo "$" ``` ```bat echo "%%" ``` ```powershell Write-Output "$env:" ``` -------------------------------- ### Initialize Async PRAW Reddit Instance Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/tutorials/reply_bot.rst Create an instance of the Reddit class to interact with the Reddit API. Ensure you have your OAuth2 credentials and Reddit account username/password. ```python import asyncpraw reddit = asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", password="PASSWORD", user_agent="LMGTFY (by u/USERNAME)", username="USERNAME", ) ``` -------------------------------- ### Check Environment Variables (Python) Source: https://github.com/praw-dev/asyncpraw/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("", "")) ``` -------------------------------- ### Initialize Async PRAW Reddit Instance Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/tutorials/comments.rst Create an instance of asyncpraw.Reddit to interact with the Reddit API. Provide your client ID, client secret, username, password, and user agent. Username and password are optional for analyzing public comments only. ```python import asyncpraw reddit = asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", password="PASSWORD", user_agent="Comment Extraction (by u/USERNAME)", username="USERNAME", ) ``` -------------------------------- ### Manage Flair with asyncpraw Source: https://context7.com/praw-dev/asyncpraw/llms.txt This snippet demonstrates how to manage user and link flair, including listing, creating templates, setting flair for users, and applying flair to submissions. Requires authentication. ```python import asyncio import asyncpraw async def main(): async with asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", username="USERNAME", password="PASSWORD", user_agent="MyBot/1.0 by u/USERNAME", ) as reddit: subreddit = await reddit.subreddit("test") # List all user flair in the subreddit async for flair in subreddit.flair(limit=100): print(f"{flair['user']}: {flair['flair_text']}") # List flair templates async for template in subreddit.flair.templates: print(template["id"], template["flair_text"]) # Create a new user flair template await subreddit.flair.templates.add( text="Contributor", css_class="contributor", text_editable=False ) # Set flair for a specific user await subreddit.flair.set("target_username", text="Helper", css_class="helper") # Set flair on a submission (mod-only) submission = await reddit.submission("abc123", fetch=False) await submission.mod.flair(text="Solved", css_class="solved") # Select flair from template on a submission choices = await submission.flair.choices() template_id = choices[0]["flair_template_id"] await submission.flair.select(template_id, text="My custom flair") asyncio.run(main()) ``` -------------------------------- ### Access Subreddit and Listings Source: https://context7.com/praw-dev/asyncpraw/llms.txt Shows how to access a subreddit instance, both lazily and fetched with full attributes. It also demonstrates combining subreddits and filtering them. ```python import asyncio import asyncpraw async def main(): async with asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", user_agent="MyBot/1.0", ) as reddit: # Lazy instance (no network request yet) subreddit = await reddit.subreddit("learnpython") # Fetched instance with full attributes subreddit = await reddit.subreddit("learnpython", fetch=True) print(subreddit.title) # "Learning Python" print(subreddit.subscribers) # e.g. 800000 print(subreddit.public_description) # Combine subreddits multi = await reddit.subreddit("python+learnpython") async for submission in multi.hot(limit=5): print(submission.title) # Filter from r/all filtered = await reddit.subreddit("all-learnpython") async for submission in filtered.new(limit=5): print(submission.title) asyncio.run(main()) ``` -------------------------------- ### Obtain Comment Instances Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/quick_start.rst Access top-level comments via the `comments` attribute of a Submission, or get all comments as a flattened list using `submission.comments.list()`. The default sort order is 'confidence', but can be changed. ```python # assume you have a asyncpraw.Reddit instance bound to variable `reddit` top_level_comments = await submission.comments() all_comments = await submission.comments.list() ``` -------------------------------- ### Obtain a Redditor Instance Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/quick_start.rst Get a Redditor instance either from the `author` attribute of a Submission or Comment, or by using the `redditor` method of a Reddit instance. `fetch=True` retrieves the redditor's details immediately. ```python # assume you have a Submission instance bound to variable `submission` redditor1 = submission.author print(redditor1.name) # Output: name of the redditor # assume you have a asyncpraw.Reddit instance bound to variable `reddit` redditor2 = await reddit.redditor("bboe", fetch=True) print(redditor2.link_karma) # Output: u/bboe's karma ``` -------------------------------- ### Obtain Refresh Token Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/tutorials/refresh_token.rst This Python 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 # Replace with your actual client ID and client secret client_id = "YOUR_CLIENT_ID" client_secret = "YOUR_CLIENT_SECRET" redirect_uri = "http://localhost:8080" # Define the scopes you need scopes = "read,submit,vote" # Initialize the Reddit instance with read-only mode r = praw.Reddit( client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, scope=scopes, # Use read-only mode to avoid accidentally making changes # when just obtaining the refresh token. read_only=True, ) # Get the authorization URL auth_url = r.auth.url(scopes, "state", "permanent") print(f"Go to this URL: {auth_url}") # The script will pause here, waiting for you to complete the authorization # in your browser and be redirected back to your redirect_uri. # The refresh token will be printed to the console after successful authorization. print("After authorizing, you will be redirected to a page where the refresh token is displayed.") print("Paste the full URL from your browser here and press Enter:") # This part simulates receiving the redirect. In a real application, you would # have a web server listening on redirect_uri to capture this. # For this example, we'll manually input the URL. redirect_response = input() r.auth.authorize(redirect_response) print(f"Refresh Token: {r.auth.refresh_token}") ``` -------------------------------- ### PRAW Lazy Loading vs. Async PRAW Full Loading Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/package_info/asyncpraw_migration.rst Compares PRAW's lazy loading with Async PRAW's default full loading upon initialization for submission objects. ```python # network request is not made and object is lazily loaded submission = reddit.submission("id") # network request is made and object is fully fetched print(submission.score) ``` ```python # network request made and object is fully loaded submission = await reddit.submission("id") # network request is not made as object is already fully fetched print(submission.score) ``` -------------------------------- ### Authenticate and Access User Info with Async PRAW Source: https://context7.com/praw-dev/asyncpraw/llms.txt Demonstrates how to authenticate with Reddit using async PRAW and access the authenticated user's information, including karma and subscribed subreddits. Also shows how to check username availability. Ensure you replace placeholders with your actual credentials. ```python import asyncio import asyncpraw async def main(): async with asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", username="USERNAME", password="PASSWORD", user_agent="MyBot/1.0 by u/USERNAME", ) as reddit: # Get the authenticated user's Redditor instance me = await reddit.user.me() print(f"Logged in as: {me}") print(f"Comment karma: {me.comment_karma}") print(f"Link karma: {me.link_karma}") # List subscribed subreddits async for subreddit in reddit.user.subreddits(limit=None): print(f"Subscribed: r/{subreddit}") # Check username availability available = await reddit.username_available("some_new_username") print(f"Available: {available}") asyncio.run(main()) ``` -------------------------------- ### Initialize asyncpraw Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/quick_start.rst Initialize asyncpraw with your client ID and client secret. This is required for authenticated requests. ```python import asyncpraw reddit = asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", user_agent="my user agent", username="my username", ) ``` -------------------------------- ### Configure ratelimit_seconds Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/ratelimits.rst Set the `ratelimit_seconds` configuration option when initializing Async PRAW to control the maximum wait time before raising an exception. ```python import asyncpraw reddit = asyncpraw.Reddit(..., ratelimit_seconds=300) ``` -------------------------------- ### Manage Wiki Pages with asyncpraw Source: https://context7.com/praw-dev/asyncpraw/llms.txt This code shows how to interact with a subreddit's wiki, including listing pages, fetching content, creating new pages, editing existing ones, and retrieving revision history. Authentication is required. ```python import asyncio import asyncpraw async def main(): async with asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", username="USERNAME", password="PASSWORD", user_agent="MyBot/1.0 by u/USERNAME", ) as reddit: subreddit = await reddit.subreddit("test") # List all wiki pages async for page in subreddit.wiki: print(page) # Fetch a specific wiki page wiki_page = await subreddit.wiki.get_page("rules") print(wiki_page.content_md) print(f"Revised by: {wiki_page.revision_by}") # Create a new wiki page new_page = await subreddit.wiki.create( name="my_page", content="# Hello\n\nThis is the page content.", reason="Initial creation", ) print(new_page) # Edit an existing wiki page await wiki_page.edit( content="# Updated\n\nNew content here.", reason="Updated rules", ) # List revisions for a page async for revision in wiki_page.revisions(limit=10): print(f"{revision['timestamp']}: {revision['reason']}") asyncio.run(main()) ``` -------------------------------- ### Activate Virtual Environment (Windows) Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/package_info/contributing.rst Activate the virtual environment on Windows Command Prompt. ```bat .venv\Scripts\activate.bat ``` -------------------------------- ### Default PRAW Configuration Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/configuration/prawini.rst The default configuration for Async PRAW as found in its package directory. ```ini [DEFAULT] client_id=%%CLIENT_ID%% client_secret=%%CLIENT_SECRET%% user_agent=%%USER_AGENT%% username=%%USERNAME%% password=%%PASSWORD%% ``` -------------------------------- ### Async PRAW Lazy Loading with fetch=False Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/package_info/asyncpraw_migration.rst Demonstrates how to maintain lazy loading in Async PRAW for specific operations like moderation by using `fetch=False` during initialization. ```python # object is not fetched and is only removed reddit.submission("id").mod.remove() ``` ```python # network request is not made and object is lazily loaded submission = await reddit.submission("id", fetch=False) # object is not fetched and is only removed await submission.mod.remove() ``` -------------------------------- ### Handle Redirect to Login Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/faq.rst This exception occurs when Async PRAW is in read-only mode. Ensure the instance is authenticated. ```text asyncprawcore.exceptions.Redirect: Redirect to /r/subreddit/login/ (You may be trying to perform a non-read-only action via a read-only instance.) ``` -------------------------------- ### Obtain a Submission Instance Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/quick_start.rst Create a Submission instance directly using its ID or a URL. This is useful when you know the specific submission you want to access. ```python # assume you have a asyncpraw.Reddit instance bound to variable `reddit` submission = await reddit.submission("39zje0") print(submission.title) # Output: reddit will soon only be available ... # or submission = await reddit.submission(url="https://www.reddit.com/...") ``` -------------------------------- ### Initialize Reddit with Saved Refresh Token Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/authentication.rst Instantiate a Reddit object using a previously saved refresh token to immediately obtain an authorized instance. ```python reddit = praw.Reddit( client_id="SI8pN3DSbt0zor", ``` -------------------------------- ### Create a Submission Source: https://github.com/praw-dev/asyncpraw/blob/main/README.rst Create a new submission to a specified subreddit using the initialized Reddit instance. ```python # Create a submission to r/test subreddit = await reddit.subreddit("test") await subreddit.submit("Test Submission", url="https://reddit.com") ``` -------------------------------- ### Async PRAW .get_ Method with Slices Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/package_info/asyncpraw_migration.rst Illustrates using the `.get_(item)` method in Async PRAW with slices to retrieve multiple items, such as the last three rules. ```python # using slices rule = await subreddit.mod.rules.get_rule(slice(-3, None)) # to get the last 3 rules ``` -------------------------------- ### Manage Subreddit Stylesheet and Images Source: https://context7.com/praw-dev/asyncpraw/llms.txt Fetch, update, upload, and delete subreddit CSS and images. Requires authentication with appropriate subreddit permissions. ```python import asyncio import asyncpraw async def main(): async with asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", username="USERNAME", password="PASSWORD", user_agent="MyBot/1.0 by u/USERNAME", ) as reddit: subreddit = await reddit.subreddit("test") # Fetch current stylesheet stylesheet = await subreddit.stylesheet() print(stylesheet.stylesheet) # Update stylesheet new_css = stylesheet.stylesheet + "\n.announcement { color: red; }" await subreddit.stylesheet.update(new_css, reason="Added announcement style") # Upload a custom named image response = await subreddit.stylesheet.upload( name="my_logo", image_path="/path/to/logo.png" ) print(response["img_src"]) # Upload redesign banner await subreddit.stylesheet.upload_banner("/path/to/banner.png") # Delete the header image await subreddit.stylesheet.delete_header() asyncio.run(main()) ``` -------------------------------- ### Initialize Reddit with Refresh Token Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/authentication.rst Initialize asyncpraw.Reddit with client ID, client secret, refresh token, and user agent. This method is used when you have a refresh token and do not need to perform the OAuth2 authorization code grant flow. ```python import asyncpraw r = asyncpraw.Reddit( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", refresh_token="YOUR_REFRESH_TOKEN", user_agent="YOUR_USER_AGENT" ) print(r.auth.scopes()) ``` -------------------------------- ### Create Authorized Reddit Instance Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/quick_start.rst Instantiate an authorized Reddit object by providing client ID, client secret, user agent, username, and password. This is required for actions beyond reading public data. ```python import asyncpraw reddit = asyncpraw.Reddit( client_id="my client id", client_secret="my client secret", password="my password", ``` -------------------------------- ### Accessing Custom Configuration Option in Async PRAW Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/configuration/options.rst Demonstrates how to retrieve the value of a custom configuration option, such as 'app_debugging', from an instance of :class:`.Reddit`. This allows for application-specific settings to be managed through Async PRAW's configuration system. ```python reddit.config.custom["app_debugging"] ``` -------------------------------- ### PRAW Object Access by Index vs. Async PRAW .get_ Method Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/package_info/asyncpraw_migration.rst Compares accessing specific objects like WikiPage in PRAW using string indices versus Async PRAW's `.get_(item)` method, highlighting the change from lazy to full loading. ```python # lazily creates a WikiPage instance page = subreddit.wiki["page"] # network request is made and item is fully fetched print(page.content_md) ``` ```python # network request made and object is fully loaded page = await subreddit.wiki.get_page("page") # network request is not made as WikiPage is already fully fetched`` print(page.content_md) ``` -------------------------------- ### Configure Async PRAW with a Custom ClientSession Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/configuration.rst Pass a custom aiohttp ClientSession instance to Async PRAW's Reddit constructor. This is useful for advanced network configurations like proxying or custom SSL contexts. ```python import asyncpraw from aiohttp import ClientSession session = ClientSession(trust_env=True) reddit = asyncpraw.Reddit( client_id="SI8pN3DSbt0zor", client_secret="xaxkj7HNh8kwg8e5t4m6KvSrbTI", password="1guiwevlfo00esyy", requestor_kwargs={"session": session}, # pass the custom Session instance user_agent="testscript by u/fakebot3", username="fakebot3", ) ``` -------------------------------- ### Submit Gallery Post with Async PRAW Source: https://context7.com/praw-dev/asyncpraw/llms.txt Submits a multi-image gallery post to a subreddit. Each image can have a path, caption, and outbound URL. Requires authentication. ```python import asyncio import asyncpraw async def main(): async with asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", username="USERNAME", password="PASSWORD", user_agent="MyBot/1.0 by u/USERNAME", ) as reddit: subreddit = await reddit.subreddit("test") images = [ {"image_path": "/path/to/image1.png"}, {"image_path": "/path/to/image2.jpg", "caption": "Second image"}, { "image_path": "/path/to/image3.png", "caption": "Third with link", "outbound_url": "https://example.com", }, ] submission = await subreddit.submit_gallery( title="My Gallery Post", images=images, nsfw=False, ) print(f"Gallery post created: {submission.shortlink}") asyncio.run(main()) ``` -------------------------------- ### Search for URLs Correctly Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/faq.rst To search for a URL, prefix it with 'url:' and enclose it in quotation marks. ```python subreddit = await reddit.subreddit("all") async for result in subreddit.search("https://google.com"): # do things with results ... ``` ```python subreddit = await reddit.subreddit("all") async for result in subreddit.search('url:"https://google.com"'): # do things with results ... ``` -------------------------------- ### Submit Post to Subreddit with Async PRAW Source: https://context7.com/praw-dev/asyncpraw/llms.txt Submits a new post to a subreddit, supporting link posts, text posts, and posts with inline images. Requires authentication credentials and async PRAW. ```python import asyncio import asyncpraw from asyncpraw.models import InlineImage async def main(): async with asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", username="USERNAME", password="PASSWORD", user_agent="MyBot/1.0 by u/USERNAME", ) as reddit: subreddit = await reddit.subreddit("test") # Submit a link post submission = await subreddit.submit( title="Check out Async PRAW docs", url="https://asyncpraw.readthedocs.io", ) print(f"Created link post: {submission.shortlink}") # Submit a text (self) post text_sub = await subreddit.submit( title="Hello from Async PRAW", selftext="This is the **body** of the post, written in Markdown.", send_replies=False, ) print(f"Created text post: {text_sub.id}") # Submit a text post with inline image image = InlineImage(path="/tmp/photo.jpg", caption="My photo") await subreddit.submit( title="Post with inline image", selftext="Here is my image {img1} in the text.", inline_media={"img1": image}, ) asyncio.run(main()) ``` -------------------------------- ### Log All HTTP Requests to Console Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/logging.rst Add this to your code to log all available information, including HTTP requests, to the console. Ensure the 'logging' module is imported. ```python 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) ``` -------------------------------- ### Set Environment Variables for Integration Tests Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/package_info/contributing.rst Export environment variables required for recording or updating integration test cassettes with vcrpy. These variables are replaced with placeholders in the recorded cassettes. ```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 ``` -------------------------------- ### Import Statements Source: https://github.com/praw-dev/asyncpraw/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 for better organization. ```python import praw import asyncpraw from asyncpraw.models import Submission from asyncpraw.models.reddit.subreddit import Subreddit from asyncpraw.models.reddit.user import Redditor from asyncpraw.exceptions import ClientException from configparser import ConfigParser from urllib.parse import quote_plus ``` -------------------------------- ### Create Read-only Reddit Instance Source: https://github.com/praw-dev/asyncpraw/blob/main/docs/getting_started/quick_start.rst Instantiate a read-only Reddit object by providing client ID, client secret, and user agent. This is useful for accessing public Reddit data. ```python import asyncpraw reddit = asyncpraw.Reddit( client_id="my client id", client_secret="my client secret", user_agent="my user agent", ) ``` -------------------------------- ### Fetching Frontpage Listings Source: https://context7.com/praw-dev/asyncpraw/llms.txt Retrieve listings from the user's frontpage, including hot, new, top, and controversial posts. Requires client ID, client secret, and user agent. ```python import asyncio import asyncpraw async def main(): async with asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", user_agent="MyBot/1.0", ) as reddit: # Iterate hot frontpage submissions async for submission in reddit.front.hot(limit=25): print(f"[{submission.score}] {submission.title}") # Iterate new frontpage submissions async for submission in reddit.front.new(limit=10): print(submission.title) # Top of the day from frontpage async for submission in reddit.front.top(time_filter="day", limit=10): print(f"{submission.title} — u/{submission.author}") asyncio.run(main()) ```