The Reddit Instance¶
- class asyncpraw.Reddit(site_name: str | None = None, *, config_interpolation: str | None = None, requestor_class: type[asyncprawcore.requestor.Requestor] | None = None, requestor_kwargs: dict[str, Any] | None = None, token_manager: BaseTokenManager | None = None, **config_settings: str | bool | int | None)¶
The Reddit class provides convenient access to Reddit’s API.
Instances of this class are the gateway to interacting with Reddit’s API through Async PRAW. The canonical way to obtain an instance of this class is via:
import asyncpraw reddit = asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", password="PASSWORD", user_agent="USERAGENT", username="USERNAME", )
- __init__(site_name: str | None = None, *, config_interpolation: str | None = None, requestor_class: type[asyncprawcore.requestor.Requestor] | None = None, requestor_kwargs: dict[str, Any] | None = None, token_manager: BaseTokenManager | None = None, **config_settings: str | bool | int | None)¶
Initialize a
Reddit
instance.- Parameters:
site_name – The name of a section in your
praw.ini
file from which to load settings from. This parameter, in tandem with an appropriately configuredpraw.ini
, file is useful if you wish to easily save credentials for different applications, or communicate with other servers running Reddit. Ifsite_name
isNone
, then the site name will be looked for in the environment variablepraw_site
. If it is not found there, theDEFAULT
site will be used (default:None
).config_interpolation – Config parser interpolation type that will be passed to
Config
(default:None
).requestor_class – A class that will be used to create a requestor. If not set, use
asyncprawcore.Requestor
(default:None
).requestor_kwargs – Dictionary with additional keyword arguments used to initialize the requestor (default:
None
).token_manager – When provided, the passed instance, a subclass of
BaseTokenManager
, will manage tokens via two callback functions. This parameter must be provided in order to work with refresh tokens (default:None
).
Additional keyword arguments will be used to initialize the
Config
object. This can be used to specify configuration settings during instantiation of theReddit
instance. For more details, please see Configuring Async PRAW.Required settings are:
client_id
client_secret
(for installed applications set this value toNone
)user_agent
The
requestor_class
andrequestor_kwargs
allow for customization of the requestorReddit
will use. This allows, e.g., easily adding behavior to the requestor or wrapping itsClientSession
in a caching layer. Example usage:import json import aiohttp from asyncprawcore import Requestor from asyncpraw import Reddit class JSONDebugRequestor(Requestor): async def request(self, *args, **kwargs): response = await super().request(*args, **kwargs) print(json.dumps(await response.json(), indent=4)) return response my_session = aiohttp.ClientSession(trust_env=True) reddit = Reddit( ..., requestor_class=JSONDebugRequestor, requestor_kwargs={"session": my_session} )
You can automatically close the requestor session by using this class as an asynchronous context manager:
async with Reddit(...) as reddit: print(await reddit.user.me())
You can also call
Reddit.close()
:reddit = Reddit(...) # do stuff with reddit ... # then close the requestor when done await reddit.close()
- auth¶
An instance of
Auth
.Provides the interface for interacting with installed and web applications.
See also
- await close()¶
Close the requestor.
- await comment(id: str | None = None, *, fetch: bool = True, url: str | None = None, **_) models.Comment ¶
Return an instance of
Comment
.- Parameters:
id – The ID of the comment.
fetch – Determines if Async PRAW will fetch the object (default:
True
).url – A permalink pointing to the comment.
If you don’t need the object fetched right away (e.g., to utilize a class method) then you can do:
comment = await reddit.comment("comment_id", fetch=False) await comment.reply("reply")
- await delete(path: str, *, data: dict[str, str | Any] | bytes | IO | str | None = None, json: dict[Any, Any] | list[Any] | None = None, params: str | dict[str, str] | None = None) Any ¶
Return parsed objects returned from a DELETE request to
path
.- Parameters:
path – The path to fetch.
data – Dictionary, bytes, or file-like object to send in the body of the request (default:
None
).json – JSON-serializable object to send in the body of the request with a Content-Type header of application/json (default:
None
). Ifjson
is provided,data
should not be.params – The query parameters to add to the request (default:
None
).
- domain(domain: str) DomainListing ¶
Return an instance of
DomainListing
.- Parameters:
domain – The domain to obtain submission listings for.
- drafts¶
An instance of
DraftHelper
.Provides the interface for working with
Draft
instances.For example, to list the currently authenticated user’s drafts:
drafts = await reddit.drafts()
You can also asynchronously iterate through the currently authenticated user’s drafts:
async for draft in reddit.drafts(): # do stuff with draft ...
To create a draft on r/test run:
await reddit.drafts.create(title="title", selftext="selftext", subreddit="test")
- front¶
An instance of
Front
.Provides the interface for interacting with front page listings. For example:
async for submission in reddit.front.hot(): print(submission)
- await get(path: str, *, params: str | dict[str, str | int] | None = None) Any ¶
Return parsed objects returned from a GET request to
path
.- Parameters:
path – The path to fetch.
params – The query parameters to add to the request (default:
None
).
- inbox¶
An instance of
Inbox
.Provides the interface to a user’s inbox which produces
Message
,Comment
, andSubmission
instances. For example, to iterate through comments which mention the authorized user run:async for comment in reddit.inbox.mentions(): print(comment)
- info(*, fullnames: Iterable[str] | None = None, subreddits: Iterable[asyncpraw.models.Subreddit | str] | None = None, url: str | None = None) AsyncGenerator[asyncpraw.models.Subreddit | asyncpraw.models.Comment | asyncpraw.models.Submission, None] ¶
Fetch information about each item in
fullnames
,url
, orsubreddits
.- Parameters:
fullnames – A list of fullnames for comments, submissions, and/or subreddits.
subreddits – A list of subreddit names or
Subreddit
objects to retrieve subreddits from.url – A url (as a string) to retrieve lists of link submissions from.
- Returns:
A generator that yields found items in their relative order.
Items that cannot be matched will not be generated. Requests will be issued in batches for each 100 fullnames.
Note
For comments that are retrieved via this method, if you want to obtain its replies, you will need to call
refresh()
on the yieldedComment
.Note
When using the URL option, it is important to be aware that URLs are treated literally by Reddit’s API. As such, the URLs
"youtube.com"
and"https://www.youtube.com"
will provide a different set of submissions.
- live¶
An instance of
LiveHelper
.Provides the interface for working with
LiveThread
instances. At present only new live threads can be created.await reddit.live.create(title="title", description="description")
- multireddit¶
An instance of
MultiredditHelper
.Provides the interface to working with
Multireddit
instances. For example, you can obtain aMultireddit
instance via:multireddit = await reddit.multireddit("samuraisam", "programming")
If you want to obtain a fetched
Multireddit
instance you can do:multireddit = await reddit.multireddit( redditor="samuraisam", name="programming", fetch=True )
- notes¶
An instance of
RedditModNotes
.Provides the interface for working with
ModNote
s for multiple redditors across multiple subreddits.Note
The authenticated user must be a moderator of the provided subreddit(s).
For example, the latest note for u/spez in r/redditdev and r/test, and for u/bboe in r/redditdev can be iterated through like so:
redditor = await reddit.redditor("bboe") subreddit = await reddit.subreddit("redditdev") pairs = [(subreddit, "spez"), ("test", "spez"), (subreddit, redditor)] async for note in reddit.notes(pairs=pairs): print(f"{note.label}: {note.note}")
- await patch(path: str, *, data: dict[str, str | Any] | bytes | IO | str | None = None, json: dict[Any, Any] | list[Any] | None = None, params: str | dict[str, str] | None = None) Any ¶
Return parsed objects returned from a PATCH request to
path
.- Parameters:
path – The path to fetch.
data – Dictionary, bytes, or file-like object to send in the body of the request (default:
None
).json – JSON-serializable object to send in the body of the request with a Content-Type header of application/json (default:
None
). Ifjson
is provided,data
should not be.params – The query parameters to add to the request (default:
None
).
- await post(path: str, *, data: dict[str, str | Any] | bytes | IO | str | None = None, files: dict[str, IO] | None = None, json: dict[Any, Any] | list[Any] | None = None, params: str | dict[str, str] | None = None) Any ¶
Return parsed objects returned from a POST request to
path
.- Parameters:
path – The path to fetch.
data – Dictionary, bytes, or file-like object to send in the body of the request (default:
None
).files – Dictionary, filename to file (like) object mapping (default:
None
).json – JSON-serializable object to send in the body of the request with a Content-Type header of application/json (default:
None
). Ifjson
is provided,data
should not be.params – The query parameters to add to the request (default:
None
).
- await put(path: str, *, data: dict[str, str | Any] | bytes | IO | str | None = None, json: dict[Any, Any] | list[Any] | None = None) Any ¶
Return parsed objects returned from a PUT request to
path
.- Parameters:
path – The path to fetch.
data – Dictionary, bytes, or file-like object to send in the body of the request (default:
None
).json – JSON-serializable object to send in the body of the request with a Content-Type header of application/json (default:
None
). Ifjson
is provided,data
should not be.
- await random_subreddit(*, nsfw: bool = False) asyncpraw.models.Subreddit ¶
Return a random instance of
Subreddit
.- Parameters:
nsfw – Return a random NSFW (not safe for work) subreddit (default:
False
).
- await redditor(name: str | None = None, *, fetch: bool = False, fullname: str | None = None) asyncpraw.models.Redditor ¶
Return an instance of
Redditor
.- Parameters:
name – The name of the redditor.
fetch – Determines if Async PRAW will fetch the object (default:
False
).fullname – The fullname of the redditor, starting with
t2_
.
Either
name
orfullname
can be provided, but not both.
- redditors¶
An instance of
Redditors
.Provides the interface for
Redditor
discovery. For example, to iterate over the newest Redditors, run:async for redditor in reddit.redditors.new(limit=None): print(redditor)
- await request(*, data: dict[str, str | Any] | bytes | IO | str | None = None, files: dict[str, IO] | None = None, json: dict[Any, Any] | list[Any] | None = None, method: str, params: str | dict[str, str | int] | None = None, path: str) Any ¶
Return the parsed JSON data returned from a request to URL.
- Parameters:
data – Dictionary, bytes, or file-like object to send in the body of the request (default:
None
).files – Dictionary, filename to file (like) object mapping (default:
None
).json – JSON-serializable object to send in the body of the request with a Content-Type header of application/json (default:
None
). Ifjson
is provided,data
should not be.method – The HTTP method (e.g.,
"GET"
,"POST"
,"PUT"
,"DELETE"
).params – The query parameters to add to the request (default:
None
).path – The path to fetch.
- await submission(id: str | None = None, *, fetch: bool = True, url: str | None = None, **_) asyncpraw.models.Submission ¶
Return an instance of
Submission
.- Parameters:
id – A Reddit base36 submission ID, e.g.,
2gmzqe
.fetch – Determines if Async PRAW will fetch the object (default:
True
).url – A URL supported by
Submission.id_from_url()
.
Either
id
orurl
can be provided, but not both.If you don’t need the object fetched right away (e.g., to utilize a class method) then you can do:
submission = await reddit.submission("submission_id", fetch=False) await submission.mod.remove()
- subreddit¶
An instance of
SubredditHelper
.Provides the interface to working with
Subreddit
instances. For example, to create aSubreddit
run:await reddit.subreddit.create(name="coolnewsubname")
To obtain a lazy
Subreddit
instance run:await reddit.subreddit("test")
To obtain a fetched
Subreddit
instance run:await reddit.subreddit("test", fetch=True)
Multiple subreddits can be combined and filtered views of r/all can also be used just like a subreddit:
await reddit.subreddit("redditdev+learnpython+botwatch") await reddit.subreddit("all-redditdev-learnpython")
- subreddits¶
An instance of
Subreddits
.Provides the interface for
Subreddit
discovery. For example, to iterate over the set of default subreddits run:async for subreddit in reddit.subreddits.default(limit=None): print(subreddit)
- user¶
An instance of
User
.Provides the interface to the currently authorized
Redditor
. For example, to get the name of the current user run:print(await reddit.user.me())
- await username_available(name: str) bool ¶
Check to see if the username is available.
For example, to check if the username
bboe
is available, try:await reddit.username_available("bboe")
- property validate_on_submit: bool¶
Get validate_on_submit.
Deprecated since version 7.0: If property
validate_on_submit
is set toFalse
, the behavior is deprecated by Reddit. This attribute will be removed around May-June 2020.