### Async Client Setup and Message Handling Source: https://context7.com/pyprohly/redditwarp/llms.txt Initialize and use the asynchronous client for concurrent operations. This example demonstrates listening for messages and replying to '!ping' commands. ```python import asyncio import redditwarp.ASYNC from redditwarp.models.message_ASYNC import ComposedMessage from redditwarp.streaming.makers.message_ASYNC import create_inbox_message_stream from redditwarp.streaming.ASYNC import flow async def main() -> None: client = redditwarp.ASYNC.Client.from_praw_config('SuvaBot') async with client: inbox_message_stream = create_inbox_message_stream(client) @inbox_message_stream.output.attach async def _(mesg: MailboxMessage) -> None: if isinstance(mesg, ComposedMessage): if mesg.subject.startswith('!ping'): await client.p.message.send( mesg.author_name, 're: ' + mesg.subject, 'pong', ) await flow(inbox_message_stream) asyncio.run(main()) ``` -------------------------------- ### PRAW Configuration File Example Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/authorization.md An example of a praw.ini file. This format is supported for client configuration. Ensure values are not enclosed in quotes. ```ini [DEFAULT] client_id = cvQTsEXAMPLE9qlKflga7L client_secret = 2reTtEXAMPLE7mDAvpdg20j3P9Iqdu user_agent = u_SuvaBot by u/Pyprohly [SuvaBot] refresh_token = 69268695264-IAyOnEXAMPLEkHXsdi9aMdULbIvFJi ``` -------------------------------- ### Install HTTPX Transport Library Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/installation.md Install the recommended HTTPX library for enhanced HTTP transport capabilities with RedditWarp. This is optional but recommended. ```bash pip install -U httpx ``` -------------------------------- ### Install RedditWarp and httpx Source: https://context7.com/pyprohly/redditwarp/llms.txt Install the RedditWarp library and the recommended httpx HTTP transport library using pip. ```bash pip install -U redditwarp pip install -U httpx ``` -------------------------------- ### Install RedditWarp Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/installation.md Use pip to install or update the RedditWarp library. Ensure Python 3.8+ is installed. ```bash pip install -U redditwarp ``` -------------------------------- ### Iterator Import Example Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-basics.md Shows an example of importing an iterator that does not follow the SYNC/ASYNC naming convention, as it's intended for use in both IO worlds. ```python # SYNC from redditwarp.iterators.call_chunk_chaining_iterator import CallChunkChainingIterator ``` -------------------------------- ### Get RedditWarp Version Source: https://context7.com/pyprohly/redditwarp/llms.txt Import the redditwarp library and print its version. This is useful for verifying the installation. ```python import redditwarp print(redditwarp.__version__) # '1.3.0.post.dev' ``` -------------------------------- ### Synchronous Reddit Client Example Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-basics.md Demonstrates setting up a synchronous Reddit client and processing incoming messages to reply to '!ping' subjects. Requires PRAW configuration. ```python #!/usr/bin/env python from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from redditwarp.models.message_SYNC import MailboxMessage import redditwarp.SYNC from redditwarp.models.message_SYNC import ComposedMessage from redditwarp.streaming.makers.message_SYNC import create_inbox_message_stream from redditwarp.streaming.SYNC import flow def main() -> None: client = redditwarp.SYNC.Client.from_praw_config('SuvaBot') with client: inbox_message_stream = create_inbox_message_stream(client) @inbox_message_stream.output.attach def _(mesg: MailboxMessage) -> None: if isinstance(mesg, ComposedMessage): if mesg.subject.startswith('!ping'): client.p.message.send( mesg.author_name, 're: ' + mesg.subject, 'pong', ) flow(inbox_message_stream) main() ``` -------------------------------- ### Example praw.ini Configuration Source: https://context7.com/pyprohly/redditwarp/llms.txt An example praw.ini file demonstrating how to configure default and specific bot credentials, including client ID, secret, user agent, and refresh token. Place this file in ~/.config/praw.ini on macOS. ```ini # Example praw.ini file (place in ~/.config/praw.ini on macOS) [DEFAULT] client_id = cvQTsEXAMPLE9qlKflga7L client_secret = 2reTtEXAMPLE7mDAvpdg20j3P9Iqdu user_agent = u_SuvaBot by u/Pyprohly [SuvaBot] refresh_token = 69268695264-IAyOnEXAMPLEkHXsdi9aMdULbIvFJi ``` -------------------------------- ### Asynchronous Reddit Client Example Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-basics.md Shows how to set up an asynchronous Reddit client and process incoming messages, including async message sending. Requires PRAW configuration and asyncio. ```python #!/usr/bin/env python from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from redditwarp.models.message_ASYNC import MailboxMessage import asyncio import redditwarp.ASYNC from redditwarp.models.message_ASYNC import ComposedMessage from redditwarp.streaming.makers.message_ASYNC import create_inbox_message_stream from redditwarp.streaming.ASYNC import flow async def main() -> None: client = redditwarp.ASYNC.Client.from_praw_config('SuvaBot') async with client: inbox_message_stream = create_inbox_message_stream(client) @inbox_message_stream.output.attach async def _(mesg: MailboxMessage) -> None: if isinstance(mesg, ComposedMessage): if mesg.subject.startswith('!ping'): await client.p.message.send( mesg.author_name, 're: ' + mesg.subject, 'pong', ) await flow(inbox_message_stream) asyncio.run(main()) ``` -------------------------------- ### Make GET Request Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/http-components.md Perform a GET request using the `request()` method and access the response data. Alternatively, use `inquire()` to get both the request and response objects. ```python resp = http.request('GET', 'http://httpbin.org/get') # OR resp = http.inquire('GET', 'http://httpbin.org/get').response print(resp.data.decode()) ``` -------------------------------- ### Installed Client Grant Type Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-client.md Shows how to use the installed client grant type, which is a Reddit-specified extension. The helper mapping object is located at `redditwarp.core.grants.InstalledClientGrant`. ```python import uuid import redditwarp.core.grants as core_grants grant = core_grants.InstalledClientGrant(str(uuid.uuid1())) Client(CLIENT_ID, CLIENT_SECRET, grant=grant) ``` -------------------------------- ### Check Global Rate Limit Headers Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/rate-limits.md Inspect the `x-ratelimit-*` headers to monitor your current global rate limit status. This example shows remaining requests, used requests, and reset time. ```default >>> client.p.ping() >>> {k: v for k, v in client.http.last.response.headers.items() if 'ratelimit' in k.lower()} {'x-ratelimit-remaining': '596.0', 'x-ratelimit-used': '4', 'x-ratelimit-reset': '139'} ``` -------------------------------- ### Stream Subreddit Submissions Asynchronously Source: https://github.com/pyprohly/redditwarp/blob/main/README.md This asynchronous example demonstrates how to create a stream of new submissions from a subreddit and process them. It includes handlers for submission output and potential errors. ```python #!/usr/bin/env python from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from redditwarp.models.submission_ASYNC import Submission import asyncio import redditwarp.ASYNC from redditwarp.streaming.makers.subreddit_ASYNC import create_submission_stream from redditwarp.streaming.ASYNC import flow async def main() -> None: client = redditwarp.ASYNC.Client() async with client: submission_stream = create_submission_stream(client, 'AskReddit') @submission_stream.output.attach async def _(subm: Submission) -> None: print(subm.id36, '~', subm.title) @submission_stream.error.attach async def _(exc: Exception) -> None: print('ERROR:', repr(exc)) await flow(submission_stream) asyncio.run(main()) ``` -------------------------------- ### Monitor New Submissions and Comments in a Subreddit Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/streaming.md This example demonstrates how to create and manage streams for new submissions and comments in a specified subreddit. It includes attaching handlers for output and errors, and using the `flow` function to run the streams concurrently. Ensure proper error handling for exceptions raised by the streaming mechanism. ```python #!/usr/bin/env python from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from redditwarp.models.submission_ASYNC import Submission from redditwarp.models.comment_ASYNC import Comment import sys import asyncio import traceback import redditwarp.ASYNC from redditwarp.streaming.makers.subreddit_ASYNC import ( create_submission_stream, create_comment_stream, ) from redditwarp.streaming.ASYNC import flow from redditwarp.util.passthru import passthru async def main() -> None: client = redditwarp.ASYNC.Client() async with client: submission_stream = create_submission_stream(client, 'AskReddit') @submission_stream.output.attach async def _(subm: Submission) -> None: print(f"{subm.id36}+", '*', repr(subm.title)) comment_stream = create_comment_stream(client, 'AskReddit') @comment_stream.output.attach async def _(comm: Comment) -> None: print(f"+{comm.id36}", '-', repr(comm.body)[:20]) @passthru(comment_stream.error.attach) @passthru(submission_stream.error.attach) async def _(exc: Exception) -> None: print('<>', file=sys.stderr) traceback.print_exception(exc.__class__, exc, exc.__traceback__) print('', file=sys.stderr) await flow( submission_stream, comment_stream, ) asyncio.run(main()) ``` -------------------------------- ### PRAW Lazy Loading Example Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/praw-comparison.md Demonstrates PRAW's lazy loading behavior where data is fetched only when an attribute is first accessed. This can lead to multiple web requests. ```python >>> subreddit = reddit.subreddit('POWERshell') >>> subreddit.display_name 'POWERshell' >>> subreddit.name # Web request performed here 't5_2qo1o' >>> subreddit.display_name 'PowerShell' ``` -------------------------------- ### New Connector for Async HTTP Transport Source: https://github.com/pyprohly/redditwarp/blob/main/CHANGELOG.md This is the new way to get a connector for the asynchronous HTTP transport. It has been moved from `redditwarp.http.transport.reg_ASYNC.new_connector()` to `redditwarp.http.transport.auto_ASYNC`. ```python redditwarp.http.transport.auto_ASYNC.new_connector() ``` -------------------------------- ### Send Query Parameters Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/http-components.md Include URL query parameters in a GET request by passing a dictionary to the `params` argument. The values in the `params` mapping must be strings. ```python >>> requ = http.inquire('GET', 'http://httpbin.org/get', params={'a': '1', 'b': '2'}).request >>> requ.url 'http://httpbin.org/get?a=1&b=2' ``` -------------------------------- ### Iterating Through Paginated Results Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/pagination.md Example of iterating through a paginated result set and printing formatted submission details. The `amount` parameter can limit the number of results. ```python >>> it = client.p.front.pull.hot(amount=5) >>> l = list(it) >>> for subm in l: ... print("r/{0.subreddit.name} | {0.id36}+ ^{0.score} | {0.title!r:.80}".format(subm)) ... ``` -------------------------------- ### Fetch Top Submission of the Week Source: https://github.com/pyprohly/redditwarp/blob/main/README.md Retrieves and displays details of the top submission from the past week in a specified subreddit. This example assumes the client is initialized. ```python m = next(client.p.subreddit.pull.top('YouShouldKnow', amount=1, time='week')) print(f'''\ {m.permalink} {m.id36}+ ^{m.score} | {m.title} Submitted {m.created_at.astimezone().ctime()}{' *' if m.is_edited else ''} \ by u/{m.author_display_name} to r/{m.subreddit.name} ''') ``` -------------------------------- ### Model Method Passthrough Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-basics.md Illustrates that model methods are passthroughs to the procedure index methods. For example, calling `subm.delete()` is functionally identical to `client.p.submission.delete(subm.idn)`. ```python subm.delete() # <== Functionally identical ==> client.p.submission.delete(subm.idn) ``` -------------------------------- ### Handle Endpoint-Local Rate Limit Exception Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/rate-limits.md Catch and handle `RedditError` with the label 'RATELIMIT' for endpoint-specific rate limits. This example includes a sleep to wait for the limit to reset before retrying. ```default try: client.p.comment.reply(1234, 'text') except redditwarp.exceptions.RedditError as e: if e.label == 'RATELIMIT': time.sleep(600) else: raise client.p.comment.reply(1234, 'text') ``` -------------------------------- ### Async Comment Tree Traversal Setup Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/comment-trees.md Imports necessary for asynchronous comment tree traversal. This snippet sets up type checking for asynchronous comment tree nodes. ```python #!/usr/bin/env python from __future__ import annotations from typing import TYPE_CHECKING, AsyncIterator if TYPE_CHECKING: # from typing import MutableSequence, Callable, Awaitable from redditwarp.models.comment_tree_ASYNC import CommentSubtreeTreeNode # from redditwarp.models.comment_tree_ASYNC import MoreCommentsTreeNode import asyncio ``` -------------------------------- ### Fetch User by Fullname ID (RedditWarp) Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/praw-comparison.md Fetches a user's data by first retrieving their summary to get their name, then fetching their full data. Handles cases where the user might not be found. ```python user_summary = client.p.user.get_user_summary('4x25quk') if user_summary is None: raise Exception user = client.p.user.fetch_by_name(user_summary.name) print(user.total_karma) ``` -------------------------------- ### Send Files via Multipart Form Data Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/http-components.md Upload files using multipart form data by passing a dictionary of file objects to the `files` parameter. The example shows opening a file in binary read mode. ```python >>> files = {'file': open('file1', 'rb')} >>> requ = http.inquire('POST', 'http://httpbin.org/post', files=files).request >>> requ.data b'--9055dc7b5eda1da2b214831aae84aaa7\r\nContent-Disposition: form-data; name="file"\r\nContent-Type: application/octet-stream\r\n\r hi\r\n--9055dc7b5eda1da2b214831aae84aaa7--\r\n' ``` -------------------------------- ### Initialize RedditWarp Client and View Procedures Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-procedure-index.md Demonstrates how to import the SYNC client, instantiate it, and view the top-level procedure groups available via `client.p`. ```python >>> import redditwarp.SYNC >>> client = redditwarp.SYNC.Client() >>> client.p. client.p.account client.p.misc client.p.collection client.p.moderation client.p.comment client.p.modmail client.p.comment_tree client.p.ping() client.p.custom_feed client.p.submission client.p.draft client.p.subreddit client.p.flair client.p.subreddit_style_new client.p.flair_emoji client.p.subreddit_style_old client.p.front client.p.user client.p.live_thread client.p.widget client.p.message client.p.wiki >>> client.p. ``` -------------------------------- ### Client Constructor Overloads Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-client.md Demonstrates different ways to construct a client instance using various grant types. The `grant` keyword parameter is the universal one, with other overloads serving as shorthands. ```python @overload def __init__(self, client_id: str, client_secret: str, /, *, grant: AuthorizationGrant) -> None: ... ``` ```python from redditwarp.SYNC import Client from redditwarp.auth import grants Client(CLIENT_ID, CLIENT_SECRET) Client(CLIENT_ID, CLIENT_SECRET, grant=grants.ClientCredentialsGrant()) ``` ```python Client(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN) Client(CLIENT_ID, CLIENT_SECRET, grant=grants.RefreshTokenGrant(REFRESH_TOKEN)) ``` ```python Client(CLIENT_ID, CLIENT_SECRET, USERNAME, PASSWORD) Client(CLIENT_ID, CLIENT_SECRET, grant=grants.ResourceOwnerPasswordCredentialsGrant(USERNAME, PASSWORD)) ``` -------------------------------- ### Create Client from PRAW Config Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/authorization.md Instantiate a RedditWarp client using credentials from a praw.ini file. Provide the section name for user-specific configurations, or an empty string for default settings. ```python client1 = redditwarp.SYNC.Client.from_praw_config('SuvaBot') print(client1.p.account.fetch().name) client0 = redditwarp.SYNC.Client.from_praw_config('') client0.p.account.fetch() # Error: no user context ``` -------------------------------- ### RedditError exception traceback example Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-procedure-index.md Illustrates the traceback when a RedditError exception, such as USER_DOESNT_EXIST, is not caught. This shows the structure of the error message. ```python Traceback (most recent call last): File "", line 2, in File "/Users/danpro/Desktop/redditwarp/redditwarp/siteprocs/message/SYNC.py", line 31, in send self._client.request('POST', '/api/compose', data=req_data) File "/Users/danpro/Desktop/redditwarp/redditwarp/client_SYNC.py", line 236, in request snub(json_data) File "/Users/danpro/Desktop/redditwarp/redditwarp/exceptions.py", line 177, in raise_for_reddit_error raise RedditError(label=label, explanation=explanation, field=field) redditwarp.exceptions.RedditError: USER_DOESNT_EXIST: "that user doesn't exist" -> to ``` -------------------------------- ### Get Top Comment of a Submission Source: https://context7.com/pyprohly/redditwarp/llms.txt Fetch the top comment of a submission using `comment_tree.fetch` with `sort='top'` and `limit=1`. Requires the submission ID. ```python tree_node = client.p.comment_tree.fetch('uc8i1g', sort='top', limit=1) c = tree_node.children[0].value print(f"{c.submission.id36}+{c.id36} ^{c.score}") print(f"u/{c.author_display_name} says:") print(c.body) ``` -------------------------------- ### Initialize RedditWarp Client and Fetch Frontpage Submissions Source: https://github.com/pyprohly/redditwarp/blob/main/README.md Demonstrates how to initialize a synchronous RedditWarp client and retrieve the latest submissions from the Reddit frontpage. Requires Python 3.8+. ```python import redditwarp.SYNC client = redditwarp.SYNC.Client() it = client.p.front.pull.hot(5) l = list(it) for subm in l: print("r/{0.subreddit.name} | {0.id36}+ ^{0.score} | {0.title!r:.80}".format(subm)) ``` -------------------------------- ### Fetch User Data with RedditWarp Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/overview.md Demonstrates how to instantiate a synchronous client and fetch user information by name. Requires importing the SYNC module. ```python >>> import redditwarp.SYNC >>> client = redditwarp.SYNC.Client() >>> user = client.p.user.fetch_by_name('Pyprohly') >>> user.id36 '4x25quk' >>> user.name 'Pyprohly' >>> str(user.created_at) '2017-06-23 15:25:50+00:00' ``` -------------------------------- ### Get HTTP Transport Adapter Module Source: https://github.com/pyprohly/redditwarp/blob/main/CHANGELOG.md Retrieve the currently registered HTTP transport adapter module. This replaces the older `load_transport()` function. ```python get_transport_adapter_module() ``` -------------------------------- ### Setting User Agent Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-client.md Demonstrates how to set a custom user agent for the client. The full user agent includes RedditWarp and httpx details. ```python >>> from redditwarp.SYNC import Client >>> client = Client() >>> client.set_user_agent("u_SuvaBot/1.0.0 (by u/Pyprohly)") >>> print(client.http.get_user_agent()) RedditWarp/0.7.0 Python/3.10.6 httpx/0.23.0 Bot !-- u_SuvaBot/1.0.0 (by u/Pyprohly) ``` -------------------------------- ### Handle Rate Limit Errors Source: https://context7.com/pyprohly/redditwarp/llms.txt Catch `RedditError` with the label 'RATELIMIT' to detect rate limiting. The example shows waiting and retrying the operation. ```python import redditwarp.exceptions import time try: client.p.comment.reply(1234, 'text') except redditwarp.exceptions.RedditError as e: if e.label == 'RATELIMIT': print('Rate limited, waiting 10 minutes...') time.sleep(600) client.p.comment.reply(1234, 'text') else: raise ``` -------------------------------- ### Fetch Account Info with Credentials Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/authorization.md Use your client ID, client secret, and refresh token to instantiate a client and fetch the authenticated user's account information. Ensure you have imported the redditwarp.SYNC module. ```python import redditwarp.SYNC CLIENT_ID = '...' CLIENT_SECRET = '...' REFRESH_TOKEN = '...' client = redditwarp.SYNC.Client(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN) me = client.p.account.fetch() print(f"Hello u/{me.name}!") ``` -------------------------------- ### Initialize HTTPClient Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/http-components.md Instantiate an HTTPClient by passing a Connector object to its constructor. The `new_connector()` function from `redditwarp.http.transport.auto_SYNC` is used to create a default connector. ```python from redditwarp.http.transport.auto_SYNC import new_connector from redditwarp.http.http_client_SYNC import HTTPClient http = HTTPClient(new_connector()) ``` -------------------------------- ### Instantiating RedditWarp Client Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/authorization.md Common ways to instantiate the RedditWarp Client. The zero-argument form provides read-only access using shared embedded credentials and is not recommended for bot programs. ```python Client() Client(CLIENT_ID, CLIENT_SECRET) Client(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN) ``` -------------------------------- ### Discover Submission Procedures in Python REPL Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-procedure-index.md Shows how to explore specific procedure groups, such as 'submission', by typing `client.p.submission.` in an interactive Python REPL to see available methods. ```python >>> client.p.submission. client.p.submission.MediaUploading( client.p.submission.media_uploading( client.p.submission.apply_removal_reason( client.p.submission.pin_to_profile( client.p.submission.approve( client.p.submission.remove( client.p.submission.bulk_fetch( client.p.submission.remove_spam( client.p.submission.bulk_hide( client.p.submission.reply( client.p.submission.bulk_unhide( client.p.submission.save( client.p.submission.create_crosspost( client.p.submission.search( client.p.submission.create_gallery_post( client.p.submission.send_removal_comment( client.p.submission.create_image_post( client.p.submission.send_removal_message( client.p.submission.create_link_post( client.p.submission.set_contest_mode( client.p.submission.create_poll_post( client.p.submission.set_event_time( client.p.submission.create_text_post( client.p.submission.set_suggested_sort( client.p.submission.create_video_post( client.p.submission.snooze_reports( client.p.submission.delete( client.p.submission.sticky( client.p.submission.disable_reply_notifications( client.p.submission.undistinguish( client.p.submission.distinguish( client.p.submission.unfollow_event( client.p.submission.duplicates( client.p.submission.unhide( client.p.submission.edit_text_post_body( client.p.submission.unignore_reports( client.p.submission.enable_reply_notifications( client.p.submission.unlock( client.p.submission.fetch( client.p.submission.unmark_nsfw( client.p.submission.follow_event( client.p.submission.unmark_spoiler( client.p.submission.get( client.p.submission.unpin_from_profile( client.p.submission.hide( client.p.submission.unsave( client.p.submission.ignore_reports( client.p.submission.unsnooze_reports( client.p.submission.lock( client.p.submission.unsticky( client.p.submission.mark_nsfw( client.p.submission.vote( client.p.submission.mark_spoiler( >>> client.p.submission. ``` -------------------------------- ### RedditWarp Client Constructor Overloads Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/authorization.md These are the available overloads for the RedditWarp Client constructor, showing different ways to initialize the client with or without credentials. ```python @overload def __init__(self) -> None: ... @overload def __init__(self, client_id: str, client_secret: str, /) -> None: ... @overload def __init__(self, client_id: str, client_secret: str, /, *, grant: AuthorizationGrant) -> None: ... @overload def __init__(self, client_id: str, client_secret: str, refresh_token: str, /) -> None: ... @overload def __init__(self, client_id: str, client_secret: str, username: str, password: str, /) -> None: ... ``` -------------------------------- ### Import Load Transport and New Connector Source: https://github.com/pyprohly/redditwarp/blob/main/CHANGELOG.md You can now import `load_transport` and `new_connector` directly from `redditwarp.http.(A)SYNC`. ```python from redditwarp.http.ASYNC import load_transport, new_connector ``` ```python from redditwarp.http.SYNC import load_transport, new_connector ``` -------------------------------- ### Initialize RedditWarp Client Source: https://context7.com/pyprohly/redditwarp/llms.txt Initialize a synchronous RedditWarp client instance with different authentication modes. Supports read-only access with shared or custom credentials, authenticated user access with a refresh token, PRAW configuration, or an existing access token. ```python import redditwarp.SYNC # Read-only client (shared credentials - for testing only) client = redditwarp.SYNC.Client() # Read-only client with your own credentials client = redditwarp.SYNC.Client('', '') # Authenticated client with refresh token CLIENT_ID = 'cvQTsEXAMPLE9qlKflga7L' CLIENT_SECRET = '2reTtEXAMPLE7mDAvpdg20j3P9Iqdu' REFRESH_TOKEN = '69268695264-IAyOnEXAMPLEkHXsdi9aMdULbIvFJi' client = redditwarp.SYNC.Client(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN) # Using praw.ini configuration file client = redditwarp.SYNC.Client.from_praw_config('SuvaBot') # Using an existing access token client = redditwarp.SYNC.Client.from_access_token('') ``` -------------------------------- ### Authenticate and Fetch User Information Source: https://github.com/pyprohly/redditwarp/blob/main/README.md Initializes a RedditWarp client with credentials (CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN) and fetches the authenticated user's information. Ensure credentials are provided. ```python CLIENT_ID = '...' CLIENT_SECRET = '...' REFRESH_TOKEN = '...' client1 = redditwarp.SYNC.Client(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN) me = client1.p.account.fetch() print(f"Hello u/{me.name}!") ``` -------------------------------- ### Fetch user by name with exception Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-procedure-index.md Demonstrates fetch_by_name() which raises a StatusCodeException (e.g., NotFound) if the user does not exist. Use when the resource is expected to exist. ```python >>> client.p.user.fetch_by_name('sdfaxzzdfv') Traceback (most recent call last): File "", line 1, in File "/Users/danpro/Desktop/redditwarp/redditwarp/siteprocs/user/SYNC.py", line 108, in fetch_by_name root = self._client.request('GET', f'/user/{name}/about') File "/Users/danpro/Desktop/redditwarp/redditwarp/client_SYNC.py", line 226, in request resp.ensure_successful_status() File "/Users/danpro/Desktop/redditwarp/redditwarp/http/response.py", line 31, in ensure_successful_status ensure_successful_status(self.status) File "/Users/danpro/Desktop/redditwarp/redditwarp/http/exceptions.py", line 124, in ensure_successful_status raise_now(n) File "/Users/danpro/Desktop/redditwarp/redditwarp/http/exceptions.py", line 119, in raise_now raise get_status_code_exception_class_by_status_code(n)(status_code=n) redditwarp.http.exceptions.StatusCodeExceptionTypes.NotFound: 404 Not Found ``` ```python >>> client.p.submission.fetch(999) Traceback (most recent call last): File "", line 1, in File "/Users/danpro/Desktop/redditwarp/redditwarp/siteprocs/submission/fetch_SYNC.py", line 22, in __call__ return self.by_id36(id36) File "/Users/danpro/Desktop/redditwarp/redditwarp/siteprocs/submission/fetch_SYNC.py", line 32, in by_id36 raise NoResultException('target not found') redditwarp.exceptions.NoResultException: target not found ``` -------------------------------- ### Fetch Submission by ID Source: https://context7.com/pyprohly/redditwarp/llms.txt Fetch a single Reddit submission by its ID using the client's procedure index. Use `fetch()` for expected existing resources or `get()` to return `None` if not found. ```python import redditwarp.SYNC client = redditwarp.SYNC.Client() # Fetch a single submission by ID subm = client.p.submission.fetch('10gudzi') print(f"Title: {subm.title}") print(f"Author: u/{subm.author_display_name}") print(f"Score: {subm.score}") print(f"Subreddit: r/{subm.subreddit.name}") print(f"Created: {subm.created_at}") print(f"Permalink: {subm.permalink}") # Get submission (returns None if not found) subm = client.p.submission.get(999999) if subm is None: print("Submission not found") ``` -------------------------------- ### Direct Paginator Usage for Specific Page Limits Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/pagination.md Demonstrates using the Paginator object directly to fetch a specific number of pages with a defined limit per page. Requires importing the SYNC client. ```python import redditwarp.SYNC client = redditwarp.SYNC.Client() it = client.p.front.pull.hot() paginator = it.get_paginator() paginator.limit = 5 for _ in range(3): page = paginator.fetch() if not page: break for subm in page: print("r/{0.subreddit.name} | {0.id36}+ ^{0.score} | {0.title!r:.80}".format(subm)) print('---') ``` -------------------------------- ### Add Zero-Arg Constructor and __reversed__ to OrderedSet Source: https://github.com/pyprohly/redditwarp/blob/main/CHANGELOG.md The `redditwarp.util.OrderedSet` class now includes a zero-argument constructor and the `__reversed__` method. ```python redditwarp.util.OrderedSet ``` -------------------------------- ### Instantiating Read-only Client with Own Credentials Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/authorization.md Instantiate a read-only RedditWarp client using your own client ID and client secret. This provides read-only access without user context and shares the same rate limit pool as the zero-argument form. ```python client = redditwarp.SYNC.Client('', '') ``` -------------------------------- ### Monitor Subreddit Comments and Send Messages Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/overview.md An asynchronous example of a Reddit bot script that monitors a subreddit for comments containing a specific string and sends a direct message. Requires importing ASYNC modules and setting up a client from PRAW configuration. ```python #!/usr/bin/env python from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from redditwarp.models.comment_ASYNC import Comment import asyncio import redditwarp.ASYNC from redditwarp.streaming.makers.subreddit_ASYNC import create_comment_stream from redditwarp.streaming.ASYNC import flow sr = 'test' user = 'test' needle = 'Hello World' async def main() -> None: client = redditwarp.ASYNC.Client.from_praw_config('SuvaBot') async with client: comment_stream = create_comment_stream(client, sr) @comment_stream.output.attach async def _(comm: Comment) -> None: if needle in comm.body: subject = f"World greeted by u/{comm.author_display_name}" body = comm.permalink await client.p.message.send(user, subject, body) await flow(comment_stream) asyncio.run(main()) ``` -------------------------------- ### New Submission Creation Method Group Source: https://github.com/pyprohly/redditwarp/blob/main/CHANGELOG.md Use the `client.p.submission.create` method group for creating submissions. All previous `client.p.submission.create_*_post()` methods are now aliases to methods within this group. ```python client.p.submission.create ``` -------------------------------- ### Making HTTP Requests Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-client.md Illustrates how to make direct HTTP requests using `client.http.request()`. This is useful for requests to other websites, as `client.request()` is designed for Reddit API specifics. ```python >>> from redditwarp.http.util.json_loading import load_json_from_response >>> resp = client.http.request('GET', 'http://httpbin.org/get') >>> json = load_json_from_response(resp) ``` -------------------------------- ### General Upload Lease Class Source: https://github.com/pyprohly/redditwarp/blob/main/CHANGELOG.md Use the general `UploadLease` class from `redditwarp.models.upload_lease`. Many specialized upload lease classes are now aliased to this general class. ```python redditwarp.models.upload_lease.UploadLease ``` -------------------------------- ### Procedure Index Overview Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-procedure-index.md The API procedures are organized under `client.p` and grouped by resource kind. This provides a structured way to access different functionalities. ```APIDOC ## Procedure Index Overview All API calls are accessible via `client.p`. Procedures are grouped into sub-objects based on resource kind for better organization. ### Example Access ```python >>> import redditwarp.SYNC >>> client = redditwarp.SYNC.Client() >>> client.p.account >>> client.p.submission >>> client.p.comment ``` ``` -------------------------------- ### Shorthand API Method Invocation in RedditWarp Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/praw-comparison.md Shows how API methods can be called directly on the client or via a shorthand on a fetched model instance in RedditWarp. Direct client invocation is preferred. ```python subm = client.p.submission.fetch('5e1az9') subm.reply("Very cool!") # Or client.p.submission.reply('5e1az9', "Very cool!") ``` -------------------------------- ### Iterating Paginator with next() Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/pagination.md Shows how to iterate through a Paginator using `next(pitr, None)` to fetch pages, breaking the loop if a page is `None`. ```python pitr = iter(paginator) for _ in range(3): page = next(pitr, None) if page is None: break for subm in page: print("r/{0.subreddit.name} | {0.id36}+ ^{0.score} | {0.title!r:.80}".format(subm)) print('---') ``` -------------------------------- ### Subreddit Paginator Imports Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-basics.md Illustrates how to import synchronous and asynchronous subreddit paginators, highlighting the 'sync1' and 'async1' naming convention for IO-committed objects. ```python # SYNC from redditwarp.pagination.paginators.subreddit_sync1 import SubredditSearchPaginator # ASYNC from redditwarp.pagination.paginators.subreddit_async1 import SubredditSearchAsyncPaginator ``` -------------------------------- ### Create Text and Link Submissions Source: https://context7.com/pyprohly/redditwarp/llms.txt Create text posts and link posts in a subreddit using an authenticated client. Requires client ID, client secret, and refresh token for authentication. ```python import redditwarp.SYNC CLIENT_ID = '...' CLIENT_SECRET = '...' REFRESH_TOKEN = '...' client = redditwarp.SYNC.Client(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN) # Create a text post client.p.submission.create.text( 'test', # subreddit name 'My Text Post Title', # title 'This is the body text.' # body (markdown) ) # Create a link post client.p.submission.create.link( 'test', 'Check out this cool website', 'https://www.reddit.com' ) ``` -------------------------------- ### Basic Pull Methods for Pagination Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/pagination.md These methods initiate pagination for retrieving data. They return objects that rely on a Paginator. ```python client.p.front.pull.hot() client.p.subreddit.pull_new_comments() client.p.message.pulls.inbox() ``` -------------------------------- ### Read-only Client with Embedded Credentials Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/authorization.md This code snippet demonstrates creating a read-only RedditWarp client using the zero-argument constructor. It fetches and prints information about a hot post from the front page. This works without prior configuration but uses shared rate limits. ```python import redditwarp.SYNC client = redditwarp.SYNC.Client() subm = next(client.p.front.pull.hot(amount=1)) print("r/{0.subreddit.name} | {0.id36}+ ^{0.score} | {0.title!r:.80}".format(subm)) ``` -------------------------------- ### Upload Video for Video Post Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/media-uploads.md Uploads a video file and a separate image file for a video post. The video is used as the post's content, and the image is used as its thumbnail. The 'location' attribute from the lease is used for both. ```python with open("/Users/danpro/Desktop/video.mp4", 'rb') as fh: video_lease = client.p.submission.media_uploading.upload(fh) with open("/Users/danpro/Desktop/image.jpg", 'rb') as fh: image_lease = client.p.submission.media_uploading.upload(fh) client.p.submission.create.video( 'Pyprohly_test3', 'My great video', video_lease.location, image_lease.location) ``` -------------------------------- ### Discovering Submission Procedures Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-procedure-index.md This section details how to discover and use procedures related to submissions, illustrating the navigation within the API structure. ```APIDOC ## Discovering Submission Procedures Procedures are organized by resource kind. For submission-related operations, navigate to `client.p.submission`. ### Example Discovery (Interactive REPL) ```python >>> client.p.submission. # IDEs or interactive REPLs can list available methods. # Example methods include: # client.p.submission.create_link_post(...) # client.p.submission.fetch(...) # client.p.submission.remove(...) ``` ### Common Methods Many resource sub-objects, like `submission`, include `get()` and `fetch()` methods for retrieving specific resource information by its ID. ``` -------------------------------- ### Low-Level API Request with RedditWarp Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/overview.md Shows how to make a direct low-level API request using the client and access the returned data. This is useful for accessing raw API responses. ```python >>> d = client.request('GET', '/user/Pyprohly/about')['data'] >>> print(d.keys() == user.d.keys()) True ``` -------------------------------- ### Alias Dark Client to Client Source: https://github.com/pyprohly/redditwarp/blob/main/CHANGELOG.md The `DarkClient` class is now an alias for `Client` in `redditwarp.dark.client_ASYNC`. ```python redditwarp.dark.client_ASYNC.DarkClient ``` -------------------------------- ### Verify RedditWarp Import and Version Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/installation.md Check if the redditwarp library can be imported and display its version in a Python REPL. ```python import redditwarp redditwarp.__version__ ``` -------------------------------- ### Submit a Link Post Source: https://github.com/pyprohly/redditwarp/blob/main/README.md Creates a new link post on a specified subreddit. Requires an authenticated client with appropriate permissions. ```python client1.p.submission.create.link('test', "Check out this cool website", "https://www.reddit.com") ``` -------------------------------- ### Configure Post Flair Post Appearance API Source: https://github.com/pyprohly/redditwarp/blob/main/CHANGELOG.md This procedure allows configuring the post flair post appearance. Use `client.p.flair.post_appearance.config()`. ```python client.p.flair.post_appearance.config() ``` -------------------------------- ### Fetch and Display Submission Details Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-procedure-index.md Illustrates how to use the `fetch()` method to retrieve a specific submission by its ID and access its attributes like author, title, creation time, and permalink. ```python subm = client.p.submission.fetch('cqufij') print(subm.author_display_name) print(subm.title) print(subm.created_at) print(subm.permalink) ``` -------------------------------- ### Fetch Submission and Comment Tree (RedditWarp) Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/praw-comparison.md Shows how RedditWarp requires separate calls to fetch a submission and its comment tree. Asserts that both methods yield the same submission ID. ```python subm1 = client.p.submission.fetch('10hoczb') tree_node = client.p.comment_tree.fetch('10hoczb') subm2 = tree_node.value assert subm1.idn == subm2.idn ``` -------------------------------- ### API Method Location: PRAW vs. RedditWarp Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/praw-comparison.md Illustrates the difference in how API methods are invoked. In PRAW, methods are often on object instances, while RedditWarp places them on the client object. ```python # PRAW reddit.submission('5e1az9').reply("Super rad!") # RedditWarp client.p.submission.reply('5e1az9', "Very cool!") ``` -------------------------------- ### Fetch User and Subreddit Information Source: https://context7.com/pyprohly/redditwarp/llms.txt Retrieve user profiles and subreddit details by name using the `fetch_by_name()` method. This provides access to user karma, creation date, and subreddit subscriber counts and descriptions. ```python import redditwarp.SYNC client = redditwarp.SYNC.Client() # Fetch user by name user = client.p.user.fetch_by_name('Pyprohly') print(f"User: u/{user.name}") print(f"ID: {user.id36}") print(f"Created: {user.created_at}") print(f"Total Karma: {user.total_karma}") # Fetch subreddit by name subr = client.p.subreddit.fetch_by_name('Python') print(f"Subreddit: r/{subr.name}") print(f"Subscribers: {subr.subscriber_count}") print(f"Description: {subr.public_description}") # Get user's recent comments for comm in client.p.user.pull.comments('Pyprohly', amount=5): print(f"Comment: {comm.body[:100]}") ``` -------------------------------- ### Upload Media for Posts Source: https://context7.com/pyprohly/redditwarp/llms.txt Upload images and videos to Reddit. This process involves obtaining an upload lease and then depositing the file. Requires client credentials and a refresh token. ```python import redditwarp.SYNC CLIENT_ID = '...' CLIENT_SECRET = '...' REFRESH_TOKEN = '...' client = redditwarp.SYNC.Client(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN) SR = 'test' # Upload an image post with open("/path/to/image.jpg", 'rb') as fh: lease = client.p.submission.media_uploading.upload(fh) client.p.submission.create.image(SR, 'My Image Post', lease.location) # Upload a video post (requires thumbnail image) with open("/path/to/video.mp4", 'rb') as fh: video_lease = client.p.submission.media_uploading.upload(fh) with open("/path/to/thumbnail.jpg", 'rb') as fh: image_lease = client.p.submission.media_uploading.upload(fh) client.p.submission.create.video( SR, 'My Video Post', video_lease.location, image_lease.location ) # Create text post with inline images using rich text with open("/path/to/flowers.jpg", 'rb') as fh: lease = client.p.submission.media_uploading.upload(fh) markdown_text = f''' Check out these flowers! ![img]({lease.media_id} "Beautiful wildflowers") ''' rtj = client.p.misc.convert_markdown_to_richtext(markdown_text) client.p.submission.create.text(SR, 'Nice flowers', rtj) ``` -------------------------------- ### Import Sync and Async Iterators Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-procedure-index.md Import statements for synchronous and asynchronous CallChunkChainingIterator classes. ```python # SYNC from redditwarp.iterators.call_chunk_chaining_iterator import CallChunkChainingIterator # ASYNC from redditwarp.iterators.call_chunk_chaining_async_iterator import CallChunkChainingAsyncIterator ``` -------------------------------- ### Generate Refresh Token CLI Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/getting-started/authorization.md Run this command in your terminal to initiate the OAuth2 flow for obtaining a refresh token. You will be prompted for your client ID and secret. ```bash $ python -m redditwarp.cli.refresh_token ``` -------------------------------- ### Apply Form Data Asynchronously Source: https://github.com/pyprohly/redditwarp/blob/main/CHANGELOG.md Use `ApplyFormData` and related classes for handling form data in asynchronous operations. These are located in the `redditwarp.http.misc.apply_form_data_ASYNC` module. ```python redditwarp.http.misc.apply_form_data_ASYNC.ApplyFormData ``` -------------------------------- ### Fetching a Submission Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/the-procedure-index.md Demonstrates how to fetch details of a specific submission using its ID. ```APIDOC ## Fetching a Submission Use the `fetch()` method within the relevant resource group (e.g., `client.p.submission`) to retrieve a specific item by its ID. ### Example ```python >>> subm = client.p.submission.fetch('cqufij') >>> print(subm.author_display_name) >>> print(subm.title) >>> print(subm.created_at) >>> print(subm.permalink) ``` ``` -------------------------------- ### Retrieve Request and Response Objects Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/http-components.md Use the `inquire()` method to obtain an `Exchange` object, which contains both the `request` (Requisition) and `response` (Response) objects for detailed inspection. ```python xchg = http.inquire('GET', '/get') requ = xchg.request resp = xchg.response ``` -------------------------------- ### CLI Command for DFS Traversal (Recursive) Source: https://github.com/pyprohly/redditwarp/blob/main/docs/source/user-guide/comment-trees.md Command-line interface command to visualize Reddit submission comment trees using the recursive DFS algorithm. This is useful for observing the output order and pace. ```bash python -m redditwarp.cli.comment_tree --algo=dfs0 t44sm0 ``` -------------------------------- ### Register HTTP Transport Adapter Module Source: https://github.com/pyprohly/redditwarp/blob/main/CHANGELOG.md Use this function to select an HTTP transport module. This replaces the older `load_transport()` function. ```python set_transport_adapter_module() ``` -------------------------------- ### Alias Create Crosspost Source: https://github.com/pyprohly/redditwarp/blob/main/CHANGELOG.md The `client.p.submission.create_cross_post()` method is now aliased to `create_crosspost()` for consistency with other `create_*_post()` methods. ```python client.p.submission.create_cross_post() ``` -------------------------------- ### Make Custom HTTP Requests Source: https://context7.com/pyprohly/redditwarp/llms.txt Execute arbitrary HTTP requests using the client's underlying HTTP utility. This is useful for interacting with endpoints not directly exposed by the library. ```python import redditwarp.SYNC from redditwarp.http.util.json_loading import load_json_from_response client = redditwarp.SYNC.Client() resp = client.http.request('GET', 'http://httpbin.org/get') json_data = load_json_from_response(resp) print(json_data) ```