Async PRAW: The Asynchronous Python Reddit API Wrapper

Async PRAW’s documentation is organized into the following sections:

Documentation Conventions

Unless otherwise mentioned, all examples in this document assume the use of a script application. See Authenticating via OAuth for information on using installed applications and web applications.

Quick Start

In this section, we go over everything you need to know to start building scripts or bots using Async PRAW, the Asynchronous Python Reddit API Wrapper. It’s fun and easy. Let’s get started.

Prerequisites

Python Knowledge

You need to know at least a little Python and some understanding of asynchronous usage in Python to use Async PRAW. Async PRAW supports Python 3.7+. If you are stuck on a problem, r/learnpython is a great place to ask for help.

Reddit Knowledge

A basic understanding of how Reddit works is a must. In the event you are not already familiar with Reddit start at Reddit Help.

Reddit Account

A Reddit account is required to access Reddit’s API. Create one at reddit.com.

Client ID & Client Secret

These two values are needed to access Reddit’s API as a script application (see Authenticating via OAuth for other application types). If you don’t already have a client ID and client secret, follow Reddit’s First Steps Guide to create them.

User Agent

A user agent is a unique identifier that helps Reddit determine the source of network requests. To use Reddit’s API, you need a unique and descriptive user agent. The recommended format is <platform>:<app ID>:<version string> (by u/<Reddit username>). For example, android:com.example.myredditapp:v1.2.3 (by u/kemitche). Read more about user agents at Reddit’s API wiki page.

With these prerequisites satisfied, you are ready to learn how to do some of the most common tasks with Reddit’s API.

Common Tasks

Obtain a Reddit Instance

Warning

For the sake of brevity, the following examples pass authentication information via arguments to asyncpraw.Reddit(). If you do this, you need to be careful not to reveal this information to the outside world if you share your code. It is recommended to use a praw.ini file in order to keep your authentication information separate from your code.

You need an instance of the Reddit class to do anything with Async PRAW. There are two distinct states a Reddit instance can be in: read-only, and authorized.

Read-only Reddit Instances

To create a read-only Reddit instance, you need three pieces of information:

  1. Client ID

  2. Client secret

  3. User agent

You may choose to provide these by passing in three keyword arguments when calling the initializer of the Reddit class: client_id, client_secret, user_agent (see Configuring Async PRAW for other methods of providing this information). For example:

import asyncpraw

reddit = asyncpraw.Reddit(
    client_id="my client id",
    client_secret="my client secret",
    user_agent="my user agent",
)

Just like that, you now have a read-only Reddit instance.

print(reddit.read_only)
# Output: True

With a read-only instance, you can do something like obtaining 10 “hot” submissions from r/test:

# continued from code above

subreddit = await reddit.subreddit("test")
async for submission in subreddit.hot(limit=10):
    print(submission.title)

# Output: 10 submissions

If you want to do more than retrieve public information from Reddit, then you need an authorized Reddit instance.

Note

In the above example we are limiting the results to 10. Without the limit parameter Async PRAW should yield as many results as it can with a single request. For most endpoints this results in 100 items per request. If you want to retrieve as many as possible pass in limit=None.

Authorized Reddit Instances

In order to create an authorized Reddit instance, two additional pieces of information are required for script applications (see Authenticating via OAuth for other application types):

  1. Your Reddit username, and

  2. Your Reddit password

Again, you may choose to provide these by passing in keyword arguments username and password when you call the Reddit initializer, like the following:

import asyncpraw

reddit = asyncpraw.Reddit(
    client_id="my client id",
    client_secret="my client secret",
    password="my password",
    user_agent="my user agent",
    username="my username",
)

print(reddit.read_only)
# Output: False

Now you can do whatever your Reddit account is authorized to do. And you can switch back to read-only mode whenever you want:

# continued from code above
reddit.read_only = True

Note

If you are uncomfortable hard-coding your credentials into your program, there are some options available to you. Please see: Configuring Async PRAW.

Obtain a Subreddit

To obtain a Subreddit instance, pass the subreddit’s name when calling subreddit on your Reddit instance. For example:

# 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 ...
Obtain Submission Instances from a Subreddit

Now that you have a Subreddit instance, you can iterate through some of its submissions, each bound to an instance of Submission. There are several sorts that you can iterate through:

  • controversial

  • gilded

  • hot

  • new

  • rising

  • top

Each of these methods will immediately return a ListingGenerator, which is to be iterated through. For example, to iterate through the first 10 submissions based on the hot sort for a given subreddit try:

# assume you have a Subreddit instance bound to variable `subreddit`
async for submission in subreddit.hot(limit=10):
    print(submission.title)
    # Output: the submission's title
    print(submission.score)
    # Output: the submission's score
    print(submission.id)
    # Output: the submission's ID
    print(submission.url)
    # Output: the URL the submission points to or the submission's URL if it's a self post

Note

The act of calling a method that returns a ListingGenerator does not result in any network requests until you begin to iterate through the ListingGenerator.

You can create Submission instances in other ways too:

# 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/...")
Obtain Redditor Instances

There are several ways to obtain a redditor (a Redditor instance). Two of the most common ones are:

For example:

# 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 Comment Instances

Submissions have a comments attribute that is a CommentForest instance. That instance is iterable and represents the top-level comments of the submission by the default comment sort (confidence). If you instead want to iterate over all comments as a flattened list you can call the list() method on a CommentForest instance. For example:

# assume you have a asyncpraw.Reddit instance bound to variable `reddit`
top_level_comments = await submission.comments()
all_comments = await submission.comments.list()

Note

The comment sort order can be changed by updating the value of comment_sort on the Submission instance prior to accessing comments (see: /api/set_suggested_sort for possible values). For example, to have comments sorted by new try something like:

# assume you have a asyncpraw.Reddit instance bound to variable `reddit`
submission = await reddit.submission("39zje0")
submission.comment_sort = "new"
top_level_comments = await submission.comments()

As you may be aware there will periodically be MoreComments instances scattered throughout the forest. Replace those MoreComments instances at any time by calling replace_more() on a CommentForest instance. Calling replace_more() access comments, and so must be done after comment_sort is updated. See Extracting comments with Async PRAW for an example.

Determine Available Attributes of an Object

If you have a Async PRAW object, e.g., Comment, Message, Redditor, or Submission, and you want to see what attributes are available along with their values, use the built-in vars() function of python. For example:

import pprint

# assume you have a asyncpraw.Reddit instance bound to variable `reddit`
submission = await reddit.submission("39zje0")
pprint.pprint(vars(submission))

Installing Async PRAW

Async PRAW supports Python 3.7+. The recommended way to install Async PRAW is via pip.

pip install asyncpraw

Note

Depending on your system, you may need to use pip3 to install packages for Python 3.

Warning

Avoid using sudo to install packages. Do you really trust this package?

For instructions on installing Python and pip see “The Hitchhiker’s Guide to Python” Installation Guides.

Updating Async PRAW

Async PRAW can be updated by running:

pip install --upgrade asyncpraw

Installing Older Versions

Older versions of Async PRAW can be installed by specifying the version number as part of the installation command:

pip install asyncpraw==7.1.0

Installing the Latest Development Version

Is there a feature that was recently merged into Async PRAW that you cannot wait to take advantage of? If so, you can install Async PRAW directly from GitHub like so:

pip install --upgrade https://github.com/praw-dev/asyncpraw/archive/master.zip

You can also directly clone a copy of the repository using git, like so:

pip install --upgrade git+https://github.com/praw-dev/asyncpraw.git

Authenticating via OAuth

Async PRAW supports all three types of applications that can be registered on Reddit. Those are:

Before you can use any one of these with Async PRAW, you must first register an application of the appropriate type on Reddit.

If your application does not require a user context, it is read-only.

Async PRAW supports the flows that each of these applications can use. The following table defines which application types can use which flows:

Application Type

Script

Web

Installed

Default Flow

Password

Code

Alternative Flows

Code

Application-Only (Client Credentials)

Implicit

Application-Only (Client Credentials)

Application-Only (Installed Client)

Warning

For the sake of brevity, the following examples pass authentication information via arguments to Reddit. If you do this, you need to be careful not to reveal this information to the outside world if you share your code. It is recommended to use a praw.ini file in order to keep your authentication information separate from your code.

Password Flow

Password Flow is the simplest type of authentication flow to work with because no callback process is involved in obtaining an access_token.

While password flow applications do not involve a redirect URI, Reddit still requires that you provide one when registering your script application – http://localhost:8080 is a simple one to use.

In order to use a password flow application with Async PRAW you need four pieces of information:

client_id

The client ID is at least a 14-character string listed just under “personal use script” for the desired developed application

client_secret

The client secret is at least a 27-character string listed adjacent to secret for the application.

password

The password for the Reddit account used to register the application.

username

The username of the Reddit account used to register the application.

With this information authorizing as username using a password flow app is as simple as:

reddit = asyncpraw.Reddit(
    client_id="SI8pN3DSbt0zor",
    client_secret="xaxkj7HNh8kwg8e5t4m6KvSrbTI",
    password="1guiwevlfo00esyy",
    user_agent="testscript by u/fakebot3",
    username="fakebot3",
)

To verify that you are authenticated as the correct user run:

print(await reddit.user.me())

The output should contain the same name as you entered for username.

Note

If the following exception is raised, double-check your credentials, and ensure that that the username and password you are using are for the same user with which the application is associated:

OAuthException: invalid_grant error processing request
Two-Factor Authentication

A 2FA token can be used by joining it to the password with a colon:

reddit = asyncpraw.Reddit(
    client_id="SI8pN3DSbt0zor",
    client_secret="xaxkj7HNh8kwg8e5t4m6KvSrbTI",
    password="1guiwevlfo00esyy:955413",
    user_agent="testscript by u/fakebot3",
    username="fakebot3",
)

However, for such an app there is little benefit to using 2FA. The token must be refreshed after one hour; therefore, the 2FA secret would have to be stored along with the rest of the credentials in order to generate the token, which defeats the point of having an extra credential beyond the password.

If you do choose to use 2FA, you must handle the asyncprawcore.OAuthException that will be raised by API calls after one hour.

Code Flow

A code flow application is useful for two primary purposes:

  • You have an application and want to be able to access Reddit from your users’ accounts.

  • You have a personal-use script application and you either want to

    • limit the access one of your Async PRAW-based programs has to Reddit

    • avoid the hassle of 2FA (described above)

    • not pass your username and password to Async PRAW (and thus not keep it in memory)

When registering your application you must provide a valid redirect URI. If you are running a website you will want to enter the appropriate callback URL and configure that endpoint to complete the code flow.

If you aren’t actually running a website, you can follow the Working with Refresh Tokens tutorial to learn how to obtain and use the initial refresh token.

Whether or not you follow the Working with Refresh Tokens tutorial there are two processes involved in obtaining access or refresh tokens.

Obtain the Authorization URL

The first step to completing the code flow is to obtain the authorization URL. You can do that as follows:

reddit = asyncpraw.Reddit(
    client_id="SI8pN3DSbt0zor",
    client_secret="xaxkj7HNh8kwg8e5t4m6KvSrbTI",
    redirect_uri="http://localhost:8080",
    user_agent="testscript by u/fakebot3",
)
print(reddit.auth.url(scopes=["identity"], state="...", duration="permanent"))

The above will output an authorization URL for a permanent token (i.e., the resulting authorization will include both a short-lived access_token, and a longer-lived, single use refresh_token)that has only the identity scope. See url() for more information on these parameters.

This URL should be accessed by the account that desires to authorize their Reddit access to your application. On completion of that flow, the user’s browser will be redirected to the specified redirect_uri. After verifying the state and extracting the code you can obtain the refresh token via:

print(await reddit.auth.authorize(code))
print(await reddit.user.me())

The first line of output is the refresh_token. You can save this for later use (see Using a Saved Refresh Token).

The second line of output reveals the name of the Redditor that completed the code flow. It also indicates that the Reddit instance is now associated with that account.

The code flow can be used with an installed application just as described above with one change: set the value of client_secret to None when initializing Reddit.

Implicit Flow

The implicit flow requires a similar instantiation of the Reddit class as done in Code Flow, however, the token is returned directly as part of the redirect. For the implicit flow call url() like so:

print(reddit.auth.url(scopes=["identity"], state="...", implicit=True))

Then use implicit() to provide the authorization to the Reddit instance.

Read-Only Mode

All application types support a read-only mode. Read-only mode provides access to Reddit like a logged out user would see including the default subreddits in the reddit.front listings.

In the absence of a refresh_token both Code Flow and Implicit Flow applications start in the read-only mode. With such applications read-only mode is disabled when authorize(), or implicit() are successfully called. Password Flow applications start up with read-only mode disabled.

Read-only mode can be toggled via:

# Enable read-only mode
reddit.read_only = True

# Disable read-only mode (must have a valid authorization)
reddit.read_only = False
Application-Only Flows

The following flows are the read-only mode flows for Reddit applications

Application-Only (Client Credentials)

This is the default flow for read-only mode in script and web applications. The idea behind this is that Reddit can trust these applications as coming from a given developer, however the application requires no logged-in user context.

An installed application cannot use this flow, because Reddit requires a client_secret to be given if this flow is being used. In other words, installed applications are not considered confidential clients.

Application-Only (Installed Client)

This is the default flow for read-only mode in installed applications. The idea behind this is that Reddit might not be able to trust these applications as coming from a given developer. This would be able to happen if someone other than the developer can potentially replicate the client information and then pretend to be the application, such as in installed applications where the end user could retrieve the client_id.

Note

No benefit is really gained from this in script or web apps. The one exception is for when a script or web app has multiple end users, this will allow you to give Reddit the information needed in order to distinguish different users of your app from each other (as the supplied device ID should be a unique string per both device (in the case of a web app, server) and user (in the case of a web app, browser session).

Using a Saved Refresh Token

A saved refresh token can be used to immediately obtain an authorized instance of Reddit like so:

reddit = praw.Reddit(
    client_id="SI8pN3DSbt0zor",
    client_secret="xaxkj7HNh8kwg8e5t4m6KvSrbTI",
    refresh_token="WeheY7PwgeCZj4S3QgUcLhKE5S2s4eAYdxM",
    user_agent="testscript by u/fakebot3",
)
print(reddit.auth.scopes())

The output from the above code displays which scopes are available on the Reddit instance.

Note

Observe that redirect_uri does not need to be provided in such cases. It is only needed when url() is used.

Configuring Async PRAW

Note

Async PRAW is fully compatible with the configuration system that PRAW uses.

Configuration Options

Async PRAW’s configuration options are broken down into the following categories:

All of these options can be provided in any of the ways mentioned in Configuring Async PRAW.

Basic Configuration Options
check_for_updates

When true, check for new versions of Async PRAW. When a newer version of Async PRAW is available a message is reported via standard error (default: true).

user_agent

(Required) A unique description of your application. The following format is recommended according to Reddit’s API Rules: <platform>:<app ID>:<version string> (by u/<reddit username>).

OAuth Configuration Options
client_id

(Required) The OAuth client ID associated with your registered Reddit application. See Authenticating via OAuth for instructions on registering a Reddit application.

client_secret

The OAuth client secret associated with your registered Reddit application. This option is required for all application types, however, the value must be set to None for installed applications.

redirect_uri

The redirect URI associated with your registered Reddit application. This field is unused for script applications and is only needed for both web applications, and installed applications when the url() method is used.

password

The password of the Reddit account associated with your registered Reddit script application. This field is required for script applications, and Async PRAW assumes it is working with a script application by its presence.

username

The username of the Reddit account associated with your registered Reddit script application. This field is required for script applications, and Async PRAW assumes it is working with a script application by its presence.

Reddit Site Configuration Options

Async PRAW can be configured to work with instances of Reddit which are not hosted at reddit.com. The following options may need to be updated in order to successfully access a third-party Reddit site:

comment_kind

The type prefix for comments on the Reddit instance (default: t1_).

message_kind

The type prefix for messages on the Reddit instance (default: t4_).

oauth_url

The URL used to access the Reddit instance’s API (default: https://oauth.reddit.com).

reddit_url

The URL used to access the Reddit instance. Async PRAW assumes the endpoints for establishing OAuth authorization are accessible under this URL (default: https://www.reddit.com).

redditor_kind

The type prefix for redditors on the Reddit instance (default: t2_).

short_url

The URL used to generate short links on the Reddit instance (default: https://redd.it).

submission_kind

The type prefix for submissions on the Reddit instance (default: t3_).

subreddit_kind

The type prefix for subreddits on the Reddit instance (default: t5_).

Miscellaneous Configuration Options

These are options that do not belong in another category, but still play a part in Async PRAW.

ratelimit_seconds

Controls the maximum number of seconds Async PRAW will capture ratelimits returned in JSON data. Because this can be as high as 14 minutes, only ratelimits of up to 5 seconds are captured and waited on by default.

Note

Async PRAW sleeps for the ratelimit value plus 1 second.

See Ratelimits for more info.

timeout

Controls the amount of time Async PRAW will wait for a request from Reddit to complete before throwing an exception. By default, Async PRAW waits 16 seconds before throwing an exception.

warn_comment_sort

When true, log a warning when the comment_sort attribute of a submission is updated after _fetch() has been called (default: true).

Custom Configuration Options

Your application can utilize PRAW’s configuration system in order to provide its own custom settings. Async PRAW utilizes the the same configuration system as PRAW.

For instance you might want to add an app_debugging: true option to your application’s praw.ini file. To retrieve the value of this custom option from an instance of Reddit you can execute:

reddit.config.custom["app_debugging"]

Note

Custom Async PRAW configuration environment variables are not supported. You can directly access environment variables via os.getenv.

Configuration options can be provided to Async PRAW in one of three ways:

praw.ini Files

Async PRAW comes with a praw.ini file in the package directory, and looks for user defined praw.ini files in a few other locations:

  1. In the current working directory at the time Reddit is initialized.

  2. In the launching user’s config directory. This directory, if available, is detected in order as one of the following:

    1. In the directory specified by the XDG_CONFIG_HOME environment variable on operating systems that define such an environment variable (some modern Linux distributions).

    2. In the directory specified by $HOME/.config if the HOME environment variable is defined (Linux and Mac OS systems).

    3. In the directory specified by the APPDATA environment variable (Windows).

      Note

      To check the values of the environment variables, you can open up a terminal (Terminal/Terminal.app/Command Prompt/Powershell) and echo the variables (replacing <variable> with the name of the variable):

      MacOS/Linux:

      echo "$<variable>"
      

      Windows Command Prompt

      echo "%<variable>%"
      

      Powershell

      Write-Output "$env:<variable>"
      

      You can also view environment variables in Python:

      import os
      
      print(os.environ.get("<variable>", ""))
      
Format of praw.ini

praw.ini uses the INI file format, which can contain multiple groups of settings separated into sections. PRAW and Async PRAW refers to each section as a site. The default site, DEFAULT, is provided in the package’s praw.ini file. This site defines the default settings for interaction with Reddit. The contents of the package’s praw.ini file are:

[DEFAULT]
# A boolean to indicate whether or not to check for package updates.
check_for_updates=True

# Object to kind mappings
comment_kind=t1
message_kind=t4
redditor_kind=t2
submission_kind=t3
subreddit_kind=t5
trophy_kind=t6

# The URL prefix for OAuth-related requests.
oauth_url=https://oauth.reddit.com

# The amount of seconds of ratelimit to sleep for upon encountering a specific type of 429 error.
ratelimit_seconds=5

# The URL prefix for regular requests.
reddit_url=https://www.reddit.com

# The URL prefix for short URLs.
short_url=https://redd.it

# The timeout for requests to Reddit in number of seconds
timeout=16

Warning

Avoid modifying the package’s praw.ini file. Prefer instead to override its values in your own praw.ini file. You can even override settings of the DEFAULT site in user defined praw.ini files.

Defining Additional Sites

In addition to the DEFAULT site, additional sites can be configured in user defined praw.ini files. All sites inherit settings from the DEFAULT site and can override whichever settings desired.

Defining additional sites is a convenient way to store OAuth credentials for various accounts, or distinct OAuth applications. For example, if you have three separate bots, you might create a site for each:

[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
Choosing a Site

Site selection is done via the site_name parameter to Reddit. For example, to use the settings defined for bot2 as shown above, initialize Reddit like so:

reddit = asyncpraw.Reddit("bot2", user_agent="bot2 user agent")

Note

In the above example you can obviate passing user_agent if you add the setting user_agent=... in the [bot2] site definition.

A site can also be selected via a praw_site environment variable. This approach has precedence over the site_name parameter described above.

Using Interpolation

By default Async PRAW doesn’t apply any interpolation on the config file but this can be changed with the config_interpolation parameter which can be set to “basic” or “extended”.

This can be useful to separate the components of the user_agent into individual variables, for example:

[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)

This uses basic interpolation thus Reddit need to be initialized as follows:

reddit = asyncpraw.Reddit("bot1", config_interpolation="basic")

Then the value of reddit.config.user_agent will be "script:MyBot:v1.2.3 (by /u/MyUser)".

See Interpolation of values for details.

Warning

The configparser.ConfigParser instance is cached internally at the class level, it is shared across all instances of Reddit and once set it’s not overridden by future invocations.

Keyword Arguments to Reddit

Most of Async PRAW’s documentation will demonstrate configuring Async PRAW through the use of keyword arguments when initializing instances of Reddit. All of the Configuration Options can be specified using a keyword argument of the same name.

For example, if we wanted to explicitly pass the information for bot3 defined in the praw.ini custom site example without using the bot3 site, we would initialize Reddit as:

reddit = asyncpraw.Reddit(
    client_id="SI8pN3DSbt0zor",
    client_secret="xaxkj7HNh8kwg8e5t4m6KvSrbTI",
    password="1guiwevlfo00esyy",
    user_agent="testscript by u/fakebot3",
    username="fakebot3",
)

Async PRAW Environment Variables

The second-highest priority configuration options can be passed to a program via environment variables prefixed with praw_.

For example, you can invoke your script as follows:

praw_username=bboe praw_password=not_my_password python my_script.py

The username and password provided via environment variables will override any values contained in a praw.ini file, but not any variables passed in through Reddit.

All Configuration Options can be provided in this manner, except for custom options.

Environment variables have the highest priority, followed by keyword arguments to Reddit, and finally settings in praw.ini files.

Using an HTTP or HTTPS proxy with Async PRAW

Async PRAW internally relies upon the aiohttp package to handle HTTP requests. Aiohttp supports use of HTTP_PROXY and HTTPS_PROXY environment variables in order to proxy HTTP and HTTPS requests respectively [ref].

Given that Async PRAW exclusively communicates with Reddit via HTTPS, only the HTTPS_PROXY option should be required.

For example, if you have a script named prawbot.py, the HTTPS_PROXY environment variable can be provided on the command line like so:

HTTPS_PROXY=http://localhost:3128 ./prawbot.py

Contrary to the Requests library, aiohttp won’t read environment variables by default. But you can do so by passing trust_env=True into a custom ClientSession and configuring Async PRAW like so:

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",
)

Configuring a custom aiohttp ClientSession

Async PRAW uses aiohttp to handle networking. If your use-case requires custom configuration, it is possible to configure a ClientSession and then use it with Async PRAW.

For example, some networks use self-signed SSL certificates when connecting to HTTPS sites. By default, this would raise an exception in aiohttp. To use a self-signed SSL certificate without an exception from aiohttp, first export the certificate as a .pem file. Then configure Async PRAW like so:

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",
)

The code above creates a ClientSession and configures it to use a custom certificate, then passes it as a parameter when creating the Reddit instance. Note that the example above uses a Password Flow authentication type, but this method will work for any authentication type.

Running Multiple Instances of Async PRAW

Async PRAW performs rate limiting dynamically based on the HTTP response headers from Reddit. As a result you can safely run a handful of Async PRAW instances without any additional configuration.

Note

Running more than a dozen or so instances of Async PRAW concurrently may occasionally result in exceeding Reddit’s rate limits as each instance can only guess how many other instances are running.

If you are authorized on other users’ behalf, each authorization should have its own rate limit, even when running from a single IP address.

Multiple Programs

The recommended way to run multiple instances of Async PRAW is to simply write separate independent Python programs. With this approach one program can monitor a comment stream and reply as needed, and another program can monitor a submission stream, for example.

If these programs need to share data consider using a third-party system such as a database or queuing system.

Logging in Async PRAW

It is occasionally useful to observe the HTTP requests that Async PRAW is issuing. To do so you have to configure and enable logging.

Add the following to your code to log everything available:

import logging

handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
for logger_name in ("asyncpraw", "asyncprawcore"):
    logger = logging.getLogger(logger_name)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(handler)

When properly configured, HTTP requests that are issued should produce output similar to the following:

Fetching: GET https://oauth.reddit.com/api/v1/me
Data: None
Params: {'raw_json': 1}
Response: 200 (876 bytes)

Furthermore, any API ratelimits from POST actions that are handled will produce a log entry with a message similar to the following message:

Rate limit hit, sleeping for 5.5 seconds

For more information on logging, see logging.Logger.

Ratelimits

Even though Async PRAW respects the X-Ratelimit-* headers and waits the appropriate time between requests, there are other unknown ratelimits that Reddit has that might require additional wait time (anywhere from milliseconds to minutes) for things such as commenting, editing comments/posts, banning users, adding moderators, etc. Async PRAW will sleep and try the request again if the requested wait time (as much as 600 seconds) is less than or equal to Async PRAW’s ratelimit_seconds configuration setting (default: 5s), Async PRAW will wait for the requested time plus 1 second. If the requested wait time exceeds the set value of ratelimit_seconds, Async PRAW will raise RedditAPIException.

For example, given the following Reddit instance:

import asyncpraw

reddit = asyncpraw.Reddit(..., ratelimit_seconds=300)

Let’s say your bot posts a comment to Reddit every 30 seconds and Reddit returns the ratelimit error: "You're doing that too much. Try again in 3 minutes.". Async PRAW will wait for 181 seconds since 181 seconds is less than the configured ratelimit_seconds of 300 seconds. However, if Reddit returns the ratelimit error: "You're doing that too much. Try again in 6 minutes.", Async PRAW will raise an exception since 360 seconds is greater than the configured ratelimit_seconds of 300 seconds.

Frequently Asked Questions

Q: How can I refresh a comment/subreddit/submission?

A: There is two ways to do this:

  • Directly calling the constructors will refresh the value:

    await reddit.comment(comment.id)
    await reddit.subreddit(subreddit.display_name)
    await reddit.submission(submission.id)
    
  • Calling load():

    await comment.load()
    await subreddit.load()
    await submission.load()
    

Q: Whenever I try to do anything, I get an invalid_grant error. What is the cause?

A: This means that either you provided the wrong password and/or the account you are trying to sign in with has 2FA enabled, and as such, either needs a 2FA token or a refresh token to sign in. A refresh token is preferred, because then you will not need to enter a 2FA token in order to sign in, and the session will last for longer than an hour. Refer to Two-Factor Authentication and Working with Refresh Tokens in order to use the respective auth methods.

Q: Some options (like getting moderator logs from r/mod) keep on timing out. How can I extend the timeout?

A: Set the timeout config option or initialize Reddit with a timeout of your choosing. Another option is to construct a Subreddit instance with a subset of subreddits (concatenated with +) that you want logs from like so:

await reddit.subreddit("pics+LifeProTips")

Q: Help, I keep on getting redirected to /r/subreddit/login/!

Q2: I keep on getting this exception:

asyncprawcore.exceptions.Redirect: Redirect to /r/subreddit/login/ (You may be trying to perform a non-read-only action via a read-only instance.)

A: Async PRAW is most likely in read-only mode. This normally occurs when Async PRAW is authenticated without a username and password or a refresh token. In order to perform this action, the Reddit instance needs to be authenticated. See OAuth Configuration Options to see the available authentication methods.

Q: Help, searching for URLs keeps on redirecting me to /submit!

Q2: I keep on getting this exception: asyncprawcore.exceptions.Redirect: Redirect to /submit

A: Reddit redirects URL searches to the submit page of the URL. To search for the URL, prefix url: to the url and surround the url in quotation marks.

For example, the code block:

subreddit = await reddit.subreddit("all")
async for result in subreddit.search("https://google.com"):
    # do things with results
    ...

Will become this code block:

subreddit = await reddit.subreddit("all")
async for result in subreddit.search('url:"https://google.com"'):
    # do things with results
    ...

The Reddit Instance

class asyncpraw.Reddit(site_name: Optional[str] = None, *, config_interpolation: Optional[str] = None, requestor_class: Optional[Type[Requestor]] = None, requestor_kwargs: Optional[Dict[str, Any]] = None, token_manager: Optional[BaseTokenManager] = None, **config_settings: Optional[Union[str, bool, int]])

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: Optional[str] = None, *, config_interpolation: Optional[str] = None, requestor_class: Optional[Type[Requestor]] = None, requestor_kwargs: Optional[Dict[str, Any]] = None, token_manager: Optional[BaseTokenManager] = None, **config_settings: Optional[Union[str, bool, int]])

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 configured praw.ini, file is useful if you wish to easily save credentials for different applications, or communicate with other servers running Reddit. If site_name is None, then the site name will be looked for in the environment variable praw_site. If it is not found there, the DEFAULT 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 the Reddit instance. For more details, please see Configuring Async PRAW.

Required settings are:

  • client_id

  • client_secret (for installed applications set this value to None)

  • user_agent

The requestor_class and requestor_kwargs allow for customization of the requestor Reddit will use. This allows, e.g., easily adding behavior to the requestor or wrapping its ClientSession 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.

await close()

Close the requestor.

await comment(id: Optional[str] = None, *, fetch: bool = True, url: Optional[str] = None, **kwargs)

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")

Note

If call this with fetch=False and you need to obtain the comment’s replies, you will need to call this without fetch=False or call refresh() on the returned Comment.

await delete(path: str, *, data: Optional[Union[Dict[str, Union[str, Any]], bytes, IO, str]] = None, json: Optional[Dict[Any, Any]] = None, params: Optional[Union[str, Dict[str, str]]] = 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). If json is provided, data should not be.

  • params – The query parameters to add to the request (default: None).

domain(domain: str)

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: Optional[Union[str, Dict[str, Union[str, int]]]] = None)

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, and Submission instances. For example, to iterate through comments which mention the authorized user run:

async for comment in reddit.inbox.mentions():
    print(comment)
info(*, fullnames: Optional[Iterable[str]] = None, subreddits: Optional[Iterable[Union[asyncpraw.models.Subreddit, str]]] = None, url: Optional[str] = None) AsyncGenerator[Union[asyncpraw.models.Subreddit, asyncpraw.models.Comment, asyncpraw.models.Submission], None]

Fetch information about each item in fullnames, url, or subreddits.

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 yielded Comment.

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 a Multireddit 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 ModNotes 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: Optional[Union[Dict[str, Union[str, Any]], bytes, IO, str]] = None, json: Optional[Dict[Any, Any]] = 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). If json is provided, data should not be.

await post(path: str, *, data: Optional[Union[Dict[str, Union[str, Any]], bytes, IO, str]] = None, files: Optional[Dict[str, IO]] = None, json: Optional[Dict[Any, Any]] = None, params: Optional[Union[str, Dict[str, str]]] = 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). If json is provided, data should not be.

  • params – The query parameters to add to the request (default: None).

await put(path: str, *, data: Optional[Union[Dict[str, Union[str, Any]], bytes, IO, str]] = None, json: Optional[Dict[Any, Any]] = None)

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). If json 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).

property read_only: bool

Return True when using the ReadOnlyAuthorizer.

await redditor(name: Optional[str] = None, *, fetch: bool = False, fullname: Optional[str] = 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 or fullname 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: Optional[Union[Dict[str, Union[str, Any]], bytes, IO, str]] = None, files: Optional[Dict[str, IO]] = None, json: Optional[Dict[Any, Any]] = None, method: str, params: Optional[Union[str, Dict[str, Union[str, int]]]] = 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). If json 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: Optional[str] = None, *, fetch: bool = True, url: Optional[str] = None, **kwargs) 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 or url 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 a Subreddit 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 to False, the behavior is deprecated by Reddit. This attribute will be removed around May-June 2020.

reddit.live

class asyncpraw.models.DraftHelper(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Provide a set of functions to interact with Draft instances.

Note

The methods provided by this class will only work on the currently authenticated user’s Drafts.

await __call__(draft_id: Optional[str] = None, fetch: bool = True) Union[List[asyncpraw.models.Draft], asyncpraw.models.Draft]

Return a list of Draft instances.

Parameters
  • draft_id – When provided, this returns a Draft instance (default: None).

  • fetch – Determines if Async PRAW will fetch the object (default: True).

Returns

A Draft instance if draft_id is provided. Otherwise, a list of Draft objects.

This method can be used to fetch a specific draft by ID, like so:

draft_id = "124862bc-e1e9-11eb-aa4f-e68667a77cbb"
draft = await reddit.drafts(draft_id)
print(draft)
__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

await create(*, flair_id: Optional[str] = None, flair_text: Optional[str] = None, is_public_link: bool = False, nsfw: bool = False, original_content: bool = False, selftext: Optional[str] = None, send_replies: bool = True, spoiler: bool = False, subreddit: Optional[Union[str, asyncpraw.models.Subreddit, asyncpraw.models.UserSubreddit]] = None, title: Optional[str] = None, url: Optional[str] = None, **draft_kwargs) asyncpraw.models.Draft

Create a new Draft.

Parameters
  • flair_id – The flair template to select (default: None).

  • flair_text – If the template’s flair_text_editable value is True, this value will set a custom text (default: None). flair_id is required when flair_text is provided.

  • is_public_link – Whether to enable public viewing of the draft before it is submitted (default: False).

  • nsfw – Whether the draft should be marked NSFW (default: False).

  • original_content – Whether the submission should be marked as original content (default: False).

  • selftext – The Markdown formatted content for a text submission draft. Use None to make a title-only submission draft (default: None). selftext can not be provided if url is provided.

  • send_replies – When True, messages will be sent to the submission author when comments are made to the submission (default: True).

  • spoiler – Whether the submission should be marked as a spoiler (default: False).

  • subreddit – The subreddit to create the draft for. This accepts a subreddit display name, Subreddit object, or UserSubreddit object. If None, the UserSubreddit of currently authenticated user will be used (default: None).

  • title – The title of the draft (default: None).

  • url – The URL for a link submission draft (default: None). url can not be provided if selftext is provided.

Additional keyword arguments can be provided to handle new parameters as Reddit introduces them.

Returns

The new Draft object.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

reddit.front

class asyncpraw.models.Front(reddit: asyncpraw.Reddit)

Front is a Listing class that represents the front page.

__init__(reddit: asyncpraw.Reddit)

Initialize a Front instance.

best(**generator_kwargs: Union[str, int]) AsyncIterator[asyncpraw.models.Submission]

Return a ListingGenerator for best items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

comments() CommentHelper

Provide an instance of CommentHelper.

For example, to output the author of the 25 most recent comments of r/test execute:

subreddit = await reddit.subreddit("test")
async for comment in subreddit.comments(limit=25):
    print(comment.author)
controversial(*, time_filter: str = 'all', **generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for controversial items.

Parameters

time_filter – Can be one of: "all", "day", "hour", "month", "week", or "year" (default: "all").

Raises

ValueError if time_filter is invalid.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").controversial(time_filter="week")

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.controversial(time_filter="day")

redditor = await reddit.redditor("spez")
redditor.controversial(time_filter="month")

redditor = await reddit.redditor("spez")
redditor.comments.controversial(time_filter="year")

redditor = await reddit.redditor("spez")
redditor.submissions.controversial(time_filter="all")

subreddit = await reddit.subreddit("all")
subreddit.controversial(time_filter="hour")
gilded(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for gilded items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get gilded items in r/test:

subreddit = await reddit.subreddit("test")
async for item in subreddit.gilded():
    print(item.id)
hot(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for hot items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").hot()

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.hot()

redditor = await reddit.redditor("spez")
redditor.hot()

redditor = await reddit.redditor("spez")
redditor.comments.hot()

redditor = await reddit.redditor("spez")
redditor.submissions.hot()

subreddit = await reddit.subreddit("all")
subreddit.hot()
new(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for new items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").new()

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.new()

redditor = await reddit.redditor("spez")
redditor.new()

redditor = await reddit.redditor("spez")
redditor.comments.new()

redditor = await reddit.redditor("spez")
redditor.submissions.new()

subreddit = await reddit.subreddit("all")
subreddit.new()
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

random_rising(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Submission]

Return a ListingGenerator for random rising submissions.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get random rising submissions for r/test:

subreddit = await reddit.subreddit("test")
async for submission in subreddit.random_rising():
    print(submission.title)
rising(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Submission]

Return a ListingGenerator for rising submissions.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get rising submissions for r/test:

subreddit = await reddit.subreddit("test")
async for submission in subreddit.rising():
    print(submission.title)
top(*, time_filter: str = 'all', **generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for top items.

Parameters

time_filter – Can be one of: "all", "day", "hour", "month", "week", or "year "``(default: ``"all").

Raises

ValueError if time_filter is invalid.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").top(time_filter="week")

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.top(time_filter="day")

redditor = await reddit.redditor("spez")
redditor.top(time_filter="month")

redditor = await reddit.redditor("spez")
redditor.comments.top(time_filter="year")

redditor = await reddit.redditor("spez")
redditor.submissions.top(time_filter="all")

subreddit = await reddit.subreddit("all")
subreddit.top(time_filter="hour")

reddit.inbox

class asyncpraw.models.Inbox(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Inbox is a Listing class that represents the inbox.

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

all(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Union[asyncpraw.models.Message, asyncpraw.models.Comment]]

Return a ListingGenerator for all inbox comments and messages.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To output the type and ID of all items available via this listing do:

async for item in reddit.inbox.all(limit=None):
    print(repr(item))
await collapse(items: List[asyncpraw.models.Message])

Mark an inbox message as collapsed.

Parameters

items – A list containing instances of Message.

Requests are batched at 25 items (reddit limit).

For example, to collapse all unread Messages, try:

from asyncpraw.models import Message

unread_messages = []
async for item in reddit.inbox.unread(limit=None):
    if isinstance(item, Message):
        unread_messages.append(item)
await reddit.inbox.collapse(unread_messages)
comment_replies(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Comment]

Return a ListingGenerator for comment replies.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To output the author of one request worth of comment replies try:

async for reply in reddit.inbox.comment_replies():
    print(reply.author)
await mark_all_read()

Mark all messages as read with just one API call.

Example usage:

await reddit.inbox.mark_all_read()

Note

This method returns after Reddit acknowledges your request, instead of after the request has been fulfilled.

await mark_read(items: List[Union[asyncpraw.models.Comment, asyncpraw.models.Message]])

Mark Comments or Messages as read.

Parameters

items – A list containing instances of Comment and/or Message to be marked as read relative to the authorized user’s inbox.

Requests are batched at 25 items (reddit limit).

For example, to mark all unread Messages as read, try:

from asyncpraw.models import Message

unread_messages = []
async for item in reddit.inbox.unread(limit=None):
    if isinstance(item, Message):
        unread_messages.append(item)
await reddit.inbox.mark_read(unread_messages)
await mark_unread(items: List[Union[asyncpraw.models.Comment, asyncpraw.models.Message]])

Unmark Comments or Messages as read.

Parameters

items – A list containing instances of Comment and/or Message to be marked as unread relative to the authorized user’s inbox.

Requests are batched at 25 items (Reddit limit).

For example, to mark the first 10 items as unread try:

to_unread = [msg async for msg in reddit.inbox.all(limit=10)]
await reddit.inbox.mark_unread(to_unread)
mentions(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Comment]

Return a ListingGenerator for mentions.

A mention is Comment in which the authorized redditor is named in its body like u/spez.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to output the author and body of the first 25 mentions try:

async for mention in reddit.inbox.mentions(limit=25):
    print(f"{mention.author}\\n{mention.body}\\n")
await message(message_id: str) asyncpraw.models.Message

Return a Message corresponding to message_id.

Parameters

message_id – The base36 ID of a message.

For example:

message = await reddit.inbox.message("7bnlgu")
messages(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Message]

Return a ListingGenerator for inbox messages.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to output the subject of the most recent 5 messages try:

async for message in reddit.inbox.messages(limit=5):
    print(message.subject)
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

sent(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Message]

Return a ListingGenerator for sent messages.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to output the recipient of the most recent 15 messages try:

async for message in reddit.inbox.sent(limit=15):
    print(message.dest)
stream(**stream_options: Union[str, int, Dict[str, str]]) AsyncIterator[Union[asyncpraw.models.Message, asyncpraw.models.Comment]]

Yield new inbox items as they become available.

Items are yielded oldest first. Up to 100 historical items will initially be returned.

Keyword arguments are passed to stream_generator().

For example, to retrieve all new inbox items, try:

async for item in reddit.inbox.stream():
    print(item)
submission_replies(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Comment]

Return a ListingGenerator for submission replies.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To output the author of one request worth of submission replies try:

async for reply in reddit.inbox.submission_replies():
    print(reply.author)
await uncollapse(items: List[asyncpraw.models.Message])

Mark an inbox message as uncollapsed.

Parameters

items – A list containing instances of Message.

Requests are batched at 25 items (reddit limit).

For example, to uncollapse all unread Messages, try:

from asyncpraw.models import Message

unread_messages = []
async for item in reddit.inbox.unread(limit=None):
    if isinstance(item, Message):
        unread_messages.append(item)
await reddit.inbox.uncollapse(unread_messages)
unread(*, mark_read: bool = False, **generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Union[asyncpraw.models.Message, asyncpraw.models.Comment]]

Return a ListingGenerator for unread comments and messages.

Parameters

mark_read – Marks the inbox as read (default: False).

Note

This only marks the inbox as read not the messages. Use Inbox.mark_read() to mark the messages.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to output the author of unread comments try:

from asyncpraw.models import Comment

async for item in reddit.inbox.unread(limit=None):
    if isinstance(item, Comment):
        print(item.author)

reddit.live

class asyncpraw.models.LiveHelper(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Provide a set of functions to interact with LiveThreads.

await __call__(id: str, fetch: bool = False) asyncpraw.models.LiveThread

Return a new instance of LiveThread.

This method is intended to be used as:

livethread = await reddit.live("ukaeu1ik4sw5")

If you need the object fetched right away (e.g., to access attributes) you can do:

livethread = await reddit.live("ukaeu1ik4sw5", fetch=True)
await livethread.close()
Parameters
  • id – A live thread ID, e.g., ukaeu1ik4sw5.

  • fetch – Determines if Async PRAW will fetch the object (default: False).

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

await create(title: str, *, description: Optional[str] = None, nsfw: bool = False, resources: str = None) asyncpraw.models.LiveThread

Create a new LiveThread.

Parameters
  • title – The title of the new LiveThread.

  • description – The new LiveThread’s description.

  • nsfw – Indicate whether this thread is not safe for work (default: False).

  • resources – Markdown formatted information that is useful for the LiveThread.

Returns

The new LiveThread object.

info(ids: List[str]) AsyncGenerator[asyncpraw.models.LiveThread, None]

Fetch information about each live thread in ids.

Parameters

ids – A list of IDs for a live thread.

Returns

A generator that yields LiveThread instances.

Raises

asyncprawcore.ServerError if invalid live threads are requested.

Requests will be issued in batches for each 100 IDs.

Note

This method doesn’t support IDs for live updates.

Warning

Unlike Reddit.info(), the output of this method may not reflect the order of input.

Usage:

ids = ["3rgnbke2rai6hen7ciytwcxadi", "sw7bubeycai6hey4ciytwamw3a", "t8jnufucss07"]
async for thread in reddit.live.info(ids):
    print(thread.title)
await now() Optional[asyncpraw.models.LiveThread]

Get the currently featured live thread.

Returns

The LiveThread object, or None if there is no currently featured live thread.

Usage:

thread = await reddit.live.now()  # LiveThread object or None
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

reddit.multireddit

class asyncpraw.models.MultiredditHelper(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Provide a set of functions to interact with multireddits.

await __call__(*, name: str, redditor: Union[str, asyncpraw.models.Redditor], fetch: bool = False) asyncpraw.models.Multireddit

Return a lazy instance of Multireddit.

If you need the object fetched right away (e.g., to access an attribute) you can do:

multireddit = await reddit.multireddit(redditor="redditor", name="multi", fetch=True)
async for comment in multireddit.comments(limit=25):
    print(comment.author)
Parameters
  • name – The name of the multireddit.

  • redditor – A redditor name or Redditor instance who owns the multireddit.

  • name – The name of the multireddit.

  • fetch – Determines if Async PRAW will fetch the object (default: False).

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

await create(*, description_md: Optional[str] = None, display_name: str, icon_name: Optional[str] = None, key_color: Optional[str] = None, subreddits: Union[str, asyncpraw.models.Subreddit], visibility: str = 'private', weighting_scheme: str = 'classic') asyncpraw.models.Multireddit

Create a new Multireddit.

Parameters
  • display_name – The display name for the new multireddit.

  • subreddits – Subreddits to add to the new multireddit. Can be a list of either Subreddit instances or subreddit display names.

  • description_md – Description for the new multireddit, formatted in markdown.

  • icon_name – Can be one of: "art and design", "ask", "books", "business", "cars", "comics", "cute animals", "diy", "entertainment", "food and drink", "funny", "games", "grooming", "health", "life advice", "military", "models pinup", "music", "news", "philosophy", "pictures and gifs", "science", "shopping", "sports", "style", "tech", "travel", "unusual stories", "video", or None.

  • key_color – RGB hex color code of the form "#FFFFFF".

  • visibility – Can be one of: "hidden", "private", or "public" (default: "private").

  • weighting_scheme – Can be one of: "classic" or "fresh" (default: "classic").

Returns

The new Multireddit object.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

reddit.redditors

class asyncpraw.models.Redditors(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Redditors is a Listing class that provides various Redditor lists.

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

new(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Subreddit]

Return a ListingGenerator for new Redditors.

Returns

Redditor profiles, which are a type of Subreddit.

Additional keyword arguments are passed in the initialization of ListingGenerator.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

async for ... in partial_redditors(ids: Iterable[str]) AsyncIterator[PartialRedditor]

Get user summary data by redditor IDs.

Parameters

ids – An iterable of redditor fullname IDs.

Returns

A iterator producing PartialRedditor objects.

Each ID must be prefixed with t2_.

Invalid IDs are ignored by the server.

popular(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Subreddit]

Return a ListingGenerator for popular Redditors.

Returns

Redditor profiles, which are a type of Subreddit.

Additional keyword arguments are passed in the initialization of ListingGenerator.

search(query: str, **generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Subreddit]

Return a ListingGenerator of Redditors for query.

Parameters

query – The query string to filter Redditors by.

Returns

Redditors.

Additional keyword arguments are passed in the initialization of ListingGenerator.

stream(**stream_options: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Subreddit]

Yield new Redditors as they are created.

Redditors are yielded oldest first. Up to 100 historical Redditors will initially be returned.

Keyword arguments are passed to stream_generator().

Returns

Redditor profiles, which are a type of Subreddit.

reddit.subreddit

class asyncpraw.models.SubredditHelper(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Provide a set of functions to interact with Subreddits.

await __call__(display_name: str, fetch: bool = False) asyncpraw.models.Subreddit

Return an instance of Subreddit.

Parameters
  • display_name – The name of the subreddit.

  • fetch – Determines if Async PRAW will fetch the object (default: False).

If you need the object fetched right away (e.g., to access an attribute) you can do:

subreddit = await reddit.subreddit("test", fetch=True)
print(subreddit.subscribers)
__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

await create(name: str, *, link_type: str = 'any', subreddit_type: str = 'public', title: Optional[str] = None, wikimode: str = 'disabled', **other_settings: Optional[str]) asyncpraw.models.Subreddit

Create a new Subreddit.

Parameters
  • name – The name for the new subreddit.

  • link_type – The types of submissions users can make. One of "any", "link", or "self" (default: "any").

  • subreddit_type – One of "archived", "employees_only", "gold_only", "gold_restricted", "private", "public", or "restricted" (default: "public").

  • title – The title of the subreddit. When None or "" use the value of name.

  • wikimode – One of "anyone", "disabled", or "modonly" (default: "disabled").

Any keyword parameters not provided, or set explicitly to None, will take on a default value assigned by the Reddit server.

See also

update() for documentation of other available settings.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

reddit.subreddits

class asyncpraw.models.Subreddits(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Subreddits is a Listing class that provides various subreddit lists.

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

default(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Subreddit]

Return a ListingGenerator for default subreddits.

Additional keyword arguments are passed in the initialization of ListingGenerator.

gold(**generator_kwargs) AsyncIterator[asyncpraw.models.Subreddit]

Alias for premium() to maintain backwards compatibility.

new(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Subreddit]

Return a ListingGenerator for new subreddits.

Additional keyword arguments are passed in the initialization of ListingGenerator.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

popular(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Subreddit]

Return a ListingGenerator for popular subreddits.

Additional keyword arguments are passed in the initialization of ListingGenerator.

premium(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Subreddit]

Return a ListingGenerator for premium subreddits.

Additional keyword arguments are passed in the initialization of ListingGenerator.

await recommended(subreddits: List[Union[str, asyncpraw.models.Subreddit]], omit_subreddits: Optional[List[Union[str, asyncpraw.models.Subreddit]]] = None) List[asyncpraw.models.Subreddit]

Return subreddits recommended for the given list of subreddits.

Parameters
  • subreddits – A list of Subreddit instances and/or subreddit names.

  • omit_subreddits – A list of Subreddit instances and/or subreddit names to exclude from the results (Reddit’s end may not work as expected).

search(query: str, **generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Subreddit]

Return a ListingGenerator of subreddits matching query.

Subreddits are searched by both their title and description.

Parameters

query – The query string to filter subreddits by.

Additional keyword arguments are passed in the initialization of ListingGenerator.

See also

search_by_name() to search by subreddit names

async for ... in search_by_name(query: str, *, include_nsfw: bool = True, exact: bool = False) List[asyncpraw.models.Subreddit]

Return list of Subreddits whose names begin with query.

Parameters
  • query – Search for subreddits beginning with this string.

  • exact – Return only exact matches to query (default: False).

  • include_nsfw – Include subreddits labeled NSFW (default: True).

async for ... in search_by_topic(query: str) AsyncIterator[asyncpraw.models.Subreddit]

Return list of Subreddits whose topics match query.

Parameters

query – Search for subreddits relevant to the search topic.

Note

As of 09/01/2020, this endpoint always returns 404.

stream(**stream_options: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Subreddit]

Yield new subreddits as they are created.

Subreddits are yielded oldest first. Up to 100 historical subreddits will initially be returned.

Keyword arguments are passed to stream_generator().

reddit.user

class asyncpraw.models.User(reddit: asyncpraw.Reddit)

The User class provides methods for the currently authenticated user.

__init__(reddit: asyncpraw.Reddit)

Initialize an User instance.

This class is intended to be interfaced with through reddit.user.

await blocked() List[asyncpraw.models.Redditor]

Return a RedditorList of blocked Redditors.

contributor_subreddits(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Subreddit]

Return a ListingGenerator of contributor Subreddits.

These are subreddits in which the user is an approved user.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To print a list of the subreddits that you are an approved user in, try:

async for subreddit in reddit.user.contributor_subreddits(limit=None):
    print(str(subreddit))
await friends(*, user: Optional[Union[asyncpraw.models.Redditor, str]] = None) Union[List[asyncpraw.models.Redditor], asyncpraw.models.Redditor]

Return a RedditorList of friends or a Redditor in the friends list.

Parameters

user – Checks to see if you are friends with the redditor. Either an instance of Redditor or a string can be given.

Returns

A list of Redditors, or a single Redditor if user is specified. The Redditor instance(s) returned also has friend attributes.

Raises

An instance of asyncprawcore.exceptions.BadRequest if you are not friends with the specified Redditor.

await karma() Dict[asyncpraw.models.Subreddit, Dict[str, int]]

Return a dictionary mapping Subreddits to their karma.

The returned dict contains subreddits as keys. Each subreddit key contains a sub-dict that have keys for comment_karma and link_karma. The dict is sorted in descending karma order.

Note

Each key of the main dict is an instance of Subreddit. It is recommended to iterate over the dict in order to retrieve the values, preferably through dict.items().

await me(*, use_cache: bool = True) Optional[asyncpraw.models.Redditor]

Return a Redditor instance for the authenticated user.

Parameters

use_cache – When True, and if this function has been previously called, returned the cached version (default: True).

Note

If you change the Reddit instance’s authorization, you might want to refresh the cached value. Prefer using separate Reddit instances, however, for distinct authorizations.

Deprecated since version 7.2: In read_only mode this method returns None. In Async PRAW 8 this method will raise ReadOnlyException when called in read_only mode. To operate in Async PRAW 8 mode, set the config variable praw8_raise_exception_on_me to True.

moderator_subreddits(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Subreddit]

Return a ListingGenerator subreddits that the user moderates.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To print a list of the names of the subreddits you moderate, try:

async for subreddit in reddit.user.moderator_subreddits(limit=None):
    print(str(subreddit))
await multireddits() List[asyncpraw.models.Multireddit]

Return a list of Multireddits belonging to the user.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

await pin(submission: asyncpraw.models.Submission, *, num: int = None, state: bool = True)

Set the pin state of a submission on the authenticated user’s profile.

Parameters
  • submission – An instance of Submission that will be pinned/unpinned.

  • num

    If specified, the slot in which the submission will be pinned into. If there is a submission already in the specified slot, it will be replaced. If None or there is not a submission in the specified slot, the first available slot will be used (default: None). If all slots are used the following will occur:

    • Old Reddit:

      1. The submission in the last slot will be unpinned.

      2. The remaining pinned submissions will be shifted down a slot.

      3. The new submission will be pinned in the first slot.

    • New Reddit:

      1. The submission in the first slot will be unpinned.

      2. The remaining pinned submissions will be shifted up a slot.

      3. The new submission will be pinned in the last slot.

    Note

    At the time of writing (10/22/2021), there are 4 pin slots available and pins are in reverse order on old Reddit. If num is an invalid value, Reddit will ignore it and the same behavior will occur as if num is None.

  • stateTrue pins the submission, False unpins (default: True).

Raises

asyncprawcore.BadRequest when pinning a removed or deleted submission.

Raises

asyncprawcore.Forbidden when pinning a submission the authenticated user is not the author of.

me = await reddit.user.me()
async for submission in me.submissions.new():
    await reddit.user.pin(submission)
    break
preferences() asyncpraw.models.Preferences

Get an instance of Preferences.

The preferences can be accessed as a dict like so:

preferences = await reddit.user.preferences()
print(preferences["show_link_flair"])

Preferences can be updated via:

await reddit.user.preferences.update(show_link_flair=True)

The Preferences.update() method returns the new state of the preferences as a dict, which can be used to check whether a change went through. Changes with invalid types or parameter names fail silently.

original_preferences = await reddit.user.preferences()
new_prefs = await original_preferences.update(invalid_param=123)
print(original_preferences == new_prefs)  # True, no change
subreddits(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Subreddit]

Return a ListingGenerator of Subreddits the user is subscribed to.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To print a list of the subreddits that you are subscribed to, try:

async for subreddit in reddit.user.subreddits(limit=None):
    print(str(subreddit))
await trusted() List[asyncpraw.models.Redditor]

Return a RedditorList of trusted Redditors.

To display the usernames of your trusted users and the times at which you decided to trust them, try:

trusted_users = await reddit.user.trusted()
for user in trusted_users:
    print(f"User: {user.name}, time: {user.date}")

Working with Async PRAW’s Models

Comment

class asyncpraw.models.Comment(reddit: asyncpraw.Reddit, id: Optional[str] = None, url: Optional[str] = None, _data: Optional[Dict[str, Any]] = None)

A class that represents a Reddit comment.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

author

Provides an instance of Redditor.

body

The body of the comment, as Markdown.

body_html

The body of the comment, as HTML.

created_utc

Time the comment was created, represented in Unix Time.

distinguished

Whether or not the comment is distinguished.

edited

Whether or not the comment has been edited.

id

The ID of the comment.

is_submitter

Whether or not the comment author is also the author of the submission.

link_id

The submission ID that the comment belongs to.

parent_id

The ID of the parent comment (prefixed with t1_). If it is a top-level comment, this returns the submission ID instead (prefixed with t3_).

permalink

A permalink for the comment. Comment objects from the inbox have a context attribute instead.

replies

Provides an instance of CommentForest.

saved

Whether or not the comment is saved.

score

The number of upvotes for the comment.

stickied

Whether or not the comment is stickied.

submission

Provides an instance of Submission. The submission that the comment belongs to.

subreddit

Provides an instance of Subreddit. The subreddit that the comment belongs to.

subreddit_id

The subreddit ID that the comment belongs to.

__init__(reddit: asyncpraw.Reddit, id: Optional[str] = None, url: Optional[str] = None, _data: Optional[Dict[str, Any]] = None)

Initialize a Comment instance.

await award(*, gild_type: str = 'gid_2', is_anonymous: bool = True, message: str = None) dict

Award the author of the item.

Parameters
  • gild_type – Type of award to give. See table below for currently know global award types.

  • is_anonymous – If True, the authenticated user’s username will not be revealed to the recipient.

  • message – Message to include with the award.

Returns

A dict containing info similar to what is shown below:

{
    "subreddit_balance": 85260,
    "treatment_tags": [],
    "coins": 8760,
    "gildings": {"gid_1": 0, "gid_2": 1, "gid_3": 0},
    "awarder_karma_received": 4,
    "all_awardings": [
        {
            "giver_coin_reward": 0,
            "subreddit_id": None,
            "is_new": False,
            "days_of_drip_extension": 0,
            "coin_price": 75,
            "id": "award_9663243a-e77f-44cf-abc6-850ead2cd18d",
            "penny_donate": 0,
            "coin_reward": 0,
            "icon_url": "https://www.redditstatic.com/gold/awards/icon/SnooClappingPremium_512.png",
            "days_of_premium": 0,
            "icon_height": 512,
            "tiers_by_required_awardings": None,
            "icon_width": 512,
            "static_icon_width": 512,
            "start_date": None,
            "is_enabled": True,
            "awardings_required_to_grant_benefits": None,
            "description": "For an especially amazing showing.",
            "end_date": None,
            "subreddit_coin_reward": 0,
            "count": 1,
            "static_icon_height": 512,
            "name": "Bravo Grande!",
            "icon_format": "APNG",
            "award_sub_type": "PREMIUM",
            "penny_price": 0,
            "award_type": "global",
            "static_icon_url": "https://i.redd.it/award_images/t5_q0gj4/59e02tmkl4451_BravoGrande-Static.png",
        }
    ],
}

Warning

Requires the authenticated user to own Reddit Coins. Calling this method will consume Reddit Coins.

To award the gold award anonymously do:

comment = await reddit.comment("dkk4qjd")
await comment.award()

submission = await reddit.submission("8dmv8z")
await submission.award()

To award the platinum award with the message ‘Nice!’ and reveal your username to the recipient do:

comment = await reddit.comment("dkk4qjd")
await comment.award(gild_type="gild_3", message="Nice!", is_anonymous=False)

submission = await reddit.submission("8dmv8z")
await submission.award(gild_type="gild_3", message="Nice!", is_anonymous=False)

This is a list of known global awards (as of 10/25/2020)

Name

Icon

Gild Type

Description

Cost

Silver

https://www.redditstatic.com/gold/awards/icon/silver_64.png

gid_1

Shows the Silver Award… and that’s it.

100

Gold

https://www.redditstatic.com/gold/awards/icon/gold_64.png

gid_2

Gives the author a week of Reddit Premium, %{coin_symbol}100 Coins to do with as they please, and shows a Gold Award.

500

Platinum

https://www.redditstatic.com/gold/awards/icon/platinum_64.png

gid_3

Gives the author a month of Reddit Premium, which includes %{coin_symbol}700 Coins for that month, and shows a Platinum Award.

1800

LOVE!

https://preview.redd.it/award_images/t5_22cerq/j3azv69qjfn51_LOVE.png?width=64&height=64&crop=smart&auto=webp&s=405d338bf34818596ab84bc26a09316917def8bb

award_5eac457f-ebac-449b-93a7-eb17b557f03c

When you follow your heart, love is the answer

20

Starstruck

https://www.redditstatic.com/gold/awards/icon/Starstruck_64.png

award_abb865cf-620b-4219-8777-3658cf9091fb

Can’t stop seeing stars

20

All-Seeing Upvote

https://preview.redd.it/award_images/t5_22cerq/rg960rc47jj41_All-SeeingUpvote.png?width=64&height=64&crop=smart&auto=webp&s=46a9f176646afded7050299a1fbad5c66e6ed1e6

award_b4ff447e-05a5-42dc-9002-63568807cfe6

A glowing commendation for all to see

30

Narwhal Salute

https://preview.redd.it/award_images/t5_22cerq/80j20o397jj41_NarwhalSalute.png?width=64&height=64&crop=smart&auto=webp&s=8629e84ef3188ad75ebca713afb4a0f97e4c3c70

award_a2506925-fc82-4d6c-ae3b-b7217e09d7f0

A golden splash of respect

30

Wholesome Seal of Approval

https://preview.redd.it/award_images/t5_22cerq/b9ks3a5k7jj41_WholesomeSealofApproval.png?width=64&height=64&crop=smart&auto=webp&s=2bcedd41a51b17ff305fc0ec6eb7c5a631a90c60

award_c4b2e438-16bb-4568-88e7-7893b7662944

A glittering stamp for a feel-good thing

30

Ally

https://preview.redd.it/award_images/t5_22cerq/5nswjpyy44551_Ally.png?width=64&height=64&crop=smart&auto=webp&s=655fb8310589a3964a82ac0e56d016eb97aa6d4d

award_69c94eb4-d6a3-48e7-9cf2-0f39fed8b87c

Listen, get educated, and get involved.

50

I am disappoint

https://preview.redd.it/award_images/t5_22cerq/3ekkailk5s551_Iamdisappoint.png?width=64&height=64&crop=smart&auto=webp&s=3aa59d2aa096aba2d6cba9709f79b788676e3731

award_03c4f93d-efc7-463b-98a7-c01814462ab0

I’m not mad, I’m just disappointed.

50

Looking Busy

https://i.redd.it/award_images/t5_22cerq/k0qzautvyyk51_LookingBusy.png

award_d33fddd7-a58a-4472-b1a2-3157d8c8b76f

Looking like you’re working is hard work.

50

Take My Energy

https://preview.redd.it/award_images/t5_22cerq/898sygoknoo41_TakeMyEnergy.png?width=64&height=64&crop=smart&auto=webp&s=e62f7cf1108ff17381b1ed42b1edca26f721dce0

award_02d9ab2c-162e-4c01-8438-317a016ed3d9

I’m in this with you.

50

Wearing is Caring

https://preview.redd.it/award_images/t5_22cerq/lcswc5d07hb51_WearingisCaring.png?width=64&height=64&crop=smart&auto=webp&s=50da94b41c2b6c8bbe2723243ed0985059bba9fa

award_80d4d339-95d0-43ac-b051-bc3fe0a9bab8

Keep the community and yourself healthy and happy.

50

Facepalm

https://preview.redd.it/award_images/t5_22cerq/ey2iodron2s41_Facepalm.png?width=64&height=64&crop=smart&auto=webp&s=9d3c8e8642dc97c655867ea5ba37b7d76d653203

award_b1b44fa1-8179-4d84-a9ed-f25bb81f1c5f

Lowers face into palm

70

Faith In Humanity Restored

https://preview.redd.it/award_images/t5_22cerq/gva4vt20qc751_FaithInHumanityRestored.png?width=64&height=64&crop=smart&auto=webp&s=a76d915a6eb1cd6d5efa2e0280d90740d2f74de9

award_7becef23-fb0b-4d62-b8a6-01d5759367cb

When goodness lifts you

70

Snek

https://preview.redd.it/award_images/t5_22cerq/rc5iesz2z8t41_Snek.png?width=64&height=64&crop=smart&auto=webp&s=2856d19d59c0af0d38fd0b6058622f6a1e91956a

award_99d95969-6100-45b2-b00c-0ec45ae19596

A smol, delicate danger noodle.

70

Tree Hug

https://preview.redd.it/award_images/t5_22cerq/fukjtec638u41_TreeHug.png?width=64&height=64&crop=smart&auto=webp&s=b46d14cae99b5519775167d0aea8418c480c28c0

award_b92370bb-b7de-4fb3-9608-c5b4a22f714a

Show nature some love.

70

Bravo Grande!

https://www.redditstatic.com/gold/awards/icon/SnooClappingPremium_64.png

award_9663243a-e77f-44cf-abc6-850ead2cd18d

For an especially amazing showing.

75

Party Train

https://www.redditstatic.com/gold/awards/icon/Train/Train_silver_64.png

award_75f9bc56-eba3-4988-a1af-aec974404a0b

All aboard! Every 5 Awards from everyone gives the author 100 Coins and 1 week of Premium. Rack up the number of Awards and watch the Train level-up.

75

Take My Power

https://www.redditstatic.com/gold/awards/icon/TakeMyPower_64.png

award_92cb6518-a71a-4217-9f8f-7ecbd7ab12ba

Add my power to yours.

75

Hugz

https://preview.redd.it/award_images/t5_22cerq/niiatoknifn51_Hugz.png?width=64&height=64&crop=smart&auto=webp&s=840debef89811f54b3f1b498bddf55c118eb62cb

award_8352bdff-3e03-4189-8a08-82501dd8f835

Everything is better with a good hug

80

‘MURICA

https://preview.redd.it/award_images/t5_22cerq/18mwqw5th9e51_MURICA.png?width=64&height=64&crop=smart&auto=webp&s=759d235c371d6ae8ad5efb1c98a74b259a3ff8fe

award_869d4135-8738-41e5-8630-de593b4f049f

Did somebody say ‘Murica?

100

Cosplay Famous

https://preview.redd.it/award_images/t5_22cerq/7ptj05lgqys51_CosplayFamous.png?width=64&height=64&crop=smart&auto=webp&s=405250108b91c08113cd9c38b4d872d9b521d116

award_6f0a496f-c3e2-484c-90d0-d26bffb2e286

The perfect cosplay doesn’t exis…

100

Dread

https://preview.redd.it/award_images/t5_22cerq/nvfe4gyawnf51_Dread.png?width=64&height=64&crop=smart&auto=webp&s=34247d8bba8dc5aa7eaed6e81135da0c935d37f3

award_81cf5c92-8500-498c-9c94-3e4034cece0a

Staring into the abyss and it’s staring right back

100

Evil Cackle

https://preview.redd.it/award_images/t5_22cerq/43zl6dfcg9e51_EvilCackle.png?width=64&height=64&crop=smart&auto=webp&s=bd7d6c66b7594ac91ff2d8a7d86340a0f49a153c

award_483d8e29-bbe5-404e-a09a-c2d7b16c4fff

Laugh like a supervillain

100

Excited

https://preview.redd.it/award_images/t5_22cerq/x069ow7ewnf51_Excited.png?width=64&height=64&crop=smart&auto=webp&s=b1d186a93a86d3bae5ad3bee36e41a9e93d35281

award_74fe5152-7906-4991-9016-bc2d8e261200

I don’t know what to do with my hands!

100

Glow Up

https://preview.redd.it/award_images/t5_22cerq/2754pa5jvsj51_GlowUp.png?width=64&height=64&crop=smart&auto=webp&s=60f710eccc52d9d05db204bb2b962372a1e45671

award_01178870-6a4f-4172-8f36-9ed5092ee4f9

You look amazing, glowing, incredible!

100

Heartwarming

https://preview.redd.it/award_images/t5_22cerq/v1mxw8i6wnf51_Heartwarming.png?width=64&height=64&crop=smart&auto=webp&s=c09f506dc0be92c9849ee7dd2cfe9d65852d6064

award_19860e30-3331-4bac-b3d1-bd28de0c7974

I needed this today

100

I’ll Drink to That

https://preview.redd.it/award_images/t5_22cerq/45aeu8mzvsj51_IllDrinktoThat.png?width=64&height=64&crop=smart&auto=webp&s=94580e58d47d0a1eb1c6cc776437c574b5bbad7c

award_3267ca1c-127a-49e9-9a3d-4ba96224af18

Let’s sip to good health and good company

100

Keep Calm

https://preview.redd.it/award_images/t5_22cerq/g77c4oud7hb51_KeepCalm.png?width=64&height=64&crop=smart&auto=webp&s=9510d2496464d0fa8ff2288e1f0e17f114226383

award_1da6ff27-7c0d-4524-9954-86e5cda5fcac

Stop, chill, relax

100

Kiss

https://preview.redd.it/award_images/t5_22cerq/sb42u5gmwsj51_Kiss.png?width=64&height=64&crop=smart&auto=webp&s=12e56d5bba8f00fe467d3efe0c962e70bcbc92ed

award_1e516e18-cbee-4668-b338-32d5530f91fe

You deserve a smooch

100

Last Minute Costume

https://preview.redd.it/award_images/t5_22cerq/icn71p34nct51_LastMinuteCostume.png?width=64&height=64&crop=smart&auto=webp&s=f6865e93870b4386ab4a7c32662200b961870d22

award_a0c3e268-87e7-4918-9a36-f6aa462e4dee

Any costume beats none

100

Lawyer Up

https://preview.redd.it/award_images/t5_22cerq/iq0sgwn5bzy41_LawyerUp.png?width=64&height=64&crop=smart&auto=webp&s=3baf45de6ba3e1535df885b91a2aa714e5ece9d5

award_ae89e420-c4a5-47b8-a007-5dacf1c0f0d4

OBJECTION!

100

Masterpiece

https://preview.redd.it/award_images/t5_22cerq/2juh333m40n51_Masterpiece.png?width=64&height=64&crop=smart&auto=webp&s=0183ad39a56ba3e46c4bcb5d8938392f75d5d9d5

award_b4072731-c0fb-4440-adc7-1063d6a5e6a0

C’est magnifique

100

Shocked

https://preview.redd.it/award_images/t5_22cerq/fck3iedi2ug51_Shocked.png?width=64&height=64&crop=smart&auto=webp&s=627fbd255cb9cce5b72551255cb061bf0c8af71a

award_fbe9527a-adb3-430e-af1a-5fd3489e641b

I’m genuinely flabbergasted.

100

Spacefaring Snoo

https://preview.redd.it/award_images/t5_22cerq/0dy3wj06qys51_SpacefaringSnoo.png?width=64&height=64&crop=smart&auto=webp&s=fb6e1c4f29f00c5229c58b769f788842f4bcb85d

award_a3df1615-dcf8-4f5f-ac7c-3c2be31332a7

On a vision quest to make life multi-planetary

100

Sweet Tooth

https://preview.redd.it/award_images/t5_22cerq/gbsaculna3u51_SweetTooth.png?width=64&height=64&crop=smart&auto=webp&s=5ce49bdf63d850847bb4dfced763fb80a8a99024

award_bd6ccb1d-118a-462a-a451-f550cd3133d2

It’s not a sugar rush, it’s a lifestyle.

100

Tearing Up

https://preview.redd.it/award_images/t5_22cerq/lop66ut2wnf51_TearingUp.png?width=64&height=64&crop=smart&auto=webp&s=a6ee8b3c876bdc7a022072134f8157a7ea85d884

award_43f3bf99-92d6-47ab-8205-130d26e7929f

This hits me right in the feels

100

Yummy

https://preview.redd.it/award_images/t5_22cerq/a7dhg27hvnf51_Yummy.png?width=64&height=64&crop=smart&auto=webp&s=7a70c563dbc8bb2659271ddd451c8e657f3a3aa8

award_ae7f17fb-6538-4c75-9ff4-5f48b4cdaa94

That looks so good

100

Wholesome

https://preview.redd.it/award_images/t5_22cerq/5izbv4fn0md41_Wholesome.png?width=64&height=64&crop=smart&auto=webp&s=89a077c4955b50fa2e57449eebf8c19e7f23ceb7

award_5f123e3d-4f48-42f4-9c11-e98b566d5897

When you come across a feel-good thing.

125

Bless Up

https://preview.redd.it/award_images/t5_22cerq/trfv6ems1md41_BlessUp.png?width=64&height=64&crop=smart&auto=webp&s=5e84fe0dae062adff22f01c384d86c0633d06b28

award_77ba55a2-c33c-4351-ac49-807455a80148

Prayers up for the blessed.

150

Buff Doge

https://preview.redd.it/award_images/t5_22cerq/zc4a9vk5zmc51_BuffDoge.png?width=64&height=64&crop=smart&auto=webp&s=04b5cf5717304307515af46c73431f11bb66c3bd

award_c42dc561-0b41-40b6-a23d-ef7e110e739e

So buff, wow

150

Cake

https://preview.redd.it/award_images/t5_22cerq/aoa99054n2s41_Cake.png?width=64&height=64&crop=smart&auto=webp&s=a1564ae45fe22bcd07a9a98d0b4c321c497ba194

award_5fb42699-4911-42a2-884c-6fc8bdc36059

Did someone say… cake?

150

Helpful

https://preview.redd.it/award_images/t5_22cerq/klvxk1wggfd41_Helpful.png?width=64&height=64&crop=smart&auto=webp&s=cc59d3722210878a975f8d97eb62f3092e472693

award_f44611f1-b89e-46dc-97fe-892280b13b82

Thank you stranger. Shows the award.

150

Press F

https://preview.redd.it/award_images/t5_22cerq/tcofsbf92md41_PressF.png?width=64&height=64&crop=smart&auto=webp&s=b33bda0aa0310bbe1877ba2d02a259d7cc52d616

award_88fdcafc-57a0-48db-99cc-76276bfaf28b

To pay respects.

150

Take My Money

https://preview.redd.it/award_images/t5_22cerq/9jr8pv84v7i51_TakeMyMoney.png?width=64&height=64&crop=smart&auto=webp&s=8cae8bb3d91b20e0d13b24010a103842e365ff9f

award_a7f9cbd7-c0f1-4569-a913-ebf8d18de00b

I’m buying what you’re selling

150

Giggle

https://www.redditstatic.com/gold/awards/icon/Giggle_64.png

award_e813313c-1002-49bf-ac37-e966710f605f

Innocent laughter

200

Got the W

https://preview.redd.it/award_images/t5_22cerq/9avdcwgupta41_GottheW.png?width=64&height=64&crop=smart&auto=webp&s=d7c1acaee0770a6a0ff7853606ba9992824cdcec

award_8dc476c7-1478-4d41-b940-f139e58f7756

200

I’d Like to Thank…

https://preview.redd.it/award_images/t5_22cerq/8ad2jffnclf41_Thanks.png?width=64&height=64&crop=smart&auto=webp&s=430fa4cf2928cc37ed0a3344c8da31277a53929c

award_1703f934-cf44-40cc-a96d-3729d0b48262

My kindergarten teacher, my cat, my mom, and you.

200

I’m Deceased

https://preview.redd.it/award_images/t5_22cerq/2jd92wtn25g41_ImDeceased.png?width=64&height=64&crop=smart&auto=webp&s=106ba80d6001af5b5b47b874b4f86da6ca88113f

award_b28d9565-4137-433d-bb65-5d4aa82ade4c

Call an ambulance, I’m laughing too hard.

200

Looking

https://preview.redd.it/award_images/t5_22cerq/kjpl76213ug51_Looking.png?width=64&height=64&crop=smart&auto=webp&s=5d6beac8304bc8fe28e0d6acb1b4b1339abecc67

award_4922c1be-3646-4d62-96ea-19a56798df51

I can’t help but look.

200

Plus One

https://preview.redd.it/award_images/t5_22cerq/6vgr8y21i9741_PlusOne.png?width=64&height=64&crop=smart&auto=webp&s=ecea37cb71525e80d9ca2dbf2bd504b9f934606e

award_f7562045-905d-413e-9ed2-0a16d4bfe349

You officially endorse and add your voice to the crowd.

200

Stonks Falling

https://preview.redd.it/award_images/t5_22cerq/ree13odobef41_StonksFalling.png?width=64&height=64&crop=smart&auto=webp&s=b1016427b3550d229b4ec93437ac8b69c28c5ae2

award_9ee30a8f-463e-4ef7-9da9-a09f270ec026

Losing value fast.

200

Stonks Rising

https://preview.redd.it/award_images/t5_22cerq/s5edqq9abef41_StonksRising.png?width=64&height=64&crop=smart&auto=webp&s=8c11db37505feb2a3e4130eb15e9470e72e65b63

award_d125d124-5c03-490d-af3d-d07c462003da

To the MOON.

200

This is 2020

https://preview.redd.it/award_images/t5_22cerq/ncon692ev7i51_Thisis2020.png?width=64&height=64&crop=smart&auto=webp&s=eb415a44432807861d7bac64d9e26c5c6ea194bb

award_dc391ef9-0df8-468f-bd3c-7b177092de35

Every reason to be alarmed

200

1UP

https://www.redditstatic.com/gold/awards/icon/Levelup_64.png

award_11be92ba-509e-46d3-991b-593239006521

Extra life

250

Awesome Answer

https://preview.redd.it/award_images/t5_22cerq/71v56o5a5v541_AwesomeAnswer.png?width=64&height=64&crop=smart&auto=webp&s=a6c7ee017a2cbab3e291b81823eb179faeb96b99

award_2adc49e8-d6c9-4923-9293-2bfab1648569

For a winning take and the kind soul who nails a question. Gives %{coin_symbol}100 Coins to both the author and the community.

250

It’s Cute!

https://preview.redd.it/award_images/t5_22cerq/n94bgm83in941_ItsCute.png?width=64&height=64&crop=smart&auto=webp&s=2632d9c9236d0501427072373b789fdb5a59377a

award_cc540de7-dfdb-4a68-9acf-6f9ce6b17d21

You made me UwU.

250

Mind Blown

https://preview.redd.it/award_images/t5_22cerq/wa987k0p4v541_MindBlown.png?width=64&height=64&crop=smart&auto=webp&s=5bcf973d6d2b64223cc5a2995c95b797bcf68dd2

award_9583d210-a7d0-4f3c-b0c7-369ad579d3d4

When a thing immediately combusts your brain. Gives %{coin_symbol}100 Coins to both the author and the community.

250

Original

https://preview.redd.it/award_images/t5_22cerq/b8xt4z8yajz31_Original.png?width=64&height=64&crop=smart&auto=webp&s=8ca70e1f45c2ddca559d456a74798fcedf36427e

award_d306c865-0d49-4a36-a1ab-a4122a0e3480

When something new and creative wows you. Gives %{coin_symbol}100 Coins to both the author and the community.

250

Timeless Beauty

https://www.redditstatic.com/gold/awards/icon/Timeless_512.png

award_31260000-2f4a-4b40-ad20-f5aa46a577bf

Beauty that’s forever. Gives %{coin_symbol}100 Coins each to the author and the community.

250

Today I Learned

https://preview.redd.it/award_images/t5_22cerq/bph2png4ajz31_TodayILearned.png?width=64&height=64&crop=smart&auto=webp&s=0dec60a8d3226978d4b824226b0c864b663293b3

award_a67d649d-5aa5-407e-a98b-32fd9e3a9696

The more you know… Gives %{coin_symbol}100 Coins to both the author and the community.

250

Yas Queen

https://preview.redd.it/award_images/t5_22cerq/kthj3e4h3bm41_YasQueen.png?width=64&height=64&crop=smart&auto=webp&s=98b385524aee26412e9dcf25bd20b4cff0eb2376

award_d48aad4b-286f-4a3a-bb41-ec05b3cd87cc

YAAAAAAAAAAASSS.

250

Coin Gift

https://preview.redd.it/award_images/t5_22cerq/cr1mq4yysv541_CoinGift.png?width=64&height=64&crop=smart&auto=webp&s=d39d0850925a193c9f2ca8203243c694d15fb40a

award_3dd248bc-3438-4c5b-98d4-24421fd6d670

Give the gift of %{coin_symbol}250 Reddit Coins.

300

Crab Rave

https://www.redditstatic.com/gold/awards/icon/CrabRave_64.png

award_f7a4fd5e-7cd1-4c11-a1c9-c18d05902e81

[Happy crab noises]

300

Frankensnoo

https://www.redditstatic.com/gold/awards/icon/Electric_64.png

award_aef30fbe-92e4-4593-8aa7-4b82cfe8d172

It’s Alive!!! Spread the Spooktober spirit.

300

GOAT

https://preview.redd.it/award_images/t5_22cerq/x52x5be57fd41_GOAT.png?width=64&height=64&crop=smart&auto=webp&s=d8a0ff8871eeebadc700284d0186073b8e56ac58

award_cc299d65-77de-4828-89de-708b088349a0

Historical anomaly - greatest in eternity.

300

Rocket Like

https://preview.redd.it/award_images/t5_22cerq/94pn64yuas941_RocketLike.png?width=64&height=64&crop=smart&auto=webp&s=381ec4bd15ab6029d5009a180f749093de815e60

award_28e8196b-d4e9-45bc-b612-cd4c7d3ed4b3

When an upvote just isn’t enough, smash the Rocket Like.

300

Spooky Season

https://www.redditstatic.com/gold/awards/icon/Spooky_64.png

award_176a3f8a-2229-4a12-bcdc-86464cfd6dc1

Too spooky for me. Spread the Spooktober spirit.

300

Table Flip

https://preview.redd.it/award_images/t5_22cerq/a05z7bb9v7i51_TableFlip.png?width=64&height=64&crop=smart&auto=webp&s=3efc978414612ce3b518813a124501b8a204e56b

award_3e000ecb-c1a4-49dc-af14-c8ac2029ca97

ARGH!

300

This

https://preview.redd.it/award_images/t5_22cerq/vu6om0xnb7e41_This.png?width=64&height=64&crop=smart&auto=webp&s=4b2a7c5439da6b4a9e2173bbf3cf9a610538600d

award_68ba1ee3-9baf-4252-be52-b808c1e8bdc4

THIS right here! Join together to give multiple This awards and see the award evolve in its display and shower benefits for the recipient. For every 3 This awards given to a post or comment, the author will get 250 coins.

300

Updoot

https://preview.redd.it/award_images/t5_22cerq/7atjjqpy1mc41_Updoot.png?width=64&height=64&crop=smart&auto=webp&s=f07dcd6402653b86d321cff6ded773cfa13d918a

award_725b427d-320b-4d02-8fb0-8bb7aa7b78aa

Sometimes you just got to doot.

300

Spit-take

https://www.redditstatic.com/gold/awards/icon/Spits_drink_64.png

award_3409a4c0-ba69-43a0-be9f-27bc27c159cc

Shower them with laughs

325

Super Heart Eyes

https://www.redditstatic.com/gold/awards/icon/Superheart_64.png

award_6220ecfe-4552-4949-aa13-fb1fb7db537c

When the love is out of control.

325

Table Slap

https://www.redditstatic.com/gold/awards/icon/TableSlap_64.png

award_9f928aff-c9f5-4e7e-aa91-8619dce60f1c

When laughter meets percussion

325

To The Stars

https://www.redditstatic.com/gold/awards/icon/Rocket_64.png

award_2bc47247-b107-44a8-a78c-613da21869ff

Boldly go where we haven’t been in a long, long time.

325

Aww-some

https://www.redditstatic.com/gold/awards/icon/Awwsome2_64.png

award_e55d1889-11f2-4d04-8abb-44b1de7dd53d

Use the Aww-some Award to highlight comments that are absolutely adorable.

350

Heartbeat

https://www.redditstatic.com/gold/awards/icon/Heartbeat_64.png

award_11eb6af3-3d0d-4d70-8261-22d216ab591d

Use the Heartbeat Award to highlight comments that make you feel warm and fuzzy

350

Into the Magic Portal

https://www.redditstatic.com/gold/awards/icon/TeleportIn_64.png

award_2ff1fdd0-ff73-47e6-a43c-bde6d4de8fbd

Hope to make it to the other side.

350

Out of the Magic Portal

https://www.redditstatic.com/gold/awards/icon/TeleportOut_64.png

award_7fe72f36-1141-4a39-ba76-0d481889b390

That was fun, but I’m glad to be back

350

Bravo!

https://www.redditstatic.com/gold/awards/icon/SnooClapping_64.png

award_84276b1e-cc8f-484f-a19c-be6c09adc1a5

An amazing showing.

400

Doot 🎵 Doot

https://www.redditstatic.com/gold/awards/icon/Updoot_64.png

award_5b39e8fd-7a58-4cbe-8ca0-bdedd5ed1f5a

Sometimes you just got to dance with the doots.

400

Pumpkin Spice

https://preview.redd.it/award_images/t5_22cerq/c1ll7h6zedq51_PumpkinSpice.png?width=64&height=64&crop=smart&auto=webp&s=c8a3297c17b9b70255353e933f5ed0a5b5bb3934

award_89164d08-80db-453b-a7aa-74c50fa84bfa

Autumn the beverage brings a bounty of 300 coins to the lucky recipient.

400

Bless Up (Pro)

https://preview.redd.it/award_images/t5_22cerq/xe5mw55w5v541_BlessUp.png?width=64&height=64&crop=smart&auto=webp&s=54b7d71c74cf41fc8ada4a2110babf8b68d2f172

award_43c43a35-15c5-4f73-91ef-fe538426435a

Prayers up for the blessed. Gives %{coin_symbol}100 Coins to both the author and the community.

500

Brighten My Day

https://www.redditstatic.com/gold/awards/icon/Sunny_64.png

award_9591a26e-b2e4-4ef2-bed4-28ff69246691

The clouds part and the sun shines through. Use the Brighten My Day Award to highlight comments that are a ray of sunshine.

500

Eureka!

https://www.redditstatic.com/gold/awards/icon/Bulb_64.png

award_65f78ca2-45d8-4cb6-bf79-a67beadf2e47

Now that is a bright idea. Use the Eureka Award to highlight comments that are brilliant.

500

Heart Eyes

https://preview.redd.it/award_images/t5_22cerq/12kz7a7j4v541_HeartEyes.png?width=64&height=64&crop=smart&auto=webp&s=02bb7182aad468e16e0a711b594110225679c79e

award_a9009ea5-1a36-42ae-aab2-5967563ee054

For love at first sight. Gives %{coin_symbol}100 Coins to both the author and the community.

500

Helpful (Pro)

https://preview.redd.it/award_images/t5_22cerq/trz28na8ajz31_Helpful.png?width=64&height=64&crop=smart&auto=webp&s=5dfea529ee529d33105b592b42696d05e7b734c2

award_2ae56630-cfe0-424e-b810-4945b9145358

Thank you stranger. Gives %{coin_symbol}100 Coins to both the author and the community.

500

Made Me Smile

https://preview.redd.it/award_images/t5_22cerq/hwnbr9l67s941_MadeMeSmile.png?width=64&height=64&crop=smart&auto=webp&s=918705b3b6804a6151b6ce4f8b1c86dfa604a470

award_a7a04d6a-8dd8-41bb-b906-04fa8f144014

When you’re smiling before you know it. Gives %{coin_symbol}100 Coins to both the author and the community.

500

Snoo Nice

https://preview.redd.it/award_images/t5_22cerq/9r7hexe6pta41_SnooNice.png?width=64&height=64&crop=smart&auto=webp&s=88748b0fe08311b512dc08909acdcdbe8d91d747

award_27d3176c-b388-4616-80ec-11b8ece5b7ee

Gives the author a week of Reddit Premium and %{coin_symbol}100 Coins to do with as they please.

500

Starry

https://www.redditstatic.com/gold/awards/icon/Starry_512.png

award_0e957fb0-c8f1-4ba1-a8ef-e1e524b60d7d

Use the Starry Award to highlight comments that deserve to stand out from the crowd.

500

Wholesome (Pro)

https://preview.redd.it/award_images/t5_22cerq/0o2j782f00e41_WholesomeSuperpro.png?width=64&height=64&crop=smart&auto=webp&s=2a04235b56e4fbc90106067bfe0d61bd60300c4f

award_1f0462ee-18f5-4f33-89cf-f1f79336a452

When you come across a feel-good thing. Gives %{coin_symbol}100 Coins to both the author and the community.

500

Pot o’ Coins

https://preview.redd.it/award_images/t5_22cerq/wg3lzllyg9n41_PotoCoins.png?width=64&height=64&crop=smart&auto=webp&s=7bb8b7ab622f25b5e6f7f2068663b5ea964d2957

award_35c78e6e-507b-4f1d-b3d8-ed43840909a8

The treasure at the end of the rainbow. Gives the author 800 Coins to do with as they please.

1000

Cornucopia

https://preview.redd.it/award_images/t5_22cerq/27xs8z0ja3u51_Cornucopia.png?width=64&height=64&crop=smart&auto=webp&s=4298b88d2511a0951817f440fe5244f6dcf513a9

award_9a123cdb-d26d-4d0c-b7fa-46750b8289fa

A candy cornucopia of love that gives the author a bounty of 1500 Coins.

2000

Argentium

https://www.redditstatic.com/gold/awards/icon/Mithril_64.png

award_4ca5a4e6-8873-4ac5-99b9-71b1d5161a91

Latin for distinguished. Shimmers like silver & stronger than steel. When someone deserves outsize recognition. This award gives a three-month Premium subscription and 2500 coins to the recipient.

20000

Ternion All-Powerful

https://www.redditstatic.com/gold/awards/icon/Trinity_64.png

award_2385c499-a1fb-44ec-b9b7-d260f3dc55de

Legendary level. A no holds barred celebration of something that hits you in the heart, mind and soul. Some might call it unachievanium. Gives the author 6 months of Premium and 5000 Coins.

50000

await block()

Block the user who sent the item.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

comment = await reddit.comment("dkk4qjd")
await comment.block()

# or, identically:
comment = await reddit.comment("dkk4qjd")
await comment.author.block()
await clear_vote()

Clear the authenticated user’s vote on the object.

Note

Votes must be cast by humans. That is, API clients proxying a human’s action one-for-one are OK, but bots deciding how to vote on content or amplifying a human’s vote are not. See the reddit rules for more details on what constitutes vote manipulation. [Ref]

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.clear_vote()

comment = await reddit.comment("dxolpyc", fetch=False)
await comment.clear_vote()
await collapse()

Mark the item as collapsed.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

inbox = reddit.inbox()

# select first inbox item and collapse it
async for message in inbox:
    await message.collapse()
    break

See also

uncollapse()

await delete()

Delete the object.

Example usage:

comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.delete()

submission = await reddit.submission("8dmv8z", fetch=False)
await submission.delete()
await disable_inbox_replies()

Disable inbox replies for the item.

Example usage:

comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.disable_inbox_replies()

submission = await reddit.submission("8dmv8z", fetch=False)
await submission.disable_inbox_replies()
await downvote()

Downvote the object.

Note

Votes must be cast by humans. That is, API clients proxying a human’s action one-for-one are OK, but bots deciding how to vote on content or amplifying a human’s vote are not. See the reddit rules for more details on what constitutes vote manipulation. [Ref]

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.downvote()

comment = await reddit.comment("dxolpyc", fetch=False)
await comment.downvote()

See also

upvote()

await edit(body: str) Union[asyncpraw.models.Comment, asyncpraw.models.Submission]

Replace the body of the object with body.

Parameters

body – The Markdown formatted content for the updated object.

Returns

The current instance after updating its attributes.

Example usage:

comment = await reddit.comment("dkk4qjd")

# construct the text of an edited comment
# by appending to the old body:
edited_body = comment.body + "Edit: thanks for the gold!"
await comment.edit(edited_body)
await enable_inbox_replies()

Enable inbox replies for the item.

Example usage:

comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.enable_inbox_replies()

submission = await reddit.submission("8dmv8z", fetch=False)
await submission.enable_inbox_replies()
property fullname: str

Return the object’s fullname.

A fullname is an object’s kind mapping like t3 followed by an underscore and the object’s base36 ID, e.g., t1_c5s96e0.

await gild() dict

Alias for award() to maintain backwards compatibility.

staticmethod id_from_url(url: str) str

Get the ID of a comment from the full URL.

property is_root: bool

Return True when the comment is a top-level comment.

Raises

AttributeError if the comment is not fetched.

await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
await mark_read()

Mark a single inbox item as read.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

inbox = reddit.inbox.unread()

async for message in inbox:
    # process unread messages
    ...

See also

mark_unread()

To mark the whole inbox as read with a single network request, use Inbox.mark_all_read()

await mark_unread()

Mark the item as unread.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

inbox = reddit.inbox(limit=10)

async for message in inbox:
    # process messages
    ...

See also

mark_read()

mod() asyncpraw.models.reddit.comment.CommentModeration

Provide an instance of CommentModeration.

Example usage:

comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.approve()
await parent() Union[Comment, asyncpraw.models.Submission]

Return the parent of the comment.

The returned parent will be an instance of either Comment, or Submission.

If this comment was obtained through a Submission, then its entire ancestry should be immediately available, requiring no extra network requests. However, if this comment was obtained through other means, e.g., await reddit.comment("COMMENT_ID"), or reddit.inbox.comment_replies, then the returned parent may be an instance of either Comment, or Submission.

Lazy comment example:

comment = await reddit.comment("cklhv0f", fetch=False)
parent = await comment.parent()
# 'replies' is empty until the comment is refreshed
print(parent.replies)  # Output: []
await parent.refresh()
print(parent.replies)  # Output is at least: [Comment(id="cklhv0f")]

Warning

Successive calls to parent() may result in a network request per call when the comment is not obtained through a Submission. See below for an example of how to minimize requests.

If you have a deeply nested comment and wish to most efficiently discover its top-most Comment ancestor you can chain successive calls to parent() with calls to refresh() at every 9 levels. For example:

ancestor = await reddit.comment("dkk4qjd")
refresh_counter = 0
while not ancestor.is_root:
    ancestor = await ancestor.parent()
    if refresh_counter % 9 == 0:
        await ancestor.refresh()
    refresh_counter += 1
print(f"Top-most Ancestor: {ancestor}")

The above code should result in 5 network requests to Reddit. Without the calls to refresh() it would make at least 31 network requests.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

await refresh()

Refresh the comment’s attributes.

If using Reddit.comment() with fetch=False, this method must be called in order to obtain the comment’s replies.

Example usage:

comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.refresh()
property replies: CommentForest

Provide an instance of CommentForest.

This property may return an empty list if the comment has not been refreshed with refresh()

Sort order and reply limit can be set with the reply_sort and reply_limit attributes before replies are fetched, including any call to refresh():

comment.reply_sort = "new"
await comment.refresh()
replies = comment.replies

Note

The appropriate values for reply_sort include "confidence", "controversial", "new", "old", "q&a", and "top".

await reply(body: str) Optional[Union[asyncpraw.models.Comment, asyncpraw.models.Message]]

Reply to the object.

Parameters

body – The Markdown formatted content for a comment.

Returns

A Comment or Message object for the newly created comment or message or None if Reddit doesn’t provide one.

Raises

asyncprawcore.exceptions.Forbidden when attempting to reply to some items, such as locked submissions/comments or non-replyable messages.

A None value can be returned if the target is a comment or submission in a quarantined subreddit and the authenticated user has not opt-ed in to viewing the content. When this happens the comment will be successfully created on Reddit and can be retried by drawing the comment from the user’s comment history.

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.reply("reply")

comment = await reddit.comment("dxolpyc", fetch=False)
await comment.reply("reply")
await report(reason: str)

Report this object to the moderators of its subreddit.

Parameters

reason – The reason for reporting.

Raises

RedditAPIException if reason is longer than 100 characters.

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.report("report reason")

comment = await reddit.comment("dxolpyc", fetch=False)
await comment.report("report reason")
await save(*, category: Optional[str] = None)

Save the object.

Parameters

category – The category to save to. If the authenticated user does not have Reddit Premium this value is ignored by Reddit (default: None).

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.save(category="view later")

comment = await reddit.comment("dxolpyc", fetch=False)
await comment.save()

See also

unsave()

property submission: asyncpraw.models.Submission

Return the Submission object this comment belongs to.

Raises

AttributeError if the comment is not fetched.

await unblock_subreddit()

Unblock a subreddit.

Note

This method pertains only to objects which were retrieved via the inbox.

For example, to unblock all blocked subreddits that you can find by going through your inbox:

from asyncpraw.models import SubredditMessage

subs = set()
async for item in reddit.inbox.messages(limit=None):
    if isinstance(item, SubredditMessage):
        if (
            item.subject == "[message from blocked subreddit]"
            and str(item.subreddit) not in subs
        ):
            item.unblock_subreddit()
            subs.add(str(item.subreddit))
await uncollapse()

Mark the item as uncollapsed.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

inbox = reddit.inbox()

# select first inbox item and uncollapse it
async for message in inbox:
    await message.uncollapse()
    break

See also

collapse()

await unsave()

Unsave the object.

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.unsave()

comment = await reddit.comment("dxolpyc", fetch=False)
await comment.unsave()

See also

save()

await upvote()

Upvote the object.

Note

Votes must be cast by humans. That is, API clients proxying a human’s action one-for-one are OK, but bots deciding how to vote on content or amplifying a human’s vote are not. See the reddit rules for more details on what constitutes vote manipulation. [Ref]

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.upvote()

comment = await reddit.comment("dxolpyc", fetch=False)
await comment.upvote()

See also

downvote()

Draft

class asyncpraw.models.Draft(reddit: asyncpraw.Reddit, id: Optional[str] = None, _data: Dict[str, Any] = None)

A class that represents a Reddit submission draft.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

link_flair_template_id

The link flair’s ID.

link_flair_text

The link flair’s text content, or None if not flaired.

modified

Time the submission draft was modified, represented in Unix Time.

original_content

Whether the submission draft will be set as original content.

selftext

The submission draft’s selftext. None if a link submission draft.

spoiler

Whether the submission will be marked as a spoiler.

subreddit

Provides an instance of Subreddit or UserSubreddit (if set).

title

The title of the submission draft.

url

The URL the submission draft links to.

__init__(reddit: asyncpraw.Reddit, id: Optional[str] = None, _data: Dict[str, Any] = None)

Initialize a Draft instance.

await delete()

Delete the Draft.

Example usage:

draft = await reddit.drafts("124862bc-e1e9-11eb-aa4f-e68667a77cbb")
await draft.delete()
await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

await submit(*, flair_id: Optional[str] = None, flair_text: Optional[str] = None, nsfw: Optional[bool] = None, selftext: Optional[str] = None, spoiler: Optional[bool] = None, subreddit: Optional[Union[str, asyncpraw.models.Subreddit, asyncpraw.models.UserSubreddit]] = None, title: Optional[str] = None, url: Optional[str] = None, **submit_kwargs) asyncpraw.models.Submission

Submit a draft.

Parameters
  • flair_id – The flair template to select (default: None).

  • flair_text – If the template’s flair_text_editable value is True, this value will set a custom text (default: None). flair_id is required when flair_text is provided.

  • nsfw – Whether or not the submission should be marked NSFW (default: None).

  • selftext – The Markdown formatted content for a text submission. Use an empty string, "", to make a title-only submission (default: None).

  • spoiler – Whether or not the submission should be marked as a spoiler (default: None).

  • subreddit – The subreddit to submit the draft to. This accepts a subreddit display name, Subreddit object, or UserSubreddit object.

  • title – The title of the submission (default: None).

  • url – The URL for a link submission (default: None).

Returns

A Submission object for the newly created submission.

Note

Parameters set here will override their respective Draft attributes.

Additional keyword arguments are passed to the Subreddit.submit() method.

For example, to submit a draft as is:

draft = await reddit.drafts("5f87d55c-e4fb-11eb-8965-6aeb41b0880e")
submission = await draft.submit()

For example, to submit a draft but use a different title than what is set:

draft = reddit.drafts("5f87d55c-e4fb-11eb-8965-6aeb41b0880e")
submission = draft.submit(title="New Title")

See also

await update(*, flair_id: Optional[str] = None, flair_text: Optional[str] = None, is_public_link: Optional[bool] = None, nsfw: Optional[bool] = None, original_content: Optional[bool] = None, selftext: Optional[str] = None, send_replies: Optional[bool] = None, spoiler: Optional[bool] = None, subreddit: Optional[Union[str, asyncpraw.models.Subreddit, asyncpraw.models.UserSubreddit]] = None, title: Optional[str] = None, url: Optional[str] = None, **draft_kwargs)

Update the Draft.

Note

Only provided values will be updated.

Parameters
  • flair_id – The flair template to select.

  • flair_text – If the template’s flair_text_editable value is True, this value will set a custom text. flair_id is required when flair_text is provided.

  • is_public_link – Whether to enable public viewing of the draft before it is submitted.

  • nsfw – Whether the draft should be marked NSFW.

  • original_content – Whether the submission should be marked as original content.

  • selftext – The Markdown formatted content for a text submission draft. Use None to make a title-only submission draft. selftext can not be provided if url is provided.

  • send_replies – When True, messages will be sent to the submission author when comments are made to the submission.

  • spoiler – Whether the submission should be marked as a spoiler.

  • subreddit – The subreddit to create the draft for. This accepts a subreddit display name, Subreddit object, or UserSubreddit object.

  • title – The title of the draft.

  • url – The URL for a link submission draft. url can not be provided if selftext is provided.

Additional keyword arguments can be provided to handle new parameters as Reddit introduces them.

For example, to update the title of a draft do:

draft = await reddit.drafts("5f87d55c-e4fb-11eb-8965-6aeb41b0880e")
await draft.update(title="New title")

LiveThread

class asyncpraw.models.LiveThread(reddit: asyncpraw.Reddit, id: Optional[str] = None, _data: Optional[Dict[str, Any]] = None)

An individual LiveThread object.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

created_utc

The creation time of the live thread, in Unix Time.

description

Description of the live thread, as Markdown.

description_html

Description of the live thread, as HTML.

id

The ID of the live thread.

nsfw

A bool representing whether or not the live thread is marked as NSFW.

__init__(reddit: asyncpraw.Reddit, id: Optional[str] = None, _data: Optional[Dict[str, Any]] = None)

Initialize a LiveThread instance.

Parameters
  • reddit – An instance of Reddit.

  • id – A live thread ID, e.g., "ukaeu1ik4sw5"

contrib() asyncpraw.models.reddit.live.LiveThreadContribution

Provide an instance of LiveThreadContribution.

Usage:

thread = await reddit.live("ukaeu1ik4sw5")
await thread.contrib.add("### update")
contributor() asyncpraw.models.reddit.live.LiveContributorRelationship

Provide an instance of LiveContributorRelationship.

You can call the instance to get a list of contributors which is represented as RedditorList instance consists of Redditor instances. Those Redditor instances have permissions attributes as contributors:

thread = await reddit.live("ukaeu1ik4sw5")
async for contributor in thread.contributor():
    # prints `Redditor(name="Acidtwist") [u"all"]`
    print(contributor, contributor.permissions)
discussions(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Submission]

Get submissions linking to the thread.

Parameters

generator_kwargs – keyword arguments passed to ListingGenerator constructor.

Returns

A ListingGenerator object which yields Submission objects.

Additional keyword arguments are passed in the initialization of ListingGenerator.

Usage:

thread = await reddit.live("ukaeu1ik4sw5")
async for submission in thread.discussions(limit=None):
    print(submission.title)
await get_update(update_id: str, fetch: bool = True, **kwargs) asyncpraw.models.LiveUpdate

Return a LiveUpdate instance.

Parameters
  • update_id – A live update ID, e.g., "7827987a-c998-11e4-a0b9-22000b6a88d2".

  • fetch – Determines if Async PRAW will fetch the object (default: True).

Usage:

thread = await reddit.live("ukaeu1ik4sw5")
update = await thread.get_update("7827987a-c998-11e4-a0b9-22000b6a88d2")
update.thread  # LiveThread(id="ukaeu1ik4sw5")
update.id  # "7827987a-c998-11e4-a0b9-22000b6a88d2"
update.author  # "umbrae"

If you don’t need the object fetched right away (e.g., to utilize a class method) you can do:

thread = await reddit.live("ukaeu1ik4sw5")
update = await thread.get_update("7827987a-c998-11e4-a0b9-22000b6a88d2", fetch=False)
update.contrib  # LiveUpdateContribution instance
await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

await report(type: str)

Report the thread violating the Reddit rules.

Parameters

type – One of "spam", "vote-manipulation", "personal-information", "sexualizing-minors", or "site-breaking".

Usage:

thread = await reddit.live("xyu8kmjvfrww")
await thread.report("spam")
stream() asyncpraw.models.reddit.live.LiveThreadStream

Provide an instance of LiveThreadStream.

Streams are used to indefinitely retrieve new updates made to a live thread, like:

for live_update in reddit.live("ta535s1hq2je").stream.updates():
    print(live_update.body)

Updates are yielded oldest first as LiveUpdate. Up to 100 historical updates will initially be returned. To only retrieve new updates starting from when the stream is created, pass skip_existing=True:

live_thread = await reddit.live("ta535s1hq2je")
async for live_update in live_thread.stream.updates(skip_existing=True):
    print(live_update.author)
async for ... in updates(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.LiveUpdate]

Return a ListingGenerator yields LiveUpdate s.

Parameters

generator_kwargs – keyword arguments passed to ListingGenerator constructor.

Returns

A ListingGenerator object which yields LiveUpdate objects.

Additional keyword arguments are passed in the initialization of ListingGenerator.

Usage:

thread = await reddit.live("ukaeu1ik4sw5")
after = "LiveUpdate_fefb3dae-7534-11e6-b259-0ef8c7233633"
async for submission in thread.updates(limit=5, params={"after": after}):
    print(submission.body)

LiveUpdate

class asyncpraw.models.LiveUpdate(reddit: asyncpraw.Reddit, thread_id: Optional[str] = None, update_id: Optional[str] = None, _data: Optional[Dict[str, Any]] = None)

An individual LiveUpdate object.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

author

The Redditor who made the update.

body

Body of the update, as Markdown.

body_html

Body of the update, as HTML.

created_utc

The time the update was created, as Unix Time.

stricken

A bool representing whether or not the update was stricken (see strike()).

__init__(reddit: asyncpraw.Reddit, thread_id: Optional[str] = None, update_id: Optional[str] = None, _data: Optional[Dict[str, Any]] = None)

Initialize a LiveUpdate instance.

Either thread_id and update_id, or _data must be provided.

Parameters
  • reddit – An instance of Reddit.

  • thread_id – A live thread ID, e.g., "ukaeu1ik4sw5".

  • update_id – A live update ID, e.g., "7827987a-c998-11e4-a0b9-22000b6a88d2".

Usage:

update = LiveUpdate(reddit, "ukaeu1ik4sw5", "7827987a-c998-11e4-a0b9-22000b6a88d2")
await update.load()
update.thread  # LiveThread(id="ukaeu1ik4sw5")
update.id  # "7827987a-c998-11e4-a0b9-22000b6a88d2"
update.author  # "umbrae"
contrib() asyncpraw.models.reddit.live.LiveUpdateContribution

Provide an instance of LiveUpdateContribution.

Usage:

thread = await reddit.live("ukaeu1ik4sw5")
update = await thread.get_update("7827987a-c998-11e4-a0b9-22000b6a88d2", fetch=False)
update.contrib  # LiveUpdateContribution instance
property fullname: str

Return the object’s fullname.

A fullname is an object’s kind mapping like t3 followed by an underscore and the object’s base36 ID, e.g., t1_c5s96e0.

await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

property thread: LiveThread

Return LiveThread object the update object belongs to.

Message

class asyncpraw.models.Message(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

A class for private messages.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

author

Provides an instance of Redditor.

body

The body of the message, as Markdown.

body_html

The body of the message, as HTML.

created_utc

Time the message was created, represented in Unix Time.

dest

Provides an instance of Redditor. The recipient of the message.

id

The ID of the message.

name

The full ID of the message, prefixed with t4_.

subject

The subject of the message.

was_comment

Whether or not the message was a comment reply.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a Message instance.

await block()

Block the user who sent the item.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

comment = await reddit.comment("dkk4qjd")
await comment.block()

# or, identically:
comment = await reddit.comment("dkk4qjd")
await comment.author.block()
await collapse()

Mark the item as collapsed.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

inbox = reddit.inbox()

# select first inbox item and collapse it
async for message in inbox:
    await message.collapse()
    break

See also

uncollapse()

await delete()

Delete the message.

Note

Reddit does not return an indication of whether or not the message was successfully deleted.

For example, to delete the most recent message in your inbox:

async for message in reddit.inbox.all():
    await message.delete()
    break
property fullname: str

Return the object’s fullname.

A fullname is an object’s kind mapping like t3 followed by an underscore and the object’s base36 ID, e.g., t1_c5s96e0.

await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
await mark_read()

Mark a single inbox item as read.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

inbox = reddit.inbox.unread()

async for message in inbox:
    # process unread messages
    ...

See also

mark_unread()

To mark the whole inbox as read with a single network request, use Inbox.mark_all_read()

await mark_unread()

Mark the item as unread.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

inbox = reddit.inbox(limit=10)

async for message in inbox:
    # process messages
    ...

See also

mark_read()

property parent: Optional[asyncpraw.models.Message]

Return the parent of the message if it exists.

Note

If the message is from an inbox listing, the returned parent will be lazy and must be fetched manually. For example:

async for message in reddit.inbox.all(limit=1):
    parent = message.parent
    await parent.load()
    print(parent.body)
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit)

Return an instance of Message or SubredditMessage from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

await reply(body: str) Optional[Union[asyncpraw.models.Comment, asyncpraw.models.Message]]

Reply to the object.

Parameters

body – The Markdown formatted content for a comment.

Returns

A Comment or Message object for the newly created comment or message or None if Reddit doesn’t provide one.

Raises

asyncprawcore.exceptions.Forbidden when attempting to reply to some items, such as locked submissions/comments or non-replyable messages.

A None value can be returned if the target is a comment or submission in a quarantined subreddit and the authenticated user has not opt-ed in to viewing the content. When this happens the comment will be successfully created on Reddit and can be retried by drawing the comment from the user’s comment history.

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.reply("reply")

comment = await reddit.comment("dxolpyc", fetch=False)
await comment.reply("reply")
await unblock_subreddit()

Unblock a subreddit.

Note

This method pertains only to objects which were retrieved via the inbox.

For example, to unblock all blocked subreddits that you can find by going through your inbox:

from asyncpraw.models import SubredditMessage

subs = set()
async for item in reddit.inbox.messages(limit=None):
    if isinstance(item, SubredditMessage):
        if (
            item.subject == "[message from blocked subreddit]"
            and str(item.subreddit) not in subs
        ):
            item.unblock_subreddit()
            subs.add(str(item.subreddit))
await uncollapse()

Mark the item as uncollapsed.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

inbox = reddit.inbox()

# select first inbox item and uncollapse it
async for message in inbox:
    await message.uncollapse()
    break

See also

collapse()

ModmailConversation

class asyncpraw.models.reddit.modmail.ModmailConversation(reddit: asyncpraw.Reddit, id: Optional[str] = None, mark_read: bool = False, _data: Optional[Dict[str, Any]] = None)

A class for modmail conversations.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

authors

Provides an ordered list of Redditor instances. The authors of each message in the modmail conversation.

id

The ID of the ModmailConversation.

is_highlighted

Whether or not the ModmailConversation is highlighted.

is_internal

Whether or not the ModmailConversation is a private mod conversation.

last_mod_update

Time of the last mod message reply, represented in the ISO 8601 standard with timezone.

last_updated

Time of the last message reply, represented in the ISO 8601 standard with timezone.

last_user_update

Time of the last user message reply, represented in the ISO 8601 standard with timezone.

num_messages

The number of messages in the ModmailConversation.

obj_ids

Provides a list of dictionaries representing mod actions on the ModmailConversation. Each dict contains attributes of "key" and "id". The key can be either ""messages" or "ModAction". "ModAction" represents archiving/highlighting etc.

owner

Provides an instance of Subreddit. The subreddit that the ModmailConversation belongs to.

participant

Provides an instance of Redditor. The participating user in the ModmailConversation.

subject

The subject of the ModmailConversation.

__init__(reddit: asyncpraw.Reddit, id: Optional[str] = None, mark_read: bool = False, _data: Optional[Dict[str, Any]] = None)

Initialize a ModmailConversation instance.

Parameters

mark_read – If True, conversation is marked as read (default: False).

await archive()

Archive the conversation.

For example:

subreddit = await reddit.subreddit("test")
conversation = await subreddit.modmail("2gmz")
await conversation.archive()
await highlight()

Highlight the conversation.

For example:

subreddit = await reddit.subreddit("test")
conversation = await subreddit.modmail("2gmz")
await conversation.highlight()
await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
await mute(*, num_days=3)

Mute the non-mod user associated with the conversation.

Parameters

num_days – Duration of mute in days. Valid options are 3, 7, or 28 (default: 3).

For example:

subreddit = await reddit.subreddit("test")
conversation = await subreddit.modmail("2gmz")
await conversation.mute()

To mute for 7 days:

subreddit = await reddit.subreddit("test")
conversation = await subreddit.modmail("2gmz")
await conversation.mute(num_days=7)
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit, convert_objects: bool = True)

Return an instance of ModmailConversation from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

  • convert_objects – If True, convert message and mod action data into objects (default: True).

await read(*, other_conversations: Optional[List[ModmailConversation]] = None)

Mark the conversation(s) as read.

Parameters

other_conversations – A list of other conversations to mark (default: None).

For example, to mark the conversation as read along with other recent conversations from the same user:

subreddit = await reddit.subreddit("test")
conversation = await subreddit.modmail.conversation("2gmz")
await conversation.read(other_conversations=conversation.user.recent_convos)
await reply(*, author_hidden: bool = False, body: str, internal: bool = False) ModmailMessage

Reply to the conversation.

Parameters
  • author_hidden – When True, author is hidden from non-moderators (default: False).

  • body – The Markdown formatted content for a message.

  • internal – When True, message is a private moderator note, hidden from non-moderators (default: False).

Returns

A ModmailMessage object for the newly created message.

For example, to reply to the non-mod user while hiding your username:

subreddit = await reddit.subreddit("test")
conversation = await subreddit.modmail("2gmz")
await conversation.reply(body="Message body", author_hidden=True)

To create a private moderator note on the conversation:

await conversation.reply(body="Message body", internal=True)
await unarchive()

Unarchive the conversation.

For example:

subreddit = await reddit.subreddit("test")
conversation = await subreddit.modmail("2gmz")
await conversation.unarchive()
await unhighlight()

Un-highlight the conversation.

For example:

subreddit = await reddit.subreddit("test")
conversation = await subreddit.modmail("2gmz")
await conversation.unhighlight()
await unmute()

Unmute the non-mod user associated with the conversation.

For example:

subreddit = await reddit.subreddit("test")
conversation = await subreddit.modmail("2gmz")
await conversation.unmute()
await unread(*, other_conversations: Optional[List[ModmailConversation]] = None)

Mark the conversation(s) as unread.

Parameters

other_conversations – A list of other conversations to mark (default: None).

For example, to mark the conversation as unread along with other recent conversations from the same user:

subreddit = await reddit.subreddit("test")
conversation = await subreddit.modmail.conversation("2gmz")
await conversation.unread(other_conversations=conversation.user.recent_convos)

MoreComments

class asyncpraw.models.MoreComments(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

A class indicating there are more comments.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a MoreComments instance.

await comments(*, update: bool = True) List[asyncpraw.models.Comment]

Fetch and return the comments for a single MoreComments object.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

Multireddit

class asyncpraw.models.Multireddit(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

A class for users’ multireddits.

This is referred to as a “Custom Feed” on the Reddit UI.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

can_edit

A bool representing whether or not the authenticated user may edit the multireddit.

copied_from

The multireddit that the multireddit was copied from, if it exists, otherwise None.

created_utc

When the multireddit was created, in Unix Time.

description_html

The description of the multireddit, as HTML.

description_md

The description of the multireddit, as Markdown.

display_name

The display name of the multireddit.

name

The name of the multireddit.

over_18

A bool representing whether or not the multireddit is restricted for users over 18.

subreddits

A list of Subreddits that make up the multireddit.

visibility

The visibility of the multireddit, either "private", "public", or "hidden".

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a Multireddit instance.

await add(subreddit: asyncpraw.models.Subreddit)

Add a subreddit to this multireddit.

Parameters

subreddit – The subreddit to add to this multi.

For example, to add r/test to multireddit bboe/test:

subreddit = await reddit.subreddit("test")
multireddit = await reddit.multireddit(redditor="bboe", name="test")
await multireddit.add(subreddit)
comments() CommentHelper

Provide an instance of CommentHelper.

For example, to output the author of the 25 most recent comments of r/test execute:

subreddit = await reddit.subreddit("test")
async for comment in subreddit.comments(limit=25):
    print(comment.author)
controversial(*, time_filter: str = 'all', **generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for controversial items.

Parameters

time_filter – Can be one of: "all", "day", "hour", "month", "week", or "year" (default: "all").

Raises

ValueError if time_filter is invalid.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").controversial(time_filter="week")

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.controversial(time_filter="day")

redditor = await reddit.redditor("spez")
redditor.controversial(time_filter="month")

redditor = await reddit.redditor("spez")
redditor.comments.controversial(time_filter="year")

redditor = await reddit.redditor("spez")
redditor.submissions.controversial(time_filter="all")

subreddit = await reddit.subreddit("all")
subreddit.controversial(time_filter="hour")
await copy(*, display_name: Optional[str] = None) asyncpraw.models.Multireddit

Copy this multireddit and return the new multireddit.

Parameters

display_name – The display name for the copied multireddit. Reddit will generate the name field from this display name. When not provided the copy will use the same display name and name as this multireddit.

To copy the multireddit bboe/test with a name of "testing":

multireddit = await reddit.multireddit(redditor="bboe", name="test")
await multireddit.copy(display_name="testing")
await delete()

Delete this multireddit.

For example, to delete multireddit bboe/test:

multireddit = await reddit.multireddit(redditor="bboe", name="test")
await multireddit.delete()
gilded(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for gilded items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get gilded items in r/test:

subreddit = await reddit.subreddit("test")
async for item in subreddit.gilded():
    print(item.id)
hot(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for hot items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").hot()

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.hot()

redditor = await reddit.redditor("spez")
redditor.hot()

redditor = await reddit.redditor("spez")
redditor.comments.hot()

redditor = await reddit.redditor("spez")
redditor.submissions.hot()

subreddit = await reddit.subreddit("all")
subreddit.hot()
await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
new(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for new items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").new()

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.new()

redditor = await reddit.redditor("spez")
redditor.new()

redditor = await reddit.redditor("spez")
redditor.comments.new()

redditor = await reddit.redditor("spez")
redditor.submissions.new()

subreddit = await reddit.subreddit("all")
subreddit.new()
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

random_rising(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Submission]

Return a ListingGenerator for random rising submissions.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get random rising submissions for r/test:

subreddit = await reddit.subreddit("test")
async for submission in subreddit.random_rising():
    print(submission.title)
await remove(subreddit: asyncpraw.models.Subreddit)

Remove a subreddit from this multireddit.

Parameters

subreddit – The subreddit to remove from this multi.

For example, to remove r/test from multireddit bboe/test:

subreddit = await reddit.subreddit("test")
multireddit = await reddit.multireddit(redditor="bboe", name="test")
await multireddit.remove(subreddit)
rising(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Submission]

Return a ListingGenerator for rising submissions.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get rising submissions for r/test:

subreddit = await reddit.subreddit("test")
async for submission in subreddit.rising():
    print(submission.title)
staticmethod sluggify(title: str)

Return a slug version of the title.

Parameters

title – The title to make a slug of.

Adapted from Reddit’s utils.py.

stream() SubredditStream

Provide an instance of SubredditStream.

Streams can be used to indefinitely retrieve new comments made to a multireddit, like:

multireddit = await reddit.multireddit(redditor="spez", name="fun")
async for comment in multireddit.stream.comments():
    print(comment)

Additionally, new submissions can be retrieved via the stream. In the following example all new submissions to the multireddit are fetched:

multireddit = await reddit.multireddit(redditor="bboe", name="games")
async for submission in multireddit.stream.submissions():
    print(submission)
top(*, time_filter: str = 'all', **generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for top items.

Parameters

time_filter – Can be one of: "all", "day", "hour", "month", "week", or "year "``(default: ``"all").

Raises

ValueError if time_filter is invalid.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").top(time_filter="week")

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.top(time_filter="day")

redditor = await reddit.redditor("spez")
redditor.top(time_filter="month")

redditor = await reddit.redditor("spez")
redditor.comments.top(time_filter="year")

redditor = await reddit.redditor("spez")
redditor.submissions.top(time_filter="all")

subreddit = await reddit.subreddit("all")
subreddit.top(time_filter="hour")
await update(**updated_settings: Union[str, List[Union[str, asyncpraw.models.Subreddit, Dict[str, str]]]])

Update this multireddit.

Keyword arguments are passed for settings that should be updated. They can any of:

Parameters
  • display_name – The display name for this multireddit. Must be no longer than 50 characters.

  • subreddits – Subreddits for this multireddit.

  • description_md – Description for this multireddit, formatted in Markdown.

  • icon_name – Can be one of: "art and design", "ask", "books", "business", "cars", "comics", "cute animals", "diy", "entertainment", "food and drink", "funny", "games", "grooming", "health", "life advice", "military", "models pinup", "music", "news", "philosophy", "pictures and gifs", "science", "shopping", "sports", "style", "tech", "travel", "unusual stories", "video", or None.

  • key_color – RGB hex color code of the form "#FFFFFF".

  • visibility – Can be one of: "hidden", "private", or "public".

  • weighting_scheme – Can be one of: "classic" or "fresh".

For example, to rename multireddit "bboe/test" to "bboe/testing":

multireddit = await reddit.multireddit(redditor="bboe", name="test")
await multireddit.update(display_name="testing")

Redditor

class asyncpraw.models.Redditor(reddit: asyncpraw.Reddit, name: Optional[str] = None, fullname: Optional[str] = None, _data: Optional[Dict[str, Any]] = None)

A class representing the users of Reddit.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Note

Shadowbanned accounts are treated the same as non-existent accounts, meaning that they will not have any attributes.

Note

Suspended/banned accounts will only return the name and is_suspended attributes.

Attribute

Description

comment_karma

The comment karma for the Redditor.

comments

Provide an instance of SubListing for comment access.

submissions

Provide an instance of SubListing for submission access.

created_utc

Time the account was created, represented in Unix Time.

has_verified_email

Whether or not the Redditor has verified their email.

icon_img

The url of the Redditors’ avatar.

id

The ID of the Redditor.

is_employee

Whether or not the Redditor is a Reddit employee.

is_friend

Whether or not the Redditor is friends with the authenticated user.

is_mod

Whether or not the Redditor mods any subreddits.

is_gold

Whether or not the Redditor has active Reddit Premium status.

is_suspended

Whether or not the Redditor is currently suspended.

link_karma

The link karma for the Redditor.

name

The Redditor’s username.

subreddit

If the Redditor has created a user-subreddit, provides a dictionary of additional attributes. See below.

subreddit["banner_img"]

The URL of the user-subreddit banner.

subreddit["name"]

The fullname of the user-subreddit.

subreddit["over_18"]

Whether or not the user-subreddit is NSFW.

subreddit["public_description"]

The public description of the user- subreddit.

subreddit["subscribers"]

The number of users subscribed to the user-subreddit.

subreddit["title"]

The title of the user-subreddit.

__init__(reddit: asyncpraw.Reddit, name: Optional[str] = None, fullname: Optional[str] = None, _data: Optional[Dict[str, Any]] = None)

Initialize a Redditor instance.

Parameters
  • reddit – An instance of Reddit.

  • name – The name of the redditor.

  • fullname – The fullname of the redditor, starting with t2_.

Exactly one of name, fullname or _data must be provided.

await block()

Block the Redditor.

For example, to block Redditor u/spez:

redditor = await reddit.redditor("spez")
await redditor.block()

Note

Blocking a trusted user will remove that user from your trusted list.

See also

trust()

comments() SubListing

Provide an instance of SubListing for comment access.

For example, to output the first line of all new comments by u/spez try:

redditor = await reddit.redditor("spez")
async for comment in redditor.comments.new(limit=None):
    print(comment.body.split("\\n", 1)[0][:79])
controversial(*, time_filter: str = 'all', **generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for controversial items.

Parameters

time_filter – Can be one of: "all", "day", "hour", "month", "week", or "year" (default: "all").

Raises

ValueError if time_filter is invalid.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").controversial(time_filter="week")

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.controversial(time_filter="day")

redditor = await reddit.redditor("spez")
redditor.controversial(time_filter="month")

redditor = await reddit.redditor("spez")
redditor.comments.controversial(time_filter="year")

redditor = await reddit.redditor("spez")
redditor.submissions.controversial(time_filter="all")

subreddit = await reddit.subreddit("all")
subreddit.controversial(time_filter="hour")
await distrust()

Remove the Redditor from your whitelist of trusted users.

For example, to remove Redditor u/spez from your whitelist:

redditor = await reddit.redditor("spez")
await redditor.distrust()

See also

trust()

downvoted(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Union[asyncpraw.models.Comment, asyncpraw.models.Submission]]

Return a ListingGenerator for items the user has downvoted.

Returns

A ListingGenerator object which yields Comment or Submission objects the user has downvoted.

Raises

asyncprawcore.Forbidden if the user is not authorized to access the list.

Note

Since this function returns a ListingGenerator the exception may not occur until sometime after this function has returned.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get all downvoted items of the authenticated user:

current_user = await reddit.user.me()
async for item in current_user.downvoted():
    print(item.id)
await friend(*, note: str = None)

Friend the Redditor.

Parameters

note – A note to save along with the relationship. Requires Reddit Premium (default: None).

Calling this method subsequent times will update the note.

For example, to friend u/spez:

redditor = await reddit.redditor("spez")
await redditor.friend()

To add a note to the friendship (requires Reddit Premium):

redditor = await reddit.redditor("spez")
await redditor.friend(note="My favorite admin")
await friend_info() asyncpraw.models.Redditor

Return a Redditor instance with specific friend-related attributes.

Returns

A Redditor instance with fields date, id, and possibly note if the authenticated user has Reddit Premium.

For example, to get the friendship information of Redditor u/spez:

redditor = await reddit.redditor("spez")
info = await redditor.friend_info
friend_data = info.date
classmethod from_data(reddit, data)

Return an instance of Redditor, or None from data.

property fullname: str

Return the object’s fullname.

A fullname is an object’s kind mapping like t3 followed by an underscore and the object’s base36 ID, e.g., t1_c5s96e0.

await gild(*, months: int = 1)

Gild the Redditor.

Parameters

months – Specifies the number of months to gild up to 36 (default: 1).

For example, to gild Redditor u/spez for 1 month:

redditor = await reddit.redditor("spez")
await redditor.gild(months=1)
gilded(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for gilded items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get gilded items in r/test:

subreddit = await reddit.subreddit("test")
async for item in subreddit.gilded():
    print(item.id)
gildings(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Union[asyncpraw.models.Comment, asyncpraw.models.Submission]]

Return a ListingGenerator for items the user has gilded.

Returns

A ListingGenerator object which yields Comment or Submission objects the user has gilded.

Raises

asyncprawcore.Forbidden if the user is not authorized to access the list.

Note

Since this function returns a ListingGenerator the exception may not occur until sometime after this function has returned.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get all gilded items of the authenticated user:

current_user = await reddit.user.me()
async for item in current_user.gildings():
    print(item.id)
hidden(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Union[asyncpraw.models.Comment, asyncpraw.models.Submission]]

Return a ListingGenerator for items the user has hidden.

Returns

A ListingGenerator object which yields Comment or Submission objects the user has hid.

Raises

asyncprawcore.Forbidden if the user is not authorized to access the list.

Note

Since this function returns a ListingGenerator the exception may not occur until sometime after this function has returned.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get all hidden items of the authenticated user:

current_user = await reddit.user.me()
async for item in current_user.hidden():
    print(item.id)
hot(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for hot items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").hot()

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.hot()

redditor = await reddit.redditor("spez")
redditor.hot()

redditor = await reddit.redditor("spez")
redditor.comments.hot()

redditor = await reddit.redditor("spez")
redditor.submissions.hot()

subreddit = await reddit.subreddit("all")
subreddit.hot()
await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
await message(*, from_subreddit: Optional[Union[asyncpraw.models.Subreddit, str]] = None, message: str, subject: str)

Send a message to a Redditor or a Subreddit’s moderators (modmail).

Parameters
  • from_subreddit

    A Subreddit instance or string to send the message from. When provided, messages are sent from the subreddit rather than from the authenticated user.

    Note

    The authenticated user must be a moderator of the subreddit and have the mail moderator permission.

  • message – The message content.

  • subject – The subject of the message.

For example, to send a private message to u/spez, try:

redditor = await reddit.redditor("spez", fetch=False)
await redditor.message(subject="TEST", message="test message from Async PRAW")

To send a message to u/spez from the moderators of r/test try:

redditor = await reddit.redditor("spez", fetch=False)
await redditor.message(
    subject="TEST", message="test message from r/test", from_subreddit="test"
)

To send a message to the moderators of r/test, try:

subreddit = await reddit.subreddit("test")
await subreddit.message(subject="TEST", message="test PM from Async PRAW")
await moderated() List[asyncpraw.models.Subreddit]

Return a list of the redditor’s moderated subreddits.

Returns

A list of Subreddit objects. Return [] if the redditor has no moderated subreddits.

Raises

asyncprawcore.ServerError in certain circumstances. See the note below.

Note

The redditor’s own user profile subreddit will not be returned, but other user profile subreddits they moderate will be returned.

Usage:

redditor = await reddit.redditor("spez")
async for subreddit in redditor.moderated():
    print(subreddit.display_name)
    print(subreddit.title)

Note

A asyncprawcore.ServerError exception may be raised if the redditor moderates a large number of subreddits. If that happens, try switching to read-only mode. For example,

reddit.read_only = True
redditor = await reddit.redditor("reddit")
async for subreddit in redditor.moderated():
    print(str(subreddit))

It is possible that requests made in read-only mode will also raise a asyncprawcore.ServerError exception.

When used in read-only mode, this method does not retrieve information about subreddits that require certain special permissions to access, e.g., private subreddits and premium-only subreddits.

await multireddits() List[asyncpraw.models.Multireddit]

Return a list of the redditor’s public multireddits.

For example, to to get Redditor u/spez’s multireddits:

redditor = await reddit.redditor("spez")
multireddits = await redditor.multireddits()
new(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for new items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").new()

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.new()

redditor = await reddit.redditor("spez")
redditor.new()

redditor = await reddit.redditor("spez")
redditor.comments.new()

redditor = await reddit.redditor("spez")
redditor.submissions.new()

subreddit = await reddit.subreddit("all")
subreddit.new()
notes() asyncpraw.models.RedditorModNotes

Provide an instance of RedditorModNotes.

This provides an interface for managing moderator notes for a redditor.

Note

The authenticated user must be a moderator of the provided subreddit(s).

For example, all the notes for u/spez in r/test can be iterated through like so:

redditor = await reddit.redditor("spez")

async for note in redditor.notes.subreddits("test"):
    print(f"{note.label}: {note.note}")
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

saved(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Union[asyncpraw.models.Comment, asyncpraw.models.Submission]]

Return a ListingGenerator for items the user has saved.

Returns

A ListingGenerator object which yields Comment or Submission objects the user has saved.

Raises

asyncprawcore.Forbidden if the user is not authorized to access the list.

Note

Since this function returns a ListingGenerator the exception may not occur until sometime after this function has returned.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get all saved items of the authenticated user:

current_user = await reddit.user.me()
async for item in current_user.saved(limit=None):
    print(item.id)
stream() asyncpraw.models.reddit.redditor.RedditorStream

Provide an instance of RedditorStream.

Streams can be used to indefinitely retrieve new comments made by a redditor, like:

redditor = await reddit.redditor("spez")
async for comment in redditor.stream.comments():
    print(comment)

Additionally, new submissions can be retrieved via the stream. In the following example all submissions are fetched via the redditor u/spez:

redditor = await reddit.redditor("spez")
async for submission in redditor.stream.submissions():
    print(submission)
submissions() SubListing

Provide an instance of SubListing for submission access.

For example, to output the title’s of top 100 of all time submissions for u/spez try:

redditor = await reddit.redditor("spez")
async for submission in redditor.submissions.top(time_filter="all"):
    print(submission.title)
top(*, time_filter: str = 'all', **generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for top items.

Parameters

time_filter – Can be one of: "all", "day", "hour", "month", "week", or "year "``(default: ``"all").

Raises

ValueError if time_filter is invalid.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").top(time_filter="week")

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.top(time_filter="day")

redditor = await reddit.redditor("spez")
redditor.top(time_filter="month")

redditor = await reddit.redditor("spez")
redditor.comments.top(time_filter="year")

redditor = await reddit.redditor("spez")
redditor.submissions.top(time_filter="all")

subreddit = await reddit.subreddit("all")
subreddit.top(time_filter="hour")
await trophies() List[asyncpraw.models.Trophy]

Return a list of the redditor’s trophies.

Returns

A list of Trophy objects. Return [] if the redditor has no trophies.

Raises

RedditAPIException if the redditor doesn’t exist.

Usage:

redditor = await reddit.redditor("spez")
async for trophy in redditor.trophies():
    print(trophy.name)
    print(trophy.description)
await trust()

Add the Redditor to your whitelist of trusted users.

Trusted users will always be able to send you PMs.

Example usage:

redditor = await reddit.redditor("AaronSw")
await redditor.trust()

Use the accept_pms parameter of Preferences.update() to toggle your accept_pms setting between "everyone" and "whitelisted". For example:

# Accept private messages from everyone:
await reddit.user.preferences.update(accept_pms="everyone")
# Only accept private messages from trusted users:
await reddit.user.preferences.update(accept_pms="whitelisted")

You may trust a user even if your accept_pms setting is switched to "everyone".

Note

You are allowed to have a user on your blocked list and your friends list at the same time. However, you cannot trust a user who is on your blocked list.

await unblock()

Unblock the Redditor.

For example, to unblock Redditor u/spez:

redditor = await reddit.redditor("spez")
await redditor.unblock()
await unfriend()

Unfriend the Redditor.

For example, to unfriend Redditor u/spez:

redditor = await reddit.redditor("spez")
await redditor.unfriend()
upvoted(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Union[asyncpraw.models.Comment, asyncpraw.models.Submission]]

Return a ListingGenerator for items the user has upvoted.

Returns

A ListingGenerator object which yields Comment or Submission objects the user has upvoted.

Raises

asyncprawcore.Forbidden if the user is not authorized to access the list.

Note

Since this function returns a ListingGenerator the exception may not occur until sometime after this function has returned.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get all upvoted items of the authenticated user:

current_user = await reddit.user.me()
async for item in current_user.upvoted():
    print(item.id)

Submission

class asyncpraw.models.Submission(reddit: asyncpraw.Reddit, id: Optional[str] = None, url: Optional[str] = None, _data: Optional[Dict[str, Any]] = None)

A class for submissions to Reddit.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

author

Provides an instance of Redditor.

author_flair_text

The text content of the author’s flair, or None if not flaired.

clicked

Whether or not the submission has been clicked by the client.

comments

Provides an instance of CommentForest.

created_utc

Time the submission was created, represented in Unix Time.

distinguished

Whether or not the submission is distinguished.

edited

Whether or not the submission has been edited.

id

ID of the submission.

is_original_content

Whether or not the submission has been set as original content.

is_self

Whether or not the submission is a selfpost (text-only).

link_flair_template_id

The link flair’s ID.

link_flair_text

The link flair’s text content, or None if not flaired.

locked

Whether or not the submission has been locked.

name

Fullname of the submission.

num_comments

The number of comments on the submission.

over_18

Whether or not the submission has been marked as NSFW.

permalink

A permalink for the submission.

poll_data

A PollData object representing the data of this submission, if it is a poll submission.

saved

Whether or not the submission is saved.

score

The number of upvotes for the submission.

selftext

The submissions’ selftext - an empty string if a link post.

spoiler

Whether or not the submission has been marked as a spoiler.

stickied

Whether or not the submission is stickied.

subreddit

Provides an instance of Subreddit.

title

The title of the submission.

upvote_ratio

The percentage of upvotes from all votes on the submission.

url

The URL the submission links to, or the permalink if a selfpost.

__init__(reddit: asyncpraw.Reddit, id: Optional[str] = None, url: Optional[str] = None, _data: Optional[Dict[str, Any]] = None)

Initialize a Submission instance.

Parameters
  • reddit – An instance of Reddit.

  • id – A reddit base36 submission ID, e.g., "2gmzqe".

  • url – A URL supported by id_from_url().

Either id or url can be provided, but not both.

await award(*, gild_type: str = 'gid_2', is_anonymous: bool = True, message: str = None) dict

Award the author of the item.

Parameters
  • gild_type – Type of award to give. See table below for currently know global award types.

  • is_anonymous – If True, the authenticated user’s username will not be revealed to the recipient.

  • message – Message to include with the award.

Returns

A dict containing info similar to what is shown below:

{
    "subreddit_balance": 85260,
    "treatment_tags": [],
    "coins": 8760,
    "gildings": {"gid_1": 0, "gid_2": 1, "gid_3": 0},
    "awarder_karma_received": 4,
    "all_awardings": [
        {
            "giver_coin_reward": 0,
            "subreddit_id": None,
            "is_new": False,
            "days_of_drip_extension": 0,
            "coin_price": 75,
            "id": "award_9663243a-e77f-44cf-abc6-850ead2cd18d",
            "penny_donate": 0,
            "coin_reward": 0,
            "icon_url": "https://www.redditstatic.com/gold/awards/icon/SnooClappingPremium_512.png",
            "days_of_premium": 0,
            "icon_height": 512,
            "tiers_by_required_awardings": None,
            "icon_width": 512,
            "static_icon_width": 512,
            "start_date": None,
            "is_enabled": True,
            "awardings_required_to_grant_benefits": None,
            "description": "For an especially amazing showing.",
            "end_date": None,
            "subreddit_coin_reward": 0,
            "count": 1,
            "static_icon_height": 512,
            "name": "Bravo Grande!",
            "icon_format": "APNG",
            "award_sub_type": "PREMIUM",
            "penny_price": 0,
            "award_type": "global",
            "static_icon_url": "https://i.redd.it/award_images/t5_q0gj4/59e02tmkl4451_BravoGrande-Static.png",
        }
    ],
}

Warning

Requires the authenticated user to own Reddit Coins. Calling this method will consume Reddit Coins.

To award the gold award anonymously do:

comment = await reddit.comment("dkk4qjd")
await comment.award()

submission = await reddit.submission("8dmv8z")
await submission.award()

To award the platinum award with the message ‘Nice!’ and reveal your username to the recipient do:

comment = await reddit.comment("dkk4qjd")
await comment.award(gild_type="gild_3", message="Nice!", is_anonymous=False)

submission = await reddit.submission("8dmv8z")
await submission.award(gild_type="gild_3", message="Nice!", is_anonymous=False)

This is a list of known global awards (as of 10/25/2020)

Name

Icon

Gild Type

Description

Cost

Silver

https://www.redditstatic.com/gold/awards/icon/silver_64.png

gid_1

Shows the Silver Award… and that’s it.

100

Gold

https://www.redditstatic.com/gold/awards/icon/gold_64.png

gid_2

Gives the author a week of Reddit Premium, %{coin_symbol}100 Coins to do with as they please, and shows a Gold Award.

500

Platinum

https://www.redditstatic.com/gold/awards/icon/platinum_64.png

gid_3

Gives the author a month of Reddit Premium, which includes %{coin_symbol}700 Coins for that month, and shows a Platinum Award.

1800

LOVE!

https://preview.redd.it/award_images/t5_22cerq/j3azv69qjfn51_LOVE.png?width=64&height=64&crop=smart&auto=webp&s=405d338bf34818596ab84bc26a09316917def8bb

award_5eac457f-ebac-449b-93a7-eb17b557f03c

When you follow your heart, love is the answer

20

Starstruck

https://www.redditstatic.com/gold/awards/icon/Starstruck_64.png

award_abb865cf-620b-4219-8777-3658cf9091fb

Can’t stop seeing stars

20

All-Seeing Upvote

https://preview.redd.it/award_images/t5_22cerq/rg960rc47jj41_All-SeeingUpvote.png?width=64&height=64&crop=smart&auto=webp&s=46a9f176646afded7050299a1fbad5c66e6ed1e6

award_b4ff447e-05a5-42dc-9002-63568807cfe6

A glowing commendation for all to see

30

Narwhal Salute

https://preview.redd.it/award_images/t5_22cerq/80j20o397jj41_NarwhalSalute.png?width=64&height=64&crop=smart&auto=webp&s=8629e84ef3188ad75ebca713afb4a0f97e4c3c70

award_a2506925-fc82-4d6c-ae3b-b7217e09d7f0

A golden splash of respect

30

Wholesome Seal of Approval

https://preview.redd.it/award_images/t5_22cerq/b9ks3a5k7jj41_WholesomeSealofApproval.png?width=64&height=64&crop=smart&auto=webp&s=2bcedd41a51b17ff305fc0ec6eb7c5a631a90c60

award_c4b2e438-16bb-4568-88e7-7893b7662944

A glittering stamp for a feel-good thing

30

Ally

https://preview.redd.it/award_images/t5_22cerq/5nswjpyy44551_Ally.png?width=64&height=64&crop=smart&auto=webp&s=655fb8310589a3964a82ac0e56d016eb97aa6d4d

award_69c94eb4-d6a3-48e7-9cf2-0f39fed8b87c

Listen, get educated, and get involved.

50

I am disappoint

https://preview.redd.it/award_images/t5_22cerq/3ekkailk5s551_Iamdisappoint.png?width=64&height=64&crop=smart&auto=webp&s=3aa59d2aa096aba2d6cba9709f79b788676e3731

award_03c4f93d-efc7-463b-98a7-c01814462ab0

I’m not mad, I’m just disappointed.

50

Looking Busy

https://i.redd.it/award_images/t5_22cerq/k0qzautvyyk51_LookingBusy.png

award_d33fddd7-a58a-4472-b1a2-3157d8c8b76f

Looking like you’re working is hard work.

50

Take My Energy

https://preview.redd.it/award_images/t5_22cerq/898sygoknoo41_TakeMyEnergy.png?width=64&height=64&crop=smart&auto=webp&s=e62f7cf1108ff17381b1ed42b1edca26f721dce0

award_02d9ab2c-162e-4c01-8438-317a016ed3d9

I’m in this with you.

50

Wearing is Caring

https://preview.redd.it/award_images/t5_22cerq/lcswc5d07hb51_WearingisCaring.png?width=64&height=64&crop=smart&auto=webp&s=50da94b41c2b6c8bbe2723243ed0985059bba9fa

award_80d4d339-95d0-43ac-b051-bc3fe0a9bab8

Keep the community and yourself healthy and happy.

50

Facepalm

https://preview.redd.it/award_images/t5_22cerq/ey2iodron2s41_Facepalm.png?width=64&height=64&crop=smart&auto=webp&s=9d3c8e8642dc97c655867ea5ba37b7d76d653203

award_b1b44fa1-8179-4d84-a9ed-f25bb81f1c5f

Lowers face into palm

70

Faith In Humanity Restored

https://preview.redd.it/award_images/t5_22cerq/gva4vt20qc751_FaithInHumanityRestored.png?width=64&height=64&crop=smart&auto=webp&s=a76d915a6eb1cd6d5efa2e0280d90740d2f74de9

award_7becef23-fb0b-4d62-b8a6-01d5759367cb

When goodness lifts you

70

Snek

https://preview.redd.it/award_images/t5_22cerq/rc5iesz2z8t41_Snek.png?width=64&height=64&crop=smart&auto=webp&s=2856d19d59c0af0d38fd0b6058622f6a1e91956a

award_99d95969-6100-45b2-b00c-0ec45ae19596

A smol, delicate danger noodle.

70

Tree Hug

https://preview.redd.it/award_images/t5_22cerq/fukjtec638u41_TreeHug.png?width=64&height=64&crop=smart&auto=webp&s=b46d14cae99b5519775167d0aea8418c480c28c0

award_b92370bb-b7de-4fb3-9608-c5b4a22f714a

Show nature some love.

70

Bravo Grande!

https://www.redditstatic.com/gold/awards/icon/SnooClappingPremium_64.png

award_9663243a-e77f-44cf-abc6-850ead2cd18d

For an especially amazing showing.

75

Party Train

https://www.redditstatic.com/gold/awards/icon/Train/Train_silver_64.png

award_75f9bc56-eba3-4988-a1af-aec974404a0b

All aboard! Every 5 Awards from everyone gives the author 100 Coins and 1 week of Premium. Rack up the number of Awards and watch the Train level-up.

75

Take My Power

https://www.redditstatic.com/gold/awards/icon/TakeMyPower_64.png

award_92cb6518-a71a-4217-9f8f-7ecbd7ab12ba

Add my power to yours.

75

Hugz

https://preview.redd.it/award_images/t5_22cerq/niiatoknifn51_Hugz.png?width=64&height=64&crop=smart&auto=webp&s=840debef89811f54b3f1b498bddf55c118eb62cb

award_8352bdff-3e03-4189-8a08-82501dd8f835

Everything is better with a good hug

80

‘MURICA

https://preview.redd.it/award_images/t5_22cerq/18mwqw5th9e51_MURICA.png?width=64&height=64&crop=smart&auto=webp&s=759d235c371d6ae8ad5efb1c98a74b259a3ff8fe

award_869d4135-8738-41e5-8630-de593b4f049f

Did somebody say ‘Murica?

100

Cosplay Famous

https://preview.redd.it/award_images/t5_22cerq/7ptj05lgqys51_CosplayFamous.png?width=64&height=64&crop=smart&auto=webp&s=405250108b91c08113cd9c38b4d872d9b521d116

award_6f0a496f-c3e2-484c-90d0-d26bffb2e286

The perfect cosplay doesn’t exis…

100

Dread

https://preview.redd.it/award_images/t5_22cerq/nvfe4gyawnf51_Dread.png?width=64&height=64&crop=smart&auto=webp&s=34247d8bba8dc5aa7eaed6e81135da0c935d37f3

award_81cf5c92-8500-498c-9c94-3e4034cece0a

Staring into the abyss and it’s staring right back

100

Evil Cackle

https://preview.redd.it/award_images/t5_22cerq/43zl6dfcg9e51_EvilCackle.png?width=64&height=64&crop=smart&auto=webp&s=bd7d6c66b7594ac91ff2d8a7d86340a0f49a153c

award_483d8e29-bbe5-404e-a09a-c2d7b16c4fff

Laugh like a supervillain

100

Excited

https://preview.redd.it/award_images/t5_22cerq/x069ow7ewnf51_Excited.png?width=64&height=64&crop=smart&auto=webp&s=b1d186a93a86d3bae5ad3bee36e41a9e93d35281

award_74fe5152-7906-4991-9016-bc2d8e261200

I don’t know what to do with my hands!

100

Glow Up

https://preview.redd.it/award_images/t5_22cerq/2754pa5jvsj51_GlowUp.png?width=64&height=64&crop=smart&auto=webp&s=60f710eccc52d9d05db204bb2b962372a1e45671

award_01178870-6a4f-4172-8f36-9ed5092ee4f9

You look amazing, glowing, incredible!

100

Heartwarming

https://preview.redd.it/award_images/t5_22cerq/v1mxw8i6wnf51_Heartwarming.png?width=64&height=64&crop=smart&auto=webp&s=c09f506dc0be92c9849ee7dd2cfe9d65852d6064

award_19860e30-3331-4bac-b3d1-bd28de0c7974

I needed this today

100

I’ll Drink to That

https://preview.redd.it/award_images/t5_22cerq/45aeu8mzvsj51_IllDrinktoThat.png?width=64&height=64&crop=smart&auto=webp&s=94580e58d47d0a1eb1c6cc776437c574b5bbad7c

award_3267ca1c-127a-49e9-9a3d-4ba96224af18

Let’s sip to good health and good company

100

Keep Calm

https://preview.redd.it/award_images/t5_22cerq/g77c4oud7hb51_KeepCalm.png?width=64&height=64&crop=smart&auto=webp&s=9510d2496464d0fa8ff2288e1f0e17f114226383

award_1da6ff27-7c0d-4524-9954-86e5cda5fcac

Stop, chill, relax

100

Kiss

https://preview.redd.it/award_images/t5_22cerq/sb42u5gmwsj51_Kiss.png?width=64&height=64&crop=smart&auto=webp&s=12e56d5bba8f00fe467d3efe0c962e70bcbc92ed

award_1e516e18-cbee-4668-b338-32d5530f91fe

You deserve a smooch

100

Last Minute Costume

https://preview.redd.it/award_images/t5_22cerq/icn71p34nct51_LastMinuteCostume.png?width=64&height=64&crop=smart&auto=webp&s=f6865e93870b4386ab4a7c32662200b961870d22

award_a0c3e268-87e7-4918-9a36-f6aa462e4dee

Any costume beats none

100

Lawyer Up

https://preview.redd.it/award_images/t5_22cerq/iq0sgwn5bzy41_LawyerUp.png?width=64&height=64&crop=smart&auto=webp&s=3baf45de6ba3e1535df885b91a2aa714e5ece9d5

award_ae89e420-c4a5-47b8-a007-5dacf1c0f0d4

OBJECTION!

100

Masterpiece

https://preview.redd.it/award_images/t5_22cerq/2juh333m40n51_Masterpiece.png?width=64&height=64&crop=smart&auto=webp&s=0183ad39a56ba3e46c4bcb5d8938392f75d5d9d5

award_b4072731-c0fb-4440-adc7-1063d6a5e6a0

C’est magnifique

100

Shocked

https://preview.redd.it/award_images/t5_22cerq/fck3iedi2ug51_Shocked.png?width=64&height=64&crop=smart&auto=webp&s=627fbd255cb9cce5b72551255cb061bf0c8af71a

award_fbe9527a-adb3-430e-af1a-5fd3489e641b

I’m genuinely flabbergasted.

100

Spacefaring Snoo

https://preview.redd.it/award_images/t5_22cerq/0dy3wj06qys51_SpacefaringSnoo.png?width=64&height=64&crop=smart&auto=webp&s=fb6e1c4f29f00c5229c58b769f788842f4bcb85d

award_a3df1615-dcf8-4f5f-ac7c-3c2be31332a7

On a vision quest to make life multi-planetary

100

Sweet Tooth

https://preview.redd.it/award_images/t5_22cerq/gbsaculna3u51_SweetTooth.png?width=64&height=64&crop=smart&auto=webp&s=5ce49bdf63d850847bb4dfced763fb80a8a99024

award_bd6ccb1d-118a-462a-a451-f550cd3133d2

It’s not a sugar rush, it’s a lifestyle.

100

Tearing Up

https://preview.redd.it/award_images/t5_22cerq/lop66ut2wnf51_TearingUp.png?width=64&height=64&crop=smart&auto=webp&s=a6ee8b3c876bdc7a022072134f8157a7ea85d884

award_43f3bf99-92d6-47ab-8205-130d26e7929f

This hits me right in the feels

100

Yummy

https://preview.redd.it/award_images/t5_22cerq/a7dhg27hvnf51_Yummy.png?width=64&height=64&crop=smart&auto=webp&s=7a70c563dbc8bb2659271ddd451c8e657f3a3aa8

award_ae7f17fb-6538-4c75-9ff4-5f48b4cdaa94

That looks so good

100

Wholesome

https://preview.redd.it/award_images/t5_22cerq/5izbv4fn0md41_Wholesome.png?width=64&height=64&crop=smart&auto=webp&s=89a077c4955b50fa2e57449eebf8c19e7f23ceb7

award_5f123e3d-4f48-42f4-9c11-e98b566d5897

When you come across a feel-good thing.

125

Bless Up

https://preview.redd.it/award_images/t5_22cerq/trfv6ems1md41_BlessUp.png?width=64&height=64&crop=smart&auto=webp&s=5e84fe0dae062adff22f01c384d86c0633d06b28

award_77ba55a2-c33c-4351-ac49-807455a80148

Prayers up for the blessed.

150

Buff Doge

https://preview.redd.it/award_images/t5_22cerq/zc4a9vk5zmc51_BuffDoge.png?width=64&height=64&crop=smart&auto=webp&s=04b5cf5717304307515af46c73431f11bb66c3bd

award_c42dc561-0b41-40b6-a23d-ef7e110e739e

So buff, wow

150

Cake

https://preview.redd.it/award_images/t5_22cerq/aoa99054n2s41_Cake.png?width=64&height=64&crop=smart&auto=webp&s=a1564ae45fe22bcd07a9a98d0b4c321c497ba194

award_5fb42699-4911-42a2-884c-6fc8bdc36059

Did someone say… cake?

150

Helpful

https://preview.redd.it/award_images/t5_22cerq/klvxk1wggfd41_Helpful.png?width=64&height=64&crop=smart&auto=webp&s=cc59d3722210878a975f8d97eb62f3092e472693

award_f44611f1-b89e-46dc-97fe-892280b13b82

Thank you stranger. Shows the award.

150

Press F

https://preview.redd.it/award_images/t5_22cerq/tcofsbf92md41_PressF.png?width=64&height=64&crop=smart&auto=webp&s=b33bda0aa0310bbe1877ba2d02a259d7cc52d616

award_88fdcafc-57a0-48db-99cc-76276bfaf28b

To pay respects.

150

Take My Money

https://preview.redd.it/award_images/t5_22cerq/9jr8pv84v7i51_TakeMyMoney.png?width=64&height=64&crop=smart&auto=webp&s=8cae8bb3d91b20e0d13b24010a103842e365ff9f

award_a7f9cbd7-c0f1-4569-a913-ebf8d18de00b

I’m buying what you’re selling

150

Giggle

https://www.redditstatic.com/gold/awards/icon/Giggle_64.png

award_e813313c-1002-49bf-ac37-e966710f605f

Innocent laughter

200

Got the W

https://preview.redd.it/award_images/t5_22cerq/9avdcwgupta41_GottheW.png?width=64&height=64&crop=smart&auto=webp&s=d7c1acaee0770a6a0ff7853606ba9992824cdcec

award_8dc476c7-1478-4d41-b940-f139e58f7756

200

I’d Like to Thank…

https://preview.redd.it/award_images/t5_22cerq/8ad2jffnclf41_Thanks.png?width=64&height=64&crop=smart&auto=webp&s=430fa4cf2928cc37ed0a3344c8da31277a53929c

award_1703f934-cf44-40cc-a96d-3729d0b48262

My kindergarten teacher, my cat, my mom, and you.

200

I’m Deceased

https://preview.redd.it/award_images/t5_22cerq/2jd92wtn25g41_ImDeceased.png?width=64&height=64&crop=smart&auto=webp&s=106ba80d6001af5b5b47b874b4f86da6ca88113f

award_b28d9565-4137-433d-bb65-5d4aa82ade4c

Call an ambulance, I’m laughing too hard.

200

Looking

https://preview.redd.it/award_images/t5_22cerq/kjpl76213ug51_Looking.png?width=64&height=64&crop=smart&auto=webp&s=5d6beac8304bc8fe28e0d6acb1b4b1339abecc67

award_4922c1be-3646-4d62-96ea-19a56798df51

I can’t help but look.

200

Plus One

https://preview.redd.it/award_images/t5_22cerq/6vgr8y21i9741_PlusOne.png?width=64&height=64&crop=smart&auto=webp&s=ecea37cb71525e80d9ca2dbf2bd504b9f934606e

award_f7562045-905d-413e-9ed2-0a16d4bfe349

You officially endorse and add your voice to the crowd.

200

Stonks Falling

https://preview.redd.it/award_images/t5_22cerq/ree13odobef41_StonksFalling.png?width=64&height=64&crop=smart&auto=webp&s=b1016427b3550d229b4ec93437ac8b69c28c5ae2

award_9ee30a8f-463e-4ef7-9da9-a09f270ec026

Losing value fast.

200

Stonks Rising

https://preview.redd.it/award_images/t5_22cerq/s5edqq9abef41_StonksRising.png?width=64&height=64&crop=smart&auto=webp&s=8c11db37505feb2a3e4130eb15e9470e72e65b63

award_d125d124-5c03-490d-af3d-d07c462003da

To the MOON.

200

This is 2020

https://preview.redd.it/award_images/t5_22cerq/ncon692ev7i51_Thisis2020.png?width=64&height=64&crop=smart&auto=webp&s=eb415a44432807861d7bac64d9e26c5c6ea194bb

award_dc391ef9-0df8-468f-bd3c-7b177092de35

Every reason to be alarmed

200

1UP

https://www.redditstatic.com/gold/awards/icon/Levelup_64.png

award_11be92ba-509e-46d3-991b-593239006521

Extra life

250

Awesome Answer

https://preview.redd.it/award_images/t5_22cerq/71v56o5a5v541_AwesomeAnswer.png?width=64&height=64&crop=smart&auto=webp&s=a6c7ee017a2cbab3e291b81823eb179faeb96b99

award_2adc49e8-d6c9-4923-9293-2bfab1648569

For a winning take and the kind soul who nails a question. Gives %{coin_symbol}100 Coins to both the author and the community.

250

It’s Cute!

https://preview.redd.it/award_images/t5_22cerq/n94bgm83in941_ItsCute.png?width=64&height=64&crop=smart&auto=webp&s=2632d9c9236d0501427072373b789fdb5a59377a

award_cc540de7-dfdb-4a68-9acf-6f9ce6b17d21

You made me UwU.

250

Mind Blown

https://preview.redd.it/award_images/t5_22cerq/wa987k0p4v541_MindBlown.png?width=64&height=64&crop=smart&auto=webp&s=5bcf973d6d2b64223cc5a2995c95b797bcf68dd2

award_9583d210-a7d0-4f3c-b0c7-369ad579d3d4

When a thing immediately combusts your brain. Gives %{coin_symbol}100 Coins to both the author and the community.

250

Original

https://preview.redd.it/award_images/t5_22cerq/b8xt4z8yajz31_Original.png?width=64&height=64&crop=smart&auto=webp&s=8ca70e1f45c2ddca559d456a74798fcedf36427e

award_d306c865-0d49-4a36-a1ab-a4122a0e3480

When something new and creative wows you. Gives %{coin_symbol}100 Coins to both the author and the community.

250

Timeless Beauty

https://www.redditstatic.com/gold/awards/icon/Timeless_512.png

award_31260000-2f4a-4b40-ad20-f5aa46a577bf

Beauty that’s forever. Gives %{coin_symbol}100 Coins each to the author and the community.

250

Today I Learned

https://preview.redd.it/award_images/t5_22cerq/bph2png4ajz31_TodayILearned.png?width=64&height=64&crop=smart&auto=webp&s=0dec60a8d3226978d4b824226b0c864b663293b3

award_a67d649d-5aa5-407e-a98b-32fd9e3a9696

The more you know… Gives %{coin_symbol}100 Coins to both the author and the community.

250

Yas Queen

https://preview.redd.it/award_images/t5_22cerq/kthj3e4h3bm41_YasQueen.png?width=64&height=64&crop=smart&auto=webp&s=98b385524aee26412e9dcf25bd20b4cff0eb2376

award_d48aad4b-286f-4a3a-bb41-ec05b3cd87cc

YAAAAAAAAAAASSS.

250

Coin Gift

https://preview.redd.it/award_images/t5_22cerq/cr1mq4yysv541_CoinGift.png?width=64&height=64&crop=smart&auto=webp&s=d39d0850925a193c9f2ca8203243c694d15fb40a

award_3dd248bc-3438-4c5b-98d4-24421fd6d670

Give the gift of %{coin_symbol}250 Reddit Coins.

300

Crab Rave

https://www.redditstatic.com/gold/awards/icon/CrabRave_64.png

award_f7a4fd5e-7cd1-4c11-a1c9-c18d05902e81

[Happy crab noises]

300

Frankensnoo

https://www.redditstatic.com/gold/awards/icon/Electric_64.png

award_aef30fbe-92e4-4593-8aa7-4b82cfe8d172

It’s Alive!!! Spread the Spooktober spirit.

300

GOAT

https://preview.redd.it/award_images/t5_22cerq/x52x5be57fd41_GOAT.png?width=64&height=64&crop=smart&auto=webp&s=d8a0ff8871eeebadc700284d0186073b8e56ac58

award_cc299d65-77de-4828-89de-708b088349a0

Historical anomaly - greatest in eternity.

300

Rocket Like

https://preview.redd.it/award_images/t5_22cerq/94pn64yuas941_RocketLike.png?width=64&height=64&crop=smart&auto=webp&s=381ec4bd15ab6029d5009a180f749093de815e60

award_28e8196b-d4e9-45bc-b612-cd4c7d3ed4b3

When an upvote just isn’t enough, smash the Rocket Like.

300

Spooky Season

https://www.redditstatic.com/gold/awards/icon/Spooky_64.png

award_176a3f8a-2229-4a12-bcdc-86464cfd6dc1

Too spooky for me. Spread the Spooktober spirit.

300

Table Flip

https://preview.redd.it/award_images/t5_22cerq/a05z7bb9v7i51_TableFlip.png?width=64&height=64&crop=smart&auto=webp&s=3efc978414612ce3b518813a124501b8a204e56b

award_3e000ecb-c1a4-49dc-af14-c8ac2029ca97

ARGH!

300

This

https://preview.redd.it/award_images/t5_22cerq/vu6om0xnb7e41_This.png?width=64&height=64&crop=smart&auto=webp&s=4b2a7c5439da6b4a9e2173bbf3cf9a610538600d

award_68ba1ee3-9baf-4252-be52-b808c1e8bdc4

THIS right here! Join together to give multiple This awards and see the award evolve in its display and shower benefits for the recipient. For every 3 This awards given to a post or comment, the author will get 250 coins.

300

Updoot

https://preview.redd.it/award_images/t5_22cerq/7atjjqpy1mc41_Updoot.png?width=64&height=64&crop=smart&auto=webp&s=f07dcd6402653b86d321cff6ded773cfa13d918a

award_725b427d-320b-4d02-8fb0-8bb7aa7b78aa

Sometimes you just got to doot.

300

Spit-take

https://www.redditstatic.com/gold/awards/icon/Spits_drink_64.png

award_3409a4c0-ba69-43a0-be9f-27bc27c159cc

Shower them with laughs

325

Super Heart Eyes

https://www.redditstatic.com/gold/awards/icon/Superheart_64.png

award_6220ecfe-4552-4949-aa13-fb1fb7db537c

When the love is out of control.

325

Table Slap

https://www.redditstatic.com/gold/awards/icon/TableSlap_64.png

award_9f928aff-c9f5-4e7e-aa91-8619dce60f1c

When laughter meets percussion

325

To The Stars

https://www.redditstatic.com/gold/awards/icon/Rocket_64.png

award_2bc47247-b107-44a8-a78c-613da21869ff

Boldly go where we haven’t been in a long, long time.

325

Aww-some

https://www.redditstatic.com/gold/awards/icon/Awwsome2_64.png

award_e55d1889-11f2-4d04-8abb-44b1de7dd53d

Use the Aww-some Award to highlight comments that are absolutely adorable.

350

Heartbeat

https://www.redditstatic.com/gold/awards/icon/Heartbeat_64.png

award_11eb6af3-3d0d-4d70-8261-22d216ab591d

Use the Heartbeat Award to highlight comments that make you feel warm and fuzzy

350

Into the Magic Portal

https://www.redditstatic.com/gold/awards/icon/TeleportIn_64.png

award_2ff1fdd0-ff73-47e6-a43c-bde6d4de8fbd

Hope to make it to the other side.

350

Out of the Magic Portal

https://www.redditstatic.com/gold/awards/icon/TeleportOut_64.png

award_7fe72f36-1141-4a39-ba76-0d481889b390

That was fun, but I’m glad to be back

350

Bravo!

https://www.redditstatic.com/gold/awards/icon/SnooClapping_64.png

award_84276b1e-cc8f-484f-a19c-be6c09adc1a5

An amazing showing.

400

Doot 🎵 Doot

https://www.redditstatic.com/gold/awards/icon/Updoot_64.png

award_5b39e8fd-7a58-4cbe-8ca0-bdedd5ed1f5a

Sometimes you just got to dance with the doots.

400

Pumpkin Spice

https://preview.redd.it/award_images/t5_22cerq/c1ll7h6zedq51_PumpkinSpice.png?width=64&height=64&crop=smart&auto=webp&s=c8a3297c17b9b70255353e933f5ed0a5b5bb3934

award_89164d08-80db-453b-a7aa-74c50fa84bfa

Autumn the beverage brings a bounty of 300 coins to the lucky recipient.

400

Bless Up (Pro)

https://preview.redd.it/award_images/t5_22cerq/xe5mw55w5v541_BlessUp.png?width=64&height=64&crop=smart&auto=webp&s=54b7d71c74cf41fc8ada4a2110babf8b68d2f172

award_43c43a35-15c5-4f73-91ef-fe538426435a

Prayers up for the blessed. Gives %{coin_symbol}100 Coins to both the author and the community.

500

Brighten My Day

https://www.redditstatic.com/gold/awards/icon/Sunny_64.png

award_9591a26e-b2e4-4ef2-bed4-28ff69246691

The clouds part and the sun shines through. Use the Brighten My Day Award to highlight comments that are a ray of sunshine.

500

Eureka!

https://www.redditstatic.com/gold/awards/icon/Bulb_64.png

award_65f78ca2-45d8-4cb6-bf79-a67beadf2e47

Now that is a bright idea. Use the Eureka Award to highlight comments that are brilliant.

500

Heart Eyes

https://preview.redd.it/award_images/t5_22cerq/12kz7a7j4v541_HeartEyes.png?width=64&height=64&crop=smart&auto=webp&s=02bb7182aad468e16e0a711b594110225679c79e

award_a9009ea5-1a36-42ae-aab2-5967563ee054

For love at first sight. Gives %{coin_symbol}100 Coins to both the author and the community.

500

Helpful (Pro)

https://preview.redd.it/award_images/t5_22cerq/trz28na8ajz31_Helpful.png?width=64&height=64&crop=smart&auto=webp&s=5dfea529ee529d33105b592b42696d05e7b734c2

award_2ae56630-cfe0-424e-b810-4945b9145358

Thank you stranger. Gives %{coin_symbol}100 Coins to both the author and the community.

500

Made Me Smile

https://preview.redd.it/award_images/t5_22cerq/hwnbr9l67s941_MadeMeSmile.png?width=64&height=64&crop=smart&auto=webp&s=918705b3b6804a6151b6ce4f8b1c86dfa604a470

award_a7a04d6a-8dd8-41bb-b906-04fa8f144014

When you’re smiling before you know it. Gives %{coin_symbol}100 Coins to both the author and the community.

500

Snoo Nice

https://preview.redd.it/award_images/t5_22cerq/9r7hexe6pta41_SnooNice.png?width=64&height=64&crop=smart&auto=webp&s=88748b0fe08311b512dc08909acdcdbe8d91d747

award_27d3176c-b388-4616-80ec-11b8ece5b7ee

Gives the author a week of Reddit Premium and %{coin_symbol}100 Coins to do with as they please.

500

Starry

https://www.redditstatic.com/gold/awards/icon/Starry_512.png

award_0e957fb0-c8f1-4ba1-a8ef-e1e524b60d7d

Use the Starry Award to highlight comments that deserve to stand out from the crowd.

500

Wholesome (Pro)

https://preview.redd.it/award_images/t5_22cerq/0o2j782f00e41_WholesomeSuperpro.png?width=64&height=64&crop=smart&auto=webp&s=2a04235b56e4fbc90106067bfe0d61bd60300c4f

award_1f0462ee-18f5-4f33-89cf-f1f79336a452

When you come across a feel-good thing. Gives %{coin_symbol}100 Coins to both the author and the community.

500

Pot o’ Coins

https://preview.redd.it/award_images/t5_22cerq/wg3lzllyg9n41_PotoCoins.png?width=64&height=64&crop=smart&auto=webp&s=7bb8b7ab622f25b5e6f7f2068663b5ea964d2957

award_35c78e6e-507b-4f1d-b3d8-ed43840909a8

The treasure at the end of the rainbow. Gives the author 800 Coins to do with as they please.

1000

Cornucopia

https://preview.redd.it/award_images/t5_22cerq/27xs8z0ja3u51_Cornucopia.png?width=64&height=64&crop=smart&auto=webp&s=4298b88d2511a0951817f440fe5244f6dcf513a9

award_9a123cdb-d26d-4d0c-b7fa-46750b8289fa

A candy cornucopia of love that gives the author a bounty of 1500 Coins.

2000

Argentium

https://www.redditstatic.com/gold/awards/icon/Mithril_64.png

award_4ca5a4e6-8873-4ac5-99b9-71b1d5161a91

Latin for distinguished. Shimmers like silver & stronger than steel. When someone deserves outsize recognition. This award gives a three-month Premium subscription and 2500 coins to the recipient.

20000

Ternion All-Powerful

https://www.redditstatic.com/gold/awards/icon/Trinity_64.png

award_2385c499-a1fb-44ec-b9b7-d260f3dc55de

Legendary level. A no holds barred celebration of something that hits you in the heart, mind and soul. Some might call it unachievanium. Gives the author 6 months of Premium and 5000 Coins.

50000

await clear_vote()

Clear the authenticated user’s vote on the object.

Note

Votes must be cast by humans. That is, API clients proxying a human’s action one-for-one are OK, but bots deciding how to vote on content or amplifying a human’s vote are not. See the reddit rules for more details on what constitutes vote manipulation. [Ref]

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.clear_vote()

comment = await reddit.comment("dxolpyc", fetch=False)
await comment.clear_vote()
comments

Provide an instance of CommentForest.

This attribute can be used, for example, to obtain a flat list of comments, with any MoreComments removed:

await submission.comments.replace_more(limit=0)
comments = submission.comments.list()
Raises

TypeError if the submission is not fetched.

Sort order and comment limit must be set with the comment_sort and comment_limit attributes before the submission and its comments are fetched, including any call to replace_more(). The fetch argument will need to set when initializing the Submission instance:

submission = await reddit.submission("8dmv8z", fetch=False)
submission.comment_sort = "new"
await submission.load()
comments = submission.comments.list()

Note

The appropriate values for comment_sort include confidence, controversial, new, old, q&a, and top

See Extracting comments with Async PRAW for more on working with a CommentForest.

await crosspost(subreddit: asyncpraw.models.Subreddit, *, flair_id: Optional[str] = None, flair_text: Optional[str] = None, nsfw: bool = False, send_replies: bool = True, spoiler: bool = False, title: Optional[str] = None) asyncpraw.models.Submission

Crosspost the submission to a subreddit.

Note

Be aware you have to be subscribed to the target subreddit.

Parameters
  • subreddit – Name of the subreddit or Subreddit object to crosspost into.

  • flair_id – The flair template to select (default: None).

  • flair_text – If the template’s flair_text_editable value is True, this value will set a custom text (default: None).

  • nsfw – Whether the submission should be marked NSFW (default: False).

  • send_replies – When True, messages will be sent to the created submission’s author when comments are made to the submission (default: True).

  • spoiler – Whether the submission should be marked as a spoiler (default: False).

  • title – Title of the submission. Will use this submission’s title if None (default: None).

Returns

A Submission object for the newly created submission.

Example usage:

submission = await reddit.submission("5or86n")
cross_post = await submission.crosspost("learnprogramming", send_replies=False)

See also

hide()

await delete()

Delete the object.

Example usage:

comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.delete()

submission = await reddit.submission("8dmv8z", fetch=False)
await submission.delete()
await disable_inbox_replies()

Disable inbox replies for the item.

Example usage:

comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.disable_inbox_replies()

submission = await reddit.submission("8dmv8z", fetch=False)
await submission.disable_inbox_replies()
await downvote()

Downvote the object.

Note

Votes must be cast by humans. That is, API clients proxying a human’s action one-for-one are OK, but bots deciding how to vote on content or amplifying a human’s vote are not. See the reddit rules for more details on what constitutes vote manipulation. [Ref]

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.downvote()

comment = await reddit.comment("dxolpyc", fetch=False)
await comment.downvote()

See also

upvote()

duplicates(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Submission]

Return a ListingGenerator for the submission’s duplicates.

Additional keyword arguments are passed in the initialization of ListingGenerator.

Example usage:

submission = await reddit.submission("5or86n", fetch=False)

async for duplicate in submission.duplicates():
    # process each duplicate
    ...

See also

upvote()

await edit(body: str) Union[asyncpraw.models.Comment, asyncpraw.models.Submission]

Replace the body of the object with body.

Parameters

body – The Markdown formatted content for the updated object.

Returns

The current instance after updating its attributes.

Example usage:

comment = await reddit.comment("dkk4qjd")

# construct the text of an edited comment
# by appending to the old body:
edited_body = comment.body + "Edit: thanks for the gold!"
await comment.edit(edited_body)
await enable_inbox_replies()

Enable inbox replies for the item.

Example usage:

comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.enable_inbox_replies()

submission = await reddit.submission("8dmv8z", fetch=False)
await submission.enable_inbox_replies()
flair() SubmissionFlair

Provide an instance of SubmissionFlair.

This attribute is used to work with flair as a regular user of the subreddit the submission belongs to. Moderators can directly use flair().

For example, to select an arbitrary editable flair text (assuming there is one) and set a custom value try:

choices = await submission.flair.choices()
template_id = next(x for x in choices if x["flair_text_editable"])["flair_template_id"]
await submission.flair.select(template_id, text="my custom value")
property fullname: str

Return the object’s fullname.

A fullname is an object’s kind mapping like t3 followed by an underscore and the object’s base36 ID, e.g., t1_c5s96e0.

await gild() dict

Alias for award() to maintain backwards compatibility.

await hide(*, other_submissions: Optional[List[asyncpraw.models.Submission]] = None)

Hide Submission.

Parameters

other_submissions – When provided, additionally hide this list of Submission instances as part of a single request (default: None).

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.hide()

See also

unhide()

staticmethod id_from_url(url: str) str

Return the ID contained within a submission URL.

Parameters

url

A url to a submission in one of the following formats (http urls will also work):

  • "https://redd.it/2gmzqe"

  • "https://reddit.com/comments/2gmzqe/"

  • "https://www.reddit.com/r/redditdev/comments/2gmzqe/praw_https/"

  • "https://www.reddit.com/gallery/2gmzqe"

Raises

InvalidURL if url is not a valid submission URL.

await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
await mark_visited()

Mark submission as visited.

This method requires a subscription to reddit premium.

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.mark_visited()
mod() SubmissionModeration

Provide an instance of SubmissionModeration.

Example usage:

submission = await reddit.submission("8dmv8z", fetch=False)
await submission.mod.approve()
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

await reply(body: str) Optional[Union[asyncpraw.models.Comment, asyncpraw.models.Message]]

Reply to the object.

Parameters

body – The Markdown formatted content for a comment.

Returns

A Comment or Message object for the newly created comment or message or None if Reddit doesn’t provide one.

Raises

asyncprawcore.exceptions.Forbidden when attempting to reply to some items, such as locked submissions/comments or non-replyable messages.

A None value can be returned if the target is a comment or submission in a quarantined subreddit and the authenticated user has not opt-ed in to viewing the content. When this happens the comment will be successfully created on Reddit and can be retried by drawing the comment from the user’s comment history.

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.reply("reply")

comment = await reddit.comment("dxolpyc", fetch=False)
await comment.reply("reply")
await report(reason: str)

Report this object to the moderators of its subreddit.

Parameters

reason – The reason for reporting.

Raises

RedditAPIException if reason is longer than 100 characters.

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.report("report reason")

comment = await reddit.comment("dxolpyc", fetch=False)
await comment.report("report reason")
await save(*, category: Optional[str] = None)

Save the object.

Parameters

category – The category to save to. If the authenticated user does not have Reddit Premium this value is ignored by Reddit (default: None).

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.save(category="view later")

comment = await reddit.comment("dxolpyc", fetch=False)
await comment.save()

See also

unsave()

Return a shortlink to the submission.

For example, https://redd.it/eorhm is a shortlink for https://www.reddit.com/r/announcements/comments/eorhm/reddit_30_less_typing/.

await unhide(*, other_submissions: Optional[List[asyncpraw.models.Submission]] = None)

Unhide Submission.

Parameters

other_submissions – When provided, additionally unhide this list of Submission instances as part of a single request (default: None).

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.unhide()

See also

hide()

await unsave()

Unsave the object.

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.unsave()

comment = await reddit.comment("dxolpyc", fetch=False)
await comment.unsave()

See also

save()

await upvote()

Upvote the object.

Note

Votes must be cast by humans. That is, API clients proxying a human’s action one-for-one are OK, but bots deciding how to vote on content or amplifying a human’s vote are not. See the reddit rules for more details on what constitutes vote manipulation. [Ref]

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.upvote()

comment = await reddit.comment("dxolpyc", fetch=False)
await comment.upvote()

See also

downvote()

Subreddit

class asyncpraw.models.Subreddit(reddit: asyncpraw.Reddit, display_name: Optional[str] = None, _data: Optional[Dict[str, Any]] = None)

A class for Subreddits.

To obtain an instance of this class for r/test execute:

subreddit = await reddit.subreddit("test")

To obtain a lazy instance of this class for subreddit r/test execute:

subreddit = await reddit.subreddit("test")

While r/all is not a real subreddit, it can still be treated like one. The following outputs the titles of the 25 hottest submissions in r/all:

subreddit = await reddit.subreddit("all")
async for submission in subreddit.hot(limit=25):
    print(submission.title)

Multiple subreddits can be combined with a + like so:

subreddit = await reddit.subreddit("redditdev+learnpython")
async for submission in subreddit.top(time_filter="all"):
    print(submission)

Subreddits can be filtered from combined listings as follows.

Note

These filters are ignored by certain methods, including comments, gilded(), and SubredditStream.comments().

subreddit = await reddit.subreddit("all-redditdev")
async for submission in subreddit.new():
    print(submission)

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

can_assign_link_flair

Whether users can assign their own link flair.

can_assign_user_flair

Whether users can assign their own user flair.

created_utc

Time the subreddit was created, represented in Unix Time.

description

Subreddit description, in Markdown.

description_html

Subreddit description, in HTML.

display_name

Name of the subreddit.

icon_img

The URL of the subreddit icon image.

id

ID of the subreddit.

name

Fullname of the subreddit.

over18

Whether the subreddit is NSFW.

public_description

Description of the subreddit, shown in searches and on the “You must be invited to visit this community” page (if applicable).

spoilers_enabled

Whether the spoiler tag feature is enabled.

subscribers

Count of subscribers.

user_is_banned

Whether the authenticated user is banned.

user_is_moderator

Whether the authenticated user is a moderator.

user_is_subscriber

Whether the authenticated user is subscribed.

Note

Trying to retrieve attributes of quarantined or private subreddits will result in a 403 error. Trying to retrieve attributes of a banned subreddit will result in a 404 error.

__init__(reddit: asyncpraw.Reddit, display_name: Optional[str] = None, _data: Optional[Dict[str, Any]] = None)

Initialize a Subreddit instance.

Parameters
  • reddit – An instance of Reddit.

  • display_name – The name of the subreddit.

Note

This class should not be initialized directly. Instead, obtain an instance via:

# to lazily load a subreddit instance
await reddit.subreddit("test")

# to fully load a subreddit instance
await reddit.subreddit("test", fetch=True)
banned() asyncpraw.models.reddit.subreddit.SubredditRelationship

Provide an instance of SubredditRelationship.

For example, to ban a user try:

subreddit = await reddit.subreddit("test")
await subreddit.banned.add("spez", ban_reason="...")

To list the banned users along with any notes, try:

subreddit = await reddit.subreddit("test")
async for ban in subreddit.banned():
    print(f"{ban}: {ban.note}")
collections() asyncpraw.models.reddit.collections.SubredditCollections

Provide an instance of SubredditCollections.

To see the permalinks of all Collections that belong to a subreddit, try:

subreddit = await reddit.subreddit("test")
async for collection in subreddit.collections:
    print(collection.permalink)

To get a specific Collection by its UUID or permalink, use one of the following:

subreddit = await reddit.subreddit("test")

collection = subreddit.collections("some_uuid")
collection = subreddit.collections(
    permalink="https://reddit.com/r/test/collection/some_uuid"
)
comments() CommentHelper

Provide an instance of CommentHelper.

For example, to output the author of the 25 most recent comments of r/test execute:

subreddit = await reddit.subreddit("test")
async for comment in subreddit.comments(limit=25):
    print(comment.author)
contributor() asyncpraw.models.reddit.subreddit.ContributorRelationship

Provide an instance of ContributorRelationship.

Contributors are also known as approved submitters.

To add a contributor try:

subreddit = await reddit.subreddit("test")
await subreddit.contributor.add("spez")
controversial(*, time_filter: str = 'all', **generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for controversial items.

Parameters

time_filter – Can be one of: "all", "day", "hour", "month", "week", or "year" (default: "all").

Raises

ValueError if time_filter is invalid.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").controversial(time_filter="week")

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.controversial(time_filter="day")

redditor = await reddit.redditor("spez")
redditor.controversial(time_filter="month")

redditor = await reddit.redditor("spez")
redditor.comments.controversial(time_filter="year")

redditor = await reddit.redditor("spez")
redditor.submissions.controversial(time_filter="all")

subreddit = await reddit.subreddit("all")
subreddit.controversial(time_filter="hour")
emoji() SubredditEmoji

Provide an instance of SubredditEmoji.

This attribute can be used to discover all emoji for a subreddit:

subreddit = await reddit.subreddit("test")
async for emoji in subreddit.emoji:
    print(emoji)

A single emoji can be lazily retrieved via:

subreddit = await reddit.subreddit("test")
emoji = await subreddit.emoji.get_emoji("emoji_name")

Note

Attempting to access attributes of a nonexistent emoji will result in a ClientException.

filters() asyncpraw.models.reddit.subreddit.SubredditFilters

Provide an instance of SubredditFilters.

For example, to add a filter, run:

subreddit = await reddit.subreddit("all")
await subreddit.filters.add("test")
flair() asyncpraw.models.reddit.subreddit.SubredditFlair

Provide an instance of SubredditFlair.

Use this attribute for interacting with a Subreddit’s flair. For example, to list all the flair for a subreddit which you have the flair moderator permission on try:

subreddit = await reddit.subreddit("test")
async for flair in subreddit.flair():
    print(flair)

Flair templates can be interacted with through this attribute via:

subreddit = await reddit.subreddit("test")
async for template in subreddit.flair.templates:
    print(template)
property fullname: str

Return the object’s fullname.

A fullname is an object’s kind mapping like t3 followed by an underscore and the object’s base36 ID, e.g., t1_c5s96e0.

gilded(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for gilded items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get gilded items in r/test:

subreddit = await reddit.subreddit("test")
async for item in subreddit.gilded():
    print(item.id)
hot(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for hot items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").hot()

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.hot()

redditor = await reddit.redditor("spez")
redditor.hot()

redditor = await reddit.redditor("spez")
redditor.comments.hot()

redditor = await reddit.redditor("spez")
redditor.submissions.hot()

subreddit = await reddit.subreddit("all")
subreddit.hot()
await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
await message(*, from_subreddit: Optional[Union[asyncpraw.models.Subreddit, str]] = None, message: str, subject: str)

Send a message to a Redditor or a Subreddit’s moderators (modmail).

Parameters
  • from_subreddit

    A Subreddit instance or string to send the message from. When provided, messages are sent from the subreddit rather than from the authenticated user.

    Note

    The authenticated user must be a moderator of the subreddit and have the mail moderator permission.

  • message – The message content.

  • subject – The subject of the message.

For example, to send a private message to u/spez, try:

redditor = await reddit.redditor("spez", fetch=False)
await redditor.message(subject="TEST", message="test message from Async PRAW")

To send a message to u/spez from the moderators of r/test try:

redditor = await reddit.redditor("spez", fetch=False)
await redditor.message(
    subject="TEST", message="test message from r/test", from_subreddit="test"
)

To send a message to the moderators of r/test, try:

subreddit = await reddit.subreddit("test")
await subreddit.message(subject="TEST", message="test PM from Async PRAW")
mod() SubredditModeration

Provide an instance of SubredditModeration.

For example, to accept a moderation invite from r/test:

subreddit = await reddit.subreddit("test")
await subreddit.mod.accept_invite()
moderator() asyncpraw.models.reddit.subreddit.ModeratorRelationship

Provide an instance of ModeratorRelationship.

For example, to add a moderator try:

subreddit = await reddit.subreddit("test")
await subreddit.moderator.add("spez")

To list the moderators along with their permissions try:

subreddit = await reddit.subreddit("test")
async for moderator in subreddit.moderator:
    print(f"{moderator}: {moderator.mod_permissions}")
modmail() asyncpraw.models.reddit.subreddit.Modmail

Provide an instance of Modmail.

For example, to send a new modmail from r/test to u/spez with the subject "test" along with a message body of "hello":

subreddit = await reddit.subreddit("test")
await subreddit.modmail.create(subject="test", body="hello", recipient="spez")
muted() asyncpraw.models.reddit.subreddit.SubredditRelationship

Provide an instance of SubredditRelationship.

For example, muted users can be iterated through like so:

subreddit = await reddit.subreddit("test")
async for mute in subreddit.muted():
    print("{mute}: {mute.note}")
new(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for new items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").new()

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.new()

redditor = await reddit.redditor("spez")
redditor.new()

redditor = await reddit.redditor("spez")
redditor.comments.new()

redditor = await reddit.redditor("spez")
redditor.submissions.new()

subreddit = await reddit.subreddit("all")
subreddit.new()
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

await post_requirements() Dict[str, Union[str, int, bool]]

Get the post requirements for a subreddit.

Returns

A dict with the various requirements.

The returned dict contains the following keys:

  • domain_blacklist

  • body_restriction_policy

  • domain_whitelist

  • title_regexes

  • body_blacklisted_strings

  • body_required_strings

  • title_text_min_length

  • is_flair_required

  • title_text_max_length

  • body_regexes

  • link_repost_age

  • body_text_min_length

  • link_restriction_policy

  • body_text_max_length

  • title_required_strings

  • title_blacklisted_strings

  • guidelines_text

  • guidelines_display_policy

For example, to fetch the post requirements for r/test:

subreddit = await reddit.subreddit("test")
post_requirements = await subreddit.post_requirements
print(post_requirements)
quaran() asyncpraw.models.reddit.subreddit.SubredditQuarantine

Provide an instance of SubredditQuarantine.

This property is named quaran because quarantine is a subreddit attribute returned by Reddit to indicate whether or not a subreddit is quarantined.

To opt-in into a quarantined subreddit:

subreddit = await reddit.subreddit("test")
await subreddit.quaran.opt_in()
await random() Optional[asyncpraw.models.Submission]

Return a random Submission.

Returns None on subreddits that do not support the random feature. One example, at the time of writing, is r/wallpapers.

For example, to get a random submission off of r/AskReddit:

subreddit = await reddit.subreddit("AskReddit")
submission = await subreddit.random()
print(submission.title)
random_rising(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Submission]

Return a ListingGenerator for random rising submissions.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get random rising submissions for r/test:

subreddit = await reddit.subreddit("test")
async for submission in subreddit.random_rising():
    print(submission.title)
rising(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Submission]

Return a ListingGenerator for rising submissions.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get rising submissions for r/test:

subreddit = await reddit.subreddit("test")
async for submission in subreddit.rising():
    print(submission.title)
rules() SubredditRules

Provide an instance of SubredditRules.

Use this attribute for interacting with a Subreddit’s rules.

For example, to list all the rules for a subreddit:

subreddit = await reddit.subreddit("test")
async for rule in subreddit.rules:
    print(rule)

Moderators can also add rules to the subreddit. For example, to make a rule called "No spam" in r/test:

subreddit = await reddit.subreddit("test")
await subreddit.rules.mod.add(
    short_name="No spam", kind="all", description="Do not spam. Spam bad"
)
search(query: str, *, sort: str = 'relevance', syntax: str = 'lucene', time_filter: str = 'all', **generator_kwargs: Any) AsyncIterator[asyncpraw.models.Submission]

Return a ListingGenerator for items that match query.

Parameters
  • query – The query string to search for.

  • sort – Can be one of: "relevance", "hot", "top", "new", or "comments". (default: "relevance").

  • syntax – Can be one of: "cloudsearch", "lucene", or "plain" (default: "lucene").

  • time_filter – Can be one of: "all", "day", "hour", "month", "week", or "year" (default: "all").

For more information on building a search query see: https://www.reddit.com/wiki/search

For example, to search all subreddits for "praw" try:

subreddit = await reddit.subreddit("all")
async for submission in subreddit.search("praw"):
    print(submission.title)
await sticky(*, number: int = 1) asyncpraw.models.Submission

Return a Submission object for a sticky of the subreddit.

Parameters

number – Specify which sticky to return. 1 appears at the top (default: 1).

Raises

asyncprawcore.NotFound if the sticky does not exist.

For example, to get the stickied post on r/test:

subreddit = await reddit.subreddit("test")
await subreddit.sticky()
stream() asyncpraw.models.reddit.subreddit.SubredditStream

Provide an instance of SubredditStream.

Streams can be used to indefinitely retrieve new comments made to a subreddit, like:

subreddit = await reddit.subreddit("test")
async for comment in subreddit.stream.comments():
    print(comment)

Additionally, new submissions can be retrieved via the stream. In the following example all submissions are fetched via the special r/all:

subreddit = await reddit.subreddit("all")
async for submission in subreddit.stream.submissions():
    print(submission)
stylesheet() asyncpraw.models.reddit.subreddit.SubredditStylesheet

Provide an instance of SubredditStylesheet.

For example, to add the css data .test{color:blue} to the existing stylesheet:

subreddit = await reddit.subreddit("test")
stylesheet = await subreddit.stylesheet()
stylesheet.stylesheet += ".test{color:blue}"
await subreddit.stylesheet.update(stylesheet.stylesheet)
await submit(title: str, *, collection_id: Optional[str] = None, discussion_type: Optional[str] = None, draft_id: Optional[str] = None, flair_id: Optional[str] = None, flair_text: Optional[str] = None, inline_media: Optional[Dict[str, asyncpraw.models.InlineMedia]] = None, nsfw: bool = False, resubmit: bool = True, selftext: Optional[str] = None, send_replies: bool = True, spoiler: bool = False, url: Optional[str] = None) asyncpraw.models.Submission

Add a submission to the Subreddit.

Parameters
  • title – The title of the submission.

  • collection_id – The UUID of a Collection to add the newly-submitted post to.

  • discussion_type – Set to "CHAT" to enable live discussion instead of traditional comments (default: None).

  • draft_id – The ID of a draft to submit.

  • flair_id – The flair template to select (default: None).

  • flair_text – If the template’s flair_text_editable value is True, this value will set a custom text (default: None). flair_id is required when flair_text is provided.

  • inline_media – A dict of InlineMedia objects where the key is the placeholder name in selftext.

  • nsfw – Whether the submission should be marked NSFW (default: False).

  • resubmit – When False, an error will occur if the URL has already been submitted (default: True).

  • selftext – The Markdown formatted content for a text submission. Use an empty string, "", to make a title-only submission.

  • send_replies – When True, messages will be sent to the submission author when comments are made to the submission (default: True).

  • spoiler – Whether the submission should be marked as a spoiler (default: False).

  • url – The URL for a link submission.

Returns

A Submission object for the newly created submission.

Either selftext or url can be provided, but not both.

For example, to submit a URL to r/test do:

title = "Async PRAW documentation"
url = "https://asyncpraw.readthedocs.io"
subreddit = await reddit.subreddit("test")
await subreddit.submit(title, url=url)

For example, to submit a self post with inline media do:

from asyncpraw.models import InlineGif, InlineImage, InlineVideo

gif = InlineGif(path="path/to/image.gif", caption="optional caption")
image = InlineImage(path="path/to/image.jpg", caption="optional caption")
video = InlineVideo(path="path/to/video.mp4", caption="optional caption")
selftext = "Text with a gif {gif1} an image {image1} and a video {video1} inline"
media = {"gif1": gif, "image1": image, "video1": video}
subreddit = await reddit.subreddit("test")
await subreddit.submit("title", inline_media=media, selftext=selftext)

Note

Inserted media will have a padding of \\n\\n automatically added. This is due to the weirdness with Reddit’s API. Using the example above the result selftext body will look like so:

Text with a gif

![gif](u1rchuphryq51 "optional caption")

an image

![img](srnr8tshryq51 "optional caption")

and video

![video](gmc7rvthryq51 "optional caption")

inline

Note

To submit a post to a subreddit with the "news" flair, you can get the flair id like this:

choices = [template async for template in subreddit.flair.link_templates.user_selectable()]
template_id = next(x for x in choices if x["flair_text"] == "news")["flair_template_id"]
await subreddit.submit("title", flair_id=template_id, url="https://www.news.com/")

See also

Add an image gallery submission to the subreddit.

Parameters
  • title – The title of the submission.

  • images – The images to post in dict with the following structure: {"image_path": "path", "caption": "caption", "outbound_url": "url"}, only image_path is required.

  • collection_id – The UUID of a Collection to add the newly-submitted post to.

  • discussion_type – Set to "CHAT" to enable live discussion instead of traditional comments (default: None).

  • flair_id – The flair template to select (default: None).

  • flair_text – If the template’s flair_text_editable value is True, this value will set a custom text (default: None). flair_id is required when flair_text is provided.

  • nsfw – Whether the submission should be marked NSFW (default: False).

  • send_replies – When True, messages will be sent to the submission author when comments are made to the submission (default: True).

  • spoiler – Whether the submission should be marked asa spoiler (default: False).

Returns

A Submission object for the newly created submission.

Raises

ClientException if image_path in images refers to a file that is not an image.

For example, to submit an image gallery to r/test do:

title = "My favorite pictures"
image = "/path/to/image.png"
image2 = "/path/to/image2.png"
image3 = "/path/to/image3.png"
images = [
    {"image_path": image},
    {
        "image_path": image2,
        "caption": "Image caption 2",
    },
    {
        "image_path": image3,
        "caption": "Image caption 3",
        "outbound_url": "https://example.com/link3",
    },
]
subreddit = await reddit.subreddit("test")
await subreddit.submit_gallery(title, images)

See also

await submit_image(title: str, image_path: str, *, collection_id: Optional[str] = None, discussion_type: Optional[str] = None, flair_id: Optional[str] = None, flair_text: Optional[str] = None, nsfw: bool = False, resubmit: bool = True, send_replies: bool = True, spoiler: bool = False, timeout: int = 10, without_websockets: bool = False)

Add an image submission to the subreddit.

Parameters
  • collection_id – The UUID of a Collection to add the newly-submitted post to.

  • discussion_type – Set to "CHAT" to enable live discussion instead of traditional comments (default: None).

  • flair_id – The flair template to select (default: None).

  • flair_text – If the template’s flair_text_editable value is True, this value will set a custom text (default: None). flair_id is required when flair_text is provided.

  • image_path – The path to an image, to upload and post.

  • nsfw – Whether the submission should be marked NSFW (default: False).

  • resubmit – When False, an error will occur if the URL has already been submitted (default: True).

  • send_replies – When True, messages will be sent to the submission author when comments are made to the submission (default: True).

  • spoiler – Whether the submission should be marked as a spoiler (default: False).

  • timeout – Specifies a particular timeout, in seconds. Use to avoid “Websocket error” exceptions (default: 10).

  • title – The title of the submission.

  • without_websockets – Set to True to disable use of WebSockets (see note below for an explanation). If True, this method doesn’t return anything (default: False).

Returns

A Submission object for the newly created submission, unless without_websockets is True.

Raises

ClientException if image_path refers to a file that is not an image.

Note

Reddit’s API uses WebSockets to respond with the link of the newly created post. If this fails, the method will raise WebSocketException. Occasionally, the Reddit post will still be created. More often, there is an error with the image file. If you frequently get exceptions but successfully created posts, try setting the timeout parameter to a value above 10.

To disable the use of WebSockets, set without_websockets=True. This will make the method return None, though the post will still be created. You may wish to do this if you are running your program in a restricted network environment, or using a proxy that doesn’t support WebSockets connections.

For example, to submit an image to r/test do:

title = "My favorite picture"
image = "/path/to/image.png"
subreddit = await reddit.subreddit("test")
await subreddit.submit_image(title, image)

See also

await submit_poll(title: str, *, collection_id: Optional[str] = None, discussion_type: Optional[str] = None, duration: int, flair_id: Optional[str] = None, flair_text: Optional[str] = None, nsfw: bool = False, options: List[str], resubmit: bool = True, selftext: str, send_replies: bool = True, spoiler: bool = False)

Add a poll submission to the subreddit.

Parameters
  • title – The title of the submission.

  • collection_id – The UUID of a Collection to add the newly-submitted post to.

  • discussion_type – Set to "CHAT" to enable live discussion instead of traditional comments (default: None).

  • duration – The number of days the poll should accept votes, as an int. Valid values are between 1 and 7, inclusive.

  • flair_id – The flair template to select (default: None).

  • flair_text – If the template’s flair_text_editable value is True, this value will set a custom text (default: None). flair_id is required when flair_text is provided.

  • nsfw – Whether the submission should be marked NSFW (default: False).

  • options – A list of two to six poll options as str.

  • resubmit – When False, an error will occur if the URL has already been submitted (default: True).

  • selftext – The Markdown formatted content for the submission. Use an empty string, "", to make a submission with no text contents.

  • send_replies – When True, messages will be sent to the submission author when comments are made to the submission (default: True).

  • spoiler – Whether the submission should be marked as a spoiler (default: False).

Returns

A Submission object for the newly created submission.

For example, to submit a poll to r/test do:

title = "Do you like Async PRAW?"
subreddit = await reddit.subreddit("test")
await subreddit.submit_poll(title, selftext="", options=["Yes", "No"], duration=3)

See also

await submit_video(title: str, video_path: str, *, collection_id: Optional[str] = None, discussion_type: Optional[str] = None, flair_id: Optional[str] = None, flair_text: Optional[str] = None, nsfw: bool = False, resubmit: bool = True, send_replies: bool = True, spoiler: bool = False, thumbnail_path: Optional[str] = None, timeout: int = 10, videogif: bool = False, without_websockets: bool = False)

Add a video or videogif submission to the subreddit.

Parameters
  • title – The title of the submission.

  • video_path – The path to a video, to upload and post.

  • collection_id – The UUID of a Collection to add the newly-submitted post to.

  • discussion_type – Set to "CHAT" to enable live discussion instead of traditional comments (default: None).

  • flair_id – The flair template to select (default: None).

  • flair_text – If the template’s flair_text_editable value is True, this value will set a custom text (default: None). flair_id is required when flair_text is provided.

  • nsfw – Whether the submission should be marked NSFW (default: False).

  • resubmit – When False, an error will occur if the URL has already been submitted (default: True).

  • send_replies – When True, messages will be sent to the submission author when comments are made to the submission (default: True).

  • spoiler – Whether the submission should be marked as a spoiler (default: False).

  • thumbnail_path – The path to an image, to be uploaded and used as the thumbnail for this video. If not provided, the PRAW logo will be used as the thumbnail.

  • timeout – Specifies a particular timeout, in seconds. Use to avoid “Websocket error” exceptions (default: 10).

  • videogif – If True, the video is uploaded as a videogif, which is essentially a silent video (default: False).

  • without_websockets – Set to True to disable use of WebSockets (see note below for an explanation). If True, this method doesn’t return anything (default: False).

Returns

A Submission object for the newly created submission, unless without_websockets is True.

Raises

ClientException if video_path refers to a file that is not a video.

Note

Reddit’s API uses WebSockets to respond with the link of the newly created post. If this fails, the method will raise WebSocketException. Occasionally, the Reddit post will still be created. More often, there is an error with the image file. If you frequently get exceptions but successfully created posts, try setting the timeout parameter to a value above 10.

To disable the use of WebSockets, set without_websockets=True. This will make the method return None, though the post will still be created. You may wish to do this if you are running your program in a restricted network environment, or using a proxy that doesn’t support WebSockets connections.

For example, to submit a video to r/test do:

title = "My favorite movie"
video = "/path/to/video.mp4"
subreddit = await reddit.subreddit("test")
await subreddit.submit_video(title, video)

See also

await subscribe(*, other_subreddits: Optional[List[asyncpraw.models.Subreddit]] = None)

Subscribe to the subreddit.

Parameters

other_subreddits – When provided, also subscribe to the provided list of subreddits.

For example, to subscribe to r/test:

subreddit = await reddit.subreddit("test")
await subreddit.subscribe()
top(*, time_filter: str = 'all', **generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for top items.

Parameters

time_filter – Can be one of: "all", "day", "hour", "month", "week", or "year "``(default: ``"all").

Raises

ValueError if time_filter is invalid.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").top(time_filter="week")

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.top(time_filter="day")

redditor = await reddit.redditor("spez")
redditor.top(time_filter="month")

redditor = await reddit.redditor("spez")
redditor.comments.top(time_filter="year")

redditor = await reddit.redditor("spez")
redditor.submissions.top(time_filter="all")

subreddit = await reddit.subreddit("all")
subreddit.top(time_filter="hour")
await traffic() Dict[str, List[List[int]]]

Return a dictionary of the Subreddit’s traffic statistics.

Raises

asyncprawcore.NotFound when the traffic stats aren’t available to the authenticated user, that is, they are not public and the authenticated user is not a moderator of the subreddit.

The traffic method returns a dict with three keys. The keys are day, hour and month. Each key contains a list of lists with 3 or 4 values. The first value is a timestamp indicating the start of the category (start of the day for the day key, start of the hour for the hour key, etc.). The second, third, and fourth values indicate the unique pageviews, total pageviews, and subscribers, respectively.

Note

The hour key does not contain subscribers, and therefore each sub-list contains three values.

For example, to get the traffic stats for r/test:

subreddit = await reddit.subreddit("test")
stats = await subreddit.traffic()
await unsubscribe(*, other_subreddits: Optional[List[asyncpraw.models.Subreddit]] = None)

Unsubscribe from the subreddit.

Parameters

other_subreddits – When provided, also unsubscribe from the provided list of subreddits.

To unsubscribe from r/test:

subreddit = await reddit.subreddit("test")
await subreddit.unsubscribe()
widgets() asyncpraw.models.SubredditWidgets

Provide an instance of SubredditWidgets.

Example usage

Get all sidebar widgets:

subreddit = await reddit.subreddit("test")
async for widget in subreddit.widgets.sidebar:
    print(widget)

Get ID card widget:

subreddit = await reddit.subreddit("test")
widget = await subreddit.widgets.id_card()
print(widget)
wiki() asyncpraw.models.reddit.subreddit.SubredditWiki

Provide an instance of SubredditWiki.

This attribute can be used to discover all wikipages for a subreddit:

subreddit = await reddit.subreddit("test")
async for wikipage in subreddit.wiki:
    print(wikipage)

To fetch the content for a given wikipage try:

subreddit = await reddit.subreddit("test")
wikipage = await subreddit.wiki.get_page("proof")
print(wikipage.content_md)

WikiPage

class asyncpraw.models.reddit.wikipage.WikiPage(reddit: asyncpraw.Reddit, subreddit: asyncpraw.models.Subreddit, name: str, revision: Optional[str] = None, _data: Optional[Dict[str, Any]] = None)

An individual WikiPage object.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

content_html

The contents of the wiki page, as HTML.

content_md

The contents of the wiki page, as Markdown.

may_revise

A bool representing whether or not the authenticated user may edit the wiki page.

name

The name of the wiki page.

revision_by

The Redditor who authored this revision of the wiki page.

revision_date

The time of this revision, in Unix Time.

subreddit

The Subreddit this wiki page belongs to.

__init__(reddit: asyncpraw.Reddit, subreddit: asyncpraw.models.Subreddit, name: str, revision: Optional[str] = None, _data: Optional[Dict[str, Any]] = None)

Initialize a WikiPage instance.

Parameters

revision – A specific revision ID to fetch. By default, fetches the most recent revision.

discussions(**generator_kwargs: Any) AsyncIterator[asyncpraw.models.Submission]

Return a ListingGenerator for discussions of a wiki page.

Discussions are site-wide links to a wiki page.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To view the titles of discussions of the page "praw_test" in r/test, try:

subreddit = await reddit.subreddit("test")
wikipage = await subreddit.get_page("praw_test")
async for submission in wikipage.discussions():
    print(submission.title)
await edit(*, content: str, reason: Optional[str] = None, **other_settings: Any)

Edit this wiki page’s contents.

Parameters
  • content – The updated Markdown content of the page.

  • reason – The reason for the revision.

  • other_settings – Additional keyword arguments to pass.

For example, to replace the first wiki page of r/test with the phrase "test wiki page":

subreddit = await reddit.subreddit("test")
page = await subreddit.wiki.get_page("test", fetch=False)
await page.edit(content="test wiki page")
await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
mod() WikiPageModeration

Provide an instance of WikiPageModeration.

For example, to add spez as an editor on the wikipage praw_test try:

subreddit = await reddit.subreddit("test")
page = await subreddit.wiki.get_page("praw_test", fetch=False)
await page.mod.add("spez")
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

await revision(revision: str)

Return a specific version of this page by revision ID.

To view revision "1234abc" of "praw_test" in r/test:

subreddit = await reddit.subreddit("test")
page = await subreddit.wiki.get_page("praw_test", fetch=False)
revision = await page.revision("1234abc")
revisions(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncGenerator[WikiPage, None]

Return a ListingGenerator for page revisions.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To view the wiki revisions for "praw_test" in r/test try:

subreddit = await reddit.subreddit("test")
page = await subreddit.wiki.get_page("test_page", fetch=False)
async for item in page.revisions():
    print(item)

To get WikiPage objects for each revision:

subreddit = await reddit.subreddit("test")
page = await subreddit.wiki.get_page("test_page", fetch=False)
async for item in page.revisions():
    print(item["page"])

Exceptions in Async PRAW

In addition to exceptions under the asyncpraw.exceptions namespace shown below, exceptions might be raised that inherit from asyncprawcore.AsyncPrawcoreException. Please see the following resource for information on those exceptions: https://github.com/praw-dev/asyncprawcore/blob/master/asyncprawcore/exceptions.py

asyncpraw.exceptions

Async PRAW exception classes.

Includes two main exceptions: RedditAPIException for when something goes wrong on the server side, and ClientException when something goes wrong on the client side. Both of these classes extend AsyncPRAWException.

All other exceptions are subclassed from ClientException.

exception asyncpraw.exceptions.APIException(items: Union[List[Union[RedditErrorItem, List[str], str]], str], *optional_args: str)

Old class preserved for alias purposes.

Deprecated since version 7.0: Class APIException has been deprecated in favor of RedditAPIException. This class will be removed in Async PRAW 8.0.

__init__(items: Union[List[Union[RedditErrorItem, List[str], str]], str], *optional_args: str)

Initialize a RedditAPIException instance.

Parameters
  • items – Either a list of instances of RedditErrorItem or a list containing lists of unformed errors.

  • optional_args – Takes the second and third arguments that APIException used to take.

property error_type: str

Get error_type.

Deprecated since version 7.0: Accessing attributes through instances of RedditAPIException is deprecated. This behavior will be removed in Async PRAW 8.0. Check out the PRAW 7 Migration tutorial on how to migrate code from this behavior.

property field: str

Get field.

Deprecated since version 7.0: Accessing attributes through instances of RedditAPIException is deprecated. This behavior will be removed in Async PRAW 8.0. Check out the PRAW 7 Migration tutorial on how to migrate code from this behavior.

property message: str

Get message.

Deprecated since version 7.0: Accessing attributes through instances of RedditAPIException is deprecated. This behavior will be removed in Async PRAW 8.0. Check out the Async PRAW 7 Migration tutorial on how to migrate code from this behavior.

staticmethod parse_exception_list(exceptions: List[Union[RedditErrorItem, List[str]]])

Covert an exception list into a RedditErrorItem list.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception asyncpraw.exceptions.AsyncPRAWException

The base Async PRAW Exception that all other exception classes extend.

__init__(*args, **kwargs)
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception asyncpraw.exceptions.ClientException

Indicate exceptions that don’t involve interaction with Reddit’s API.

__init__(*args, **kwargs)
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception asyncpraw.exceptions.DuplicateReplaceException

Indicate exceptions that involve the replacement of MoreComments.

__init__()

Initialize a DuplicateReplaceException instance.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class asyncpraw.exceptions.ExceptionWrapper(wrapped)

Wrapper to facilitate showing depreciation for PRAWException class rename.

__init__(wrapped)

Initialize Wrapper instance.

exception asyncpraw.exceptions.InvalidFlairTemplateID(template_id: str)

Indicate exceptions where an invalid flair template ID is given.

__init__(template_id: str)

Initialize an InvalidFlairTemplateID instance.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception asyncpraw.exceptions.InvalidImplicitAuth

Indicate exceptions where an implicit auth type is used incorrectly.

__init__()

Initialize an InvalidImplicitAuth instance.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception asyncpraw.exceptions.InvalidURL(url: str, *, message: str = 'Invalid URL: {}')

Indicate exceptions where an invalid URL is entered.

__init__(url: str, *, message: str = 'Invalid URL: {}')

Initialize an InvalidURL instance.

Parameters
  • url – The invalid URL.

  • message – The message to display. Must contain a format identifier ({} or {0}) (default: "Invalid URL: {}").

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception asyncpraw.exceptions.MediaPostFailed

Indicate exceptions where media uploads failed..

__init__()

Initialize a MediaPostFailed instance.

property original_exception: Exception

Access the original_exception attribute (now deprecated).

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception asyncpraw.exceptions.MissingRequiredAttributeException

Indicate exceptions caused by not including a required attribute.

__init__(*args, **kwargs)
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

asyncpraw.exceptions.PRAWException

alias of AsyncPRAWException

exception asyncpraw.exceptions.ReadOnlyException

Raised when a method call requires read_only mode to be disabled.

__init__(*args, **kwargs)
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception asyncpraw.exceptions.RedditAPIException(items: Union[List[Union[RedditErrorItem, List[str], str]], str], *optional_args: str)

Container for error messages from Reddit’s API.

__init__(items: Union[List[Union[RedditErrorItem, List[str], str]], str], *optional_args: str)

Initialize a RedditAPIException instance.

Parameters
  • items – Either a list of instances of RedditErrorItem or a list containing lists of unformed errors.

  • optional_args – Takes the second and third arguments that APIException used to take.

property error_type: str

Get error_type.

Deprecated since version 7.0: Accessing attributes through instances of RedditAPIException is deprecated. This behavior will be removed in Async PRAW 8.0. Check out the PRAW 7 Migration tutorial on how to migrate code from this behavior.

property field: str

Get field.

Deprecated since version 7.0: Accessing attributes through instances of RedditAPIException is deprecated. This behavior will be removed in Async PRAW 8.0. Check out the PRAW 7 Migration tutorial on how to migrate code from this behavior.

property message: str

Get message.

Deprecated since version 7.0: Accessing attributes through instances of RedditAPIException is deprecated. This behavior will be removed in Async PRAW 8.0. Check out the Async PRAW 7 Migration tutorial on how to migrate code from this behavior.

staticmethod parse_exception_list(exceptions: List[Union[RedditErrorItem, List[str]]])

Covert an exception list into a RedditErrorItem list.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class asyncpraw.exceptions.RedditErrorItem(error_type: str, *, field: Optional[str] = None, message: Optional[str] = None)

Represents a single error returned from Reddit’s API.

__init__(error_type: str, *, field: Optional[str] = None, message: Optional[str] = None)

Initialize a RedditErrorItem instance.

Parameters
  • error_type – The error type set on Reddit’s end.

  • field – The input field associated with the error, if available.

  • message – The associated message for the error.

property error_message: str

Get the completed error message string.

exception asyncpraw.exceptions.TooLargeMediaException(*, actual: int, maximum_size: int)

Indicate exceptions from uploading media that’s too large.

__init__(*, actual: int, maximum_size: int)

Initialize a TooLargeMediaException instance.

Parameters
  • actual – The actual size of the uploaded media.

  • maximum_size – The maximum size of the uploaded media.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception asyncpraw.exceptions.WebSocketException(message: str, exception: Optional[Exception])

Indicate exceptions caused by use of WebSockets.

__init__(message: str, exception: Optional[Exception])

Initialize a WebSocketException instance.

Parameters
  • message – The exception message.

  • exception

    The exception thrown by the websocket library.

    Note

    This parameter is deprecated. It will be removed in Async PRAW 8.0.

property original_exception: Exception

Access the original_exception attribute (now deprecated).

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

Other Classes

The following list of classes are provided here for complete documentation. You should not likely need to work with these classes directly, but rather through instances of them bound to an attribute of one of the Async PRAW models.

Collection

class asyncpraw.models.Collection(reddit: asyncpraw.Reddit, _data: Dict[str, Any] = None, collection_id: Optional[str] = None, permalink: Optional[str] = None)

Class to represent a Collection.

Obtain an instance via:

subreddit = await reddit.subreddit("test")
collection = await subreddit.collections("some_uuid")

or

subreddit = await reddit.subreddit("test")
collection = await subreddit.collections(
    permalink="https://reddit.com/r/test/collection/some_uuid"
)

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

author

The Redditor who created the collection.

collection_id

The UUID of the collection.

created_at_utc

Time the collection was created, represented in Unix Time.

description

The collection description.

display_layout

The collection display layout.

last_update_utc

Time the collection was last updated, represented in Unix Time.

link_ids

A list of Submission fullnames.

permalink

The collection’s permalink (to view on the web).

sorted_links

An iterable listing of the posts in this collection.

title

The title of the collection.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any] = None, collection_id: Optional[str] = None, permalink: Optional[str] = None)

Initialize a Collection instance.

Parameters
for ... in __iter__() Generator[Any, None, None]

Provide a way to iterate over the posts in this Collection.

Example usage:

subreddit = await reddit.subreddit("test")
collection = await subreddit.collections("some_uuid")
for submission in collection:
    print(submission.title, submission.permalink)
__len__() int

Get the number of posts in this Collection.

Example usage:

subreddit = await reddit.subreddit("test")
collection = await subreddit.collections("some_uuid")
print(len(collection))
await follow()

Follow this Collection.

Example usage:

subreddit = await reddit.subreddit("test")
collection = await subreddit.collections("some_uuid")
await collection.follow()

See also

unfollow()

await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
mod() CollectionModeration

Get an instance of CollectionModeration.

Provides access to various methods, including add_post(), delete(), reorder(), and update_title().

Example usage:

subreddit = await reddit.subreddit("test")
collection = await subreddit.collections("some_uuid")
await collection.mod.update_title("My new title!")
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

await subreddit() asyncpraw.models.Subreddit

Get the subreddit that this collection belongs to.

For example:

subreddit = await reddit.subreddit("test")
collection = await subreddit.collections("some_uuid")
print(await collection.subreddit())
await unfollow()

Unfollow this Collection.

Example usage:

subreddit = await reddit.subreddit("test")
collection = await subreddit.collections("some_uuid")
await collection.unfollow()

See also

follow()

CollectionModeration

class asyncpraw.models.reddit.collections.CollectionModeration(reddit: asyncpraw.Reddit, collection_id: str)

Class to support moderation actions on a Collection.

Obtain an instance via:

subreddit = await reddit.subreddit("test")
collection = await subreddit.collections("some_uuid")
collection.mod
__init__(reddit: asyncpraw.Reddit, collection_id: str)

Initialize a CollectionModeration instance.

Parameters

collection_id – The ID of a Collection.

await add_post(submission: asyncpraw.models.Submission)

Add a post to the collection.

Parameters

submission – The post to add, a Submission, its permalink as a str, its fullname as a str, or its ID as a str.

Example usage:

subreddit = await reddit.subreddit("test")
collection = await subreddit.collections("some_uuid")
await collection.mod.add_post("bgibu9")

See also

remove_post()

await delete()

Delete this collection.

Example usage:

subreddit = await reddit.subreddit("test")
collection = await subreddit.collections("some_uuid")
await collection.mod.delete()

See also

create()

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

await remove_post(submission: asyncpraw.models.Submission)

Remove a post from the collection.

Parameters

submission – The post to remove, a Submission, its permalink as a str, its fullname as a str, or its ID as a str.

Example usage:

subreddit = await reddit.subreddit("test")
collection = await subreddit.collections("some_uuid")
await collection.mod.remove_post("bgibu9")

See also

add_post()

await reorder(links: List[Union[str, asyncpraw.models.Submission]])

Reorder posts in the collection.

Parameters

links – A list of Submissions or a str that is either a fullname or an ID.

Example usage:

subreddit = await reddit.subreddit("test")
collection = await subreddit.collections("some_uuid")
current_order = collection.link_ids
new_order = reversed(current_order)
await collection.mod.reorder(new_order)
await update_description(description: str)

Update the collection’s description.

Parameters

description – The new description.

Example usage:

subreddit = await reddit.subreddit("test")
collection = await subreddit.collections("some_uuid")
await collection.mod.update_description("Please enjoy these links")

See also

update_title()

await update_display_layout(display_layout: str)

Update the collection’s display layout.

Parameters

display_layout – Either "TIMELINE" for events or discussions or "GALLERY" for images or memes. Passing None will clear the set layout and collection.display_layout will be None, however, the collection will appear on Reddit as if display_layout is set to "TIMELINE".

Example usage:

subreddit = await reddit.subreddit("test")
collection = await subreddit.collections("some_uuid")
await collection.mod.update_display_layout("GALLERY")
await update_title(title: str)

Update the collection’s title.

Parameters

title – The new title.

Example usage:

subreddit = await reddit.subreddit("test")
collection = await subreddit.collections("some_uuid")
await collection.mod.update_title("Titley McTitleface")

SubredditCollections

class asyncpraw.models.reddit.collections.SubredditCollections(reddit: asyncpraw.Reddit, subreddit: asyncpraw.models.Subreddit, _data: Optional[Dict[str, Any]] = None)

Class to represent a Subreddit’s Collections.

Obtain an instance via:

subreddit = await reddit.subreddit("test")
subreddit.collections
await __call__(collection_id: Optional[str] = None, permalink: Optional[str] = None, fetch: bool = True, **kwargs)

Return the Collection with the specified ID.

Parameters
  • collection_id – The ID of a Collection (default: None).

  • permalink – The permalink of a collection (default: None).

  • fetch – Determines if Async PRAW will fetch the object (default: True).

Returns

The specified Collection.

Exactly one of collection_id or permalink is required.

Example usage:

subreddit = await reddit.subreddit("test")

uuid = "847e4548-a3b5-4ad7-afb4-edbfc2ed0a6b"
collection = await subreddit.collections(uuid)
print(collection.title)
print(collection.description)

permalink = "https://www.reddit.com/r/test/collection/" + uuid
collection = await subreddit.collections(permalink=permalink)
print(collection.title)
print(collection.description)

If you don’t need the object fetched right away (e.g., to utilize a class method) you can do:

subreddit = await reddit.subreddit("test", fetch=True)
collection = await subreddit.collections(uuid, fetch=False)
await collection.mod.add("submission_id")
__init__(reddit: asyncpraw.Reddit, subreddit: asyncpraw.models.Subreddit, _data: Optional[Dict[str, Any]] = None)

Initialize a SubredditCollections instance.

mod() SubredditCollectionsModeration

Get an instance of SubredditCollectionsModeration.

Provides create():

my_sub = await reddit.subreddit("test", fetch=True)
new_collection = await my_sub.collections.mod.create(title="Title", description="desc")
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

SubredditCollectionsModeration

class asyncpraw.models.reddit.collections.SubredditCollectionsModeration(reddit: asyncpraw.Reddit, subreddit: asyncpraw.models.Subreddit, _data: Optional[Dict[str, Any]] = None)

Class to represent moderator actions on a Subreddit’s Collections.

Obtain an instance via:

subreddit = await reddit.subreddit("test")
subreddit.collections.mod
__init__(reddit: asyncpraw.Reddit, subreddit: asyncpraw.models.Subreddit, _data: Optional[Dict[str, Any]] = None)

Initialize a SubredditCollectionsModeration instance.

await create(*, description: str, display_layout: Optional[str] = None, title: str)

Create a new Collection.

The authenticated account must have appropriate moderator permissions in the subreddit this collection belongs to.

Parameters
  • description – The description, up to 500 characters.

  • display_layout – Either "TIMELINE" for events or discussions or "GALLERY" for images or memes. Passing "" or None will make the collection appear on Reddit as if this is set to "TIMELINE" (default: None).

  • title – The title of the collection, up to 300 characters.

Returns

The newly created Collection.

Example usage:

sub = await reddit.subreddit("test")
new_collection = await sub.collections.mod.create(title="Title", description="desc")
await new_collection.mod.add_post("bgibu9")

To specify the display layout as "GALLERY" when creating the collection:

my_sub = await reddit.subreddit("test")
new_collection = await my_sub.collections.mod.create(
    title="Title", description="desc", display_layout="GALLERY"
)
await new_collection.mod.add_post("bgibu9")

See also

delete()

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

SubmissionFlair

class asyncpraw.models.reddit.submission.SubmissionFlair(submission: asyncpraw.models.Submission)

Provide a set of functions pertaining to Submission flair.

__init__(submission: asyncpraw.models.Submission)

Initialize a SubmissionFlair instance.

Parameters

submission – The Submission associated with the flair functions.

await choices() List[Dict[str, Union[bool, list, str]]]

Return list of available flair choices.

Choices are required in order to use select().

For example:

choices = await submission.flair.choices()
await select(flair_template_id: str, *, text: Optional[str] = None)

Select flair for submission.

Parameters
  • flair_template_id – The flair template to select. The possible values can be discovered through choices().

  • text – If the template’s flair_text_editable value is True, this value will set a custom text (default: None).

For example, to select an arbitrary editable flair text (assuming there is one) and set a custom value try:

choices = await submission.flair.choices()
template_id = next(x for x in choices if x["flair_text_editable"])["flair_template_id"]
await submission.flair.select(template_id, text="my custom value")

SubredditFlair

class asyncpraw.models.reddit.subreddit.SubredditFlair(subreddit: asyncpraw.models.Subreddit)

Provide a set of functions to interact with a Subreddit’s flair.

__call__(redditor: Optional[Union[asyncpraw.models.Redditor, str]] = None, **generator_kwargs: Any) AsyncIterator[asyncpraw.models.Redditor]

Return a ListingGenerator for Redditors and their flairs.

Parameters

redditor – When provided, yield at most a single Redditor instance (default: None).

Additional keyword arguments are passed in the initialization of ListingGenerator.

Usage:

subreddit = await reddit.subreddit("test")
async for flair in subreddit.flair(limit=None):
    print(flair)
__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a SubredditFlair instance.

Parameters

subreddit – The subreddit whose flair to work with.

await configure(*, link_position: str = 'left', link_self_assign: bool = False, position: str = 'right', self_assign: bool = False, **settings: Any)

Update the Subreddit’s flair configuration.

Parameters
  • link_position – One of "left", "right", or False to disable (default: "left").

  • link_self_assign – Permit self assignment of link flair (default: False).

  • position – One of "left", "right", or False to disable (default: "right").

  • self_assign – Permit self assignment of user flair (default: False).

subreddit = reddit.subreddit("test")
subreddit.flair.configure(link_position="right", self_assign=True)

Additional keyword arguments can be provided to handle new settings as Reddit introduces them.

await delete(redditor: Union[asyncpraw.models.Redditor, str])

Delete flair for a Redditor.

Parameters

redditor – A redditor name or Redditor instance.

See also

update() to delete the flair of many redditors at once.

await delete_all() List[Dict[str, Union[str, bool, Dict[str, str]]]]

Delete all Redditor flair in the Subreddit.

Returns

List of dictionaries indicating the success or failure of each delete.

Provide an instance of SubredditLinkFlairTemplates.

Use this attribute for interacting with a Subreddit’s link flair templates. For example, to list all the link flair templates for a subreddit which you have the flair moderator permission on try:

subreddit = await reddit.subreddit("test")
async for template in subreddit.flair.link_templates:
    print(template)
await set(redditor: Union[asyncpraw.models.Redditor, str], *, css_class: str = '', flair_template_id: Optional[str] = None, text: str = '')

Set flair for a Redditor.

Parameters
  • redditor – A redditor name or Redditor instance.

  • text – The flair text to associate with the Redditor or Submission (default: "").

  • css_class – The css class to associate with the flair html (default: ""). Use either this or flair_template_id.

  • flair_template_id – The ID of the flair template to be used (default: None). Use either this or css_class.

This method can only be used by an authenticated user who is a moderator of the associated Subreddit.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.flair.set("bboe", text="PRAW author", css_class="mods")
template = "6bd28436-1aa7-11e9-9902-0e05ab0fad46"
subreddit = await reddit.subreddit("test")
await subreddit.flair.set("spez", text="Reddit CEO", flair_template_id=template)
templates() asyncpraw.models.reddit.subreddit.SubredditRedditorFlairTemplates

Provide an instance of SubredditRedditorFlairTemplates.

Use this attribute for interacting with a Subreddit’s flair templates. For example, to list all the flair templates for a subreddit which you have the flair moderator permission on try:

subreddit = await reddit.subreddit("test")
async for template in subreddit.flair.templates:
    print(template)
await update(flair_list: Iterator[Union[str, asyncpraw.models.Redditor, Dict[str, Union[str, asyncpraw.models.Redditor]]]], *, text: str = '', css_class: str = '') List[Dict[str, Union[str, bool, Dict[str, str]]]]

Set or clear the flair for many redditors at once.

Parameters
  • flair_list

    Each item in this list should be either:

    • The name of a redditor.

    • An instance of Redditor.

    • A dictionary mapping keys "user", "flair_text", and "flair_css_class" to their respective values. The "user" key should map to a redditor, as described above. When a dictionary isn’t provided, or the dictionary is missing either "flair_text" or "flair_css_class" keys, the default values will come from the other arguments.

  • css_class – The css class to use when not explicitly provided in flair_list (default: "").

  • text – The flair text to use when not explicitly provided in flair_list (default: "").

Returns

List of dictionaries indicating the success or failure of each update.

For example, to clear the flair text, and set the "praw" flair css class on a few users try:

await subreddit.flair.update(["bboe", "spez", "spladug"], css_class="praw")

SubredditFlairTemplates

class asyncpraw.models.reddit.subreddit.SubredditFlairTemplates(subreddit: asyncpraw.models.Subreddit)

Provide functions to interact with a Subreddit’s flair templates.

__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a SubredditFlairTemplates instance.

Parameters

subreddit – The subreddit whose flair templates to work with.

Note

This class should not be initialized directly. Instead, obtain an instance via:

subreddit = await reddit.subreddit("test")
subreddit.flair.templates

or via

subreddit = await reddit.subreddit("test")
subreddit.flair.link_templates
await delete(template_id: str)

Remove a flair template provided by template_id.

For example, to delete the first Redditor flair template listed, try:

async for template_info in subreddit.flair.templates:
    await subreddit.flair.templates.delete(template_info["id"])
    break
staticmethod flair_type(is_link: bool) str

Return "LINK_FLAIR" or "USER_FLAIR" depending on is_link value.

await update(template_id: str, *, allowable_content: Optional[str] = None, background_color: Optional[str] = None, css_class: Optional[str] = None, fetch: bool = True, max_emojis: Optional[int] = None, mod_only: Optional[bool] = None, text: Optional[str] = None, text_color: Optional[str] = None, text_editable: Optional[bool] = None)

Update the flair template provided by template_id.

Parameters
  • template_id – The flair template to update. If not valid then an exception will be thrown.

  • allowable_content – If specified, most be one of "all", "emoji", or "text" to restrict content to that type. If set to "emoji" then the "text" param must be a valid emoji string, for example, ":snoo:".

  • background_color – The flair template’s new background color, as a hex color.

  • css_class – The flair template’s new css_class (default: "").

  • fetch – Whether Async PRAW will fetch existing information on the existing flair before updating (default: True).

  • max_emojis – Maximum emojis in the flair (Reddit defaults this value to 10).

  • mod_only – Indicate if the flair can only be used by moderators.

  • text – The flair template’s new text.

  • text_color – The flair template’s new text color, either "light" or "dark".

  • text_editable – Indicate if the flair text can be modified for each redditor that sets it (default: False).

Warning

If parameter fetch is set to False, all parameters not provided will be reset to their default (None or False) values.

For example, to make a user flair template text editable, try:

async for template_info in subreddit.flair.templates:
    await subreddit.flair.templates.update(
        template_info["id"],
        text=template_info["flair_text"],
        text_editable=True,
    )
    break

SubredditLinkFlairTemplates

class asyncpraw.models.reddit.subreddit.SubredditLinkFlairTemplates(subreddit: asyncpraw.models.Subreddit)

Provide functions to interact with link flair templates.

__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a SubredditFlairTemplates instance.

Parameters

subreddit – The subreddit whose flair templates to work with.

Note

This class should not be initialized directly. Instead, obtain an instance via:

subreddit = await reddit.subreddit("test")
subreddit.flair.templates

or via

subreddit = await reddit.subreddit("test")
subreddit.flair.link_templates
await add(text: str, *, allowable_content: Optional[str] = None, background_color: Optional[str] = None, css_class: str = '', max_emojis: Optional[int] = None, mod_only: Optional[bool] = None, text_color: Optional[str] = None, text_editable: bool = False)

Add a link flair template to the associated subreddit.

Parameters
  • text – The flair template’s text.

  • allowable_content – If specified, most be one of "all", "emoji", or "text" to restrict content to that type. If set to "emoji" then the "text" param must be a valid emoji string, for example, ":snoo:".

  • background_color – The flair template’s new background color, as a hex color.

  • css_class – The flair template’s css_class (default: "").

  • max_emojis – Maximum emojis in the flair (Reddit defaults this value to 10).

  • mod_only – Indicate if the flair can only be used by moderators.

  • text_color – The flair template’s new text color, either "light" or "dark".

  • text_editable – Indicate if the flair text can be modified for each redditor that sets it (default: False).

For example, to add an editable link flair try:

subreddit = await reddit.subreddit("test")
await subreddit.flair.link_templates.add(
    "Async PRAW",
    css_class="asyncpraw",
    text_editable=True,
)
await clear()

Remove all link flair templates from the subreddit.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.flair.link_templates.clear()
await delete(template_id: str)

Remove a flair template provided by template_id.

For example, to delete the first Redditor flair template listed, try:

async for template_info in subreddit.flair.templates:
    await subreddit.flair.templates.delete(template_info["id"])
    break
staticmethod flair_type(is_link: bool) str

Return "LINK_FLAIR" or "USER_FLAIR" depending on is_link value.

await update(template_id: str, *, allowable_content: Optional[str] = None, background_color: Optional[str] = None, css_class: Optional[str] = None, fetch: bool = True, max_emojis: Optional[int] = None, mod_only: Optional[bool] = None, text: Optional[str] = None, text_color: Optional[str] = None, text_editable: Optional[bool] = None)

Update the flair template provided by template_id.

Parameters
  • template_id – The flair template to update. If not valid then an exception will be thrown.

  • allowable_content – If specified, most be one of "all", "emoji", or "text" to restrict content to that type. If set to "emoji" then the "text" param must be a valid emoji string, for example, ":snoo:".

  • background_color – The flair template’s new background color, as a hex color.

  • css_class – The flair template’s new css_class (default: "").

  • fetch – Whether Async PRAW will fetch existing information on the existing flair before updating (default: True).

  • max_emojis – Maximum emojis in the flair (Reddit defaults this value to 10).

  • mod_only – Indicate if the flair can only be used by moderators.

  • text – The flair template’s new text.

  • text_color – The flair template’s new text color, either "light" or "dark".

  • text_editable – Indicate if the flair text can be modified for each redditor that sets it (default: False).

Warning

If parameter fetch is set to False, all parameters not provided will be reset to their default (None or False) values.

For example, to make a user flair template text editable, try:

async for template_info in subreddit.flair.templates:
    await subreddit.flair.templates.update(
        template_info["id"],
        text=template_info["flair_text"],
        text_editable=True,
    )
    break
async for ... in user_selectable() AsyncGenerator[Dict[str, Union[str, bool]], None]

Iterate through the link flair templates as a regular user.

For example:

subreddit = await reddit.subreddit("test")
async for template in subreddit.flair.link_templates.user_selectable():
    print(template)

SubredditRedditorFlairTemplates

class asyncpraw.models.reddit.subreddit.SubredditRedditorFlairTemplates(subreddit: asyncpraw.models.Subreddit)

Provide functions to interact with Redditor flair templates.

__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a SubredditFlairTemplates instance.

Parameters

subreddit – The subreddit whose flair templates to work with.

Note

This class should not be initialized directly. Instead, obtain an instance via:

subreddit = await reddit.subreddit("test")
subreddit.flair.templates

or via

subreddit = await reddit.subreddit("test")
subreddit.flair.link_templates
await add(text: str, *, allowable_content: Optional[str] = None, background_color: Optional[str] = None, css_class: str = '', max_emojis: Optional[int] = None, mod_only: Optional[bool] = None, text_color: Optional[str] = None, text_editable: bool = False)

Add a redditor flair template to the associated subreddit.

Parameters
  • text – The flair template’s text.

  • allowable_content – If specified, most be one of "all", "emoji", or "text" to restrict content to that type. If set to "emoji" then the "text" param must be a valid emoji string, for example, ":snoo:".

  • background_color – The flair template’s new background color, as a hex color.

  • css_class – The flair template’s css_class (default: "").

  • max_emojis – Maximum emojis in the flair (Reddit defaults this value to 10).

  • mod_only – Indicate if the flair can only be used by moderators.

  • text_color – The flair template’s new text color, either "light" or "dark".

  • text_editable – Indicate if the flair text can be modified for each redditor that sets it (default: False).

For example, to add an editable redditor flair try:

subreddit = await reddit.subreddit("test")
await subreddit.flair.templates.add(
    "PRAW",
    css_class="praw",
    text_editable=True,
)
await clear()

Remove all Redditor flair templates from the subreddit.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.flair.templates.clear()
await delete(template_id: str)

Remove a flair template provided by template_id.

For example, to delete the first Redditor flair template listed, try:

async for template_info in subreddit.flair.templates:
    await subreddit.flair.templates.delete(template_info["id"])
    break
staticmethod flair_type(is_link: bool) str

Return "LINK_FLAIR" or "USER_FLAIR" depending on is_link value.

await update(template_id: str, *, allowable_content: Optional[str] = None, background_color: Optional[str] = None, css_class: Optional[str] = None, fetch: bool = True, max_emojis: Optional[int] = None, mod_only: Optional[bool] = None, text: Optional[str] = None, text_color: Optional[str] = None, text_editable: Optional[bool] = None)

Update the flair template provided by template_id.

Parameters
  • template_id – The flair template to update. If not valid then an exception will be thrown.

  • allowable_content – If specified, most be one of "all", "emoji", or "text" to restrict content to that type. If set to "emoji" then the "text" param must be a valid emoji string, for example, ":snoo:".

  • background_color – The flair template’s new background color, as a hex color.

  • css_class – The flair template’s new css_class (default: "").

  • fetch – Whether Async PRAW will fetch existing information on the existing flair before updating (default: True).

  • max_emojis – Maximum emojis in the flair (Reddit defaults this value to 10).

  • mod_only – Indicate if the flair can only be used by moderators.

  • text – The flair template’s new text.

  • text_color – The flair template’s new text color, either "light" or "dark".

  • text_editable – Indicate if the flair text can be modified for each redditor that sets it (default: False).

Warning

If parameter fetch is set to False, all parameters not provided will be reset to their default (None or False) values.

For example, to make a user flair template text editable, try:

async for template_info in subreddit.flair.templates:
    await subreddit.flair.templates.update(
        template_info["id"],
        text=template_info["flair_text"],
        text_editable=True,
    )
    break

InlineGif

class asyncpraw.models.InlineGif(*, caption: str = None, path: str)

Class to provide a gif to embed in text.

__init__(*, caption: str = None, path: str)

Initialize an InlineMedia instance.

Parameters
  • caption – An optional caption to add to the image (default: None).

  • path – The path to a media file.

InlineImage

class asyncpraw.models.InlineImage(*, caption: str = None, path: str)

Class to provide am image to embed in text.

__init__(*, caption: str = None, path: str)

Initialize an InlineMedia instance.

Parameters
  • caption – An optional caption to add to the image (default: None).

  • path – The path to a media file.

InlineMedia

class asyncpraw.models.InlineMedia(*, caption: str = None, path: str)

Provides a way to embed media in self posts.

__init__(*, caption: str = None, path: str)

Initialize an InlineMedia instance.

Parameters
  • caption – An optional caption to add to the image (default: None).

  • path – The path to a media file.

InlineVideo

class asyncpraw.models.InlineVideo(*, caption: str = None, path: str)

Class to provide a video to embed in text.

__init__(*, caption: str = None, path: str)

Initialize an InlineMedia instance.

Parameters
  • caption – An optional caption to add to the image (default: None).

  • path – The path to a media file.

BaseModNotes

class asyncpraw.models.mod_notes.BaseModNotes(reddit: asyncpraw.Reddit)

Provides base methods to interact with moderator notes.

__init__(reddit: asyncpraw.Reddit)

Initialize a BaseModNotes instance.

Parameters

reddit – An instance of Reddit.

await create(*, label: Optional[str] = None, note: str, redditor: Optional[Union[Redditor, str]] = None, subreddit: Optional[Union[asyncpraw.models.Subreddit, str]] = None, thing: Optional[Union[Comment, Submission, str]] = None, **other_settings: Any) asyncpraw.models.ModNote

Create a ModNote for a redditor in the specified subreddit.

Parameters
  • label – The label for the note. As of this writing, this can be one of the following: "ABUSE_WARNING", "BAN", "BOT_BAN", "HELPFUL_USER", "PERMA_BAN", "SOLID_CONTRIBUTOR", "SPAM_WARNING", "SPAM_WATCH", or None (default: None).

  • note – The content of the note. As of this writing, this is limited to 250 characters.

  • redditor

    The redditor to create the note for (default: None).

    Note

    This parameter is required if thing is not provided or this is not called from a Redditor instance (e.g., reddit.redditor.notes).

  • subreddit

    The subreddit associated with the note (default: None).

    Note

    This parameter is required if thing is not provided or this is not called from a Subreddit instance (e.g., reddit.subreddit.mod).

  • thing – Either the fullname of a comment/submission, a Comment, or a Submission to associate with the note.

  • other_settings – Additional keyword arguments can be provided to handle new parameters as Reddit introduces them.

Returns

The new ModNote object.

For example, to create a note for u/spez in r/test:

subreddit = await reddit.subreddit("test")
await subreddit.mod.notes.create(
    label="HELPFUL_USER", note="Test note", redditor="spez"
)
# or
redditor = await reddit.redditor("spez")
await redditor.mod.notes.create(
    label="HELPFUL_USER", note="Test note", subreddit="test"
)
# or
await reddit.notes.create(
    label="HELPFUL_USER", note="Test note", redditor="spez", subreddit="test"
)
await delete(*, delete_all: bool = False, note_id: Optional[str] = None, redditor: Optional[Union[Redditor, str]] = None, subreddit: Optional[Union[asyncpraw.models.Subreddit, str]] = None)

Delete note(s) for a redditor.

Parameters
  • delete_all

    When True, delete all notes for the specified redditor in the specified subreddit (default: False).

    Note

    This will make a request for each note.

  • note_id – The ID of the note to delete. This parameter is ignored if delete_all is True.

  • redditor

    The redditor to delete the note(s) for (default: None). Can be a Redditor instance or a redditor name.

    Note

    This parameter is required if this method is not called from a Redditor instance (e.g., redditor.notes).

  • subreddit

    The subreddit to delete the note(s) from (default: None). Can be a Subreddit instance or a subreddit name.

    Note

    This parameter is required if this method is not called from a Subreddit instance (e.g., reddit.subreddit.mod).

For example, to delete a note with the ID "ModNote_d324b280-5ecc-435d-8159-3e259e84e339", try:

subreddit = await reddit.subreddit("test")
await subreddit.mod.notes.delete(
    note_id="ModNote_d324b280-5ecc-435d-8159-3e259e84e339", redditor="spez"
)
# or
redditor = await reddit.redditor("spez")
await redditor.notes.delete(
    note_id="ModNote_d324b280-5ecc-435d-8159-3e259e84e339", subreddit="test"
)
# or
await reddit.notes.delete(
    note_id="ModNote_d324b280-5ecc-435d-8159-3e259e84e339",
    subreddit="test",
    redditor="spez",
)

To delete all notes for u/spez, try:

subreddit = await reddit.subreddit("test")
await subreddit.mod.notes.delete(delete_all=True, redditor="spez")
# or
redditor = await reddit.redditor("spez")
await redditor.notes.delete(delete_all=True, subreddit="test")
# or
await reddit.notes.delete(delete_all=True, subreddit="test", redditor="spez")

ModNote

class asyncpraw.models.ModNote(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Represent a moderator note.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

action

If this note represents a moderator action, this field indicates the type of action. For example, "banuser" if the action was banning a user.

created_at

Time the moderator note was created, represented in Unix Time.

description

If this note represents a moderator action, this field indicates the description of the action. For example, if the action was banning the user, this is the ban reason.

details

If this note represents a moderator action, this field indicates the details of the action. For example, if the action was banning the user, this is the duration of the ban.

id

The ID of the moderator note.

label

The label applied to the note, currently one of: "ABUSE_WARNING", "BAN", "BOT_BAN", "HELPFUL_USER", "PERMA_BAN", "SOLID_CONTRIBUTOR", "SPAM_WARNING", "SPAM_WATCH", or None.

moderator

The moderator who created the note.

note

The text of the note.

reddit_id

The fullname of the object this note is attributed to, or None if not set. If this note represents a moderators action, this is the fullname of the object the action was performed on.

subreddit

The subreddit this note belongs to.

type

The type of note, currently one of: "APPROVAL", "BAN", "CONTENT_CHANGE", "INVITE", "MUTE", "NOTE", "REMOVAL", or "SPAM".

user

The redditor the note is for.

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

await delete()

Delete this note.

For example, to delete the last note for u/spez from r/test, try:

for note in reddit.subreddit("test").mod.notes("spez"):
    note.delete()
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

ModNoteMixin

class asyncpraw.models.reddit.mixins.ModNoteMixin

Interface for classes that can have a moderator note set on them.

author_notes(**generator_kwargs) AsyncGenerator[asyncpraw.models.ModNote, None]

Get the moderator notes for the author of this object in the subreddit it’s posted in.

Parameters

generator_kwargs – Additional keyword arguments are passed in the initialization of the moderator note generator.

Returns

A generator of ModNote.

For example, to list all notes the author of a submission, try:

for note in reddit.submission("92dd8").mod.author_notes():
    print(f"{note.label}: {note.note}")
await create_note(*, label: Optional[str] = None, note: str, **other_settings) asyncpraw.models.ModNote

Create a moderator note on the author of this object in the subreddit it’s posted in.

Parameters
  • label – The label for the note. As of this writing, this can be one of the following: "ABUSE_WARNING", "BAN", "BOT_BAN", "HELPFUL_USER", "PERMA_BAN", "SOLID_CONTRIBUTOR", "SPAM_WARNING", "SPAM_WATCH", or None (default: None).

  • note – The content of the note. As of this writing, this is limited to 250 characters.

  • other_settings – Additional keyword arguments are passed to create().

Returns

The new ModNote object.

For example, to create a note on a Submission, try:

submission = await reddit.submission("92dd8")
await submission.mod.create_note(label="HELPFUL_USER", note="Test note")

RedditModNotes

class asyncpraw.models.RedditModNotes(reddit: asyncpraw.Reddit)

Provides methods to interact with moderator notes at a global level.

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}")
__call__(*, all_notes: bool = False, pairs: Optional[List[Tuple[Union[asyncpraw.models.Subreddit, str], Union[Redditor, str]]]] = None, redditors: Optional[List[Union[Redditor, str]]] = None, subreddits: Optional[List[Union[str, asyncpraw.models.Subreddit]]] = None, things: Optional[List[Union[Comment, Submission]]] = None, **generator_kwargs: Any) AsyncGenerator[asyncpraw.models.ModNote, None]

Get note(s) for each subreddit/user pair, or None if they don’t have any.

Parameters
  • all_notes

    Whether to return all notes or only the latest note for each subreddit/redditor pair (default: False).

    Note

    Setting this to True will result in a request for each unique subreddit/redditor pair. If subreddits and redditors are provided, this will make a request equivalent to number of redditors multiplied by the number of subreddits.

  • pairs

    A list of subreddit/redditor tuples.

    Note

    Required if subreddits, redditors, nor things are provided.

  • redditors

    A list of redditors to return notes for. This parameter is used in tandem with subreddits to get notes from multiple subreddits for each of the provided redditors.

    Note

    Required if items or things is not provided or if subreddits is provided.

  • subreddits

    A list of subreddits to return notes for. This parameter is used in tandem with redditors to get notes for multiple redditors from each of the provided subreddits.

    Note

    Required if items or things is not provided or if redditors is provided.

  • things – A list of comments and/or submissions to return notes for.

  • generator_kwargs – Additional keyword arguments passed to the generator. This parameter is ignored when all_notes is False.

Returns

A generator that yields the most recent ModNote (or None if the user doesn’t have any notes) per entry in their relative order. If all_notes is True, this will yield all notes for each entry.

Note

This method will merge the subreddits and redditors provided from pairs, redditors, subreddits, and things.

Note

This method accepts Redditor instances or redditor names and Subreddit instances or subreddit names where applicable.

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}")

For example, all the notes for u/spez and u/bboe in r/announcements, r/redditdev, and r/test can be iterated through like so:

redditor = await reddit.redditor("bboe")
subreddit = await reddit.subreddit("redditdev")

async for note in reddit.notes(
    redditors=["spez", redditor],
    subreddits=["announcements", subreddit, "test"],
    all_notes=True,
):
    print(f"{note.label}: {note.note}")

For example, the latest note for the authors of the last 5 comments and submissions from r/test can be iterated through like so:

submissions = [submission async for submission in reddit.subreddit("test").new(limit=5)]
comments = [comment async for comment in reddit.subreddit("test").comments(limit=5)]

async for note in reddit.notes(things=submissions + comments):
    print(f"{note.label}: {note.note}")

Note

Setting all_notes to True will make a request for each redditor and subreddit combination. The previous example will make 6 requests.

__init__(reddit: asyncpraw.Reddit)

Initialize a BaseModNotes instance.

Parameters

reddit – An instance of Reddit.

await create(*, label: Optional[str] = None, note: str, redditor: Optional[Union[Redditor, str]] = None, subreddit: Optional[Union[asyncpraw.models.Subreddit, str]] = None, thing: Optional[Union[Comment, Submission, str]] = None, **other_settings: Any) asyncpraw.models.ModNote

Create a ModNote for a redditor in the specified subreddit.

Parameters
  • label – The label for the note. As of this writing, this can be one of the following: "ABUSE_WARNING", "BAN", "BOT_BAN", "HELPFUL_USER", "PERMA_BAN", "SOLID_CONTRIBUTOR", "SPAM_WARNING", "SPAM_WATCH", or None (default: None).

  • note – The content of the note. As of this writing, this is limited to 250 characters.

  • redditor

    The redditor to create the note for (default: None).

    Note

    This parameter is required if thing is not provided or this is not called from a Redditor instance (e.g., reddit.redditor.notes).

  • subreddit

    The subreddit associated with the note (default: None).

    Note

    This parameter is required if thing is not provided or this is not called from a Subreddit instance (e.g., reddit.subreddit.mod).

  • thing – Either the fullname of a comment/submission, a Comment, or a Submission to associate with the note.

  • other_settings – Additional keyword arguments can be provided to handle new parameters as Reddit introduces them.

Returns

The new ModNote object.

For example, to create a note for u/spez in r/test:

subreddit = await reddit.subreddit("test")
await subreddit.mod.notes.create(
    label="HELPFUL_USER", note="Test note", redditor="spez"
)
# or
redditor = await reddit.redditor("spez")
await redditor.mod.notes.create(
    label="HELPFUL_USER", note="Test note", subreddit="test"
)
# or
await reddit.notes.create(
    label="HELPFUL_USER", note="Test note", redditor="spez", subreddit="test"
)
await delete(*, delete_all: bool = False, note_id: Optional[str] = None, redditor: Optional[Union[Redditor, str]] = None, subreddit: Optional[Union[asyncpraw.models.Subreddit, str]] = None)

Delete note(s) for a redditor.

Parameters
  • delete_all

    When True, delete all notes for the specified redditor in the specified subreddit (default: False).

    Note

    This will make a request for each note.

  • note_id – The ID of the note to delete. This parameter is ignored if delete_all is True.

  • redditor

    The redditor to delete the note(s) for (default: None). Can be a Redditor instance or a redditor name.

    Note

    This parameter is required if this method is not called from a Redditor instance (e.g., redditor.notes).

  • subreddit

    The subreddit to delete the note(s) from (default: None). Can be a Subreddit instance or a subreddit name.

    Note

    This parameter is required if this method is not called from a Subreddit instance (e.g., reddit.subreddit.mod).

For example, to delete a note with the ID "ModNote_d324b280-5ecc-435d-8159-3e259e84e339", try:

subreddit = await reddit.subreddit("test")
await subreddit.mod.notes.delete(
    note_id="ModNote_d324b280-5ecc-435d-8159-3e259e84e339", redditor="spez"
)
# or
redditor = await reddit.redditor("spez")
await redditor.notes.delete(
    note_id="ModNote_d324b280-5ecc-435d-8159-3e259e84e339", subreddit="test"
)
# or
await reddit.notes.delete(
    note_id="ModNote_d324b280-5ecc-435d-8159-3e259e84e339",
    subreddit="test",
    redditor="spez",
)

To delete all notes for u/spez, try:

subreddit = await reddit.subreddit("test")
await subreddit.mod.notes.delete(delete_all=True, redditor="spez")
# or
redditor = await reddit.redditor("spez")
await redditor.notes.delete(delete_all=True, subreddit="test")
# or
await reddit.notes.delete(delete_all=True, subreddit="test", redditor="spez")
things(*things: Union[Comment, Submission], all_notes: Optional[bool] = None, **generator_kwargs: Any) AsyncGenerator[asyncpraw.models.ModNote, None]

Return notes associated with the author of a Comment or Submission.

Parameters
  • things – One or more things to return notes on. Must be a Comment or Submission.

  • all_notes

    Whether to return all notes, or only the latest (default: True if only one thing is provided otherwise False).

    Note

    Setting this to True will result in a request for each thing.

Returns

A generator that yields the most recent ModNote (or None if the user doesn’t have any notes) per entry in their relative order. If all_notes is True, this will yield all notes for each entry.

For example, to get the latest note for the authors of the top 25 submissions in r/test:

subreddit = await reddit.subreddit("test")
submissions = [submission async for submission in subreddit.top(limit=25)]
async for note in reddit.notes.things(*submissions):
    print(f"{note.label}: {note.note}")

For example, to get the latest note for the authors of the last 25 comments in r/test:

subreddit = await reddit.subreddit("test")
comments = [comment async for comment in subreddit.comments(limit=25)]
async for note in reddit.notes.things(*comments):
    print(f"{note.label}: {note.note}")

RedditorModNotes

class asyncpraw.models.RedditorModNotes(reddit: asyncpraw.Reddit, redditor: Union[Redditor, str])

Provides methods to interact with moderator notes at the redditor level.

Note

The authenticated user must be a moderator of the provided subreddit(s).

For example, all the notes for u/spez in r/test can be iterated through like so:

redditor = await reddit.redditor("spez")

async for note in redditor.notes.subreddits("test"):
    print(f"{note.label}: {note.note}")
__init__(reddit: asyncpraw.Reddit, redditor: Union[Redditor, str])

Initialize a RedditorModNotes instance.

Parameters
  • reddit – An instance of Reddit.

  • redditor – An instance of Redditor.

await create(*, label: Optional[str] = None, note: str, redditor: Optional[Union[Redditor, str]] = None, subreddit: Optional[Union[asyncpraw.models.Subreddit, str]] = None, thing: Optional[Union[Comment, Submission, str]] = None, **other_settings: Any) asyncpraw.models.ModNote

Create a ModNote for a redditor in the specified subreddit.

Parameters
  • label – The label for the note. As of this writing, this can be one of the following: "ABUSE_WARNING", "BAN", "BOT_BAN", "HELPFUL_USER", "PERMA_BAN", "SOLID_CONTRIBUTOR", "SPAM_WARNING", "SPAM_WATCH", or None (default: None).

  • note – The content of the note. As of this writing, this is limited to 250 characters.

  • redditor

    The redditor to create the note for (default: None).

    Note

    This parameter is required if thing is not provided or this is not called from a Redditor instance (e.g., reddit.redditor.notes).

  • subreddit

    The subreddit associated with the note (default: None).

    Note

    This parameter is required if thing is not provided or this is not called from a Subreddit instance (e.g., reddit.subreddit.mod).

  • thing – Either the fullname of a comment/submission, a Comment, or a Submission to associate with the note.

  • other_settings – Additional keyword arguments can be provided to handle new parameters as Reddit introduces them.

Returns

The new ModNote object.

For example, to create a note for u/spez in r/test:

subreddit = await reddit.subreddit("test")
await subreddit.mod.notes.create(
    label="HELPFUL_USER", note="Test note", redditor="spez"
)
# or
redditor = await reddit.redditor("spez")
await redditor.mod.notes.create(
    label="HELPFUL_USER", note="Test note", subreddit="test"
)
# or
await reddit.notes.create(
    label="HELPFUL_USER", note="Test note", redditor="spez", subreddit="test"
)
await delete(*, delete_all: bool = False, note_id: Optional[str] = None, redditor: Optional[Union[Redditor, str]] = None, subreddit: Optional[Union[asyncpraw.models.Subreddit, str]] = None)

Delete note(s) for a redditor.

Parameters
  • delete_all

    When True, delete all notes for the specified redditor in the specified subreddit (default: False).

    Note

    This will make a request for each note.

  • note_id – The ID of the note to delete. This parameter is ignored if delete_all is True.

  • redditor

    The redditor to delete the note(s) for (default: None). Can be a Redditor instance or a redditor name.

    Note

    This parameter is required if this method is not called from a Redditor instance (e.g., redditor.notes).

  • subreddit

    The subreddit to delete the note(s) from (default: None). Can be a Subreddit instance or a subreddit name.

    Note

    This parameter is required if this method is not called from a Subreddit instance (e.g., reddit.subreddit.mod).

For example, to delete a note with the ID "ModNote_d324b280-5ecc-435d-8159-3e259e84e339", try:

subreddit = await reddit.subreddit("test")
await subreddit.mod.notes.delete(
    note_id="ModNote_d324b280-5ecc-435d-8159-3e259e84e339", redditor="spez"
)
# or
redditor = await reddit.redditor("spez")
await redditor.notes.delete(
    note_id="ModNote_d324b280-5ecc-435d-8159-3e259e84e339", subreddit="test"
)
# or
await reddit.notes.delete(
    note_id="ModNote_d324b280-5ecc-435d-8159-3e259e84e339",
    subreddit="test",
    redditor="spez",
)

To delete all notes for u/spez, try:

subreddit = await reddit.subreddit("test")
await subreddit.mod.notes.delete(delete_all=True, redditor="spez")
# or
redditor = await reddit.redditor("spez")
await redditor.notes.delete(delete_all=True, subreddit="test")
# or
await reddit.notes.delete(delete_all=True, subreddit="test", redditor="spez")
subreddits(*subreddits: Union[asyncpraw.models.Subreddit, str], all_notes: Optional[bool] = None, **generator_kwargs: Any) AsyncGenerator[asyncpraw.models.ModNote, None]

Return notes for this Redditor from one or more subreddits.

Parameters
  • subreddits – One or more subreddits to retrieve the notes from. Must be either a Subreddit or a subreddit name.

  • all_notes

    Whether to return all notes or only the latest note (default: True if only one subreddit is provided otherwise False).

    Note

    Setting this to True will result in a request for each subreddit.

Returns

A generator that yields the most recent ModNote (or None if this redditor doesn’t have any notes) per subreddit in their relative order. If all_notes is True, this will yield all notes or None from each subreddit for this redditor.

For example, all the notes for u/spez in r/test can be iterated through like so:

redditor = await reddit.redditor("spez")

async for note in redditor.notes.subreddits("test"):
    print(f"{note.label}: {note.note}")

For example, the latest note for u/spez from r/test and r/redditdev can be iterated through like so:

redditor = await reddit.redditor("spez")
subreddit = await reddit.subreddit("redditdev")

async for note in redditor.notes.subreddits("test", subreddit):
    print(f"{note.label}: {note.note}")

For example, all the notes for u/spez in r/test and r/redditdev can be iterated through like so:

redditor = await reddit.redditor("spez")
subreddit = await reddit.subreddit("redditdev")

async for note in redditor.notes.subreddits("test", subreddit, all_notes=True):
    print(f"{note.label}: {note.note}")

SubredditModNotes

class asyncpraw.models.SubredditModNotes(reddit: asyncpraw.Reddit, subreddit: Union[asyncpraw.models.Subreddit, str])

Provides methods to interact with moderator notes at the subreddit level.

Note

The authenticated user must be a moderator of this subreddit.

For example, all the notes for u/spez in r/test can be iterated through like so:

subreddit = await reddit.subreddit("test")

async for note in subreddit.mod.notes.redditors("spez"):
    print(f"{note.label}: {note.note}")
__init__(reddit: asyncpraw.Reddit, subreddit: Union[asyncpraw.models.Subreddit, str])

Initialize a SubredditModNotes instance.

Parameters
  • reddit – An instance of Reddit.

  • subreddit – An instance of Subreddit.

await create(*, label: Optional[str] = None, note: str, redditor: Optional[Union[Redditor, str]] = None, subreddit: Optional[Union[asyncpraw.models.Subreddit, str]] = None, thing: Optional[Union[Comment, Submission, str]] = None, **other_settings: Any) asyncpraw.models.ModNote

Create a ModNote for a redditor in the specified subreddit.

Parameters
  • label – The label for the note. As of this writing, this can be one of the following: "ABUSE_WARNING", "BAN", "BOT_BAN", "HELPFUL_USER", "PERMA_BAN", "SOLID_CONTRIBUTOR", "SPAM_WARNING", "SPAM_WATCH", or None (default: None).

  • note – The content of the note. As of this writing, this is limited to 250 characters.

  • redditor

    The redditor to create the note for (default: None).

    Note

    This parameter is required if thing is not provided or this is not called from a Redditor instance (e.g., reddit.redditor.notes).

  • subreddit

    The subreddit associated with the note (default: None).

    Note

    This parameter is required if thing is not provided or this is not called from a Subreddit instance (e.g., reddit.subreddit.mod).

  • thing – Either the fullname of a comment/submission, a Comment, or a Submission to associate with the note.

  • other_settings – Additional keyword arguments can be provided to handle new parameters as Reddit introduces them.

Returns

The new ModNote object.

For example, to create a note for u/spez in r/test:

subreddit = await reddit.subreddit("test")
await subreddit.mod.notes.create(
    label="HELPFUL_USER", note="Test note", redditor="spez"
)
# or
redditor = await reddit.redditor("spez")
await redditor.mod.notes.create(
    label="HELPFUL_USER", note="Test note", subreddit="test"
)
# or
await reddit.notes.create(
    label="HELPFUL_USER", note="Test note", redditor="spez", subreddit="test"
)
await delete(*, delete_all: bool = False, note_id: Optional[str] = None, redditor: Optional[Union[Redditor, str]] = None, subreddit: Optional[Union[asyncpraw.models.Subreddit, str]] = None)

Delete note(s) for a redditor.

Parameters
  • delete_all

    When True, delete all notes for the specified redditor in the specified subreddit (default: False).

    Note

    This will make a request for each note.

  • note_id – The ID of the note to delete. This parameter is ignored if delete_all is True.

  • redditor

    The redditor to delete the note(s) for (default: None). Can be a Redditor instance or a redditor name.

    Note

    This parameter is required if this method is not called from a Redditor instance (e.g., redditor.notes).

  • subreddit

    The subreddit to delete the note(s) from (default: None). Can be a Subreddit instance or a subreddit name.

    Note

    This parameter is required if this method is not called from a Subreddit instance (e.g., reddit.subreddit.mod).

For example, to delete a note with the ID "ModNote_d324b280-5ecc-435d-8159-3e259e84e339", try:

subreddit = await reddit.subreddit("test")
await subreddit.mod.notes.delete(
    note_id="ModNote_d324b280-5ecc-435d-8159-3e259e84e339", redditor="spez"
)
# or
redditor = await reddit.redditor("spez")
await redditor.notes.delete(
    note_id="ModNote_d324b280-5ecc-435d-8159-3e259e84e339", subreddit="test"
)
# or
await reddit.notes.delete(
    note_id="ModNote_d324b280-5ecc-435d-8159-3e259e84e339",
    subreddit="test",
    redditor="spez",
)

To delete all notes for u/spez, try:

subreddit = await reddit.subreddit("test")
await subreddit.mod.notes.delete(delete_all=True, redditor="spez")
# or
redditor = await reddit.redditor("spez")
await redditor.notes.delete(delete_all=True, subreddit="test")
# or
await reddit.notes.delete(delete_all=True, subreddit="test", redditor="spez")
redditors(*redditors: Union[Redditor, str], all_notes: Optional[bool] = None, **generator_kwargs: Any) AsyncGenerator[asyncpraw.models.ModNote, None]

Return notes from this Subreddit for one or more redditors.

Parameters
  • redditors – One or more redditors to retrieve notes for. Must be either a Redditor or a redditor name.

  • all_notes

    Whether to return all notes or only the latest note (default: True if only one redditor is provided otherwise False).

    Note

    Setting this to True will result in a request for each redditor.

Returns

A generator that yields the most recent ModNote (or None if the user doesn’t have any notes in this subreddit) per redditor in their relative order. If all_notes is True, this will yield all notes for each redditor.

For example, all the notes for u/spez in r/test can be iterated through like so:

subreddit = await reddit.subreddit("test")

async for note in subreddit.mod.notes.redditors("spez"):
    print(f"{note.label}: {note.note}")

For example, the latest note for u/spez and u/bboe from r/test can be iterated through like so:

subreddit = await reddit.subreddit("test")
redditor = await reddit.redditor("bboe")

async for note in subreddit.mod.notes.redditors("spez", redditor):
    print(f"{note.label}: {note.note}")

For example, all the notes for both u/spez and u/bboe in r/test can be iterated through like so:

subreddit = await reddit.subreddit("test")
redditor = await reddit.redditor("bboe")

async for note in subreddit.mod.notes.redditors("spez", redditor, all_notes=True):
    print(f"{note.label}: {note.note}")

CommentModeration

class asyncpraw.models.reddit.comment.CommentModeration(comment: asyncpraw.models.Comment)

Provide a set of functions pertaining to Comment moderation.

Example usage:

comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.approve()
__init__(comment: asyncpraw.models.Comment)

Initialize a CommentModeration instance.

Parameters

comment – The comment to moderate.

await approve()

Approve a Comment or Submission.

Approving a comment or submission reverts a removal, resets the report counter, adds a green check mark indicator (only visible to other moderators) on the website view, and sets the approved_by attribute to the authenticated user.

Example usage:

# approve a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.approve()
# approve a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.approve()
author_notes(**generator_kwargs) AsyncGenerator[asyncpraw.models.ModNote, None]

Get the moderator notes for the author of this object in the subreddit it’s posted in.

Parameters

generator_kwargs – Additional keyword arguments are passed in the initialization of the moderator note generator.

Returns

A generator of ModNote.

For example, to list all notes the author of a submission, try:

for note in reddit.submission("92dd8").mod.author_notes():
    print(f"{note.label}: {note.note}")
await create_note(*, label: Optional[str] = None, note: str, **other_settings) asyncpraw.models.ModNote

Create a moderator note on the author of this object in the subreddit it’s posted in.

Parameters
  • label – The label for the note. As of this writing, this can be one of the following: "ABUSE_WARNING", "BAN", "BOT_BAN", "HELPFUL_USER", "PERMA_BAN", "SOLID_CONTRIBUTOR", "SPAM_WARNING", "SPAM_WATCH", or None (default: None).

  • note – The content of the note. As of this writing, this is limited to 250 characters.

  • other_settings – Additional keyword arguments are passed to create().

Returns

The new ModNote object.

For example, to create a note on a Submission, try:

submission = await reddit.submission("92dd8")
await submission.mod.create_note(label="HELPFUL_USER", note="Test note")
await distinguish(*, how: str = 'yes', sticky: bool = False)

Distinguish a Comment or Submission.

Parameters
  • how – One of "yes", "no", "admin", or "special". "yes" adds a moderator level distinguish. "no" removes any distinction. "admin" and "special" require special user privileges to use (default "yes").

  • stickyComment is stickied if True, placing it at the top of the comment page regardless of score. If thing is not a top-level comment, this parameter is silently ignored (default False).

Example usage:

# distinguish and sticky a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.distinguish(sticky=True)
# undistinguish a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.distinguish(how="no")

See also

undistinguish()

await ignore_reports()

Ignore future reports on a Comment or Submission.

Calling this method will prevent future reports on this Comment or Submission from both triggering notifications and appearing in the various moderation listings. The report count will still increment on the Comment or Submission.

Example usage:

# ignore future reports on a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.ignore_reports()
# ignore future reports on a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.ignore_reports()
await lock()

Lock a Comment or Submission.

Example usage:

# lock a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.lock()
# lock a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.lock()

See also

unlock()

await remove(*, mod_note: str = '', spam: bool = False, reason_id: Optional[str] = None)

Remove a Comment or Submission.

Parameters
  • mod_note – A message for the other moderators.

  • spam – When True, use the removal to help train the Subreddit’s spam filter (default: False).

  • reason_id – The removal reason ID.

If either reason_id or mod_note are provided, a second API call is made to add the removal reason.

Example usage:

# remove a comment and mark as spam:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.remove(spam=True)
# remove a submission
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.remove()
# remove a submission with a removal reason
sub = await reddit.subreddit("test")
reason = await sub.mod.removal_reasons.get_reason("110ni21zo23ql")
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.remove(reason_id=reason.id)
await send_removal_message(*, message: str, title: str = 'ignored', type: str = 'public') Optional[asyncpraw.models.Comment]

Send a removal message for a Comment or Submission.

Warning

The object has to be removed before giving it a removal reason. Remove the object with remove(). Trying to add a removal reason without removing the object will result in RedditAPIException being thrown with an INVALID_ID error_type.

Reddit adds human-readable information about the object to the message.

Parameters
  • type – One of "public", "private", or "private_exposed". "public" leaves a stickied comment on the post. "private" sends a modmail message with hidden username. "private_exposed" sends a modmail message without hidden username (default: "public").

  • title – The short reason given in the message. Ignored if type is "public".

  • message – The body of the message.

Returns

The new Comment if type is "public".

await show()

Uncollapse a Comment that has been collapsed by Crowd Control.

Example usage:

# Uncollapse a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.show()
await undistinguish()

Remove mod, admin, or special distinguishing from an object.

Also unstickies the object if applicable.

Example usage:

# undistinguish a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.undistinguish()
# undistinguish a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.undistinguish()

See also

distinguish()

await unignore_reports()

Resume receiving future reports on a Comment or Submission.

Future reports on this Comment or Submission will cause notifications, and appear in the various moderation listings.

Example usage:

# accept future reports on a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.unignore_reports()
# accept future reports on a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.unignore_reports()

See also

ignore_reports()

await unlock()

Unlock a Comment or Submission.

Example usage:

# unlock a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.unlock()
# unlock a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.unlock()

See also

lock()

RuleModeration

class asyncpraw.models.reddit.rules.RuleModeration(rule: asyncpraw.models.Rule)

Contain methods used to moderate rules.

To delete "No spam" from r/test try:

subreddit = await reddit.subreddit("test")
rule = await subreddit.rules.get_rule("No Spam")
await rule.mod.delete()

To update "No spam" from r/test try:

subreddit = await reddit.subreddit("test")
rule = await subreddit.rules.get_rule("No Spam")
await rule.mod.update(description="Don't do this!", violation_reason="Spam post")
__init__(rule: asyncpraw.models.Rule)

Initialize a RuleModeration instance.

await delete()

Delete a rule from this subreddit.

To delete "No spam" from r/test try:

subreddit = await reddit.subreddit("test")
rule = await subreddit.rules.get_rule("No Spam")
await rule.mod.delete()
await update(*, description: Optional[str] = None, kind: Optional[str] = None, short_name: Optional[str] = None, violation_reason: Optional[str] = None) asyncpraw.models.Rule

Update the rule from this subreddit.

Note

Existing values will be used for any unspecified arguments.

Parameters
  • description – The new description for the rule. Can be empty.

  • kind – The kind of item that the rule applies to. One of "link", "comment", or "all".

  • short_name – The name of the rule.

  • violation_reason – The reason that is shown on the report menu.

Returns

A Rule object containing the updated values.

To update "No spam" from r/test try:

subreddit = reddit.subreddit("test")
rule = await subreddit.rules.get_rule("No Spam")
await rule.mod.update(description="Don't do this!", violation_reason="Spam post")

SubmissionModeration

class asyncpraw.models.reddit.submission.SubmissionModeration(submission: asyncpraw.models.Submission)

Provide a set of functions pertaining to Submission moderation.

Example usage:

submission = await reddit.submission("8dmv8z", fetch=False)
await submission.mod.approve()
__init__(submission: asyncpraw.models.Submission)

Initialize a SubmissionModeration instance.

Parameters

submission – The submission to moderate.

await approve()

Approve a Comment or Submission.

Approving a comment or submission reverts a removal, resets the report counter, adds a green check mark indicator (only visible to other moderators) on the website view, and sets the approved_by attribute to the authenticated user.

Example usage:

# approve a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.approve()
# approve a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.approve()
author_notes(**generator_kwargs) AsyncGenerator[asyncpraw.models.ModNote, None]

Get the moderator notes for the author of this object in the subreddit it’s posted in.

Parameters

generator_kwargs – Additional keyword arguments are passed in the initialization of the moderator note generator.

Returns

A generator of ModNote.

For example, to list all notes the author of a submission, try:

for note in reddit.submission("92dd8").mod.author_notes():
    print(f"{note.label}: {note.note}")
await contest_mode(*, state: bool = True)

Set contest mode for the comments of this submission.

Parameters

stateTrue enables contest mode and False disables (default: True).

Contest mode have the following effects:

  • The comment thread will default to being sorted randomly.

  • Replies to top-level comments will be hidden behind “[show replies]” buttons.

  • Scores will be hidden from non-moderators.

  • Scores accessed through the API (mobile apps, bots) will be obscured to “1” for non-moderators.

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.contest_mode()
await create_note(*, label: Optional[str] = None, note: str, **other_settings) asyncpraw.models.ModNote

Create a moderator note on the author of this object in the subreddit it’s posted in.

Parameters
  • label – The label for the note. As of this writing, this can be one of the following: "ABUSE_WARNING", "BAN", "BOT_BAN", "HELPFUL_USER", "PERMA_BAN", "SOLID_CONTRIBUTOR", "SPAM_WARNING", "SPAM_WATCH", or None (default: None).

  • note – The content of the note. As of this writing, this is limited to 250 characters.

  • other_settings – Additional keyword arguments are passed to create().

Returns

The new ModNote object.

For example, to create a note on a Submission, try:

submission = await reddit.submission("92dd8")
await submission.mod.create_note(label="HELPFUL_USER", note="Test note")
await distinguish(*, how: str = 'yes', sticky: bool = False)

Distinguish a Comment or Submission.

Parameters
  • how – One of "yes", "no", "admin", or "special". "yes" adds a moderator level distinguish. "no" removes any distinction. "admin" and "special" require special user privileges to use (default "yes").

  • stickyComment is stickied if True, placing it at the top of the comment page regardless of score. If thing is not a top-level comment, this parameter is silently ignored (default False).

Example usage:

# distinguish and sticky a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.distinguish(sticky=True)
# undistinguish a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.distinguish(how="no")

See also

undistinguish()

await flair(*, css_class: str = '', flair_template_id: Optional[str] = None, text: str = '')

Set flair for the submission.

Parameters
  • css_class – The css class to associate with the flair html (default: "").

  • flair_template_id – The flair template ID to use when flairing.

  • text – The flair text to associate with the Submission (default: "").

This method can only be used by an authenticated user who is a moderator of the submission’s Subreddit.

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.flair(text="PRAW", css_class="bot")
await ignore_reports()

Ignore future reports on a Comment or Submission.

Calling this method will prevent future reports on this Comment or Submission from both triggering notifications and appearing in the various moderation listings. The report count will still increment on the Comment or Submission.

Example usage:

# ignore future reports on a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.ignore_reports()
# ignore future reports on a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.ignore_reports()
await lock()

Lock a Comment or Submission.

Example usage:

# lock a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.lock()
# lock a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.lock()

See also

unlock()

await nsfw()

Mark as not safe for work.

This method can be used both by the submission author and moderators of the subreddit that the submission belongs to.

Example usage:

subreddit = await reddit.subreddit("test")
submission = await subreddit.submit("nsfw test", selftext="nsfw")
await submission.mod.nsfw()

See also

sfw()

await remove(*, mod_note: str = '', spam: bool = False, reason_id: Optional[str] = None)

Remove a Comment or Submission.

Parameters
  • mod_note – A message for the other moderators.

  • spam – When True, use the removal to help train the Subreddit’s spam filter (default: False).

  • reason_id – The removal reason ID.

If either reason_id or mod_note are provided, a second API call is made to add the removal reason.

Example usage:

# remove a comment and mark as spam:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.remove(spam=True)
# remove a submission
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.remove()
# remove a submission with a removal reason
sub = await reddit.subreddit("test")
reason = await sub.mod.removal_reasons.get_reason("110ni21zo23ql")
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.remove(reason_id=reason.id)
await send_removal_message(*, message: str, title: str = 'ignored', type: str = 'public') Optional[asyncpraw.models.Comment]

Send a removal message for a Comment or Submission.

Warning

The object has to be removed before giving it a removal reason. Remove the object with remove(). Trying to add a removal reason without removing the object will result in RedditAPIException being thrown with an INVALID_ID error_type.

Reddit adds human-readable information about the object to the message.

Parameters
  • type – One of "public", "private", or "private_exposed". "public" leaves a stickied comment on the post. "private" sends a modmail message with hidden username. "private_exposed" sends a modmail message without hidden username (default: "public").

  • title – The short reason given in the message. Ignored if type is "public".

  • message – The body of the message.

Returns

The new Comment if type is "public".

await set_original_content()

Mark as original content.

This method can be used by moderators of the subreddit that the submission belongs to. If the subreddit has enabled the Original Content beta feature in settings, then the submission’s author can use it as well.

Example usage:

subreddit = await reddit.subreddit("test")
submission = await subreddit.submit("oc test", selftext="original")
await submission.mod.set_original_content()
await sfw()

Mark as safe for work.

This method can be used both by the submission author and moderators of the subreddit that the submission belongs to.

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.sfw()

See also

nsfw()

await spoiler()

Indicate that the submission contains spoilers.

This method can be used both by the submission author and moderators of the subreddit that the submission belongs to.

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.spoiler()

See also

unspoiler()

await sticky(*, bottom: bool = True, state: bool = True)

Set the submission’s sticky state in its subreddit.

Parameters
  • bottom – When True, set the submission as the bottom sticky. If no top sticky exists, this submission will become the top sticky regardless (default: True).

  • stateTrue sets the sticky for the submission and False unsets (default: True).

Note

When a submission is stickied two or more times, the Reddit API responds with a 409 error that is raised as a Conflict by asyncprawcore. This method suppresses these Conflict errors.

This submission will replace the second stickied submission if one exists.

For example:

submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.sticky()
await suggested_sort(*, sort: str = 'blank')

Set the suggested sort for the comments of the submission.

Parameters

sort – Can be one of: "confidence", "top", "new", "controversial", "old", "random", "qa", or "blank" (default: "blank").

await undistinguish()

Remove mod, admin, or special distinguishing from an object.

Also unstickies the object if applicable.

Example usage:

# undistinguish a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.undistinguish()
# undistinguish a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.undistinguish()

See also

distinguish()

await unignore_reports()

Resume receiving future reports on a Comment or Submission.

Future reports on this Comment or Submission will cause notifications, and appear in the various moderation listings.

Example usage:

# accept future reports on a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.unignore_reports()
# accept future reports on a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.unignore_reports()

See also

ignore_reports()

await unlock()

Unlock a Comment or Submission.

Example usage:

# unlock a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.unlock()
# unlock a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.unlock()

See also

lock()

await unset_original_content()

Indicate that the submission is not original content.

This method can be used by moderators of the subreddit that the submission belongs to. If the subreddit has enabled the Original Content beta feature in settings, then the submission’s author can use it as well.

Example usage:

subreddit = await reddit.subreddit("test")
submission = await subreddit.submit("oc test", selftext="original")
await submission.mod.unset_original_content()
await unspoiler()

Indicate that the submission does not contain spoilers.

This method can be used both by the submission author and moderators of the subreddit that the submission belongs to.

For example:

sub = await reddit.subreddit("test")
submission = await sub.submit("not spoiler", selftext="spoiler")
await submission.mod.unspoiler()

See also

spoiler()

await update_crowd_control_level(level: int)

Change the Crowd Control level of the submission.

Parameters

level – An integer between 0 and 3.

Level Descriptions

Level

Name

Description

0

Off

Crowd Control will not action any of the submission’s comments.

1

Lenient

Comments from users who have negative karma in the subreddit are automatically collapsed.

2

Moderate

Comments from new users and users with negative karma in the subreddit are automatically collapsed.

3

Strict

Comments from users who haven’t joined the subreddit, new users, and users with negative karma in the subreddit are automatically collapsed.

Example usage:

submission = await reddit.submission("745ryj")
await submission.mod.update_crowd_control_level(2)

See also

show()

SubredditModeration

class asyncpraw.models.reddit.subreddit.SubredditModeration(subreddit: asyncpraw.models.Subreddit)

Provides a set of moderation functions to a Subreddit.

For example, to accept a moderation invite from r/test:

subreddit = await reddit.subreddit("test")
await subreddit.mod.accept_invite()
__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a SubredditModeration instance.

Parameters

subreddit – The subreddit to moderate.

await accept_invite()

Accept an invitation as a moderator of the community.

edited(*, only: Optional[str] = None, **generator_kwargs: Any) AsyncIterator[Union[asyncpraw.models.Comment, asyncpraw.models.Submission]]

Return a ListingGenerator for edited comments and submissions.

Parameters

only – If specified, one of "comments" or "submissions" to yield only results of that type.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To print all items in the edited queue try:

subreddit = await reddit.subreddit("mod")
async for item in subreddit.mod.edited(limit=None):
    print(item)
inbox(**generator_kwargs: Any) AsyncIterator[asyncpraw.models.SubredditMessage]

Return a ListingGenerator for moderator messages.

Warning

Legacy modmail is being deprecated in June 2021. Please see https://www.reddit.com/r/modnews/comments/mar9ha/even_more_modmail_improvements/ for more info.

Additional keyword arguments are passed in the initialization of ListingGenerator.

See also

unread() for unread moderator messages.

To print the last 5 moderator mail messages and their replies, try:

subreddit = await reddit.subreddit("mod")
async for message in subreddit.mod.inbox(limit=5):
    print("From: {}, Body: {}".format(message.author, message.body))
    for reply in message.replies:
        print("From: {}, Body: {}".format(reply.author, reply.body))
log(*, action: Optional[str] = None, mod: Optional[Union[asyncpraw.models.Redditor, str]] = None, **generator_kwargs: Any) AsyncIterator[asyncpraw.models.ModAction]

Return a ListingGenerator for moderator log entries.

Parameters
  • action – If given, only return log entries for the specified action.

  • mod – If given, only return log entries for actions made by the passed in redditor.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To print the moderator and subreddit of the last 5 modlog entries try:

subreddit = await reddit.subreddit("mod")
async for log in subreddit.mod.log(limit=5):
    print("Mod: {}, Subreddit: {}".format(log.mod, log.subreddit))
modqueue(*, only: Optional[str] = None, **generator_kwargs: Any) AsyncIterator[Union[asyncpraw.models.Comment, asyncpraw.models.Submission]]

Return a ListingGenerator for modqueue items.

Parameters

only – If specified, one of "comments" or "submissions" to yield only results of that type.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To print all modqueue items try:

subreddit = await reddit.subreddit("mod")
async for item in subreddit.mod.modqueue(limit=None):
    print(item)
notes() asyncpraw.models.SubredditModNotes

Provide an instance of SubredditModNotes.

This provides an interface for managing moderator notes for this subreddit.

For example, all the notes for u/spez in r/test can be iterated through like so:

subreddit = await reddit.subreddit("test")

async for note in subreddit.mod.notes.redditors("spez"):
    print(f"{note.label}: {note.note}")
removal_reasons() SubredditRemovalReasons

Provide an instance of SubredditRemovalReasons.

Use this attribute for interacting with a Subreddit’s removal reasons. For example, to list all the removal reasons for a subreddit which you have the posts moderator permission on, try:

subreddit = await reddit.subreddit("test")
async for removal_reason in subreddit.mod.removal_reasons:
    print(removal_reason)

A single removal reason can be retrieved via:

subreddit = await reddit.subreddit("test")
await subreddit.mod.removal_reasons.get_reason("reason_id")

Note

Attempting to access attributes of a nonexistent removal reason will result in a ClientException.

reports(*, only: Optional[str] = None, **generator_kwargs: Any) AsyncIterator[Union[asyncpraw.models.Comment, asyncpraw.models.Submission]]

Return a ListingGenerator for reported comments and submissions.

Parameters

only – If specified, one of "comments" or "submissions" to yield only results of that type.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To print the user and mod report reasons in the report queue try:

subreddit = await reddit.subreddit("mod")
async for reported_item in subreddit.mod.reports():
    print("User Reports: {}".format(reported_item.user_reports))
    print("Mod Reports: {}".format(reported_item.mod_reports))
await settings() Dict[str, Union[str, int, bool]]

Return a dictionary of the Subreddit’s current settings.

spam(*, only: Optional[str] = None, **generator_kwargs: Any) AsyncIterator[Union[asyncpraw.models.Comment, asyncpraw.models.Submission]]

Return a ListingGenerator for spam comments and submissions.

Parameters

only – If specified, one of "comments" or "submissions" to yield only results of that type.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To print the items in the spam queue try:

subreddit = await reddit.subreddit("mod")
async for item in subreddit.mod.spam():
    print(item)
stream() asyncpraw.models.reddit.subreddit.SubredditModerationStream

Provide an instance of SubredditModerationStream.

Streams can be used to indefinitely retrieve Moderator only items from SubredditModeration made to moderated subreddits, like:

subreddit = await reddit.subreddit("mod")
async for log in subreddit.mod.stream.log():
    print("Mod: {}, Subreddit: {}".format(log.mod, log.subreddit))
unmoderated(**generator_kwargs: Any) AsyncIterator[asyncpraw.models.Submission]

Return a ListingGenerator for unmoderated submissions.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To print the items in the unmoderated queue try:

subreddit = await reddit.subreddit("mod")
async for item in subreddit.mod.unmoderated():
    print(item)
unread(**generator_kwargs: Any) AsyncIterator[asyncpraw.models.SubredditMessage]

Return a ListingGenerator for unread moderator messages.

Warning

Legacy modmail is being deprecated in June 2021. Please see https://www.reddit.com/r/modnews/comments/mar9ha/even_more_modmail_improvements/ for more info.

Additional keyword arguments are passed in the initialization of ListingGenerator.

See also

inbox() for all messages.

To print the mail in the unread modmail queue try:

subreddit = await reddit.subreddit("mod")
async for message in subreddit.mod.unread():
    print("From: {}, To: {}".format(message.author, message.dest))
await update(**settings: Union[str, int, bool]) Dict[str, Union[str, int, bool]]

Update the Subreddit’s settings.

See https://www.reddit.com/dev/api#POST_api_site_admin for the full list.

Parameters
  • all_original_content – Mandate all submissions to be original content only.

  • allow_chat_post_creation – Allow users to create chat submissions.

  • allow_images – Allow users to upload images using the native image hosting.

  • allow_polls – Allow users to post polls to the subreddit.

  • allow_post_crossposts – Allow users to crosspost submissions from other subreddits.

  • allow_videos – Allow users to upload videos using the native image hosting.

  • collapse_deleted_comments – Collapse deleted and removed comments on comments pages by default.

  • comment_score_hide_mins – The number of minutes to hide comment scores.

  • content_options – The types of submissions users can make. One of "any", "link", or "self".

  • crowd_control_chat_level – Controls the crowd control level for chat rooms. Goes from 0-3.

  • crowd_control_level – Controls the crowd control level for submissions. Goes from 0-3.

  • crowd_control_mode – Enables/disables crowd control.

  • default_set – Allow the subreddit to appear on r/all as well as the default and trending lists.

  • disable_contributor_requests – Specifies whether redditors may send automated modmail messages requesting approval as a submitter.

  • exclude_banned_modqueue – Exclude posts by site-wide banned users from modqueue/unmoderated.

  • free_form_reports – Allow users to specify custom reasons in the report menu.

  • header_hover_text – The text seen when hovering over the snoo.

  • hide_ads – Don’t show ads within this subreddit. Only applies to Premium-user only subreddits.

  • key_color – A 6-digit rgb hex color (e.g., "#AABBCC"), used as a thematic color for your subreddit on mobile.

  • language – A valid IETF language tag (underscore separated).

  • original_content_tag_enabled – Enables the use of the original content label for submissions.

  • over_18 – Viewers must be over 18 years old (i.e., NSFW).

  • public_description – Public description blurb. Appears in search results and on the landing page for private subreddits.

  • restrict_commenting – Specifies whether approved users have the ability to comment.

  • restrict_posting – Specifies whether approved users have the ability to submit posts.

  • show_media – Show thumbnails on submissions.

  • show_media_preview – Expand media previews on comments pages.

  • spam_comments – Spam filter strength for comments. One of "all", "low", or "high".

  • spam_links – Spam filter strength for links. One of "all", "low", or "high".

  • spam_selfposts – Spam filter strength for selfposts. One of "all", "low", or "high".

  • spoilers_enabled – Enable marking posts as containing spoilers.

  • submit_link_label – Custom label for submit link button (None for default).

  • submit_text – Text to show on submission page.

  • submit_text_label – Custom label for submit text post button (None for default).

  • subreddit_type – One of "archived", "employees_only", "gold_only", gold_restricted, "private", "public", or "restricted".

  • suggested_comment_sort – All comment threads will use this sorting method by default. Leave None, or choose one of "confidence", "controversial", "live", "new", "old", "qa", "random", or "top".

  • title – The title of the subreddit.

  • welcome_message_enabled – Enables the subreddit welcome message.

  • welcome_message_text – The text to be used as a welcome message. A welcome message is sent to all new subscribers by a Reddit bot.

  • wiki_edit_age – Account age, in days, required to edit and create wiki pages.

  • wiki_edit_karma – Subreddit karma required to edit and create wiki pages.

  • wikimode – One of "anyone", "disabled", or "modonly".

Note

Updating the subreddit sidebar on old reddit (description) is no longer supported using this method. You can update the sidebar by editing the "config/sidebar" wiki page. For example:

subreddit = await reddit.subreddit("test")
sidebar = await subreddit.wiki.get_page("config/sidebar")
await sidebar.edit(content="new sidebar content")

Additional keyword arguments can be provided to handle new settings as Reddit introduces them.

Settings that are documented here and aren’t explicitly set by you in a call to SubredditModeration.update() should retain their current value. If they do not, please file a bug.

SubredditRulesModeration

class asyncpraw.models.reddit.rules.SubredditRulesModeration(subreddit_rules: SubredditRules)

Contain methods to moderate subreddit rules as a whole.

To add rule "No spam" to r/test try:

subreddit = await reddit.subreddit("test")
await subreddit.rules.mod.add(
    short_name="No spam", kind="all", description="Do not spam. Spam bad"
)

To move the fourth rule to the first position, and then to move the prior first rule to where the third rule originally was in r/test:

subreddit = await reddit.subreddit("test")
rules = [rule async for rule in subreddit.rules]
new_rules = rules[3:4] + rules[1:3] + rules[0:1] + rules[4:]
# Alternate: [rules[3]] + rules[1:3] + [rules[0]] + rules[4:]
new_rule_list = await subreddit.rules.mod.reorder(new_rules)
__init__(subreddit_rules: SubredditRules)

Initialize a SubredditRulesModeration instance.

await add(*, description: str = '', kind: str, short_name: str, violation_reason: Optional[str] = None) asyncpraw.models.Rule

Add a removal reason to this subreddit.

Parameters
  • description – The description for the rule.

  • kind – The kind of item that the rule applies to. One of "link", "comment", or "all".

  • short_name – The name of the rule.

  • violation_reason – The reason that is shown on the report menu. If a violation reason is not specified, the short name will be used as the violation reason.

Returns

The added Rule.

To add rule "No spam" to r/test try:

subreddit = await reddit.subreddit("test")
await subreddit.rules.mod.add(
    short_name="No spam", kind="all", description="Do not spam. Spam bad"
)
await reorder(rule_list: List[asyncpraw.models.Rule]) List[asyncpraw.models.Rule]

Reorder the rules of a subreddit.

Parameters

rule_list – The list of rules, in the wanted order. Each index of the list indicates the position of the rule.

Returns

A list containing the rules in the specified order.

For example, to move the fourth rule to the first position, and then to move the prior first rule to where the third rule originally was in r/test:

subreddit = await reddit.subreddit("test")
rules = [rule async for rule in subreddit.rules]
new_rules = rules[3:4] + rules[1:3] + rules[0:1] + rules[4:]
# Alternate: [rules[3]] + rules[1:3] + [rules[0]] + rules[4:]
new_rule_list = await subreddit.rules.mod.reorder(new_rules)

SubredditWidgetsModeration

class asyncpraw.models.SubredditWidgetsModeration(subreddit: asyncpraw.models.Subreddit, reddit: asyncpraw.Reddit)

Class for moderating a Subreddit’s widgets.

Get an instance of this class from SubredditWidgets.mod.

Example usage:

styles = {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}
subreddit = await reddit.subreddit("test")
await subreddit.widgets.mod.add_text_area(
    short_name="My title", text="**bold text**", styles=styles
)

Note

To use this class’s methods, the authenticated user must be a moderator with appropriate permissions.

__init__(subreddit: asyncpraw.models.Subreddit, reddit: asyncpraw.Reddit)

Initialize a SubredditWidgetsModeration instance.

await add_button_widget(*, buttons: List[Dict[str, Union[Dict[str, str], str, int, Dict[str, Union[str, int]]]]], description: str, short_name: str, styles: Dict[str, str], **other_settings) asyncpraw.models.ButtonWidget

Add and return a ButtonWidget.

Parameters
  • buttons

    A list of dictionaries describing buttons, as specified in Reddit docs. As of this writing, the format is:

    Each button is either a text button or an image button. A text button looks like this:

    {
        "kind": "text",
        "text": a string no longer than 30 characters,
        "url": a valid URL,
        "color": a 6-digit rgb hex color, e.g., `#AABBCC`,
        "textColor": a 6-digit rgb hex color, e.g., `#AABBCC`,
        "fillColor": a 6-digit rgb hex color, e.g., `#AABBCC`,
        "hoverState": {...}
    }
    

    An image button looks like this:

    {
        "kind": "image",
        "text": a string no longer than 30 characters,
        "linkUrl": a valid URL,
        "url": a valid URL of a Reddit-hosted image,
        "height": an integer,
        "width": an integer,
        "hoverState": {...}
    }
    

    Both types of buttons have the field hoverState. The field does not have to be included (it is optional). If it is included, it can be one of two types: "text" or "image". A text hoverState looks like this:

    {
        "kind": "text",
        "text": a string no longer than 30 characters,
        "color": a 6-digit rgb hex color, e.g., `#AABBCC`,
        "textColor": a 6-digit rgb hex color, e.g., `#AABBCC`,
        "fillColor": a 6-digit rgb hex color, e.g., `#AABBCC`
    }
    

    An image hoverState looks like this:

    {
        "kind": "image",
        "url": a valid URL of a Reddit-hosted image,
        "height": an integer,
        "width": an integer
    }
    

    Note

    The method upload_image() can be used to upload images to Reddit for a url field that holds a Reddit-hosted image.

    Note

    An image hoverState may be paired with a text widget, and a text hoverState may be paired with an image widget.

  • description – Markdown text to describe the widget.

  • short_name – A name for the widget, no longer than 30 characters.

  • styles – A dictionary with keys "backgroundColor" and "headerColor", and values of hex colors. For example, {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}.

Returns

The created ButtonWidget.

Example usage:

subreddit = await reddit.subreddit("test")
widget_moderation = subreddit.widgets.mod
my_image = await widget_moderation.upload_image("/path/to/pic.jpg")
buttons = [
    {
        "kind": "text",
        "text": "View source",
        "url": "https://github.com/asyncpraw-dev/asyncpraw",
        "color": "#FF0000",
        "textColor": "#00FF00",
        "fillColor": "#0000FF",
        "hoverState": {
            "kind": "text",
            "text": "ecruos weiV",
            "color": "#FFFFFF",
            "textColor": "#000000",
            "fillColor": "#0000FF",
        },
    },
    {
        "kind": "image",
        "text": "View documentation",
        "linkUrl": "https://asyncpraw.readthedocs.io",
        "url": my_image,
        "height": 200,
        "width": 200,
        "hoverState": {"kind": "image", "url": my_image, "height": 200, "width": 200},
    },
]
styles = {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}
new_widget = await widget_moderation.add_button_widget(
    short_name="Things to click",
    description="Click some of these *cool* links!",
    buttons=buttons,
    styles=styles,
)
await add_calendar(*, configuration: Dict[str, Union[bool, int]], google_calendar_id: str, requires_sync: bool, short_name: str, styles: Dict[str, str], **other_settings) asyncpraw.models.Calendar

Add and return a Calendar widget.

Parameters
  • configuration

    A dictionary as specified in Reddit docs. For example:

    {
        "numEvents": 10,
        "showDate": True,
        "showDescription": False,
        "showLocation": False,
        "showTime": True,
        "showTitle": True,
    }
    

  • google_calendar_id – An email-style calendar ID. To share a Google Calendar, make it public, then find the “Calendar ID”.

  • requires_sync – Whether the calendar needs synchronization.

  • short_name – A name for the widget, no longer than 30 characters.

  • styles – A dictionary with keys "backgroundColor" and "headerColor", and values of hex colors. For example, {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}.

Returns

The created Calendar.

Example usage:

subreddit = await reddit.subreddit("test")
widget_moderation = subreddit.widgets.mod
styles = {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}
config = {
    "numEvents": 10,
    "showDate": True,
    "showDescription": False,
    "showLocation": False,
    "showTime": True,
    "showTitle": True,
}
calendar_id = "y6nm89jy427drk8l71w75w9wjn@group.calendar.google.com"
new_widget = await widget_moderation.add_calendar(
    short_name="Upcoming Events",
    google_calendar_id=calendar_id,
    requires_sync=True,
    configuration=config,
    styles=styles,
)
await add_community_list(*, data: List[Union[str, asyncpraw.models.Subreddit]], description: str = '', short_name: str, styles: Dict[str, str], **other_settings) asyncpraw.models.CommunityList

Add and return a CommunityList widget.

Parameters
  • data – A list of subreddits. Subreddits can be represented as str or as Subreddit. These types may be mixed within the list.

  • description – A string containing Markdown (default: "").

  • short_name – A name for the widget, no longer than 30 characters.

  • styles – A dictionary with keys "backgroundColor" and "headerColor", and values of hex colors. For example, {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}.

Returns

The created CommunityList.

Example usage:

subreddit = await reddit.subreddit("test")
widget_moderation = subreddit.widgets.mod
styles = {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}
new_subreddit = await reddit.subreddit("test")
subreddits = ["learnpython", new_subreddit]
new_widget = await widget_moderation.add_community_list(
    short_name="My fav subs", data=subreddits, styles=styles, description="description"
)
await add_custom_widget(*, css: str, height: int, image_data: List[Dict[str, Union[str, int]]], short_name: str, styles: Dict[str, str], text: str, **other_settings) asyncpraw.models.CustomWidget

Add and return a CustomWidget.

Parameters
  • css

    The CSS for the widget, no longer than 100000 characters.

    Note

    As of this writing, Reddit will not accept empty CSS. If you wish to create a custom widget without CSS, consider using "/**/" (an empty comment) as your CSS.

  • height – The height of the widget, between 50 and 500.

  • image_data

    A list of dictionaries as specified in Reddit docs. Each dictionary represents an image and has the key "url" which maps to the URL of an image hosted on Reddit’s servers. Images should be uploaded using upload_image().

    For example:

    [
        {
            "url": "https://some.link",  # from upload_image()
            "width": 600,
            "height": 450,
            "name": "logo",
        },
        {
            "url": "https://other.link",  # from upload_image()
            "width": 450,
            "height": 600,
            "name": "icon",
        },
    ]
    

  • short_name – A name for the widget, no longer than 30 characters.

  • styles – A dictionary with keys "backgroundColor" and "headerColor", and values of hex colors. For example, {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}.

  • text – The Markdown text displayed in the widget.

Returns

The created CustomWidget.

Example usage:

subreddit = await reddit.subreddit("test")
widget_moderation = subreddit.widgets.mod
image_paths = ["/path/to/image1.jpg", "/path/to/image2.png"]
image_urls = [widget_moderation.upload_image(img_path) for img_path in image_paths]
image_data = [
    {"width": 600, "height": 450, "name": "logo", "url": image_urls[0]},
    {"width": 450, "height": 600, "name": "icon", "url": image_urls[1]},
]
styles = {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}
new_widget = await widget_moderation.add_custom_widget(
    image_short_name="My widget",
    text="# Hello world!",
    css="/**/",
    height=200,
    image_data=image_data,
    styles=styles,
)
await add_image_widget(*, data: List[Dict[str, Union[str, int]]], short_name: str, styles: Dict[str, str], **other_settings) asyncpraw.models.ImageWidget

Add and return an ImageWidget.

Parameters
  • data

    A list of dictionaries as specified in Reddit docs. Each dictionary has the key "url" which maps to the URL of an image hosted on Reddit’s servers. Images should be uploaded using upload_image().

    For example:

    [
        {
            "url": "https://some.link",  # from upload_image()
            "width": 600,
            "height": 450,
            "linkUrl": "https://github.com/asyncpraw-dev/asyncpraw",
        },
        {
            "url": "https://other.link",  # from upload_image()
            "width": 450,
            "height": 600,
            "linkUrl": "https://asyncpraw.readthedocs.io",
        },
    ]
    

  • short_name – A name for the widget, no longer than 30 characters.

  • styles – A dictionary with keys "backgroundColor" and "headerColor", and values of hex colors. For example, {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}.

Returns

The created ImageWidget.

Example usage:

subreddit = await reddit.subreddit("test")
widget_moderation = subreddit.widgets.mod
image_paths = ["/path/to/image1.jpg", "/path/to/image2.png"]
image_data = [
    {
        "width": 600,
        "height": 450,
        "linkUrl": "",
        "url": widget_moderation.upload_image(img_path),
    }
    for img_path in image_paths
]
styles = {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}
new_widget = await widget_moderation.add_image_widget(
    short_name="My cool pictures", data=image_data, styles=styles
)
await add_menu(*, data: List[Dict[str, Union[List[Dict[str, str]], str]]], **other_settings) asyncpraw.models.Menu

Add and return a Menu widget.

Parameters

data

A list of dictionaries describing menu contents, as specified in Reddit docs. As of this writing, the format is:

[
    {
        "text": a string no longer than 20 characters,
        "url": a valid URL
    },

    OR

    {
        "children": [
            {
                "text": a string no longer than 20 characters,
                "url": a valid URL,
            },
            ...
        ],
        "text": a string no longer than 20 characters,
    },
    ...
]

Returns

The created Menu.

Example usage:

subreddit = await reddit.subreddit("test")
widget_moderation = subreddit.widgets.mod
menu_contents = [
    {"text": "My homepage", "url": "https://example.com"},
    {
        "text": "Python packages",
        "children": [
            {"text": "asyncpraw", "url": "https://asyncpraw.readthedocs.io/"},
            {"text": "requests", "url": "https://docs.python-requests.org/"},
        ],
    },
    {"text": "Reddit homepage", "url": "https://reddit.com"},
]
new_widget = await widget_moderation.add_menu(data=menu_contents)
await add_post_flair_widget(*, display: str, order: List[str], short_name: str, styles: Dict[str, str], **other_settings) asyncpraw.models.PostFlairWidget

Add and return a PostFlairWidget.

Parameters
  • display – Display style. Either "cloud" or "list".

  • order

    A list of flair template IDs. You can get all flair template IDs in a subreddit with:

    flairs = [f["id"] for f in subreddit.flair.link_templates]
    

  • short_name – A name for the widget, no longer than 30 characters.

  • styles – A dictionary with keys "backgroundColor" and "headerColor", and values of hex colors. For example, {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}.

Returns

The created PostFlairWidget.

Example usage:

subreddit = await reddit.subreddit("test")
widget_moderation = subreddit.widgets.mod
flairs = [f["id"] async for f in subreddit.flair.link_templates]
styles = {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}
new_widget = await widget_moderation.add_post_flair_widget(
    short_name="Some flairs", display="list", order=flairs, styles=styles
)
await add_text_area(*, short_name: str, styles: Dict[str, str], text: str, **other_settings) asyncpraw.models.TextArea

Add and return a TextArea widget.

Parameters
  • short_name – A name for the widget, no longer than 30 characters.

  • styles – A dictionary with keys "backgroundColor" and "headerColor", and values of hex colors. For example, {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}.

  • text – The Markdown text displayed in the widget.

Returns

The created TextArea.

Example usage:

subreddit = await reddit.subreddit("test")
widget_moderation = subreddit.widgets.mod
styles = {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}
new_widget = await widget_moderation.add_text_area(
    short_name="My cool title", text="*Hello* **world**!", styles=styles
)
await reorder(new_order: List[Union[asyncpraw.models.ButtonWidget, asyncpraw.models.Calendar, asyncpraw.models.CommunityList, asyncpraw.models.CustomWidget, asyncpraw.models.IDCard, asyncpraw.models.ImageWidget, asyncpraw.models.Menu, asyncpraw.models.ModeratorsWidget, asyncpraw.models.PostFlairWidget, asyncpraw.models.RulesWidget, asyncpraw.models.TextArea, asyncpraw.models.Widget, str]], *, section: str = 'sidebar')

Reorder the widgets.

Parameters
  • new_order – A list of widgets. Represented as a list that contains Widget objects, or widget IDs as strings. These types may be mixed.

  • section – The section to reorder (default: "sidebar").

Example usage:

subreddit = await reddit.subreddit("test")
widgets = [widget async for widget in subreddit.widgets]
order = list(widgets.sidebar)
order.reverse()
await widgets.mod.reorder(order)
await upload_image(file_path: str) str

Upload an image to Reddit and get the URL.

Parameters

file_path – The path to the local file.

Returns

The URL of the uploaded image as a str.

This method is used to upload images for widgets. For example, it can be used in conjunction with add_image_widget(), add_custom_widget(), and add_button_widget().

Example usage:

my_sub = await reddit.subreddit("test")
image_url = await my_sub.widgets.mod.upload_image("/path/to/image.jpg")
image_data = [{"width": 300, "height": 300, "url": image_url, "linkUrl": ""}]
styles = {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}
await my_sub.widgets.mod.add_image_widget(
    short_name="My cool pictures", data=image_data, styles=styles
)

ThingModerationMixin

class asyncpraw.models.reddit.mixins.ThingModerationMixin

Provides moderation methods for Comments and Submissions.

__init__()
await approve()

Approve a Comment or Submission.

Approving a comment or submission reverts a removal, resets the report counter, adds a green check mark indicator (only visible to other moderators) on the website view, and sets the approved_by attribute to the authenticated user.

Example usage:

# approve a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.approve()
# approve a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.approve()
author_notes(**generator_kwargs) AsyncGenerator[asyncpraw.models.ModNote, None]

Get the moderator notes for the author of this object in the subreddit it’s posted in.

Parameters

generator_kwargs – Additional keyword arguments are passed in the initialization of the moderator note generator.

Returns

A generator of ModNote.

For example, to list all notes the author of a submission, try:

for note in reddit.submission("92dd8").mod.author_notes():
    print(f"{note.label}: {note.note}")
await create_note(*, label: Optional[str] = None, note: str, **other_settings) asyncpraw.models.ModNote

Create a moderator note on the author of this object in the subreddit it’s posted in.

Parameters
  • label – The label for the note. As of this writing, this can be one of the following: "ABUSE_WARNING", "BAN", "BOT_BAN", "HELPFUL_USER", "PERMA_BAN", "SOLID_CONTRIBUTOR", "SPAM_WARNING", "SPAM_WATCH", or None (default: None).

  • note – The content of the note. As of this writing, this is limited to 250 characters.

  • other_settings – Additional keyword arguments are passed to create().

Returns

The new ModNote object.

For example, to create a note on a Submission, try:

submission = await reddit.submission("92dd8")
await submission.mod.create_note(label="HELPFUL_USER", note="Test note")
await distinguish(*, how: str = 'yes', sticky: bool = False)

Distinguish a Comment or Submission.

Parameters
  • how – One of "yes", "no", "admin", or "special". "yes" adds a moderator level distinguish. "no" removes any distinction. "admin" and "special" require special user privileges to use (default "yes").

  • stickyComment is stickied if True, placing it at the top of the comment page regardless of score. If thing is not a top-level comment, this parameter is silently ignored (default False).

Example usage:

# distinguish and sticky a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.distinguish(sticky=True)
# undistinguish a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.distinguish(how="no")

See also

undistinguish()

await ignore_reports()

Ignore future reports on a Comment or Submission.

Calling this method will prevent future reports on this Comment or Submission from both triggering notifications and appearing in the various moderation listings. The report count will still increment on the Comment or Submission.

Example usage:

# ignore future reports on a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.ignore_reports()
# ignore future reports on a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.ignore_reports()
await lock()

Lock a Comment or Submission.

Example usage:

# lock a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.lock()
# lock a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.lock()

See also

unlock()

await remove(*, mod_note: str = '', spam: bool = False, reason_id: Optional[str] = None)

Remove a Comment or Submission.

Parameters
  • mod_note – A message for the other moderators.

  • spam – When True, use the removal to help train the Subreddit’s spam filter (default: False).

  • reason_id – The removal reason ID.

If either reason_id or mod_note are provided, a second API call is made to add the removal reason.

Example usage:

# remove a comment and mark as spam:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.remove(spam=True)
# remove a submission
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.remove()
# remove a submission with a removal reason
sub = await reddit.subreddit("test")
reason = await sub.mod.removal_reasons.get_reason("110ni21zo23ql")
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.remove(reason_id=reason.id)
await send_removal_message(*, message: str, title: str = 'ignored', type: str = 'public') Optional[asyncpraw.models.Comment]

Send a removal message for a Comment or Submission.

Warning

The object has to be removed before giving it a removal reason. Remove the object with remove(). Trying to add a removal reason without removing the object will result in RedditAPIException being thrown with an INVALID_ID error_type.

Reddit adds human-readable information about the object to the message.

Parameters
  • type – One of "public", "private", or "private_exposed". "public" leaves a stickied comment on the post. "private" sends a modmail message with hidden username. "private_exposed" sends a modmail message without hidden username (default: "public").

  • title – The short reason given in the message. Ignored if type is "public".

  • message – The body of the message.

Returns

The new Comment if type is "public".

await undistinguish()

Remove mod, admin, or special distinguishing from an object.

Also unstickies the object if applicable.

Example usage:

# undistinguish a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.undistinguish()
# undistinguish a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.undistinguish()

See also

distinguish()

await unignore_reports()

Resume receiving future reports on a Comment or Submission.

Future reports on this Comment or Submission will cause notifications, and appear in the various moderation listings.

Example usage:

# accept future reports on a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.unignore_reports()
# accept future reports on a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.unignore_reports()

See also

ignore_reports()

await unlock()

Unlock a Comment or Submission.

Example usage:

# unlock a comment:
comment = await reddit.comment("dkk4qjd", fetch=False)
await comment.mod.unlock()
# unlock a submission:
submission = await reddit.submission("5or86n", fetch=False)
await submission.mod.unlock()

See also

lock()

UserSubredditModeration

class asyncpraw.models.reddit.user_subreddit.UserSubredditModeration(subreddit: asyncpraw.models.Subreddit)

Provides a set of moderation functions to a UserSubreddit.

For example, to accept a moderation invite from the user subreddit of u/spez:

redditor = await reddit.redditor("spez")
await redditor.subreddit.mod.accept_invite()
__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a SubredditModeration instance.

Parameters

subreddit – The subreddit to moderate.

await accept_invite()

Accept an invitation as a moderator of the community.

edited(*, only: Optional[str] = None, **generator_kwargs: Any) AsyncIterator[Union[asyncpraw.models.Comment, asyncpraw.models.Submission]]

Return a ListingGenerator for edited comments and submissions.

Parameters

only – If specified, one of "comments" or "submissions" to yield only results of that type.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To print all items in the edited queue try:

subreddit = await reddit.subreddit("mod")
async for item in subreddit.mod.edited(limit=None):
    print(item)
inbox(**generator_kwargs: Any) AsyncIterator[asyncpraw.models.SubredditMessage]

Return a ListingGenerator for moderator messages.

Warning

Legacy modmail is being deprecated in June 2021. Please see https://www.reddit.com/r/modnews/comments/mar9ha/even_more_modmail_improvements/ for more info.

Additional keyword arguments are passed in the initialization of ListingGenerator.

See also

unread() for unread moderator messages.

To print the last 5 moderator mail messages and their replies, try:

subreddit = await reddit.subreddit("mod")
async for message in subreddit.mod.inbox(limit=5):
    print("From: {}, Body: {}".format(message.author, message.body))
    for reply in message.replies:
        print("From: {}, Body: {}".format(reply.author, reply.body))
log(*, action: Optional[str] = None, mod: Optional[Union[asyncpraw.models.Redditor, str]] = None, **generator_kwargs: Any) AsyncIterator[asyncpraw.models.ModAction]

Return a ListingGenerator for moderator log entries.

Parameters
  • action – If given, only return log entries for the specified action.

  • mod – If given, only return log entries for actions made by the passed in redditor.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To print the moderator and subreddit of the last 5 modlog entries try:

subreddit = await reddit.subreddit("mod")
async for log in subreddit.mod.log(limit=5):
    print("Mod: {}, Subreddit: {}".format(log.mod, log.subreddit))
modqueue(*, only: Optional[str] = None, **generator_kwargs: Any) AsyncIterator[Union[asyncpraw.models.Comment, asyncpraw.models.Submission]]

Return a ListingGenerator for modqueue items.

Parameters

only – If specified, one of "comments" or "submissions" to yield only results of that type.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To print all modqueue items try:

subreddit = await reddit.subreddit("mod")
async for item in subreddit.mod.modqueue(limit=None):
    print(item)
notes() asyncpraw.models.SubredditModNotes

Provide an instance of SubredditModNotes.

This provides an interface for managing moderator notes for this subreddit.

For example, all the notes for u/spez in r/test can be iterated through like so:

subreddit = await reddit.subreddit("test")

async for note in subreddit.mod.notes.redditors("spez"):
    print(f"{note.label}: {note.note}")
removal_reasons() SubredditRemovalReasons

Provide an instance of SubredditRemovalReasons.

Use this attribute for interacting with a Subreddit’s removal reasons. For example, to list all the removal reasons for a subreddit which you have the posts moderator permission on, try:

subreddit = await reddit.subreddit("test")
async for removal_reason in subreddit.mod.removal_reasons:
    print(removal_reason)

A single removal reason can be retrieved via:

subreddit = await reddit.subreddit("test")
await subreddit.mod.removal_reasons.get_reason("reason_id")

Note

Attempting to access attributes of a nonexistent removal reason will result in a ClientException.

reports(*, only: Optional[str] = None, **generator_kwargs: Any) AsyncIterator[Union[asyncpraw.models.Comment, asyncpraw.models.Submission]]

Return a ListingGenerator for reported comments and submissions.

Parameters

only – If specified, one of "comments" or "submissions" to yield only results of that type.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To print the user and mod report reasons in the report queue try:

subreddit = await reddit.subreddit("mod")
async for reported_item in subreddit.mod.reports():
    print("User Reports: {}".format(reported_item.user_reports))
    print("Mod Reports: {}".format(reported_item.mod_reports))
await settings() Dict[str, Union[str, int, bool]]

Return a dictionary of the Subreddit’s current settings.

spam(*, only: Optional[str] = None, **generator_kwargs: Any) AsyncIterator[Union[asyncpraw.models.Comment, asyncpraw.models.Submission]]

Return a ListingGenerator for spam comments and submissions.

Parameters

only – If specified, one of "comments" or "submissions" to yield only results of that type.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To print the items in the spam queue try:

subreddit = await reddit.subreddit("mod")
async for item in subreddit.mod.spam():
    print(item)
stream() asyncpraw.models.reddit.subreddit.SubredditModerationStream

Provide an instance of SubredditModerationStream.

Streams can be used to indefinitely retrieve Moderator only items from SubredditModeration made to moderated subreddits, like:

subreddit = await reddit.subreddit("mod")
async for log in subreddit.mod.stream.log():
    print("Mod: {}, Subreddit: {}".format(log.mod, log.subreddit))
unmoderated(**generator_kwargs: Any) AsyncIterator[asyncpraw.models.Submission]

Return a ListingGenerator for unmoderated submissions.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To print the items in the unmoderated queue try:

subreddit = await reddit.subreddit("mod")
async for item in subreddit.mod.unmoderated():
    print(item)
unread(**generator_kwargs: Any) AsyncIterator[asyncpraw.models.SubredditMessage]

Return a ListingGenerator for unread moderator messages.

Warning

Legacy modmail is being deprecated in June 2021. Please see https://www.reddit.com/r/modnews/comments/mar9ha/even_more_modmail_improvements/ for more info.

Additional keyword arguments are passed in the initialization of ListingGenerator.

See also

inbox() for all messages.

To print the mail in the unread modmail queue try:

subreddit = await reddit.subreddit("mod")
async for message in subreddit.mod.unread():
    print("From: {}, To: {}".format(message.author, message.dest))
await update(**settings: Union[str, int, bool]) Dict[str, Union[str, int, bool]]

Update the Subreddit’s settings.

Parameters
  • all_original_content – Mandate all submissions to be original content only.

  • allow_chat_post_creation – Allow users to create chat submissions.

  • allow_images – Allow users to upload images using the native image hosting.

  • allow_polls – Allow users to post polls to the subreddit.

  • allow_post_crossposts – Allow users to crosspost submissions from other subreddits.

  • allow_top – Allow the subreddit to appear on r/all as well as the default and trending lists.

  • allow_videos – Allow users to upload videos using the native image hosting.

  • collapse_deleted_comments – Collapse deleted and removed comments on comments pages by default.

  • crowd_control_chat_level – Controls the crowd control level for chat rooms. Goes from 0-3.

  • crowd_control_level – Controls the crowd control level for submissions. Goes from 0-3.

  • crowd_control_mode – Enables/disables crowd control.

  • comment_score_hide_mins – The number of minutes to hide comment scores.

  • description – Shown in the sidebar of your subreddit.

  • disable_contributor_requests – Specifies whether redditors may send automated modmail messages requesting approval as a submitter.

  • exclude_banned_modqueue – Exclude posts by site-wide banned users from modqueue/unmoderated.

  • free_form_reports – Allow users to specify custom reasons in the report menu.

  • header_hover_text – The text seen when hovering over the snoo.

  • hide_ads – Don’t show ads within this subreddit. Only applies to Premium-user only subreddits.

  • key_color – A 6-digit rgb hex color (e.g., "#AABBCC"), used as a thematic color for your subreddit on mobile.

  • lang – A valid IETF language tag (underscore separated).

  • link_type – The types of submissions users can make. One of "any", "link", or "self".

  • original_content_tag_enabled – Enables the use of the original content label for submissions.

  • over_18 – Viewers must be over 18 years old (i.e., NSFW).

  • public_description – Public description blurb. Appears in search results and on the landing page for private subreddits.

  • public_traffic – Make the traffic stats page public.

  • restrict_commenting – Specifies whether approved users have the ability to comment.

  • restrict_posting – Specifies whether approved users have the ability to submit posts.

  • show_media – Show thumbnails on submissions.

  • show_media_preview – Expand media previews on comments pages.

  • spam_comments – Spam filter strength for comments. One of "all", "low", or "high".

  • spam_links – Spam filter strength for links. One of "all", "low", or "high".

  • spam_selfposts – Spam filter strength for selfposts. One of "all", "low", or "high".

  • spoilers_enabled – Enable marking posts as containing spoilers.

  • submit_link_label – Custom label for submit link button (None for default).

  • submit_text – Text to show on submission page.

  • submit_text_label – Custom label for submit text post button (None for default).

  • subreddit_type – The string "user".

  • suggested_comment_sort – All comment threads will use this sorting method by default. Leave None, or choose one of confidence, "controversial", "live", "new", "old", "qa", "random", or "top".

  • title – The title of the subreddit.

  • welcome_message_enabled – Enables the subreddit welcome message.

  • welcome_message_text – The text to be used as a welcome message. A welcome message is sent to all new subscribers by a Reddit bot.

  • wiki_edit_age – Account age, in days, required to edit and create wiki pages.

  • wiki_edit_karma – Subreddit karma required to edit and create wiki pages.

  • wikimode – One of "anyone", "disabled", or "modonly".

Additional keyword arguments can be provided to handle new settings as Reddit introduces them.

Settings that are documented here and aren’t explicitly set by you in a call to SubredditModeration.update() should retain their current value. If they do not please file a bug.

Warning

Undocumented settings, or settings that were very recently documented, may not retain their current value when updating. This often occurs when Reddit adds a new setting but forgets to add that setting to the API endpoint that is used to fetch the current settings.

WidgetModeration

class asyncpraw.models.WidgetModeration(widget: asyncpraw.models.Widget, subreddit: Union[asyncpraw.models.Subreddit, str], reddit: asyncpraw.Reddit)

Class for moderating a particular widget.

Example usage:

subreddit = await reddit.subreddit("test")
sidebar = [widget async for widget in subreddit.widgets.sidebar()]
widget = sidebar[0]
await widget.mod.update(shortName="My new title")
await widget.mod.delete()
__init__(widget: asyncpraw.models.Widget, subreddit: Union[asyncpraw.models.Subreddit, str], reddit: asyncpraw.Reddit)

Initialize a WidgetModeration instance.

await delete()

Delete the widget.

Example usage:

await widget.mod.delete()
await update(**kwargs) Union[asyncpraw.models.ButtonWidget, asyncpraw.models.Calendar, asyncpraw.models.CommunityList, asyncpraw.models.CustomWidget, asyncpraw.models.IDCard, asyncpraw.models.ImageWidget, asyncpraw.models.Menu, asyncpraw.models.ModeratorsWidget, asyncpraw.models.PostFlairWidget, asyncpraw.models.RulesWidget, asyncpraw.models.TextArea, asyncpraw.models.Widget]

Update the widget. Returns the updated widget.

Parameters differ based on the type of widget. See Reddit documentation or the document of the particular type of widget.

Returns

The updated Widget.

For example, update a text widget like so:

await text_widget.mod.update(shortName="New text area", text="Hello!")

Note

Most parameters follow the lowerCamelCase convention. When in doubt, check the Reddit documentation linked above.

WikiPageModeration

class asyncpraw.models.reddit.wikipage.WikiPageModeration(wikipage: WikiPage)

Provides a set of moderation functions for a WikiPage.

For example, to add spez as an editor on the wikipage praw_test try:

subreddit = await reddit.subreddit("test")
page = await subreddit.wiki.get_page("praw_test")
await page.mod.add("spez")
__init__(wikipage: WikiPage)

Initialize a WikiPageModeration instance.

Parameters

wikipage – The wikipage to moderate.

await add(redditor: asyncpraw.models.Redditor)

Add an editor to this WikiPage.

Parameters

redditor – A redditor name or Redditor instance.

To add u/spez as an editor on the wikipage "praw_test" try:

subreddit = await reddit.subreddit("test")
page = await subreddit.wiki.get_page("praw_test", fetch=False)
await page.mod.add("spez")
await remove(redditor: asyncpraw.models.Redditor)

Remove an editor from this WikiPage.

Parameters

redditor – A redditor name or Redditor instance.

To remove u/spez as an editor on the wikipage "praw_test" try:

subreddit = await reddit.subreddit("test")
page = await subreddit.wiki.get_page("praw_test", fetch=False)
await page.mod.remove("spez")
await revert()

Revert a wikipage back to a specific revision.

To revert the page "praw_test" in r/test to revision "1234abc", try

subreddit = await reddit.subreddit("test")
wikipage = await subreddit.wiki.get_page("praw_test")
revision = await wikipage.revision("1234abc")
await revision.mod.revert()

Note

When you attempt to revert the page config/stylesheet, Reddit checks to see if the revision being reverted to passes the CSS filter. If the check fails, then the revision attempt will also fail, and a asyncprawcore.Forbidden exception will be raised. For example, you can’t revert to a revision that contains a link to url(%%PRAW%%) if there is no image named PRAW on the current stylesheet.

Here is an example of how to look for this type of error:

from asyncprawcore.exceptions import Forbidden

try:
    subreddit = await reddit.subreddit("test")
    wikipage = await subreddit.wiki.get_page("config/stylesheet")
    revision = await wikipage.revision("1234abc")
    await revision.mod.revert()
except Forbidden as exception:
    try:
        await exception.response.json()
    except ValueError:
        exception.response.text

If the error occurs, the output will look something like

{"reason": "INVALID_CSS", "message": "Forbidden", "explanation": "%(css_error)s"}
await settings() Dict[str, Any]

Return the settings for this WikiPage.

await update(*, listed: bool, permlevel: int, **other_settings: Any) Dict[str, Any]

Update the settings for this WikiPage.

Parameters
  • listed – Show this page on page list.

  • permlevel – Who can edit this page? 0 use subreddit wiki permissions, 1 only approved wiki contributors for this page may edit (see WikiPageModeration.add()), 2 only mods may edit and view.

  • other_settings – Additional keyword arguments to pass.

Returns

The updated WikiPage settings.

To set the wikipage praw_test in r/test to mod only and disable it from showing in the page list, try:

subreddit = await reddit.subreddit("test")
page = await subreddit.wiki.get_page("praw_test", fetch=False)
await page.mod.update(listed=False, permlevel=2)

LiveContributorRelationship

class asyncpraw.models.reddit.live.LiveContributorRelationship(thread: asyncpraw.models.LiveThread)

Provide methods to interact with live threads’ contributors.

__call__() AsyncIterator[asyncpraw.models.Redditor]

Return a RedditorList for live threads’ contributors.

Usage:

thread = await reddit.live("ukaeu1ik4sw5")
async for contributor in thread.contributor():
    print(contributor)
__init__(thread: asyncpraw.models.LiveThread)

Initialize a LiveContributorRelationship instance.

Parameters

thread – An instance of LiveThread.

Note

This class should not be initialized directly. Instead, obtain an instance via: LiveThread.contributor().

await accept_invite()

Accept an invite to contribute the live thread.

Usage:

thread = await reddit.live("ydwwxneu7vsa")
await thread.contributor.accept_invite()
await invite(redditor: Union[str, asyncpraw.models.Redditor], *, permissions: Optional[List[str]] = None)

Invite a redditor to be a contributor of the live thread.

Parameters
  • redditor – A redditor name or Redditor instance.

  • permissions – When provided (not None), permissions should be a list of strings specifying which subset of permissions to grant. An empty list [] indicates no permissions, and when not provided (None), indicates full permissions.

Raises

RedditAPIException if the invitation already exists.

Usage:

thread = await reddit.live("ukaeu1ik4sw5")
redditor = await reddit.redditor("spez", fetch=False)

# "manage" and "settings" permissions
await thread.contributor.invite(redditor, permissions=["manage", "settings"])

See also

LiveContributorRelationship.remove_invite() to remove the invite for redditor.

await leave()

Abdicate the live thread contributor position (use with care).

Usage:

thread = await reddit.live("ydwwxneu7vsa")
await thread.contributor.leave()
await remove(redditor: Union[str, asyncpraw.models.Redditor])

Remove the redditor from the live thread contributors.

Parameters

redditor – A redditor fullname (e.g., "t2_1w72") or Redditor instance.

Usage:

thread = await reddit.live("ukaeu1ik4sw5")
redditor = await reddit.redditor("spez", fetch=False)
await thread.contributor.remove(redditor)
await thread.contributor.remove("t2_1w72")  # with fullname
await remove_invite(redditor: Union[str, asyncpraw.models.Redditor])

Remove the invite for redditor.

Parameters

redditor – A redditor fullname (e.g., "t2_1w72") or Redditor instance.

Usage:

thread = await reddit.live("ukaeu1ik4sw5")
redditor = await reddit.redditor("spez", fetch=False)
await thread.contributor.remove_invite(redditor)
await thread.contributor.remove_invite("t2_1w72")  # with fullname

See also

LiveContributorRelationship.invite() to invite a redditor to be a contributor of the live thread.

await update(redditor: Union[str, asyncpraw.models.Redditor], *, permissions: Optional[List[str]] = None)

Update the contributor permissions for redditor.

Parameters
  • redditor – A redditor name or Redditor instance.

  • permissions – When provided (not None), permissions should be a list of strings specifying which subset of permissions to grant (other permissions are removed). An empty list [] indicates no permissions, and when not provided (None), indicates full permissions.

For example, to grant all permissions to the contributor, try:

thread = await reddit.live("ukaeu1ik4sw5")
await thread.contributor.update("spez")

To grant "access" and "edit" permissions (and to remove other permissions), try:

await thread.contributor.update("spez", permissions=["access", "edit"])

To remove all permissions from the contributor, try:

await subreddit.moderator.update("spez", permissions=[])
await update_invite(redditor: Union[str, asyncpraw.models.Redditor], *, permissions: Optional[List[str]] = None)

Update the contributor invite permissions for redditor.

Parameters
  • redditor – A redditor name or Redditor instance.

  • permissions – When provided (not None), permissions should be a list of strings specifying which subset of permissions to grant (other permissions are removed). An empty list [] indicates no permissions, and when not provided (None), indicates full permissions.

For example, to set all permissions to the invitation, try:

thread = await reddit.live("ukaeu1ik4sw5")
await thread.contributor.update_invite("spez")

To set "access" and "edit" permissions (and to remove other permissions) to the invitation, try:

await thread.contributor.update_invite("spez", permissions=["access", "edit"])

To remove all permissions from the invitation, try:

await thread.contributor.update_invite("spez", permissions=[])

LiveThreadContribution

class asyncpraw.models.reddit.live.LiveThreadContribution(thread: asyncpraw.models.LiveThread)

Provides a set of contribution functions to a LiveThread.

__init__(thread: asyncpraw.models.LiveThread)

Initialize a LiveThreadContribution instance.

Parameters

thread – An instance of LiveThread.

This instance can be retrieved through thread.contrib where thread is a LiveThread instance. E.g.,

thread = await reddit.live("ukaeu1ik4sw5")
await thread.contrib.add("### update")
await add(body: str)

Add an update to the live thread.

Parameters

body – The Markdown formatted content for the update.

Usage:

thread = await reddit.live("ydwwxneu7vsa")
await thread.contrib.add("test `LiveThreadContribution.add()`")
await close()

Close the live thread permanently (cannot be undone).

Usage:

thread = await reddit.live("ukaeu1ik4sw5")
await thread.contrib.close()
await update(*, description: Optional[str] = None, nsfw: Optional[bool] = None, resources: Optional[str] = None, title: Optional[str] = None, **other_settings: Optional[str])

Update settings of the live thread.

Parameters
  • description – The live thread’s description (default: None).

  • nsfw – Indicate whether this thread is not safe for work (default: None).

  • resources – Markdown formatted information that is useful for the live thread (default: None).

  • title – The title of the live thread (default: None).

Does nothing if no arguments are provided.

Each setting will maintain its current value if None is specified.

Additional keyword arguments can be provided to handle new settings as Reddit introduces them.

Usage:

thread = await reddit.live("xyu8kmjvfrww")

# update 'title' and 'nsfw'
updated_thread = await thread.contrib.update(title=new_title, nsfw=True)

If Reddit introduces new settings, you must specify None for the setting you want to maintain:

# update 'nsfw' and maintain new setting 'foo'
await thread.contrib.update(nsfw=True, foo=None)

LiveThreadStream

class asyncpraw.models.reddit.live.LiveThreadStream(live_thread: asyncpraw.models.LiveThread)

Provides a LiveThread stream.

Usually used via:

for live_update in reddit.live("ta535s1hq2je").stream.updates():
    print(live_update.body)
__init__(live_thread: asyncpraw.models.LiveThread)

Initialize a LiveThreadStream instance.

Parameters

live_thread – The live thread associated with the stream.

updates(**stream_options: Dict[str, Any]) AsyncIterator[asyncpraw.models.LiveUpdate]

Yield new updates to the live thread as they become available.

Parameters

skip_existing – Set to True to only fetch items created after the stream (default: False).

As with LiveThread.updates(), updates are yielded as LiveUpdate.

Updates are yielded oldest first. Up to 100 historical updates will initially be returned.

Keyword arguments are passed to stream_generator().

For example, to retrieve all new updates made to the "ta535s1hq2je" live thread, try:

live_thread = await reddit.live("ta535s1hq2je")
async for live_update in live.stream.updates():
    print(live_update.body)

To only retrieve new updates starting from when the stream is created, pass skip_existing=True:

live_thread = await reddit.live("ta535s1hq2je")
async for live_update in live_thread.stream.updates(skip_existing=True):
    print(live_update.author)

LiveUpdateContribution

class asyncpraw.models.reddit.live.LiveUpdateContribution(update: asyncpraw.models.LiveUpdate)

Provides a set of contribution functions to LiveUpdate.

__init__(update: asyncpraw.models.LiveUpdate)

Initialize a LiveUpdateContribution instance.

Parameters

update – An instance of LiveUpdate.

This instance can be retrieved through update.contrib where update is a LiveUpdate instance. E.g.,

thread = await reddit.live("ukaeu1ik4sw5")
update = await thread.get_update("7827987a-c998-11e4-a0b9-22000b6a88d2")
update.contrib  # LiveUpdateContribution instance
await update.contrib.remove()
await remove()

Remove a live update.

Usage:

thread = await reddit.live("ydwwxneu7vsa")
update = await thread.get_update("6854605a-efec-11e6-b0c7-0eafac4ff094")
await update.contrib.remove()
await strike()

Strike a content of a live update.

thread = await reddit.live("xyu8kmjvfrww")
update = await thread.get_update("cb5fe532-dbee-11e6-9a91-0e6d74fabcc4")
await update.contrib.strike()

To check whether the update is stricken or not, use update.stricken attribute.

Note

Accessing lazy attributes on updates (includes update.stricken) may raise AttributeError. See LiveUpdate for details.

ContributorRelationship

class asyncpraw.models.reddit.subreddit.ContributorRelationship(subreddit: asyncpraw.models.Subreddit, relationship: str)

Provides methods to interact with a Subreddit’s contributors.

Contributors are also known as approved submitters.

Contributors of a subreddit can be iterated through like so:

subreddit = await reddit.subreddit("test")
async for contributor in subreddit.contributor():
    print(contributor)
__call__(redditor: Optional[Union[asyncpraw.models.Redditor, str]] = None, **generator_kwargs) AsyncIterator[asyncpraw.models.Redditor]

Return a ListingGenerator for Redditors in the relationship.

Parameters

redditor – When provided, yield at most a single Redditor instance. This is useful to confirm if a relationship exists, or to fetch the metadata associated with a particular relationship (default: None).

Additional keyword arguments are passed in the initialization of ListingGenerator.

__init__(subreddit: asyncpraw.models.Subreddit, relationship: str)

Initialize a SubredditRelationship instance.

Parameters
  • subreddit – The Subreddit for the relationship.

  • relationship – The name of the relationship.

await add(redditor: Union[str, asyncpraw.models.Redditor], **other_settings: Any)

Add redditor to this relationship.

Parameters

redditor – A redditor name or Redditor instance.

await leave()

Abdicate the contributor position.

await remove(redditor: Union[str, asyncpraw.models.Redditor])

Remove redditor from this relationship.

Parameters

redditor – A redditor name or Redditor instance.

ModeratorRelationship

class asyncpraw.models.reddit.subreddit.ModeratorRelationship(subreddit: asyncpraw.models.Subreddit, relationship: str)

Provides methods to interact with a Subreddit’s moderators.

Moderators of a subreddit can be iterated through like so:

subreddit = await reddit.subreddit("test")
async for moderator in subreddit.moderator:
    print(moderator)
await __call__(redditor: Optional[Union[asyncpraw.models.Redditor, str]] = None) List[asyncpraw.models.Redditor]

Return a list of Redditors who are moderators.

Parameters

redditor – When provided, return a list containing at most one Redditor instance. This is useful to confirm if a relationship exists, or to fetch the metadata associated with a particular relationship (default: None).

Note

To help mitigate targeted moderator harassment, this call requires the Reddit instance to be authenticated i.e., read_only must return False. This call, however, only makes use of the read scope. For more information on why the moderator list is hidden can be found here: https://reddit.zendesk.com/hc/en-us/articles/360049499032-Why-is-the-moderator-list-hidden-

Note

Unlike other relationship callables, this relationship is not paginated. Thus it simply returns the full list, rather than an iterator for the results.

To be used like:

subreddit = await reddit.subreddit("test")
moderators = await subreddit.moderator()

For example, to list the moderators along with their permissions try:

subreddit = await reddit.subreddit("test")
moderators = await subreddit.moderator()
for moderator in moderators:
    print(f"{moderator}: {moderator.mod_permissions}")
__init__(subreddit: asyncpraw.models.Subreddit, relationship: str)

Initialize a SubredditRelationship instance.

Parameters
  • subreddit – The Subreddit for the relationship.

  • relationship – The name of the relationship.

await add(redditor: Union[str, asyncpraw.models.Redditor], *, permissions: Optional[List[str]] = None, **other_settings: Any)

Add or invite redditor to be a moderator of the Subreddit.

Parameters
  • redditor – A redditor name or Redditor instance.

  • permissions – When provided (not None), permissions should be a list of strings specifying which subset of permissions to grant. An empty list [] indicates no permissions, and when not provided None, indicates full permissions (default: None).

An invite will be sent unless the user making this call is an admin user.

For example, to invite u/spez with "posts" and "mail" permissions to r/test, try:

subreddit = await reddit.subreddit("test")
await subreddit.moderator.add("spez", permissions=["posts", "mail"])
await invite(redditor: Union[str, asyncpraw.models.Redditor], *, permissions: Optional[List[str]] = None, **other_settings: Any)

Invite redditor to be a moderator of the Subreddit.

Parameters
  • redditor – A redditor name or Redditor instance.

  • permissions – When provided (not None), permissions should be a list of strings specifying which subset of permissions to grant. An empty list [] indicates no permissions, and when not provided None, indicates full permissions (default: None).

For example, to invite u/spez with "posts" and "mail"

permissions to r/test, try:

subreddit = await reddit.subreddit("test")
await subreddit.moderator.invite("spez", permissions=["posts", "mail"])
invited(*, redditor: Optional[Union[asyncpraw.models.Redditor, str]] = None, **generator_kwargs: Any) AsyncIterator[asyncpraw.models.Redditor]

Return a ListingGenerator for Redditors invited to be moderators.

Parameters

redditor – When provided, return a list containing at most one Redditor instance. This is useful to confirm if a relationship exists, or to fetch the metadata associated with a particular relationship (default: None).

Additional keyword arguments are passed in the initialization of ListingGenerator.

Note

Unlike other usages of ListingGenerator, limit has no effect in the quantity returned. This endpoint always returns moderators in batches of 25 at a time regardless of what limit is set to.

Usage:

subreddit = await reddit.subreddit("test")
async for invited_mod in subreddit.moderator.invited():
    print(invited_mod)
await leave()

Abdicate the moderator position (use with care).

For example:

subreddit = await reddit.subreddit("test")
await subreddit.moderator.leave()
await remove(redditor: Union[str, asyncpraw.models.Redditor])

Remove redditor from this relationship.

Parameters

redditor – A redditor name or Redditor instance.

await remove_invite(redditor: Union[str, asyncpraw.models.Redditor])

Remove the moderator invite for redditor.

Parameters

redditor – A redditor name or Redditor instance.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.moderator.remove_invite("spez")
await update(redditor: Union[str, asyncpraw.models.Redditor], *, permissions: Optional[List[str]] = None)

Update the moderator permissions for redditor.

Parameters
  • redditor – A redditor name or Redditor instance.

  • permissions – When provided (not None), permissions should be a list of strings specifying which subset of permissions to grant. An empty list [] indicates no permissions, and when not provided, None, indicates full permissions (default: None).

For example, to add all permissions to the moderator, try:

await subreddit.moderator.update("spez")

To remove all permissions from the moderator, try:

await subreddit.moderator.update("spez", permissions=[])
await update_invite(redditor: Union[str, asyncpraw.models.Redditor], *, permissions: Optional[List[str]] = None)

Update the moderator invite permissions for redditor.

Parameters
  • redditor – A redditor name or Redditor instance.

  • permissions – When provided (not None), permissions should be a list of strings specifying which subset of permissions to grant. An empty list [] indicates no permissions, and when not provided, None, indicates full permissions (default: None).

For example, to grant the "flair" and "mail" permissions to the moderator invite, try:

await subreddit.moderator.update_invite("spez", permissions=["flair", "mail"])

SubredditRelationship

class asyncpraw.models.reddit.subreddit.SubredditRelationship(subreddit: asyncpraw.models.Subreddit, relationship: str)

Represents a relationship between a Redditor and Subreddit.

Instances of this class can be iterated through in order to discover the Redditors that make up the relationship.

For example, banned users of a subreddit can be iterated through like so:

subreddit = await reddit.subreddit("test")
async for ban in subreddit.banned():
    print("{ban}: {ban.note}")
__call__(redditor: Optional[Union[asyncpraw.models.Redditor, str]] = None, **generator_kwargs) AsyncIterator[asyncpraw.models.Redditor]

Return a ListingGenerator for Redditors in the relationship.

Parameters

redditor – When provided, yield at most a single Redditor instance. This is useful to confirm if a relationship exists, or to fetch the metadata associated with a particular relationship (default: None).

Additional keyword arguments are passed in the initialization of ListingGenerator.

__init__(subreddit: asyncpraw.models.Subreddit, relationship: str)

Initialize a SubredditRelationship instance.

Parameters
  • subreddit – The Subreddit for the relationship.

  • relationship – The name of the relationship.

await add(redditor: Union[str, asyncpraw.models.Redditor], **other_settings: Any)

Add redditor to this relationship.

Parameters

redditor – A redditor name or Redditor instance.

await remove(redditor: Union[str, asyncpraw.models.Redditor])

Remove redditor from this relationship.

Parameters

redditor – A redditor name or Redditor instance.

SubredditEmoji

class asyncpraw.models.reddit.emoji.SubredditEmoji(subreddit: asyncpraw.models.Subreddit)

Provides a set of functions to a Subreddit for emoji.

__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a SubredditEmoji instance.

Parameters

subreddit – The subreddit whose emoji are affected.

await add(*, image_path: str, mod_flair_only: Optional[bool] = None, name: str, post_flair_allowed: Optional[bool] = None, user_flair_allowed: Optional[bool] = None) Emoji

Add an emoji to this subreddit.

Parameters
  • image_path – A path to a jpeg or png image.

  • mod_flair_only – When provided, indicate whether the emoji is restricted to mod use only (default: None).

  • name – The name of the emoji.

  • post_flair_allowed – When provided, indicate whether the emoji may appear in post flair (default: None).

  • user_flair_allowed – When provided, indicate whether the emoji may appear in user flair (default: None).

Returns

The Emoji added.

To add "emoji" to r/test try:

subreddit = await reddit.subreddit("test")
await subreddit.emoji.add(name="emoji", image_path="emoji.png")
await get_emoji(name: str, fetch: bool = True, **kwargs) Emoji

Return the Emoji for the subreddit named name.

Parameters
  • name – The name of the emoji.

  • fetch – Determines if Async PRAW will fetch the object (default: True).

This method is to be used to fetch a specific emoji url, like so:

subreddit = await reddit.subreddit("test")
emoji = await subreddit.emoji.get_emoji("emoji")
print(emoji)

If you don’t need the object fetched right away (e.g., to utilize a class method) you can do:

subreddit = await reddit.subreddit("test")
emoji = await subreddit.emoji.get_emoji("emoji", fetch=False)
await emoji.delete()

SubredditFilters

class asyncpraw.models.reddit.subreddit.SubredditFilters(subreddit: asyncpraw.models.Subreddit)

Provide functions to interact with the special Subreddit’s filters.

Members of this class should be utilized via Subreddit.filters(). For example, to add a filter, run:

subreddit = await reddit.subreddit("all")
await subreddit.filters.add("test")
__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a SubredditFilters instance.

Parameters

subreddit – The special subreddit whose filters to work with.

As of this writing filters can only be used with the special subreddits all and mod.

await add(subreddit: Union[asyncpraw.models.Subreddit, str])

Add subreddit to the list of filtered subreddits.

Parameters

subreddit – The subreddit to add to the filter list.

Items from subreddits added to the filtered list will no longer be included when obtaining listings for r/all.

Alternatively, you can filter a subreddit temporarily from a special listing in a manner like so:

await reddit.subreddit("all-redditdev-learnpython")
Raises

asyncprawcore.NotFound when calling on a non-special subreddit.

await remove(subreddit: Union[asyncpraw.models.Subreddit, str])

Remove subreddit from the list of filtered subreddits.

Parameters

subreddit – The subreddit to remove from the filter list.

Raises

asyncprawcore.NotFound when calling on a non-special subreddit.

SubredditModerationStream

class asyncpraw.models.reddit.subreddit.SubredditModerationStream(subreddit: asyncpraw.models.Subreddit)

Provides moderator streams.

__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a SubredditModerationStream instance.

Parameters

subreddit – The moderated subreddit associated with the streams.

edited(*, only: Optional[str] = None, **stream_options: Any) AsyncGenerator[Union[asyncpraw.models.Comment, asyncpraw.models.Submission], None]

Yield edited comments and submissions as they become available.

Parameters

only – If specified, one of "comments" or "submissions" to yield only results of that type.

Keyword arguments are passed to stream_generator().

For example, to retrieve all new edited submissions/comments made to all moderated subreddits, try:

subreddit = await reddit.subreddit("mod")
async for item in subreddit.mod.stream.edited():
    print(item)
log(*, action: Optional[str] = None, mod: Optional[Union[asyncpraw.models.Redditor, str]] = None, **stream_options: Any) AsyncGenerator[asyncpraw.models.ModAction, None]

Yield moderator log entries as they become available.

Parameters
  • action – If given, only return log entries for the specified action.

  • mod – If given, only return log entries for actions made by the passed in redditor.

For example, to retrieve all new mod actions made to all moderated subreddits, try:

subreddit = await reddit.subreddit("mod")
async for log in subreddit.mod.stream.log():
    print("Mod: {}, Subreddit: {}".format(log.mod, log.subreddit))
modmail_conversations(*, other_subreddits: Optional[List[asyncpraw.models.Subreddit]] = None, sort: Optional[str] = None, state: Optional[str] = None, **stream_options: Any) AsyncGenerator[ModmailConversation, None]

Yield new-modmail conversations as they become available.

Parameters
  • other_subreddits – A list of Subreddit instances for which to fetch conversations (default: None).

  • sort – Can be one of: "mod", "recent", "unread", or "user" (default: "recent").

  • state – Can be one of: "all", "appeals", "archived", "default", "highlighted", "inbox", "inprogress", "join_requests", "mod", "new", or "notifications" (default: "all"). "all" does not include mod or archived conversations. "inbox" does not include appeals conversations.

Keyword arguments are passed to stream_generator().

To print new mail in the unread modmail queue try:

subreddit = await reddit.subreddit("all")
async for message in subreddit.mod.stream.modmail_conversations():
    print("From: {}, To: {}".format(message.owner, message.participant))
modqueue(*, only: Optional[str] = None, **stream_options: Any) AsyncGenerator[Union[asyncpraw.models.Comment, asyncpraw.models.Submission], None]

Yield Comments and Submissions in the modqueue as they become available.

Parameters

only – If specified, one of "comments" or "submissions" to yield only results of that type.

Keyword arguments are passed to stream_generator().

To print all new modqueue items try:

subreddit = await reddit.subreddit("mod")
async for item in subreddit.mod.stream.modqueue():
    print(item)
reports(*, only: Optional[str] = None, **stream_options: Any) AsyncGenerator[Union[asyncpraw.models.Comment, asyncpraw.models.Submission], None]

Yield reported Comments and Submissions as they become available.

Parameters

only – If specified, one of "comments" or "submissions" to yield only results of that type.

Keyword arguments are passed to stream_generator().

To print new user and mod report reasons in the report queue try:

subreddit = await reddit.subreddit("mod")
async for item in subreddit.mod.stream.reports():
    print(item)
spam(*, only: Optional[str] = None, **stream_options: Any) AsyncGenerator[Union[asyncpraw.models.Comment, asyncpraw.models.Submission], None]

Yield spam Comments and Submissions as they become available.

Parameters

only – If specified, one of "comments" or "submissions" to yield only results of that type.

Keyword arguments are passed to stream_generator().

To print new items in the spam queue try:

subreddit = await reddit.subreddit("mod")
async for item in subreddit.mod.stream.spam():
    print(item)
unmoderated(**stream_options: Any) AsyncGenerator[asyncpraw.models.Submission, None]

Yield unmoderated Submissions as they become available.

Keyword arguments are passed to stream_generator().

To print new items in the unmoderated queue try:

subreddit = await reddit.subreddit("mod")
async for item in subreddit.mod.stream.unmoderated():
    print(item)
unread(**stream_options: Any) AsyncGenerator[asyncpraw.models.SubredditMessage, None]

Yield unread old modmail messages as they become available.

Keyword arguments are passed to stream_generator().

See also

SubredditModeration.inbox() for all messages.

To print new mail in the unread modmail queue try:

subreddit = await reddit.subreddit("mod")
async for message in subreddit.mod.stream.unread():
    print("From: {}, To: {}".format(message.author, message.dest))

SubredditQuarantine

class asyncpraw.models.reddit.subreddit.SubredditQuarantine(subreddit: asyncpraw.models.Subreddit)

Provides subreddit quarantine related methods.

To opt-in into a quarantined subreddit:

subreddit = await reddit.subreddit("test")
await subreddit.quaran.opt_in()
__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a SubredditQuarantine instance.

Parameters

subreddit – The Subreddit associated with the quarantine.

await opt_in()

Permit your user access to the quarantined subreddit.

Usage:

subreddit = await reddit.subreddit("QUESTIONABLE")
async for submission in subreddit.hot():  # Raises asyncprawcore.Forbidden
    print(submission)

await subreddit.quaran.opt_in()
async for submission in subreddit.hot():
    print(submission)  # Returns Submission
await opt_out()

Remove access to the quarantined subreddit.

Usage:

subreddit = await reddit.subreddit("QUESTIONABLE")
async for submission in subreddit.hot():
    print(submission)  # Returns Submission

await subreddit.quaran.opt_out()
async for submission in subreddit.hot():  # Raises asyncprawcore.Forbidden
    print(submission)

SubredditRemovalReasons

class asyncpraw.models.reddit.removal_reasons.SubredditRemovalReasons(subreddit: asyncpraw.models.Subreddit)

Provide a set of functions to a Subreddit’s removal reasons.

__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a SubredditRemovalReasons instance.

Parameters

subreddit – The subreddit whose removal reasons to work with.

await add(*, message: str, title: str) RemovalReason

Add a removal reason to this subreddit.

Parameters
  • message – The message associated with the removal reason.

  • title – The title of the removal reason.

Returns

The RemovalReason added.

The message will be prepended with Hi u/username, automatically.

To add "Test" to r/test try:

subreddit = await reddit.subreddit("test")
await subreddit.mod.removal_reasons.add(title="Test", message="Foobar")
await get_reason(reason_id: Union[str, int, slice], fetch: bool = True, **kwargs) RemovalReason

Return the Removal Reason with the ID/number/slice reason_id.

Parameters
  • reason_id – The ID or index of the removal reason.

  • fetch – Determines if Async PRAW will fetch the object (default: True).

This method is to be used to fetch a specific removal reason, like so:

reason_id = "141vv5c16py7d"
subreddit = await reddit.subreddit("test")
reason = await subreddit.mod.removal_reasons.get_reason(reason_id)
print(reason)

You can also use indices to get a numbered removal reason. Since Python uses 0-indexing, the first removal reason is index 0, and so on.

Note

Both negative indices and slices can be used to interact with the removal reasons.

Raises

IndexError if a removal reason of a specific number does not exist.

For example, to get the second removal reason of r/test:

subreddit = await reddit.subreddit("test")
await subreddit.mod.removal_reasons.get_reason(1)

To get the last three removal reasons in a subreddit:

subreddit = await reddit.subreddit("test")
reasons = await subreddit.mod.removal_reasons.get_reason(slice(-3, None))
for reason in reasons:
    print(reason)

If you don’t need the object fetched right away (e.g., to utilize a class method) you can do:

reason_id = "141vv5c16py7d"
subreddit = await reddit.subreddit("test")
reason = await subreddit.mod.removal_reasons.get_reason(reason_id, fetch=False)
await reason.delete()

SubredditRules

class asyncpraw.models.reddit.rules.SubredditRules(subreddit: asyncpraw.models.Subreddit)

Provide a set of functions to access a Subreddit’s rules.

For example, to list all the rules for a subreddit:

subreddit = await reddit.subreddit("test")
async for rule in subreddit.rules:
    print(rule)

Moderators can also add rules to the subreddit. For example, to make a rule called "No spam" in r/test:

subreddit = await reddit.subreddit("test")
await subreddit.rules.mod.add(
    short_name="No spam", kind="all", description="Do not spam. Spam bad"
)
await __call__() List[asyncpraw.models.Rule]

Return a list of Rules (Deprecated).

Returns

A list of instances of Rule.

Deprecated since version 7.1: Use the iterator by removing the call to SubredditRules. For example, in order to use the iterator:

subreddit = await reddit.subreddit("test")
async for rule in subreddit.rules:
    print(rule)
__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a SubredditRules instance.

Parameters

subreddit – The subreddit whose rules to work with.

await get_rule(short_name: Union[str, int, slice]) asyncpraw.models.Rule

Return the Rule for the subreddit with short_name short_name.

Parameters

short_name – The short_name of the rule, or the rule number.

This method is to be used to fetch a specific rule, like so:

rule_name = "No spam"
subreddit = await reddit.subreddit("test")
rule = await subreddit.rules.get_rule(rule_name)
print(rule)

You can also fetch a numbered rule of a subreddit.

Rule numbers start at 0, so the first rule is at index 0, and the second rule is at index 1, and so on.

Raises

IndexError if a rule of a specific number does not exist.

Note

You can use negative indexes, such as -1, to get the last rule. You can also use slices, to get a subset of rules, such as the last three rules with get_rule(slice(-3, None)).

For example, to fetch the second rule of r/test:

subreddit = await reddit.subreddit("test")
rule = await subreddit.rules.get_rule(1)
mod() SubredditRulesModeration

Contain methods to moderate subreddit rules as a whole.

To add rule "No spam" to r/test try:

subreddit = await reddit.subreddit("test")
await subreddit.rules.mod.add(
    short_name="No spam", kind="all", description="Do not spam. Spam bad"
)

To move the fourth rule to the first position, and then to move the prior first rule to where the third rule originally was in r/test:

subreddit = await reddit.subreddit("test")
rules = [rule async for rule in subreddit.rules]
new_rules = rules[3:4] + rules[1:3] + rules[0:1] + rules[4:]
# Alternate: [rules[3]] + rules[1:3] + [rules[0]] + rules[4:]
new_rule_list = await subreddit.rules.mod.reorder(new_rules)

SubredditStream

class asyncpraw.models.reddit.subreddit.SubredditStream(subreddit: asyncpraw.models.Subreddit)

Provides submission and comment streams.

__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a SubredditStream instance.

Parameters

subreddit – The subreddit associated with the streams.

comments(**stream_options: Any) AsyncGenerator[asyncpraw.models.Comment, None]

Yield new comments as they become available.

Comments are yielded oldest first. Up to 100 historical comments will initially be returned.

Keyword arguments are passed to stream_generator().

Note

While Async PRAW tries to catch all new comments, some high-volume streams, especially the r/all stream, may drop some comments.

For example, to retrieve all new comments made to r/test, try:

subreddit = await reddit.subreddit("test")
async for comment in subreddit.stream.comments():
    print(comment)

To only retrieve new submissions starting when the stream is created, pass skip_existing=True:

subreddit = await reddit.subreddit("test")
async for comment in subreddit.stream.comments(skip_existing=True):
    print(comment)
submissions(**stream_options: Any) AsyncGenerator[asyncpraw.models.Submission, None]

Yield new Submissions as they become available.

Submissions are yielded oldest first. Up to 100 historical submissions will initially be returned.

Keyword arguments are passed to stream_generator().

Note

While Async PRAW tries to catch all new submissions, some high-volume streams, especially the r/all stream, may drop some submissions.

For example, to retrieve all new submissions made to all of Reddit, try:

subreddit = await reddit.subreddit("all")
async for submission in subreddit.stream.submissions():
    print(submission)

SubredditStylesheet

class asyncpraw.models.reddit.subreddit.SubredditStylesheet(subreddit: asyncpraw.models.Subreddit)

Provides a set of stylesheet functions to a Subreddit.

For example, to add the css data .test{color:blue} to the existing stylesheet:

subreddit = await reddit.subreddit("test")
stylesheet = await subreddit.stylesheet()
stylesheet.stylesheet.stylesheet += ".test{color:blue}"
await subreddit.stylesheet.update(stylesheet.stylesheet)
await __call__() asyncpraw.models.Stylesheet

Return the Subreddit’s stylesheet.

To be used as:

subreddit = await reddit.subreddit("test")
stylesheet = await subreddit.stylesheet()
__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a SubredditStylesheet instance.

Parameters

subreddit – The Subreddit associated with the stylesheet.

An instance of this class is provided as:

subreddit = await reddit.subreddit("test")
subreddit.stylesheet
await delete_banner()

Remove the current Subreddit (redesign) banner image.

Succeeds even if there is no banner image.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.stylesheet.delete_banner()
await delete_banner_additional_image()

Remove the current Subreddit (redesign) banner additional image.

Succeeds even if there is no additional image. Will also delete any configured hover image.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.stylesheet.delete_banner_additional_image()
await delete_banner_hover_image()

Remove the current Subreddit (redesign) banner hover image.

Succeeds even if there is no hover image.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.stylesheet.delete_banner_hover_image()
await delete_header()

Remove the current Subreddit header image.

Succeeds even if there is no header image.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.stylesheet.delete_header()
await delete_image(name: str)

Remove the named image from the Subreddit.

Succeeds even if the named image does not exist.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.stylesheet.delete_image("smile")
await delete_mobile_header()

Remove the current Subreddit mobile header.

Succeeds even if there is no mobile header.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.stylesheet.delete_mobile_header()
await delete_mobile_icon()

Remove the current Subreddit mobile icon.

Succeeds even if there is no mobile icon.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.stylesheet.delete_mobile_icon()
await update(stylesheet: str, *, reason: Optional[str] = None)

Update the Subreddit’s stylesheet.

Parameters
  • stylesheet – The CSS for the new stylesheet.

  • reason – The reason for updating the stylesheet.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.stylesheet.update("p { color: green; }", reason="color text green")
await upload(*, image_path: str, name: str) Dict[str, str]

Upload an image to the Subreddit.

Parameters
  • image_path – A path to a jpeg or png image.

  • name – The name to use for the image. If an image already exists with the same name, it will be replaced.

Returns

A dictionary containing a link to the uploaded image under the key img_src.

Raises

asyncprawcore.TooLarge if the overall request body is too large.

Raises

RedditAPIException if there are other issues with the uploaded image. Unfortunately the exception info might not be very specific, so try through the website with the same image to see what the problem actually might be.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.stylesheet.upload(name="smile", image_path="img.png")
await upload_banner(image_path: str)

Upload an image for the Subreddit’s (redesign) banner image.

Parameters

image_path – A path to a jpeg or png image.

Raises

asyncprawcore.TooLarge if the overall request body is too large.

Raises

RedditAPIException if there are other issues with the uploaded image. Unfortunately the exception info might not be very specific, so try through the website with the same image to see what the problem actually might be.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.stylesheet.upload_banner("banner.png")
await upload_banner_additional_image(image_path: str, *, align: Optional[str] = None)

Upload an image for the Subreddit’s (redesign) additional image.

Parameters
  • image_path – A path to a jpeg or png image.

  • align – Either "left", "centered", or "right". (default: "left").

Raises

asyncprawcore.TooLarge if the overall request body is too large.

Raises

RedditAPIException if there are other issues with the uploaded image. Unfortunately the exception info might not be very specific, so try through the website with the same image to see what the problem actually might be.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.stylesheet.upload_banner_additional_image("banner.png")
await upload_banner_hover_image(image_path: str)

Upload an image for the Subreddit’s (redesign) additional image.

Parameters

image_path – A path to a jpeg or png image.

Fails if the Subreddit does not have an additional image defined.

Raises

asyncprawcore.TooLarge if the overall request body is too large.

Raises

RedditAPIException if there are other issues with the uploaded image. Unfortunately the exception info might not be very specific, so try through the website with the same image to see what the problem actually might be.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.stylesheet.upload_banner_hover_image("banner.png")
await upload_header(image_path: str) Dict[str, str]

Upload an image to be used as the Subreddit’s header image.

Parameters

image_path – A path to a jpeg or png image.

Returns

A dictionary containing a link to the uploaded image under the key img_src.

Raises

asyncprawcore.TooLarge if the overall request body is too large.

Raises

RedditAPIException if there are other issues with the uploaded image. Unfortunately the exception info might not be very specific, so try through the website with the same image to see what the problem actually might be.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.stylesheet.upload_header("header.png")
await upload_mobile_header(image_path: str) Dict[str, str]

Upload an image to be used as the Subreddit’s mobile header.

Parameters

image_path – A path to a jpeg or png image.

Returns

A dictionary containing a link to the uploaded image under the key img_src.

Raises

asyncprawcore.TooLarge if the overall request body is too large.

Raises

RedditAPIException if there are other issues with the uploaded image. Unfortunately the exception info might not be very specific, so try through the website with the same image to see what the problem actually might be.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.stylesheet.upload_mobile_header("header.png")
await upload_mobile_icon(image_path: str) Dict[str, str]

Upload an image to be used as the Subreddit’s mobile icon.

Parameters

image_path – A path to a jpeg or png image.

Returns

A dictionary containing a link to the uploaded image under the key img_src.

Raises

asyncprawcore.TooLarge if the overall request body is too large.

Raises

RedditAPIException if there are other issues with the uploaded image. Unfortunately the exception info might not be very specific, so try through the website with the same image to see what the problem actually might be.

For example:

subreddit = await reddit.subreddit("test")
await subreddit.stylesheet.upload_mobile_icon("icon.png")

SubredditWidgets

class asyncpraw.models.SubredditWidgets(subreddit: asyncpraw.models.Subreddit)

Class to represent a Subreddit’s widgets.

Create an instance like so:

subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets

Data will be lazy-loaded. By default, Async PRAW will not request progressively loading images from Reddit. To enable this, instantiate a SubredditWidgets object via widgets(), then set the attribute progressive_images to True before performing any action that would result in a network request.

subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
widgets.progressive_images = True
async for widget in widgets.sidebar():
    # do something
    ...

Access a Subreddit’s widgets with the following attributes:

print(await widgets.id_card())
print(await widgets.moderators_widget())
print([widget async for widget in widgets.sidebar()])
print([widget async for widget in widgets.topbar()])

The attribute id_card contains the Subreddit’s ID card, which displays information like the number of subscribers.

The attribute moderators_widget contains the Subreddit’s moderators widget, which lists the moderators of the subreddit.

The attribute sidebar contains a list of widgets which make up the sidebar of the subreddit.

The attribute topbar contains a list of widgets which make up the top bar of the subreddit.

To edit a Subreddit’s widgets, use mod. For example:

await widgets.mod.add_text_area(
    short_name="My title",
    text="**bold text**",
    styles={"backgroundColor": "#FFFF66", "headerColor": "#3333EE"},
)

For more information, see SubredditWidgetsModeration.

To edit a particular widget, use .mod on the widget. For example:

async for widget in widgets.sidebar():
    await widget.mod.update(shortName="Exciting new name")

For more information, see WidgetModeration.

Currently available widgets:

__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a SubredditWidgets instance.

Parameters

subreddit – The Subreddit the widgets belong to.

await id_card() asyncpraw.models.IDCard

Get this Subreddit’s IDCard widget.

await items() Dict[str, asyncpraw.models.Widget]

Get this Subreddit’s widgets as a dict from ID to widget.

mod() asyncpraw.models.SubredditWidgetsModeration

Get an instance of SubredditWidgetsModeration.

Note

Using any of the methods of SubredditWidgetsModeration will likely result in the data of this SubredditWidgets being outdated. To re-sync, call refresh().

await moderators_widget() asyncpraw.models.ModeratorsWidget

Get this Subreddit’s ModeratorsWidget.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

await refresh()

Refresh the Subreddit’s widgets.

By default, Async PRAW will not request progressively loading images from Reddit. To enable this, set the attribute progressive_images to True prior to calling refresh().

subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
widgets.progressive_images = True
await widgets.refresh()
async for ... in sidebar() List[asyncpraw.models.Widget]

Get a list of Widgets that make up the sidebar.

async for ... in topbar() List[asyncpraw.models.Menu]

Get a list of Widgets that make up the top bar.

SubredditWiki

class asyncpraw.models.reddit.subreddit.SubredditWiki(subreddit: asyncpraw.models.Subreddit)

Provides a set of wiki functions to a Subreddit.

__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a SubredditWiki instance.

Parameters

subreddit – The subreddit whose wiki to work with.

await create(*, content: str, name: str, reason: Optional[str] = None, **other_settings: Any)

Create a new WikiPage.

Parameters
  • name – The name of the new WikiPage. This name will be normalized.

  • content – The content of the new WikiPage.

  • reason – The reason for the creation.

  • other_settings – Additional keyword arguments to pass.

To create the wiki page "praw_test" in r/test try:

subreddit = await reddit.subreddit("test")
await subreddit.wiki.create(
    name="praw_test", content="wiki body text", reason="Async PRAW Test Creation"
)
await get_page(page_name, fetch: bool = True, **kwargs) WikiPage

Return the WikiPage for the Subreddit named page_name.

Parameters
  • page_name – Name of the wikipage.

  • fetch – Determines if Async PRAW will fetch the object (default: True).

This method is to be used to fetch a specific wikipage, like so:

subreddit = await reddit.subreddit("test")
wikipage = await subreddit.wiki.get_page("proof")
print(wikipage.content_md)
revisions(**generator_kwargs: Any) AsyncGenerator[Dict[str, Optional[Union[asyncpraw.models.Redditor, WikiPage, str, int, bool]]], None]

Return a ListingGenerator for recent wiki revisions.

Additional keyword arguments are passed in the initialization of ListingGenerator.

To view the wiki revisions for "praw_test" in r/test try:

subreddit = await reddit.subreddit("test")
page = await subreddit.wiki.get_page("praw_test")
async for item in page.revisions():
    print(item)

Button

class asyncpraw.models.Button(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Class to represent a single button inside a ButtonWidget.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

color

The hex color used to outline the button.

fillColor

The hex color for the background of the button.

height

Image height. Only present on image buttons.

hoverState

A dict describing the state of the button when hovered over. Optional.

kind

Either "text" or "image".

linkUrl

A link that can be visited by clicking the button. Only present on image buttons.

text

The text displayed on the button.

textColor

The hex color for the text of the button.

url

  • If the button is a text button, a link that can be visited by clicking the button.

  • If the button is an image button, the URL of a Reddit-hosted image.

width

Image width. Only present on image buttons.

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

ButtonWidget

class asyncpraw.models.ButtonWidget(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Class to represent a widget containing one or more buttons.

Find an existing one:

button_widget = None
subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
async for widget in widgets.sidebar():
    if isinstance(widget, asyncpraw.models.ButtonWidget):
        button_widget = widget
        break

for button in button_widget:
    print(button.text, button.url)

Create one:

subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
buttons = [
    {
        "kind": "text",
        "text": "View source",
        "url": "https://github.com/asyncpraw-dev/asyncpraw",
        "color": "#FF0000",
        "textColor": "#00FF00",
        "fillColor": "#0000FF",
        "hoverState": {
            "kind": "text",
            "text": "ecruos weiV",
            "color": "#000000",
            "textColor": "#FFFFFF",
            "fillColor": "#0000FF",
        },
    },
    {
        "kind": "text",
        "text": "View documentation",
        "url": "https://asyncpraw.readthedocs.io",
        "color": "#FFFFFF",
        "textColor": "#FFFF00",
        "fillColor": "#0000FF",
    },
]
styles = {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}
button_widget = await widgets.mod.add_button_widget(
    "Things to click", "Click some of these *cool* links!", buttons, styles
)

For more information on creation, see add_button_widget().

Update one:

new_styles = {"backgroundColor": "#FFFFFF", "headerColor": "#FF9900"}
button_widget = await button_widget.mod.update(
    shortName="My fav buttons", styles=new_styles
)

Delete one:

await button_widget.mod.delete()

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

buttons

A list of Buttons. These can also be accessed just by iterating over the ButtonWidget (e.g., for button in button_widget).

description

The description, in Markdown.

description_html

The description, in HTML.

id

The widget ID.

kind

The widget kind (always "button").

shortName

The short name of the widget.

styles

A dict with the keys "backgroundColor" and "headerColor".

subreddit

The Subreddit the button widget belongs to.

__contains__(item: Any) bool

Test if item exists in the list.

__getitem__(index: int) Any

Return the item at position index in the list.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a Widget instance.

__iter__() Iterator[Any]

Return an iterator to the list.

__len__() int

Return the number of items in the list.

mod() asyncpraw.models.WidgetModeration

Get an instance of WidgetModeration for this widget.

Note

Using any of the methods of WidgetModeration will likely make outdated the data in the SubredditWidgets that this widget belongs to. To remedy this, call refresh().

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

Calendar

class asyncpraw.models.Calendar(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Class to represent a calendar widget.

Find an existing one:

calendar = None
subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
async for widget in widgets.sidebar():
    if isinstance(widget, asyncpraw.models.Calendar):
        calendar = widget
        break

print(calendar.googleCalendarId)

Create one:

subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
styles = {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}
config = {
    "numEvents": 10,
    "showDate": True,
    "showDescription": False,
    "showLocation": False,
    "showTime": True,
    "showTitle": True,
}
cal_id = "y6nm89jy427drk8l71w75w9wjn@group.calendar.google.com"
calendar = await widgets.mod.add_calendar(
    short_name="Upcoming Events",
    google_calendar_id=cal_id,
    requires_sync=True,
    configuration=config,
    styles=styles,
)

For more information on creation, see add_calendar().

Update one:

new_styles = {"backgroundColor": "#FFFFFF", "headerColor": "#FF9900"}
calendar = await calendar.mod.update(shortName="My fav events", styles=new_styles)

Delete one:

await calendar.mod.delete()

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

configuration

A dict describing the calendar configuration.

data

A list of dictionaries that represent events.

id

The widget ID.

kind

The widget kind (always "calendar").

requiresSync

A bool representing whether the calendar requires synchronization.

shortName

The short name of the widget.

styles

A dict with the keys "backgroundColor" and "headerColor".

subreddit

The Subreddit the button widget belongs to.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a Widget instance.

mod() asyncpraw.models.WidgetModeration

Get an instance of WidgetModeration for this widget.

Note

Using any of the methods of WidgetModeration will likely make outdated the data in the SubredditWidgets that this widget belongs to. To remedy this, call refresh().

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

CalendarConfiguration

class asyncpraw.models.CalendarConfiguration(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Class to represent the configuration of a Calendar.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

numEvents

The number of events to display on the calendar.

showDate

Whether to show the dates of events.

showDescription

Whether to show the descriptions of events.

showLocation

Whether to show the locations of events.

showTime

Whether to show the times of events.

showTitle

Whether to show the titles of events.

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

CommunityList

class asyncpraw.models.CommunityList(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Class to represent a Related Communities widget.

Find an existing one:

community_list = None
subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
async for widget in widgets.sidebar():
    if isinstance(widget, asyncpraw.models.CommunityList):
        community_list = widget
        break

print(community_list)

Create one:

subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
styles = {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}
new_subreddit = await reddit.subreddit("test")
subreddits = ["learnpython", new_subreddit]
community_list = await widgets.mod.add_community_list(
    short_name="Related subreddits",
    data=subreddits,
    styles=styles,
    description="description",
)

For more information on creation, see add_community_list().

Update one:

new_styles = {"backgroundColor": "#FFFFFF", "headerColor": "#FF9900"}
community_list = await community_list.mod.update(
    shortName="My fav subs", styles=new_styles
)

Delete one:

await community_list.mod.delete()

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

data

A list of Subreddits. These can also be iterated over by iterating over the CommunityList (e.g., for sub in community_list).

id

The widget ID.

kind

The widget kind (always "community-list").

shortName

The short name of the widget.

styles

A dict with the keys "backgroundColor" and "headerColor".

subreddit

The Subreddit the button widget belongs to.

__contains__(item: Any) bool

Test if item exists in the list.

__getitem__(index: int) Any

Return the item at position index in the list.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a Widget instance.

__iter__() Iterator[Any]

Return an iterator to the list.

__len__() int

Return the number of items in the list.

mod() asyncpraw.models.WidgetModeration

Get an instance of WidgetModeration for this widget.

Note

Using any of the methods of WidgetModeration will likely make outdated the data in the SubredditWidgets that this widget belongs to. To remedy this, call refresh().

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

CustomWidget

class asyncpraw.models.CustomWidget(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Class to represent a custom widget.

Find an existing one:

custom = None
subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
async for widget in widgets.sidebar():
    if isinstance(widget, asyncpraw.models.CustomWidget):
        custom = widget
        break

print(custom.text)
print(custom.css)

Create one:

subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
styles = {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}
custom = await widgets.mod.add_custom_widget(
    short_name="My custom widget",
    text="# Hello world!",
    css="/**/",
    height=200,
    image_data=[],
    styles=styles,
)

For more information on creation, see add_custom_widget().

Update one:

new_styles = {"backgroundColor": "#FFFFFF", "headerColor": "#FF9900"}
custom = await custom.mod.update(shortName="My fav customization", styles=new_styles)

Delete one:

await custom.mod.delete()

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

css

The CSS of the widget, as a str.

height

The height of the widget, as an int.

id

The widget ID.

imageData

A list of ImageData that belong to the widget.

kind

The widget kind (always "custom").

shortName

The short name of the widget.

styles

A dict with the keys "backgroundColor" and "headerColor".

stylesheetUrl

A link to the widget’s stylesheet.

subreddit

The Subreddit the button widget belongs to.

text

The text contents, as Markdown.

textHtml

The text contents, as HTML.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a CustomWidget instance.

mod() asyncpraw.models.WidgetModeration

Get an instance of WidgetModeration for this widget.

Note

Using any of the methods of WidgetModeration will likely make outdated the data in the SubredditWidgets that this widget belongs to. To remedy this, call refresh().

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

Hover

class asyncpraw.models.Hover(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Class to represent the hover data for a ButtonWidget.

These values will take effect when the button is hovered over (the user moves their cursor so it’s on top of the button).

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

color

The hex color used to outline the button.

fillColor

The hex color for the background of the button.

textColor

The hex color for the text of the button.

height

Image height. Only present on image buttons.

kind

Either text or image.

text

The text displayed on the button.

url

  • If the button is a text button, a link that can be visited by clicking the button.

  • If the button is an image button, the URL of a Reddit-hosted image.

width

Image width. Only present on image buttons.

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

IDCard

class asyncpraw.models.IDCard(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Class to represent an ID card widget.

subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
id_card = await widgets.id_card()
print(id_card.subscribersText)

Update one:

id_card = await widgets.id_card()
await id_card.mod.update(currentlyViewingText="Bots")

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

currentlyViewingCount

The number of redditors viewing the subreddit.

currentlyViewingText

The text displayed next to the view count. For example, "users online".

description

The subreddit description.

id

The widget ID.

kind

The widget kind (always "id-card").

shortName

The short name of the widget.

styles

A dict with the keys "backgroundColor" and "headerColor".

subreddit

The Subreddit the button widget belongs to.

subscribersCount

The number of subscribers to the subreddit.

subscribersText

The text displayed next to the subscriber count. For example, “users subscribed”.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a Widget instance.

mod() asyncpraw.models.WidgetModeration

Get an instance of WidgetModeration for this widget.

Note

Using any of the methods of WidgetModeration will likely make outdated the data in the SubredditWidgets that this widget belongs to. To remedy this, call refresh().

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

Image

class asyncpraw.models.Image(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Class to represent an image that’s part of a ImageWidget.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

height

Image height.

linkUrl

A link that can be visited by clicking the image.

url

The URL of the (Reddit-hosted) image.

width

Image width.

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

ImageData

class asyncpraw.models.ImageData(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Class for image data that’s part of a CustomWidget.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

height

The image height.

name

The image name.

url

The URL of the image on Reddit’s servers.

width

The image width.

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

ImageWidget

class asyncpraw.models.ImageWidget(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Class to represent an image widget.

Find an existing one:

image_widget = None
subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
async for widget in widgets.sidebar():
    if isinstance(widget, asyncpraw.models.ImageWidget):
        image_widget = widget
        break

for image in image_widget:
    print(image.url)

Create one:

subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
image_paths = ["/path/to/image1.jpg", "/path/to/image2.png"]
image_data = [
    {
        "width": 600,
        "height": 450,
        "linkUrl": "",
        "url": await widgets.mod.upload_image(img_path),
    }
    for img_path in image_paths
]
styles = {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}
image_widget = await widgets.mod.add_image_widget(
    short_name="My cool pictures", data=image_data, styles=styles
)

For more information on creation, see add_image_widget().

Update one:

new_styles = {"backgroundColor": "#FFFFFF", "headerColor": "#FF9900"}
image_widget = await image_widget.mod.update(
    shortName="My fav images", styles=new_styles
)

Delete one:

await image_widget.mod.delete()

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

data

A list of the Images in this widget. Can be iterated over by iterating over the ImageWidget (e.g., for img in image_widget).

id

The widget ID.

kind

The widget kind (always "image").

shortName

The short name of the widget.

styles

A dict with the keys "backgroundColor" and "headerColor".

subreddit

The Subreddit the button widget belongs to.

__contains__(item: Any) bool

Test if item exists in the list.

__getitem__(index: int) Any

Return the item at position index in the list.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a Widget instance.

__iter__() Iterator[Any]

Return an iterator to the list.

__len__() int

Return the number of items in the list.

mod() asyncpraw.models.WidgetModeration

Get an instance of WidgetModeration for this widget.

Note

Using any of the methods of WidgetModeration will likely make outdated the data in the SubredditWidgets that this widget belongs to. To remedy this, call refresh().

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

ModeratorsWidget

class asyncpraw.models.ModeratorsWidget(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Class to represent a moderators widget.

subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
print(await widgets.moderators_widget())

Update one:

new_styles = {"backgroundColor": "#FFFFFF", "headerColor": "#FF9900"}
moderator_widget = await widgets.moderators_widget()
await moderator_widget.mod.update(styles=new_styles)

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

id

The widget ID.

kind

The widget kind (always "moderators").

mods

A list of the Redditors that moderate the subreddit. Can be iterated over by iterating over the ModeratorsWidget (e.g., for mod in widgets.moderators_widget).

styles

A dict with the keys "backgroundColor" and "headerColor".

subreddit

The Subreddit the button widget belongs to.

totalMods

The total number of moderators in the subreddit.

__contains__(item: Any) bool

Test if item exists in the list.

__getitem__(index: int) Any

Return the item at position index in the list.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a ModeratorsWidget instance.

__iter__() Iterator[Any]

Return an iterator to the list.

__len__() int

Return the number of items in the list.

mod() asyncpraw.models.WidgetModeration

Get an instance of WidgetModeration for this widget.

Note

Using any of the methods of WidgetModeration will likely make outdated the data in the SubredditWidgets that this widget belongs to. To remedy this, call refresh().

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

PostFlairWidget

class asyncpraw.models.PostFlairWidget(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Class to represent a post flair widget.

Find an existing one:

post_flair_widget = None
subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
async for widget in widgets.sidebar():
    if isinstance(widget, asyncpraw.models.PostFlairWidget):
        post_flair_widget = widget
        break

async for flair in post_flair_widget:
    print(flair)
    print(post_flair_widget.templates[flair])

Create one:

subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
flairs = [f["id"] async for f in subreddit.flair.link_templates]
styles = {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}
post_flair = await widgets.mod.add_post_flair_widget(
    short_name="Some flairs", display="list", order=flairs, styles=styles
)

For more information on creation, see add_post_flair_widget().

Update one:

new_styles = {"backgroundColor": "#FFFFFF", "headerColor": "#FF9900"}
post_flair = await post_flair.mod.update(shortName="My fav flairs", styles=new_styles)

Delete one:

await post_flair.mod.delete()

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

display

The display style of the widget, either "cloud" or "list".

id

The widget ID.

kind

The widget kind (always "post-flair").

order

A list of the flair IDs in this widget. Can be iterated over by iterating over the PostFlairWidget (e.g., for flair_id in post_flair).

shortName

The short name of the widget.

styles

A dict with the keys "backgroundColor" and "headerColor".

subreddit

The Subreddit the button widget belongs to.

templates

A dict that maps flair IDs to dictionaries that describe flairs.

__contains__(item: Any) bool

Test if item exists in the list.

__getitem__(index: int) Any

Return the item at position index in the list.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a Widget instance.

__iter__() Iterator[Any]

Return an iterator to the list.

__len__() int

Return the number of items in the list.

mod() asyncpraw.models.WidgetModeration

Get an instance of WidgetModeration for this widget.

Note

Using any of the methods of WidgetModeration will likely make outdated the data in the SubredditWidgets that this widget belongs to. To remedy this, call refresh().

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

RulesWidget

class asyncpraw.models.RulesWidget(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Class to represent a rules widget.

subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
rules_widget = None
async for widget in widgets.sidebar():
    if isinstance(widget, asyncpraw.models.RulesWidget):
        rules_widget = widget
        break
from pprint import pprint

pprint(rules_widget.data)

Update one:

new_styles = {"backgroundColor": "#FFFFFF", "headerColor": "#FF9900"}
await rules_widget.mod.update(
    display="compact", shortName="The LAWS", styles=new_styles
)

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

data

A list of the subreddit rules. Can be iterated over by iterating over the RulesWidget (e.g., for rule in rules_widget).

display

The display style of the widget, either "full" or "compact".

id

The widget ID.

kind

The widget kind (always "subreddit-rules").

shortName

The short name of the widget.

styles

A dict with the keys "backgroundColor" and "headerColor".

subreddit

The Subreddit the button widget belongs to.

__contains__(item: Any) bool

Test if item exists in the list.

__getitem__(index: int) Any

Return the item at position index in the list.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a RulesWidget instance.

__iter__() Iterator[Any]

Return an iterator to the list.

__len__() int

Return the number of items in the list.

mod() asyncpraw.models.WidgetModeration

Get an instance of WidgetModeration for this widget.

Note

Using any of the methods of WidgetModeration will likely make outdated the data in the SubredditWidgets that this widget belongs to. To remedy this, call refresh().

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

Styles

class asyncpraw.models.Styles(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Class to represent the style information of a widget.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

backgroundColor

The background color of a widget, given as a hexadecimal (0x######).

headerColor

The header color of a widget, given as a hexadecimal (0x######).

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

TextArea

class asyncpraw.models.TextArea(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Class to represent a text area widget.

Find a text area in a subreddit:

subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
text_area = None
async for widget in widgets.sidebar():
    if isinstance(widget, asyncpraw.models.TextArea):
        text_area = widget
        break
print(text_area.text)

Create one:

subreddit = await reddit.subreddit("test")
widgets = subreddit.widgets
styles = {"backgroundColor": "#FFFF66", "headerColor": "#3333EE"}
text_area = await widgets.mod.add_text_area(
    short_name="My cool title", text="*Hello* **world**!", styles=styles
)

For more information on creation, see add_text_area().

Update one:

new_styles = {"backgroundColor": "#FFFFFF", "headerColor": "#FF9900"}
text_area = await text_area.mod.update(shortName="My fav text", styles=new_styles)

Delete one:

await text_area.mod.delete()

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

id

The widget ID.

kind

The widget kind (always "textarea").

shortName

The short name of the widget.

styles

A dict with the keys "backgroundColor" and "headerColor".

subreddit

The Subreddit the button widget belongs to.

text

The widget’s text, as Markdown.

textHtml

The widget’s text, as HTML.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a Widget instance.

mod() asyncpraw.models.WidgetModeration

Get an instance of WidgetModeration for this widget.

Note

Using any of the methods of WidgetModeration will likely make outdated the data in the SubredditWidgets that this widget belongs to. To remedy this, call refresh().

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

Widget

class asyncpraw.models.Widget(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Base class to represent a Widget.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a Widget instance.

mod() asyncpraw.models.WidgetModeration

Get an instance of WidgetModeration for this widget.

Note

Using any of the methods of WidgetModeration will likely make outdated the data in the SubredditWidgets that this widget belongs to. To remedy this, call refresh().

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

AsyncPRAWBase

class asyncpraw.models.base.AsyncPRAWBase(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Superclass for all models in Async PRAW.

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

Auth

class asyncpraw.models.Auth(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Auth provides an interface to Reddit’s authorization.

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

await authorize(code: str) Optional[str]

Complete the web authorization flow and return the refresh token.

Parameters

code – The code obtained through the request to the redirect uri.

Returns

The obtained refresh token, if available, otherwise None.

The session’s active authorization will be updated upon success.

implicit(*, access_token: str, expires_in: int, scope: str) None

Set the active authorization to be an implicit authorization.

Parameters
  • access_token – The access_token obtained from Reddit’s callback.

  • expires_in – The number of seconds the access_token is valid for. The origin of this value was returned from Reddit’s callback. You may need to subtract an offset before passing in this number to account for a delay between when Reddit prepared the response, and when you make this function call.

  • scope – A space-delimited string of Reddit OAuth2 scope names as returned from Reddit’s callback.

Raises

InvalidImplicitAuth if Reddit was initialized for a non-installed application type.

property limits: Dict[str, Optional[Union[int, str]]]

Return a dictionary containing the rate limit info.

The keys are:

Remaining

The number of requests remaining to be made in the current rate limit window.

Reset_timestamp

A unix timestamp providing an upper bound on when the rate limit counters will reset.

Used

The number of requests made in the current rate limit window.

All values are initially None as these values are set in response to issued requests.

The reset_timestamp value is an upper bound as the real timestamp is computed on Reddit’s end in preparation for sending the response. This value may change slightly within a given window due to slight changes in response times and rounding.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

await scopes() Set[str]

Return a set of scopes included in the current authorization.

For read-only authorizations this should return {"*"}.

url(*, duration: str = 'permanent', implicit: bool = False, scopes: List[str], state: str) str

Return the URL used out-of-band to grant access to your application.

Parameters
  • duration – Either "permanent" or "temporary" (default: "permanent"). "temporary" authorizations generate access tokens that last only 1 hour. "permanent" authorizations additionally permanent authorizations additionally generate a refresh token that expires 1 year after the last use and can be used indefinitelyto generate new hour-long access tokens. This value is ignored when implicit=True.

  • implicit – For installed applications, this value can be set to use the implicit, rather than the code flow. When True, the duration argument has no effect as only temporary tokens can be retrieved.

  • scopes – A list of OAuth scopes to request authorization for.

  • state – A string that will be reflected in the callback to redirect_uri. This value should be temporarily unique to the client for whom the URL was generated for.

BaseList

class asyncpraw.models.list.base.BaseList(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

An abstract class to coerce a list into an AsyncPRAWBase.

__contains__(item: Any) bool

Test if item exists in the list.

__getitem__(index: int) Any

Return the item at position index in the list.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a BaseList instance.

Parameters

reddit – An instance of Reddit.

__iter__() Iterator[Any]

Return an iterator to the list.

__len__() int

Return the number of items in the list.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

CommentForest

class asyncpraw.models.comment_forest.CommentForest(submission: asyncpraw.models.Submission, comments: Optional[List[asyncpraw.models.Comment]] = None)

A forest of comments starts with multiple top-level comments.

Each of these comments can be a tree of replies.

await __call__()

Call self as a function.

__getitem__(index: int)

Return the comment at position index in the list.

This method is to be used like an array access, such as:

first_comment = submission.comments[0]

Alternatively, the presence of this method enables one to iterate over all top level comments, like so:

for comment in submission.comments:
    print(comment.body)
__init__(submission: asyncpraw.models.Submission, comments: Optional[List[asyncpraw.models.Comment]] = None)

Initialize a CommentForest instance.

Parameters
  • submission – An instance of Submission that is the parent of the comments.

  • comments – Initialize the Forest with a list of comments (default: None).

__len__() int

Return the number of top-level comments in the forest.

list() Union[List[Union[asyncpraw.models.Comment, asyncpraw.models.MoreComments]], Coroutine[Any, Any, List[Union[asyncpraw.models.Comment, asyncpraw.models.MoreComments]]]]

Return a flattened list of all Comments.

This list may contain MoreComments instances if replace_more() was not called first.

await replace_more(*, limit: int = 32, threshold: int = 0) List[asyncpraw.models.MoreComments]

Update the comment forest by resolving instances of MoreComments.

Parameters
  • limit – The maximum number of MoreComments instances to replace. Each replacement requires 1 API request. Set to None to have no limit, or to 0 to remove all MoreComments instances without additional requests (default: 32).

  • threshold – The minimum number of children comments a MoreComments instance must have in order to be replaced. MoreComments instances that represent “continue this thread” links unfortunately appear to have 0 children (default: 0).

Returns

A list of MoreComments instances that were not replaced.

Raises

asyncprawcore.TooManyRequests when used concurrently.

For example, to replace up to 32 MoreComments instances of a submission try:

submission = await reddit.submission("3hahrw", fetch=False)
await submission.comments.replace_more()

Alternatively, to replace MoreComments instances within the replies of a single comment try:

comment = await reddit.comment("d8r4im1", fetch=False)
await comment.refresh()
await comment.replies.replace_more()

Note

This method can take a long time as each replacement will discover at most 100 new Comment instances. As a result, consider looping and handling exceptions until the method returns successfully. For example:

while True:
    try:
        await submission.comments.replace_more()
        break
    except PossibleExceptions:
        print("Handling replace_more exception")
        await asyncio.sleep(1)

Warning

If this method is called, and the comments are refreshed, calling this method again will result in a DuplicateReplaceException.

CommentHelper

class asyncpraw.models.listing.mixins.subreddit.CommentHelper(subreddit: asyncpraw.models.Subreddit)

Provide a set of functions to interact with a Subreddit’s comments.

__call__(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Comment]

Return a ListingGenerator for the Subreddit’s comments.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method should be used in a way similar to the example below:

subreddit = await reddit.subreddit("test")
async for comment in subreddit.comments(limit=25):
    print(comment.author)
__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a CommentHelper instance.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

Config

class asyncpraw.config.Config(site_name: str, config_interpolation: Optional[str] = None, **settings: str)

A class containing the configuration for a Reddit site.

__init__(site_name: str, config_interpolation: Optional[str] = None, **settings: str)

Initialize a Config instance.

property short_url: str

Return the short url.

Raises

ClientException if it is not set.

DomainListing

class asyncpraw.models.DomainListing(reddit: asyncpraw.Reddit, domain: str)

Provide a set of functions to interact with domain listings.

__init__(reddit: asyncpraw.Reddit, domain: str)

Initialize a DomainListing instance.

Parameters
  • reddit – An instance of Reddit.

  • domain – The domain for which to obtain listings.

controversial(*, time_filter: str = 'all', **generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for controversial items.

Parameters

time_filter – Can be one of: "all", "day", "hour", "month", "week", or "year" (default: "all").

Raises

ValueError if time_filter is invalid.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").controversial(time_filter="week")

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.controversial(time_filter="day")

redditor = await reddit.redditor("spez")
redditor.controversial(time_filter="month")

redditor = await reddit.redditor("spez")
redditor.comments.controversial(time_filter="year")

redditor = await reddit.redditor("spez")
redditor.submissions.controversial(time_filter="all")

subreddit = await reddit.subreddit("all")
subreddit.controversial(time_filter="hour")
hot(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for hot items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").hot()

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.hot()

redditor = await reddit.redditor("spez")
redditor.hot()

redditor = await reddit.redditor("spez")
redditor.comments.hot()

redditor = await reddit.redditor("spez")
redditor.submissions.hot()

subreddit = await reddit.subreddit("all")
subreddit.hot()
new(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for new items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").new()

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.new()

redditor = await reddit.redditor("spez")
redditor.new()

redditor = await reddit.redditor("spez")
redditor.comments.new()

redditor = await reddit.redditor("spez")
redditor.submissions.new()

subreddit = await reddit.subreddit("all")
subreddit.new()
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

random_rising(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Submission]

Return a ListingGenerator for random rising submissions.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get random rising submissions for r/test:

subreddit = await reddit.subreddit("test")
async for submission in subreddit.random_rising():
    print(submission.title)
rising(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Submission]

Return a ListingGenerator for rising submissions.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get rising submissions for r/test:

subreddit = await reddit.subreddit("test")
async for submission in subreddit.rising():
    print(submission.title)
top(*, time_filter: str = 'all', **generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for top items.

Parameters

time_filter – Can be one of: "all", "day", "hour", "month", "week", or "year "``(default: ``"all").

Raises

ValueError if time_filter is invalid.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").top(time_filter="week")

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.top(time_filter="day")

redditor = await reddit.redditor("spez")
redditor.top(time_filter="month")

redditor = await reddit.redditor("spez")
redditor.comments.top(time_filter="year")

redditor = await reddit.redditor("spez")
redditor.submissions.top(time_filter="all")

subreddit = await reddit.subreddit("all")
subreddit.top(time_filter="hour")

DraftList

class asyncpraw.models.DraftList(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

A list of Draft objects. Works just like a regular list.

__contains__(item: Any) bool

Test if item exists in the list.

__getitem__(index: int) Any

Return the item at position index in the list.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a BaseList instance.

Parameters

reddit – An instance of Reddit.

__iter__() Iterator[Any]

Return an iterator to the list.

__len__() int

Return the number of items in the list.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

Emoji

class asyncpraw.models.reddit.emoji.Emoji(reddit: asyncpraw.Reddit, subreddit: asyncpraw.models.Subreddit, name: str, _data: Optional[Dict[str, Any]] = None)

An individual Emoji object.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

mod_flair_only

Whether the emoji is restricted for mod use only.

name

The name of the emoji.

post_flair_allowed

Whether the emoji may appear in post flair.

url

The URL of the emoji image.

user_flair_allowed

Whether the emoji may appear in user flair.

__init__(reddit: asyncpraw.Reddit, subreddit: asyncpraw.models.Subreddit, name: str, _data: Optional[Dict[str, Any]] = None)

Initialize an Emoji instance.

await delete()

Delete an emoji from this subreddit by Emoji.

To delete "emoji" as an emoji on r/test try:

subreddit = await reddit.subreddit("test")
emoji = await subreddit.emoji.get_emoji("emoji")
await emoji.delete()
await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

await update(*, mod_flair_only: Optional[bool] = None, post_flair_allowed: Optional[bool] = None, user_flair_allowed: Optional[bool] = None)

Update the permissions of an emoji in this subreddit.

Parameters
  • mod_flair_only – Indicate whether the emoji is restricted to mod use only. Respects pre-existing settings if not provided.

  • post_flair_allowed – Indicate whether the emoji may appear in post flair. Respects pre-existing settings if not provided.

  • user_flair_allowed – Indicate whether the emoji may appear in user flair. Respects pre-existing settings if not provided.

Note

In order to retain pre-existing values for those that are not explicitly passed, a network request is issued. To avoid that network request, explicitly provide all values.

To restrict the emoji "emoji" in r/test to mod use only, try:

subreddit = await reddit.subreddit("test")
emoji = await subreddit.emoji.get_emoji("emoji")
await emoji.update(mod_flair_only=True)

FullnameMixin

class asyncpraw.models.reddit.mixins.FullnameMixin

Interface for classes that have a fullname.

__init__()
property fullname: str

Return the object’s fullname.

A fullname is an object’s kind mapping like t3 followed by an underscore and the object’s base36 ID, e.g., t1_c5s96e0.

InboxableMixin

class asyncpraw.models.reddit.mixins.InboxableMixin

Interface for RedditBase subclasses that originate from the inbox.

__init__()
await block()

Block the user who sent the item.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

comment = await reddit.comment("dkk4qjd")
await comment.block()

# or, identically:
comment = await reddit.comment("dkk4qjd")
await comment.author.block()
await collapse()

Mark the item as collapsed.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

inbox = reddit.inbox()

# select first inbox item and collapse it
async for message in inbox:
    await message.collapse()
    break

See also

uncollapse()

await mark_read()

Mark a single inbox item as read.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

inbox = reddit.inbox.unread()

async for message in inbox:
    # process unread messages
    ...

See also

mark_unread()

To mark the whole inbox as read with a single network request, use Inbox.mark_all_read()

await mark_unread()

Mark the item as unread.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

inbox = reddit.inbox(limit=10)

async for message in inbox:
    # process messages
    ...

See also

mark_read()

await unblock_subreddit()

Unblock a subreddit.

Note

This method pertains only to objects which were retrieved via the inbox.

For example, to unblock all blocked subreddits that you can find by going through your inbox:

from asyncpraw.models import SubredditMessage

subs = set()
async for item in reddit.inbox.messages(limit=None):
    if isinstance(item, SubredditMessage):
        if (
            item.subject == "[message from blocked subreddit]"
            and str(item.subreddit) not in subs
        ):
            item.unblock_subreddit()
            subs.add(str(item.subreddit))
await uncollapse()

Mark the item as uncollapsed.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

inbox = reddit.inbox()

# select first inbox item and uncollapse it
async for message in inbox:
    await message.uncollapse()
    break

See also

collapse()

ListingGenerator

class asyncpraw.models.ListingGenerator(reddit: asyncpraw.Reddit, url: str, limit: int = 100, params: Optional[Dict[str, Union[str, int]]] = None)

Instances of this class generate RedditBase instances.

Warning

This class should not be directly utilized. Instead, you will find a number of methods that return instances of the class here.

__init__(reddit: asyncpraw.Reddit, url: str, limit: int = 100, params: Optional[Dict[str, Union[str, int]]] = None)

Initialize a ListingGenerator instance.

Parameters
  • reddit – An instance of Reddit.

  • url – A URL returning a Reddit listing.

  • limit – The number of content entries to fetch. If limit is None, then fetch as many entries as possible. Most of Reddit’s listings contain a maximum of 1000 items, and are returned 100 at a time. This class will automatically issue all necessary requests (default: 100).

  • params – A dictionary containing additional query string parameters to send with the request.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

ModAction

class asyncpraw.models.ModAction(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Represent a moderator action.

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

property mod: asyncpraw.models.Redditor

Return the Redditor who the action was issued by.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

ModeratedList

class asyncpraw.models.ModeratedList(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

A list of moderated Subreddit objects. Works just like a regular list.

__contains__(item: Any) bool

Test if item exists in the list.

__getitem__(index: int) Any

Return the item at position index in the list.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a BaseList instance.

Parameters

reddit – An instance of Reddit.

__iter__() Iterator[Any]

Return an iterator to the list.

__len__() int

Return the number of items in the list.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

Modmail

class asyncpraw.models.reddit.subreddit.Modmail(subreddit: asyncpraw.models.Subreddit)

Provides modmail functions for a Subreddit.

For example, to send a new modmail from r/test to u/spez with the subject "test" along with a message body of "hello":

subreddit = await reddit.subreddit("test")
await subreddit.modmail.create(subject="test", body="hello", recipient="spez")
await __call__(id: Optional[str] = None, mark_read: bool = False, fetch=True)

Return an individual conversation.

Parameters
  • id – A reddit base36 conversation ID, e.g., "2gmz".

  • mark_read – If True, conversation is marked as read (default: False).

  • fetch – Determines if Async PRAW will fetch the object (default: False).

For example:

subreddit = await reddit.subreddit("test")
await subreddit.modmail("2gmz", mark_read=True)

If you don’t need the object fetched right away (e.g., to utilize a class method) you can do:

subreddit = await reddit.subreddit("test")
message = await subreddit.modmail("2gmz", fetch=False)
await message.archive()

To print all messages from a conversation as Markdown source:

subreddit = await reddit.subreddit("test")
conversation = await subreddit.modmail("2gmz", mark_read=True)
for message in conversation.messages:
    print(message.body_markdown)

ModmailConversation.user is a special instance of Redditor with extra attributes describing the non-moderator user’s recent posts, comments, and modmail messages within the subreddit, as well as information on active bans and mutes. This attribute does not exist on internal moderator discussions.

For example, to print the user’s ban status:

subreddit = await reddit.subreddit("test")
conversation = await subreddit.modmail("2gmz", mark_read=True)
print(conversation.user.ban_status)

To print a list of recent submissions by the user:

subreddit = await reddit.subreddit("test")
conversation = await subreddit.modmail("2gmz", mark_read=True)
print(conversation.user.recent_posts)
__init__(subreddit: asyncpraw.models.Subreddit)

Initialize a Modmail instance.

await bulk_read(*, other_subreddits: Optional[List[Union[str, asyncpraw.models.Subreddit]]] = None, state: Optional[str] = None) List[ModmailConversation]

Mark conversations for subreddit(s) as read.

Note

Due to server-side restrictions, r/all is not a valid subreddit for this method. Instead, use subreddits() to get a list of subreddits using the new modmail.

Parameters
  • other_subreddits – A list of Subreddit instances for which to mark conversations (default: None).

  • state – Can be one of: "all", "archived", or "highlighted", "inprogress", "join_requests", "mod", "new", "notifications", or "appeals" (default: "all"). "all" does not include internal, archived, or appeals conversations.

Returns

A list of lazy ModmailConversation instances that were marked read.

For example, to mark all notifications for a subreddit as read:

subreddit = await reddit.subreddit("test")
await subreddit.modmail.bulk_read(state="notifications")
conversations(*, after: Optional[str] = None, other_subreddits: Optional[List[asyncpraw.models.Subreddit]] = None, sort: Optional[str] = None, state: Optional[str] = None, **generator_kwargs) AsyncIterator[ModmailConversation]

Generate ModmailConversation objects for subreddit(s).

Parameters
  • after

    A base36 modmail conversation id. When provided, the listing begins after this conversation (default: None).

    Deprecated since version 7.5.0: This parameter is deprecated and will be removed in Async PRAW 8.0. This method will automatically fetch the next batch. Please pass it in the params argument like so:

    async for convo in subreddit.modmail.conversations(params={"after": "qovbn"}):
        # process conversation
        ...
    

  • other_subreddits – A list of Subreddit instances for which to fetch conversations (default: None).

  • sort – Can be one of: "mod", "recent", "unread", or "user" (default: "recent").

  • state – Can be one of: "all", "archived", "highlighted", "inprogress", "join_requests", "mod", "new", "notifications", or "appeals" (default: "all"). "all" does not include internal, archived, or appeals conversations.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example:

sub = await reddit.subreddit("all")
async for conversation in sub.modmail.conversations(state="mod"):
    # do stuff with conversations
    ...
await create(*, author_hidden: bool = False, body: str, recipient: Union[str, asyncpraw.models.Redditor], subject: str) ModmailConversation

Create a new ModmailConversation.

Parameters
  • author_hidden – When True, author is hidden from non-moderators (default: False).

  • body – The message body. Cannot be empty.

  • recipient – The recipient; a username or an instance of Redditor.

  • subject – The message subject. Cannot be empty.

Returns

A ModmailConversation object for the newly created conversation.

subreddit = await reddit.subreddit("test")
redditor = await reddit.redditor("bboe")
await subreddit.modmail.create(subject="Subject", body="Body", recipient=redditor)
async for ... in subreddits() AsyncGenerator[asyncpraw.models.Subreddit, None]

Yield subreddits using the new modmail that the user moderates.

For example:

sub = await reddit.subreddit("all")
async for subreddit in sub.modmail.subreddits():
    # do stuff with subreddit
    ...
await unread_count() Dict[str, int]

Return unread conversation count by conversation state.

At time of writing, possible states are: "archived", "highlighted", "inprogress", "join_requests", "mod", "new", "notifications", or "appeals".

Returns

A dict mapping conversation states to unread counts.

For example, to print the count of unread moderator discussions:

subreddit = await reddit.subreddit("test")
unread_counts = await subreddit.modmail.unread_count()
print(unread_counts["mod"])

ModmailMessage

class asyncpraw.models.ModmailMessage(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]], _extra_attribute_to_check: Optional[str] = None, _fetched: bool = False, _str_field: bool = True)

A class for modmail messages.

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]], _extra_attribute_to_check: Optional[str] = None, _fetched: bool = False, _str_field: bool = True)

Initialize a RedditBase instance.

Parameters

reddit – An instance of Reddit.

await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

PollData

class asyncpraw.models.reddit.poll.PollData(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Class to represent poll data on a poll submission.

If submission is a poll Submission, access the poll data like so:

poll_data = submission.poll_data
print(f"There are {poll_data.total_vote_count} votes total.")
print("The options are:")
for option in poll_data.options:
    print(f"{option} ({option.vote_count} votes)")
print(f"I voted for {poll_data.user_selection}.")

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

options

A list of PollOption of the poll.

total_vote_count

The total number of votes cast in the poll.

user_selection

The poll option selected by the authenticated user (possibly None).

voting_end_timestamp

Time the poll voting closes, represented in Unix Time.

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

option(option_id: str) PollOption

Get the option with the specified ID.

Parameters

option_id – The ID of a poll option, as a str.

Returns

The specified PollOption.

Raises

KeyError if no option exists with the specified ID.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

user_selection() Optional[PollOption]

Get the user’s selection in this poll, if any.

Returns

The user’s selection as a PollOption, or None if there is no choice.

PollOption

class asyncpraw.models.reddit.poll.PollOption(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Class to represent one option of a poll.

If submission is a poll Submission, access the poll’s options like so:

poll_data = submission.poll_data

# By index -- print the first option
print(poll_data.options[0])

# By ID -- print the option with ID "576797"
print(poll_data.option("576797"))

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

id

ID of the poll option.

text

The text of the poll option.

vote_count

The number of votes the poll option has received.

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

PartialRedditor

class asyncpraw.models.redditors.PartialRedditor

A namespace object that provides a subset of Redditor attributes.

__init__(*args, **kwargs)

Preferences

class asyncpraw.models.Preferences(reddit: asyncpraw.Reddit)

A class for Reddit preferences.

The Preferences class provides access to the Reddit preferences of the currently authenticated user.

await __call__() Dict[str, Union[str, int, bool]]

Return the preference settings of the authenticated user as a dict.

This method is intended to be accessed as reddit.user.preferences() like so:

preferences = await reddit.user.preferences()
print(preferences["show_link_flair"])

See https://www.reddit.com/dev/api#GET_api_v1_me_prefs for the list of possible values.

__init__(reddit: asyncpraw.Reddit)

Initialize a Preferences instance.

Parameters

reddit – The Reddit instance.

await update(**preferences: Union[bool, int, str])

Modify the specified settings.

Parameters
  • accept_pms – Who can send you personal messages (one of "everyone" or "whitelisted").

  • activity_relevant_ads – Allow Reddit to use your activity on Reddit to show you more relevant advertisements.

  • allow_clicktracking – Allow Reddit to log my outbound clicks for personalization.

  • beta – I would like to beta test features for Reddit.

  • clickgadget – Show me links I’ve recently viewed.

  • collapse_read_messages – Collapse messages after I’ve read them.

  • compress – Compress the link display.

  • creddit_autorenew – Use a creddit to automatically renew my gold if it expires.

  • default_comment_sort – Default comment sort (one of "confidence", "top", "new", "controversial", "old", "random", "qa", or "live").

  • domain_details (bool) – Show additional details in the domain text when available, such as the source subreddit or the content author’s url/name.

  • email_chat_request (bool) – Send chat requests as emails.

  • email_comment_reply (bool) – Send comment replies as emails.

  • email_digests (bool) – Send email digests.

  • email_messages (bool) – Send messages as emails.

  • email_post_reply (bool) – Send post replies as emails.

  • email_private_message (bool) – Send private messages as emails.

  • email_unsubscribe_all (bool) – Unsubscribe from all emails.

  • email_upvote_comment (bool) – Send comment upvote updates as emails.

  • email_upvote_post (bool) – Send post upvote updates as emails.

  • email_user_new_follower (bool) – Send new follower alerts as emails.

  • email_username_mention (bool) – Send username mentions as emails.

  • enable_default_themes (bool) – Use Reddit theme.

  • feed_recommendations_enabled (bool) – Enable feed recommendations.

  • geopopular (str) – Location (one of "GLOBAL", "AR", "AU", "BG", "CA", "CL", "CO", "CZ", "FI", "GB", "GR", "HR", "HU", "IE", "IN", "IS", "JP", "MX", "MY", "NZ", "PH", "PL", "PR", "PT", "RO", "RS", "SE", "SG", "TH", "TR", "TW", "US", "US_AK", "US_AL", "US_AR", "US_AZ", "US_CA", "US_CO", "US_CT", "US_DC", "US_DE", "US_FL", "US_GA", "US_HI", "US_IA", "US_ID", "US_IL", "US_IN", "US_KS", "US_KY", "US_LA", "US_MA", "US_MD", "US_ME", "US_MI", "US_MN", "US_MO", "US_MS", "US_MT", "US_NC", "US_ND", "US_NE", "US_NH", "US_NJ", "US_NM", "US_NV", "US_NY", "US_OH", "US_OK", "US_OR", "US_PA", "US_RI", "US_SC", "US_SD", "US_TN", "US_TX", "US_UT", "US_VA", "US_VT", "US_WA", "US_WI", "US_WV", or "US_WY").

  • hide_ads (bool) – Hide ads.

  • hide_downs (bool) – Don’t show me submissions after I’ve downvoted them, except my own.

  • hide_from_robots (bool) – Don’t allow search engines to index my user profile.

  • hide_ups (bool) – Don’t show me submissions after I’ve upvoted them, except my own.

  • highlight_controversial (bool) – Show a dagger on comments voted controversial.

  • highlight_new_comments (bool) – Highlight new comments.

  • ignore_suggested_sort (bool) – Ignore suggested sorts.

  • in_redesign_beta (bool) – In redesign beta.

  • label_nsfw (bool) – Label posts that are not safe for work.

  • lang (str) – Interface language (IETF language tag, underscore separated).

  • legacy_search (bool) – Show legacy search page.

  • live_orangereds (bool) – Send message notifications in my browser.

  • mark_messages_read (bool) – Mark messages as read when I open my inbox.

  • media (str) – Thumbnail preference (one of "on", "off", or "subreddit").

  • media_preview (str) – Media preview preference (one of "on", "off", or "subreddit").

  • min_comment_score (int) – Don’t show me comments with a score less than this number (between -100 and 100).

  • min_link_score (int) – Don’t show me submissions with a score less than this number (between -100 and 100).

  • monitor_mentions (bool) – Notify me when people say my username.

  • newwindow (bool) – Open links in a new window.

  • nightmode (bool) – Enable night mode.

  • no_profanity (bool) – Don’t show thumbnails or media previews for anything labeled NSFW.

  • num_comments (int) – Display this many comments by default (between 1 and 500).

  • numsites (int) – Number of links to display at once (between 1 and 100).

  • organic (bool) – Show the spotlight box on the home feed.

  • other_theme (str) – Subreddit theme to use (subreddit name).

  • over_18 (bool) – I am over eighteen years old and willing to view adult content.

  • private_feeds (bool) – Enable private RSS feeds.

  • profile_opt_out (bool) – View user profiles on desktop using legacy mode.

  • public_votes (bool) – Make my votes public.

  • research (bool) – Allow my data to be used for research purposes.

  • search_include_over_18 (bool) – Include not safe for work (NSFW) search results in searches.

  • send_crosspost_messages (bool) – Send crosspost messages.

  • send_welcome_messages (bool) – Send welcome messages.

  • show_flair (bool) – Show user flair.

  • show_gold_expiration (bool) – Show how much gold you have remaining on your userpage.

  • show_link_flair (bool) – Show link flair.

  • show_location_based_recommendations (bool) – Show location based recommendations.

  • show_presence (bool) – Show presence.

  • show_promote (bool) – Show promote.

  • show_stylesheets (bool) – Allow subreddits to show me custom themes.

  • show_trending (bool) – Show trending subreddits on the home feed.

  • show_twitter (bool) – Show a link to your Twitter account on your profile.

  • store_visits (bool) – Store visits.

  • theme_selector (bool) – Theme selector (subreddit name).

  • third_party_data_personalized_ads (bool) – Allow Reddit to use data provided by third-parties to show you more relevant advertisements on Reddit.

  • third_party_personalized_ads (bool) – Allow personalization of advertisements.

  • third_party_site_data_personalized_ads (bool) – Allow personalization of advertisements using third-party website data.

  • third_party_site_data_personalized_content (bool) – Allow personalization of content using third-party website data.

  • threaded_messages (bool) – Show message conversations in the inbox.

  • threaded_modmail (bool) – Enable threaded modmail display.

  • top_karma_subreddits (bool) – Top karma subreddits.

  • use_global_defaults (bool) – Use global defaults.

  • video_autoplay (bool) – Autoplay Reddit videos on the desktop comments page.

Additional keyword arguments can be provided to handle new settings as Reddit introduces them.

See https://www.reddit.com/dev/api#PATCH_api_v1_me_prefs for the most up-to-date list of possible parameters.

This is intended to be used like so:

await reddit.user.preferences.update(show_link_flair=True)

This method returns the new state of the preferences as a dict, which can be used to check whether a change went through.

original_preferences = await reddit.user.preferences()
new_preferences = await original_preferences.update(invalid_param=123)
print(original_preferences == new_preferences)  # True, no change

Warning

Passing an unknown parameter name or an illegal value (such as an int when a boolean is expected) does not result in an error from the Reddit API. As a consequence, any invalid input will fail silently. To verify that changes have been made, use the return value of this method, which is a dict of the preferences after the update action has been performed.

Some preferences have names that are not valid keyword arguments in Python. To update these, construct a dict and use ** to unpack it as keyword arguments:

await reddit.user.preferences.update(**{"third_party_data_personalized_ads": False})

RedditBase

class asyncpraw.models.reddit.base.RedditBase(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]], _extra_attribute_to_check: Optional[str] = None, _fetched: bool = False, _str_field: bool = True)

Base class that represents actual Reddit objects.

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]], _extra_attribute_to_check: Optional[str] = None, _fetched: bool = False, _str_field: bool = True)

Initialize a RedditBase instance.

Parameters

reddit – An instance of Reddit.

await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

RedditorList

class asyncpraw.models.RedditorList(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

A list of Redditor objects. Works just like a regular list.

__contains__(item: Any) bool

Test if item exists in the list.

__getitem__(index: int) Any

Return the item at position index in the list.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a BaseList instance.

Parameters

reddit – An instance of Reddit.

__iter__() Iterator[Any]

Return an iterator to the list.

__len__() int

Return the number of items in the list.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

RedditorStream

class asyncpraw.models.reddit.redditor.RedditorStream(redditor: asyncpraw.models.Redditor)

Provides submission and comment streams.

__init__(redditor: asyncpraw.models.Redditor)

Initialize a RedditorStream instance.

Parameters

redditor – The redditor associated with the streams.

comments(**stream_options: Union[str, int, Dict[str, str]]) AsyncGenerator[asyncpraw.models.Comment, None]

Yield new comments as they become available.

Comments are yielded oldest first. Up to 100 historical comments will initially be returned.

Keyword arguments are passed to stream_generator().

For example, to retrieve all new comments made by redditor u/spez, try:

redditor = await reddit.redditor("spez")
async for comment in redditor.stream.comments():
    print(comment)
submissions(**stream_options: Union[str, int, Dict[str, str]]) AsyncGenerator[asyncpraw.models.Submission, None]

Yield new submissions as they become available.

Submissions are yielded oldest first. Up to 100 historical submissions will initially be returned.

Keyword arguments are passed to stream_generator().

For example, to retrieve all new submissions made by redditor u/spez, try:

redditor = await reddit.redditor("spez")
async for submission in redditor.stream.submissions():
    print(submission)

RemovalReason

class asyncpraw.models.reddit.removal_reasons.RemovalReason(reddit: asyncpraw.Reddit, subreddit: asyncpraw.models.Subreddit, id: Optional[str] = None, reason_id: Optional[str] = None, _data: Optional[Dict[str, Any]] = None)

An individual Removal Reason object.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

id

The ID of the removal reason.

message

The message of the removal reason.

title

The title of the removal reason.

__init__(reddit: asyncpraw.Reddit, subreddit: asyncpraw.models.Subreddit, id: Optional[str] = None, reason_id: Optional[str] = None, _data: Optional[Dict[str, Any]] = None)

Initialize a RemovalReason instance.

Parameters
  • reddit – An instance of Reddit.

  • subreddit – An instance of Subreddit.

  • id – The ID of the removal reason.

  • reason_id – The original name of the id parameter. Used for backwards compatibility. This parameter should not be used.

await delete()

Delete a removal reason from this subreddit.

To delete "141vv5c16py7d" from r/test try:

subreddit = await reddit.subreddit("test")
reason = await subreddit.mod.removal_reasons.get_reason("141vv5c16py7d")
await reason.delete()
await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

await update(*, message: Optional[str] = None, title: Optional[str] = None)

Update the removal reason from this subreddit.

Note

Existing values will be used for any unspecified arguments.

Parameters
  • message – The removal reason’s new message.

  • title – The removal reason’s new title.

To update "141vv5c16py7d" from r/test try:

subreddit = await reddit.subreddit("test")
reason = await subreddit.mod.removal_reasons.get_reason("141vv5c16py7d")
await reason.update(title="New title", message="New message")

Rule

class asyncpraw.models.Rule(reddit: asyncpraw.Reddit, subreddit: Optional[asyncpraw.models.Subreddit] = None, short_name: Optional[str] = None, _data: Optional[Dict[str, str]] = None)

An individual Rule object.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

created_utc

Time the rule was created, represented in Unix Time.

description

The description of the rule, if provided, otherwise a blank string.

kind

The kind of rule. Can be "link", comment", or "all".

priority

Represents where the rule is ranked. For example, the first rule is at priority 0. Serves as an index number on the list of rules.

short_name

The name of the rule.

violation_reason

The reason that is displayed on the report menu for the rule.

__init__(reddit: asyncpraw.Reddit, subreddit: Optional[asyncpraw.models.Subreddit] = None, short_name: Optional[str] = None, _data: Optional[Dict[str, str]] = None)

Initialize a Rule instance.

await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
mod() asyncpraw.models.reddit.rules.RuleModeration

Contain methods used to moderate rules.

To delete "No spam" from r/test try:

subreddit = await reddit.subreddit("test")
rule = await subreddit.rules.get_rule("No Spam")
await rule.mod.delete()

To update "No spam" from r/test try:

subreddit = await reddit.subreddit("test")
await subreddit.rules.get_rule("No spam")
await rule.mod.update(description="Don't do this!", violation_reason="Spam post")
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

Stylesheet

class asyncpraw.models.Stylesheet(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Represent a stylesheet.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

images

A list of images used by the stylesheet.

stylesheet

The contents of the stylesheet, as CSS.

__init__(reddit: asyncpraw.Reddit, _data: Optional[Dict[str, Any]])

Initialize a AsyncPRAWBase instance.

Parameters

reddit – An instance of Reddit.

classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

SubListing

class asyncpraw.models.listing.mixins.redditor.SubListing(reddit: asyncpraw.Reddit, base_path: str, subpath: str)

Helper class for generating ListingGenerator objects.

__init__(reddit: asyncpraw.Reddit, base_path: str, subpath: str)

Initialize a SubListing instance.

Parameters
  • reddit – An instance of Reddit.

  • base_path – The path to the object up to this point.

  • subpath – The additional path to this sublisting.

controversial(*, time_filter: str = 'all', **generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for controversial items.

Parameters

time_filter – Can be one of: "all", "day", "hour", "month", "week", or "year" (default: "all").

Raises

ValueError if time_filter is invalid.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").controversial(time_filter="week")

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.controversial(time_filter="day")

redditor = await reddit.redditor("spez")
redditor.controversial(time_filter="month")

redditor = await reddit.redditor("spez")
redditor.comments.controversial(time_filter="year")

redditor = await reddit.redditor("spez")
redditor.submissions.controversial(time_filter="all")

subreddit = await reddit.subreddit("all")
subreddit.controversial(time_filter="hour")
hot(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for hot items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").hot()

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.hot()

redditor = await reddit.redditor("spez")
redditor.hot()

redditor = await reddit.redditor("spez")
redditor.comments.hot()

redditor = await reddit.redditor("spez")
redditor.submissions.hot()

subreddit = await reddit.subreddit("all")
subreddit.hot()
new(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for new items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").new()

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.new()

redditor = await reddit.redditor("spez")
redditor.new()

redditor = await reddit.redditor("spez")
redditor.comments.new()

redditor = await reddit.redditor("spez")
redditor.submissions.new()

subreddit = await reddit.subreddit("all")
subreddit.new()
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

top(*, time_filter: str = 'all', **generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for top items.

Parameters

time_filter – Can be one of: "all", "day", "hour", "month", "week", or "year "``(default: ``"all").

Raises

ValueError if time_filter is invalid.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").top(time_filter="week")

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.top(time_filter="day")

redditor = await reddit.redditor("spez")
redditor.top(time_filter="month")

redditor = await reddit.redditor("spez")
redditor.comments.top(time_filter="year")

redditor = await reddit.redditor("spez")
redditor.submissions.top(time_filter="all")

subreddit = await reddit.subreddit("all")
subreddit.top(time_filter="hour")

SubredditMessage

class asyncpraw.models.SubredditMessage(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

A class for messages to a subreddit.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

author

Provides an instance of Redditor.

body

The body of the message, as Markdown.

body_html

The body of the message, as HTML.

created_utc

Time the message was created, represented in Unix Time.

dest

Provides an instance of Redditor. The recipient of the message.

id

The ID of the message.

name

The full ID of the message, prefixed with t4_.

subject

The subject of the message.

subreddit

If the message was sent from a subreddit, provides an instance of Subreddit.

was_comment

Whether or not the message was a comment reply.

__init__(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Initialize a Message instance.

await block()

Block the user who sent the item.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

comment = await reddit.comment("dkk4qjd")
await comment.block()

# or, identically:
comment = await reddit.comment("dkk4qjd")
await comment.author.block()
await collapse()

Mark the item as collapsed.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

inbox = reddit.inbox()

# select first inbox item and collapse it
async for message in inbox:
    await message.collapse()
    break

See also

uncollapse()

await delete()

Delete the message.

Note

Reddit does not return an indication of whether or not the message was successfully deleted.

For example, to delete the most recent message in your inbox:

async for message in reddit.inbox.all():
    await message.delete()
    break
property fullname: str

Return the object’s fullname.

A fullname is an object’s kind mapping like t3 followed by an underscore and the object’s base36 ID, e.g., t1_c5s96e0.

await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
await mark_read()

Mark a single inbox item as read.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

inbox = reddit.inbox.unread()

async for message in inbox:
    # process unread messages
    ...

See also

mark_unread()

To mark the whole inbox as read with a single network request, use Inbox.mark_all_read()

await mark_unread()

Mark the item as unread.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

inbox = reddit.inbox(limit=10)

async for message in inbox:
    # process messages
    ...

See also

mark_read()

await mute()

Mute the sender of this SubredditMessage.

For example, to mute the sender of the first SubredditMessage in the authenticated users’ inbox:

from asyncpraw.models import SubredditMessage

async for message in reddit.inbox.all():
    if isinstance(message, SubredditMessage):
        await msg.mute()
        break
property parent: Optional[asyncpraw.models.Message]

Return the parent of the message if it exists.

Note

If the message is from an inbox listing, the returned parent will be lazy and must be fetched manually. For example:

async for message in reddit.inbox.all(limit=1):
    parent = message.parent
    await parent.load()
    print(parent.body)
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit)

Return an instance of Message or SubredditMessage from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

await reply(body: str) Optional[Union[asyncpraw.models.Comment, asyncpraw.models.Message]]

Reply to the object.

Parameters

body – The Markdown formatted content for a comment.

Returns

A Comment or Message object for the newly created comment or message or None if Reddit doesn’t provide one.

Raises

asyncprawcore.exceptions.Forbidden when attempting to reply to some items, such as locked submissions/comments or non-replyable messages.

A None value can be returned if the target is a comment or submission in a quarantined subreddit and the authenticated user has not opt-ed in to viewing the content. When this happens the comment will be successfully created on Reddit and can be retried by drawing the comment from the user’s comment history.

Example usage:

submission = await reddit.submission("5or86n", fetch=False)
await submission.reply("reply")

comment = await reddit.comment("dxolpyc", fetch=False)
await comment.reply("reply")
await unblock_subreddit()

Unblock a subreddit.

Note

This method pertains only to objects which were retrieved via the inbox.

For example, to unblock all blocked subreddits that you can find by going through your inbox:

from asyncpraw.models import SubredditMessage

subs = set()
async for item in reddit.inbox.messages(limit=None):
    if isinstance(item, SubredditMessage):
        if (
            item.subject == "[message from blocked subreddit]"
            and str(item.subreddit) not in subs
        ):
            item.unblock_subreddit()
            subs.add(str(item.subreddit))
await uncollapse()

Mark the item as uncollapsed.

Note

This method pertains only to objects which were retrieved via the inbox.

Example usage:

inbox = reddit.inbox()

# select first inbox item and uncollapse it
async for message in inbox:
    await message.uncollapse()
    break

See also

collapse()

await unmute()

Unmute the sender of this SubredditMessage.

For example, to unmute the sender of the first SubredditMessage in the authenticated users’ inbox:

from asyncpraw.models import SubredditMessage

async for message in reddit.inbox.all():
    if isinstance(message, SubredditMessage):
        await msg.unmute()
        break

Token Manager

Token Manager classes.

There should be a 1-to-1 mapping between an instance of a subclass of BaseTokenManager and a Reddit instance.

A few proof of concept token manager classes are provided here, but it is expected that Async PRAW users will create their own token manager classes suitable for their needs.

Deprecated since version 7.4.0: Tokens managers have been deprecated and will be removed in the near future.

class asyncpraw.util.token_manager.BaseTokenManager

An abstract class for all token managers.

__init__()

Initialize a BaseTokenManager instance.

abstractmethod post_refresh_callback(authorizer)

Handle callback that is invoked after a refresh token is used.

Parameters

authorizer – The asyncprawcore.Authorizer instance used containing access_token and refresh_token attributes.

This function will be called after refreshing the access and refresh tokens. This callback can be used for saving the updated refresh_token.

abstractmethod pre_refresh_callback(authorizer)

Handle callback that is invoked before refreshing PRAW’s authorization.

Parameters

authorizer – The asyncprawcore.Authorizer instance used containing access_token and refresh_token attributes.

This callback can be used to inspect and modify the attributes of the asyncprawcore.Authorizer instance, such as setting the refresh_token.

property reddit

Return the Reddit instance bound to the token manager.

class asyncpraw.util.token_manager.FileTokenManager(filename)

Provides a single-file based token manager.

It is expected that the file with the initial refresh_token is created prior to use.

Warning

The same file should not be used by more than one instance of this class concurrently. Doing so may result in data corruption. Consider using SQLiteTokenManager if you want more than one instance of PRAW to concurrently manage a specific refresh_token chain.

__init__(filename)

Initialize a FileTokenManager instance.

Parameters

filename – The file the contains the refresh token.

await post_refresh_callback(authorizer)

Update the saved copy of the refresh token.

await pre_refresh_callback(authorizer)

Load the refresh token from the file.

property reddit

Return the Reddit instance bound to the token manager.

class asyncpraw.util.token_manager.SQLiteTokenManager(*, database, key)

Provides a SQLite3 based token manager.

Unlike, FileTokenManager, the initial database need not be created ahead of time, as it’ll automatically be created on first use. However, initial refresh tokens will need to be registered via register() prior to use.

Warning

This class is untested on Windows because we encountered file locking issues in the test environment.

__init__(*, database, key)

Initialize a SQLiteTokenManager instance.

Parameters
  • database – The path to the SQLite database.

  • key – The key used to locate the refresh token. This key can be anything. You might use the client_id if you expect to have unique a refresh token for each client_id, or you might use a redditor’s username if you’re managing multiple users’ authentications.

await close()

Close the sqlite3 connection.

async for ... in connection()

Asynchronously setup and provide the sqlite3 connection.

await is_registered()

Return whether key already has a refresh_token.

await post_refresh_callback(authorizer)

Update the refresh token in the database.

await pre_refresh_callback(authorizer)

Load the refresh token from the database.

property reddit

Return the Reddit instance bound to the token manager.

await register(refresh_token)

Register the initial refresh token in the database.

Returns

True if refresh_token is saved to the database, otherwise, False if there is already a refresh_token for the associated key.

Trophy

class asyncpraw.models.Trophy(reddit: asyncpraw.Reddit, _data: Dict[str, Any])

Represent a trophy.

End users should not instantiate this class directly. Redditor.trophies() can be used to get a list of the redditor’s trophies.

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

award_id

The ID of the trophy (sometimes None).

description

The description of the trophy (sometimes None).

icon_40

The URL of a 41x41 px icon for the trophy.

icon_70

The URL of a 71x71 px icon for the trophy.

name

The name of the trophy.

url

A relevant URL (sometimes None).

__str__() str

Return a name of the trophy.

UserSubreddit

class asyncpraw.models.UserSubreddit(reddit: asyncpraw.Reddit, *args, **kwargs)

A class for User Subreddits.

To obtain an instance of this class execute:

subreddit = (await reddit.user.me()).subreddit

Typical Attributes

Note

This table describes attributes that typically belong to objects of this class. Async PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, Async PRAW makes no effort to document any new/removed/changed attributes, other than to instruct you on how to discover what is available. As a result, this table of attributes may not be complete. See Determine Available Attributes of an Object for detailed information.

If you would like to add an attribute to this table, feel free to open a pull request.

Attribute

Description

can_assign_link_flair

Whether users can assign their own link flair.

can_assign_user_flair

Whether users can assign their own user flair.

created_utc

Time the subreddit was created, represented in Unix Time.

description

Subreddit description, in Markdown.

description_html

Subreddit description, in HTML.

display_name

Name of the subreddit.

icon_img

The URL of the subreddit icon image.

id

ID of the subreddit.

name

Fullname of the subreddit.

over18

Whether the subreddit is NSFW.

public_description

Description of the subreddit, shown in searches and on the “You must be invited to visit this community” page (if applicable).

spoilers_enabled

Whether the spoiler tag feature is enabled.

subscribers

Count of subscribers. This will be 0 unless unless the authenticated user is a moderator.

user_is_banned

Whether the authenticated user is banned.

user_is_moderator

Whether the authenticated user is a moderator.

user_is_subscriber

Whether the authenticated user is subscribed.

__getitem__(item)

Show deprecation notice for dict method __getitem__.

__init__(reddit: asyncpraw.Reddit, *args, **kwargs)

Initialize an UserSubreddit instance.

Parameters

reddit – An instance of Reddit.

Note

This class should not be initialized directly. Instead, obtain an instance via:

user = await reddit.user.me()
user.subreddit

# or

redditor = await reddit.redditor("redditor_name")
redditor.subreddit
banned() asyncpraw.models.reddit.subreddit.SubredditRelationship

Provide an instance of SubredditRelationship.

For example, to ban a user try:

subreddit = await reddit.subreddit("test")
await subreddit.banned.add("spez", ban_reason="...")

To list the banned users along with any notes, try:

subreddit = await reddit.subreddit("test")
async for ban in subreddit.banned():
    print(f"{ban}: {ban.note}")
collections() asyncpraw.models.reddit.collections.SubredditCollections

Provide an instance of SubredditCollections.

To see the permalinks of all Collections that belong to a subreddit, try:

subreddit = await reddit.subreddit("test")
async for collection in subreddit.collections:
    print(collection.permalink)

To get a specific Collection by its UUID or permalink, use one of the following:

subreddit = await reddit.subreddit("test")

collection = subreddit.collections("some_uuid")
collection = subreddit.collections(
    permalink="https://reddit.com/r/test/collection/some_uuid"
)
comments() CommentHelper

Provide an instance of CommentHelper.

For example, to output the author of the 25 most recent comments of r/test execute:

subreddit = await reddit.subreddit("test")
async for comment in subreddit.comments(limit=25):
    print(comment.author)
contributor() asyncpraw.models.reddit.subreddit.ContributorRelationship

Provide an instance of ContributorRelationship.

Contributors are also known as approved submitters.

To add a contributor try:

subreddit = await reddit.subreddit("test")
await subreddit.contributor.add("spez")
controversial(*, time_filter: str = 'all', **generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for controversial items.

Parameters

time_filter – Can be one of: "all", "day", "hour", "month", "week", or "year" (default: "all").

Raises

ValueError if time_filter is invalid.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").controversial(time_filter="week")

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.controversial(time_filter="day")

redditor = await reddit.redditor("spez")
redditor.controversial(time_filter="month")

redditor = await reddit.redditor("spez")
redditor.comments.controversial(time_filter="year")

redditor = await reddit.redditor("spez")
redditor.submissions.controversial(time_filter="all")

subreddit = await reddit.subreddit("all")
subreddit.controversial(time_filter="hour")
emoji() SubredditEmoji

Provide an instance of SubredditEmoji.

This attribute can be used to discover all emoji for a subreddit:

subreddit = await reddit.subreddit("test")
async for emoji in subreddit.emoji:
    print(emoji)

A single emoji can be lazily retrieved via:

subreddit = await reddit.subreddit("test")
emoji = await subreddit.emoji.get_emoji("emoji_name")

Note

Attempting to access attributes of a nonexistent emoji will result in a ClientException.

filters() asyncpraw.models.reddit.subreddit.SubredditFilters

Provide an instance of SubredditFilters.

For example, to add a filter, run:

subreddit = await reddit.subreddit("all")
await subreddit.filters.add("test")
flair() asyncpraw.models.reddit.subreddit.SubredditFlair

Provide an instance of SubredditFlair.

Use this attribute for interacting with a Subreddit’s flair. For example, to list all the flair for a subreddit which you have the flair moderator permission on try:

subreddit = await reddit.subreddit("test")
async for flair in subreddit.flair():
    print(flair)

Flair templates can be interacted with through this attribute via:

subreddit = await reddit.subreddit("test")
async for template in subreddit.flair.templates:
    print(template)
property fullname: str

Return the object’s fullname.

A fullname is an object’s kind mapping like t3 followed by an underscore and the object’s base36 ID, e.g., t1_c5s96e0.

gilded(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for gilded items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get gilded items in r/test:

subreddit = await reddit.subreddit("test")
async for item in subreddit.gilded():
    print(item.id)
hot(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for hot items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").hot()

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.hot()

redditor = await reddit.redditor("spez")
redditor.hot()

redditor = await reddit.redditor("spez")
redditor.comments.hot()

redditor = await reddit.redditor("spez")
redditor.submissions.hot()

subreddit = await reddit.subreddit("all")
subreddit.hot()
await load()

Re-fetches the object.

This is used to explicitly fetch or re-fetch the object from reddit. This method can be used on any RedditBase object.

await reddit_base_object.load()
await message(*, from_subreddit: Optional[Union[asyncpraw.models.Subreddit, str]] = None, message: str, subject: str)

Send a message to a Redditor or a Subreddit’s moderators (modmail).

Parameters
  • from_subreddit

    A Subreddit instance or string to send the message from. When provided, messages are sent from the subreddit rather than from the authenticated user.

    Note

    The authenticated user must be a moderator of the subreddit and have the mail moderator permission.

  • message – The message content.

  • subject – The subject of the message.

For example, to send a private message to u/spez, try:

redditor = await reddit.redditor("spez", fetch=False)
await redditor.message(subject="TEST", message="test message from Async PRAW")

To send a message to u/spez from the moderators of r/test try:

redditor = await reddit.redditor("spez", fetch=False)
await redditor.message(
    subject="TEST", message="test message from r/test", from_subreddit="test"
)

To send a message to the moderators of r/test, try:

subreddit = await reddit.subreddit("test")
await subreddit.message(subject="TEST", message="test PM from Async PRAW")
mod() asyncpraw.models.reddit.user_subreddit.UserSubredditModeration

Provide an instance of UserSubredditModeration.

For example, to update the authenticated user’s display name:

user = await reddit.user.me()
await user.subreddit.mod.update(title="New display name")
moderator() asyncpraw.models.reddit.subreddit.ModeratorRelationship

Provide an instance of ModeratorRelationship.

For example, to add a moderator try:

subreddit = await reddit.subreddit("test")
await subreddit.moderator.add("spez")

To list the moderators along with their permissions try:

subreddit = await reddit.subreddit("test")
async for moderator in subreddit.moderator:
    print(f"{moderator}: {moderator.mod_permissions}")
modmail() asyncpraw.models.reddit.subreddit.Modmail

Provide an instance of Modmail.

For example, to send a new modmail from r/test to u/spez with the subject "test" along with a message body of "hello":

subreddit = await reddit.subreddit("test")
await subreddit.modmail.create(subject="test", body="hello", recipient="spez")
muted() asyncpraw.models.reddit.subreddit.SubredditRelationship

Provide an instance of SubredditRelationship.

For example, muted users can be iterated through like so:

subreddit = await reddit.subreddit("test")
async for mute in subreddit.muted():
    print("{mute}: {mute.note}")
new(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for new items.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").new()

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.new()

redditor = await reddit.redditor("spez")
redditor.new()

redditor = await reddit.redditor("spez")
redditor.comments.new()

redditor = await reddit.redditor("spez")
redditor.submissions.new()

subreddit = await reddit.subreddit("all")
subreddit.new()
classmethod parse(data: Dict[str, Any], reddit: asyncpraw.Reddit) Any

Return an instance of cls from data.

Parameters
  • data – The structured data.

  • reddit – An instance of Reddit.

await post_requirements() Dict[str, Union[str, int, bool]]

Get the post requirements for a subreddit.

Returns

A dict with the various requirements.

The returned dict contains the following keys:

  • domain_blacklist

  • body_restriction_policy

  • domain_whitelist

  • title_regexes

  • body_blacklisted_strings

  • body_required_strings

  • title_text_min_length

  • is_flair_required

  • title_text_max_length

  • body_regexes

  • link_repost_age

  • body_text_min_length

  • link_restriction_policy

  • body_text_max_length

  • title_required_strings

  • title_blacklisted_strings

  • guidelines_text

  • guidelines_display_policy

For example, to fetch the post requirements for r/test:

subreddit = await reddit.subreddit("test")
post_requirements = await subreddit.post_requirements
print(post_requirements)
quaran() asyncpraw.models.reddit.subreddit.SubredditQuarantine

Provide an instance of SubredditQuarantine.

This property is named quaran because quarantine is a subreddit attribute returned by Reddit to indicate whether or not a subreddit is quarantined.

To opt-in into a quarantined subreddit:

subreddit = await reddit.subreddit("test")
await subreddit.quaran.opt_in()
await random() Optional[asyncpraw.models.Submission]

Return a random Submission.

Returns None on subreddits that do not support the random feature. One example, at the time of writing, is r/wallpapers.

For example, to get a random submission off of r/AskReddit:

subreddit = await reddit.subreddit("AskReddit")
submission = await subreddit.random()
print(submission.title)
random_rising(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Submission]

Return a ListingGenerator for random rising submissions.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get random rising submissions for r/test:

subreddit = await reddit.subreddit("test")
async for submission in subreddit.random_rising():
    print(submission.title)
rising(**generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[asyncpraw.models.Submission]

Return a ListingGenerator for rising submissions.

Additional keyword arguments are passed in the initialization of ListingGenerator.

For example, to get rising submissions for r/test:

subreddit = await reddit.subreddit("test")
async for submission in subreddit.rising():
    print(submission.title)
rules() SubredditRules

Provide an instance of SubredditRules.

Use this attribute for interacting with a Subreddit’s rules.

For example, to list all the rules for a subreddit:

subreddit = await reddit.subreddit("test")
async for rule in subreddit.rules:
    print(rule)

Moderators can also add rules to the subreddit. For example, to make a rule called "No spam" in r/test:

subreddit = await reddit.subreddit("test")
await subreddit.rules.mod.add(
    short_name="No spam", kind="all", description="Do not spam. Spam bad"
)
search(query: str, *, sort: str = 'relevance', syntax: str = 'lucene', time_filter: str = 'all', **generator_kwargs: Any) AsyncIterator[asyncpraw.models.Submission]

Return a ListingGenerator for items that match query.

Parameters
  • query – The query string to search for.

  • sort – Can be one of: "relevance", "hot", "top", "new", or "comments". (default: "relevance").

  • syntax – Can be one of: "cloudsearch", "lucene", or "plain" (default: "lucene").

  • time_filter – Can be one of: "all", "day", "hour", "month", "week", or "year" (default: "all").

For more information on building a search query see: https://www.reddit.com/wiki/search

For example, to search all subreddits for "praw" try:

subreddit = await reddit.subreddit("all")
async for submission in subreddit.search("praw"):
    print(submission.title)
await sticky(*, number: int = 1) asyncpraw.models.Submission

Return a Submission object for a sticky of the subreddit.

Parameters

number – Specify which sticky to return. 1 appears at the top (default: 1).

Raises

asyncprawcore.NotFound if the sticky does not exist.

For example, to get the stickied post on r/test:

subreddit = await reddit.subreddit("test")
await subreddit.sticky()
stream() asyncpraw.models.reddit.subreddit.SubredditStream

Provide an instance of SubredditStream.

Streams can be used to indefinitely retrieve new comments made to a subreddit, like:

subreddit = await reddit.subreddit("test")
async for comment in subreddit.stream.comments():
    print(comment)

Additionally, new submissions can be retrieved via the stream. In the following example all submissions are fetched via the special r/all:

subreddit = await reddit.subreddit("all")
async for submission in subreddit.stream.submissions():
    print(submission)
stylesheet() asyncpraw.models.reddit.subreddit.SubredditStylesheet

Provide an instance of SubredditStylesheet.

For example, to add the css data .test{color:blue} to the existing stylesheet:

subreddit = await reddit.subreddit("test")
stylesheet = await subreddit.stylesheet()
stylesheet.stylesheet += ".test{color:blue}"
await subreddit.stylesheet.update(stylesheet.stylesheet)
await submit(title: str, *, collection_id: Optional[str] = None, discussion_type: Optional[str] = None, draft_id: Optional[str] = None, flair_id: Optional[str] = None, flair_text: Optional[str] = None, inline_media: Optional[Dict[str, asyncpraw.models.InlineMedia]] = None, nsfw: bool = False, resubmit: bool = True, selftext: Optional[str] = None, send_replies: bool = True, spoiler: bool = False, url: Optional[str] = None) asyncpraw.models.Submission

Add a submission to the Subreddit.

Parameters
  • title – The title of the submission.

  • collection_id – The UUID of a Collection to add the newly-submitted post to.

  • discussion_type – Set to "CHAT" to enable live discussion instead of traditional comments (default: None).

  • draft_id – The ID of a draft to submit.

  • flair_id – The flair template to select (default: None).

  • flair_text – If the template’s flair_text_editable value is True, this value will set a custom text (default: None). flair_id is required when flair_text is provided.

  • inline_media – A dict of InlineMedia objects where the key is the placeholder name in selftext.

  • nsfw – Whether the submission should be marked NSFW (default: False).

  • resubmit – When False, an error will occur if the URL has already been submitted (default: True).

  • selftext – The Markdown formatted content for a text submission. Use an empty string, "", to make a title-only submission.

  • send_replies – When True, messages will be sent to the submission author when comments are made to the submission (default: True).

  • spoiler – Whether the submission should be marked as a spoiler (default: False).

  • url – The URL for a link submission.

Returns

A Submission object for the newly created submission.

Either selftext or url can be provided, but not both.

For example, to submit a URL to r/test do:

title = "Async PRAW documentation"
url = "https://asyncpraw.readthedocs.io"
subreddit = await reddit.subreddit("test")
await subreddit.submit(title, url=url)

For example, to submit a self post with inline media do:

from asyncpraw.models import InlineGif, InlineImage, InlineVideo

gif = InlineGif(path="path/to/image.gif", caption="optional caption")
image = InlineImage(path="path/to/image.jpg", caption="optional caption")
video = InlineVideo(path="path/to/video.mp4", caption="optional caption")
selftext = "Text with a gif {gif1} an image {image1} and a video {video1} inline"
media = {"gif1": gif, "image1": image, "video1": video}
subreddit = await reddit.subreddit("test")
await subreddit.submit("title", inline_media=media, selftext=selftext)

Note

Inserted media will have a padding of \\n\\n automatically added. This is due to the weirdness with Reddit’s API. Using the example above the result selftext body will look like so:

Text with a gif

![gif](u1rchuphryq51 "optional caption")

an image

![img](srnr8tshryq51 "optional caption")

and video

![video](gmc7rvthryq51 "optional caption")

inline

Note

To submit a post to a subreddit with the "news" flair, you can get the flair id like this:

choices = [template async for template in subreddit.flair.link_templates.user_selectable()]
template_id = next(x for x in choices if x["flair_text"] == "news")["flair_template_id"]
await subreddit.submit("title", flair_id=template_id, url="https://www.news.com/")

See also

Add an image gallery submission to the subreddit.

Parameters
  • title – The title of the submission.

  • images – The images to post in dict with the following structure: {"image_path": "path", "caption": "caption", "outbound_url": "url"}, only image_path is required.

  • collection_id – The UUID of a Collection to add the newly-submitted post to.

  • discussion_type – Set to "CHAT" to enable live discussion instead of traditional comments (default: None).

  • flair_id – The flair template to select (default: None).

  • flair_text – If the template’s flair_text_editable value is True, this value will set a custom text (default: None). flair_id is required when flair_text is provided.

  • nsfw – Whether the submission should be marked NSFW (default: False).

  • send_replies – When True, messages will be sent to the submission author when comments are made to the submission (default: True).

  • spoiler – Whether the submission should be marked asa spoiler (default: False).

Returns

A Submission object for the newly created submission.

Raises

ClientException if image_path in images refers to a file that is not an image.

For example, to submit an image gallery to r/test do:

title = "My favorite pictures"
image = "/path/to/image.png"
image2 = "/path/to/image2.png"
image3 = "/path/to/image3.png"
images = [
    {"image_path": image},
    {
        "image_path": image2,
        "caption": "Image caption 2",
    },
    {
        "image_path": image3,
        "caption": "Image caption 3",
        "outbound_url": "https://example.com/link3",
    },
]
subreddit = await reddit.subreddit("test")
await subreddit.submit_gallery(title, images)

See also

await submit_image(title: str, image_path: str, *, collection_id: Optional[str] = None, discussion_type: Optional[str] = None, flair_id: Optional[str] = None, flair_text: Optional[str] = None, nsfw: bool = False, resubmit: bool = True, send_replies: bool = True, spoiler: bool = False, timeout: int = 10, without_websockets: bool = False)

Add an image submission to the subreddit.

Parameters
  • collection_id – The UUID of a Collection to add the newly-submitted post to.

  • discussion_type – Set to "CHAT" to enable live discussion instead of traditional comments (default: None).

  • flair_id – The flair template to select (default: None).

  • flair_text – If the template’s flair_text_editable value is True, this value will set a custom text (default: None). flair_id is required when flair_text is provided.

  • image_path – The path to an image, to upload and post.

  • nsfw – Whether the submission should be marked NSFW (default: False).

  • resubmit – When False, an error will occur if the URL has already been submitted (default: True).

  • send_replies – When True, messages will be sent to the submission author when comments are made to the submission (default: True).

  • spoiler – Whether the submission should be marked as a spoiler (default: False).

  • timeout – Specifies a particular timeout, in seconds. Use to avoid “Websocket error” exceptions (default: 10).

  • title – The title of the submission.

  • without_websockets – Set to True to disable use of WebSockets (see note below for an explanation). If True, this method doesn’t return anything (default: False).

Returns

A Submission object for the newly created submission, unless without_websockets is True.

Raises

ClientException if image_path refers to a file that is not an image.

Note

Reddit’s API uses WebSockets to respond with the link of the newly created post. If this fails, the method will raise WebSocketException. Occasionally, the Reddit post will still be created. More often, there is an error with the image file. If you frequently get exceptions but successfully created posts, try setting the timeout parameter to a value above 10.

To disable the use of WebSockets, set without_websockets=True. This will make the method return None, though the post will still be created. You may wish to do this if you are running your program in a restricted network environment, or using a proxy that doesn’t support WebSockets connections.

For example, to submit an image to r/test do:

title = "My favorite picture"
image = "/path/to/image.png"
subreddit = await reddit.subreddit("test")
await subreddit.submit_image(title, image)

See also

await submit_poll(title: str, *, collection_id: Optional[str] = None, discussion_type: Optional[str] = None, duration: int, flair_id: Optional[str] = None, flair_text: Optional[str] = None, nsfw: bool = False, options: List[str], resubmit: bool = True, selftext: str, send_replies: bool = True, spoiler: bool = False)

Add a poll submission to the subreddit.

Parameters
  • title – The title of the submission.

  • collection_id – The UUID of a Collection to add the newly-submitted post to.

  • discussion_type – Set to "CHAT" to enable live discussion instead of traditional comments (default: None).

  • duration – The number of days the poll should accept votes, as an int. Valid values are between 1 and 7, inclusive.

  • flair_id – The flair template to select (default: None).

  • flair_text – If the template’s flair_text_editable value is True, this value will set a custom text (default: None). flair_id is required when flair_text is provided.

  • nsfw – Whether the submission should be marked NSFW (default: False).

  • options – A list of two to six poll options as str.

  • resubmit – When False, an error will occur if the URL has already been submitted (default: True).

  • selftext – The Markdown formatted content for the submission. Use an empty string, "", to make a submission with no text contents.

  • send_replies – When True, messages will be sent to the submission author when comments are made to the submission (default: True).

  • spoiler – Whether the submission should be marked as a spoiler (default: False).

Returns

A Submission object for the newly created submission.

For example, to submit a poll to r/test do:

title = "Do you like Async PRAW?"
subreddit = await reddit.subreddit("test")
await subreddit.submit_poll(title, selftext="", options=["Yes", "No"], duration=3)

See also

await submit_video(title: str, video_path: str, *, collection_id: Optional[str] = None, discussion_type: Optional[str] = None, flair_id: Optional[str] = None, flair_text: Optional[str] = None, nsfw: bool = False, resubmit: bool = True, send_replies: bool = True, spoiler: bool = False, thumbnail_path: Optional[str] = None, timeout: int = 10, videogif: bool = False, without_websockets: bool = False)

Add a video or videogif submission to the subreddit.

Parameters
  • title – The title of the submission.

  • video_path – The path to a video, to upload and post.

  • collection_id – The UUID of a Collection to add the newly-submitted post to.

  • discussion_type – Set to "CHAT" to enable live discussion instead of traditional comments (default: None).

  • flair_id – The flair template to select (default: None).

  • flair_text – If the template’s flair_text_editable value is True, this value will set a custom text (default: None). flair_id is required when flair_text is provided.

  • nsfw – Whether the submission should be marked NSFW (default: False).

  • resubmit – When False, an error will occur if the URL has already been submitted (default: True).

  • send_replies – When True, messages will be sent to the submission author when comments are made to the submission (default: True).

  • spoiler – Whether the submission should be marked as a spoiler (default: False).

  • thumbnail_path – The path to an image, to be uploaded and used as the thumbnail for this video. If not provided, the PRAW logo will be used as the thumbnail.

  • timeout – Specifies a particular timeout, in seconds. Use to avoid “Websocket error” exceptions (default: 10).

  • videogif – If True, the video is uploaded as a videogif, which is essentially a silent video (default: False).

  • without_websockets – Set to True to disable use of WebSockets (see note below for an explanation). If True, this method doesn’t return anything (default: False).

Returns

A Submission object for the newly created submission, unless without_websockets is True.

Raises

ClientException if video_path refers to a file that is not a video.

Note

Reddit’s API uses WebSockets to respond with the link of the newly created post. If this fails, the method will raise WebSocketException. Occasionally, the Reddit post will still be created. More often, there is an error with the image file. If you frequently get exceptions but successfully created posts, try setting the timeout parameter to a value above 10.

To disable the use of WebSockets, set without_websockets=True. This will make the method return None, though the post will still be created. You may wish to do this if you are running your program in a restricted network environment, or using a proxy that doesn’t support WebSockets connections.

For example, to submit a video to r/test do:

title = "My favorite movie"
video = "/path/to/video.mp4"
subreddit = await reddit.subreddit("test")
await subreddit.submit_video(title, video)

See also

await subscribe(*, other_subreddits: Optional[List[asyncpraw.models.Subreddit]] = None)

Subscribe to the subreddit.

Parameters

other_subreddits – When provided, also subscribe to the provided list of subreddits.

For example, to subscribe to r/test:

subreddit = await reddit.subreddit("test")
await subreddit.subscribe()
top(*, time_filter: str = 'all', **generator_kwargs: Union[str, int, Dict[str, str]]) AsyncIterator[Any]

Return a ListingGenerator for top items.

Parameters

time_filter – Can be one of: "all", "day", "hour", "month", "week", or "year "``(default: ``"all").

Raises

ValueError if time_filter is invalid.

Additional keyword arguments are passed in the initialization of ListingGenerator.

This method can be used like:

reddit.domain("imgur.com").top(time_filter="week")

multireddit = await reddit.multireddit(redditor="samuraisam", name="programming")
multireddit.top(time_filter="day")

redditor = await reddit.redditor("spez")
redditor.top(time_filter="month")

redditor = await reddit.redditor("spez")
redditor.comments.top(time_filter="year")

redditor = await reddit.redditor("spez")
redditor.submissions.top(time_filter="all")

subreddit = await reddit.subreddit("all")
subreddit.top(time_filter="hour")
await traffic() Dict[str, List[List[int]]]

Return a dictionary of the Subreddit’s traffic statistics.

Raises

asyncprawcore.NotFound when the traffic stats aren’t available to the authenticated user, that is, they are not public and the authenticated user is not a moderator of the subreddit.

The traffic method returns a dict with three keys. The keys are day, hour and month. Each key contains a list of lists with 3 or 4 values. The first value is a timestamp indicating the start of the category (start of the day for the day key, start of the hour for the hour key, etc.). The second, third, and fourth values indicate the unique pageviews, total pageviews, and subscribers, respectively.

Note

The hour key does not contain subscribers, and therefore each sub-list contains three values.

For example, to get the traffic stats for r/test:

subreddit = await reddit.subreddit("test")
stats = await subreddit.traffic()
await unsubscribe(*, other_subreddits: Optional[List[asyncpraw.models.Subreddit]] = None)

Unsubscribe from the subreddit.

Parameters

other_subreddits – When provided, also unsubscribe from the provided list of subreddits.

To unsubscribe from r/test:

subreddit = await reddit.subreddit("test")
await subreddit.unsubscribe()
widgets() asyncpraw.models.SubredditWidgets

Provide an instance of SubredditWidgets.

Example usage

Get all sidebar widgets:

subreddit = await reddit.subreddit("test")
async for widget in subreddit.widgets.sidebar:
    print(widget)

Get ID card widget:

subreddit = await reddit.subreddit("test")
widget = await subreddit.widgets.id_card()
print(widget)
wiki() asyncpraw.models.reddit.subreddit.SubredditWiki

Provide an instance of SubredditWiki.

This attribute can be used to discover all wikipages for a subreddit:

subreddit = await reddit.subreddit("test")
async for wikipage in subreddit.wiki:
    print(wikipage)

To fetch the content for a given wikipage try:

subreddit = await reddit.subreddit("test")
wikipage = await subreddit.wiki.get_page("proof")
print(wikipage.content_md)

Util

class asyncpraw.models.util.BoundedSet(max_items: int)

A set with a maximum size that evicts the oldest items when necessary.

This class does not implement the complete set interface.

__contains__(item: Any) bool

Test if the BoundedSet contains item.

__init__(max_items: int)

Initialize a BoundedSet instance.

add(item: Any)

Add an item to the set discarding the oldest item if necessary.

class asyncpraw.models.util.ExponentialCounter(max_counter: int)

A class to provide an exponential counter with jitter.

__init__(max_counter: int)

Initialize an ExponentialCounter instance.

Parameters

max_counter

The maximum base value.

Note

The computed value may be 3.125% higher due to jitter.

counter() Union[int, float]

Increment the counter and return the current value with jitter.

reset()

Reset the counter to 1.

asyncpraw.models.util.permissions_string(*, known_permissions: Set[str], permissions: Optional[List[str]]) str

Return a comma separated string of permission changes.

Parameters
  • known_permissions – A set of strings representing the available permissions.

  • permissions – A list of strings, or None. These strings can exclusively contain + or - prefixes, or contain no prefixes at all. When prefixed, the resulting string will simply be the joining of these inputs. When not prefixed, all permissions are considered to be additions, and all permissions in the known_permissions set that aren’t provided are considered to be removals. When None, the result is "+all".

async for ... in asyncpraw.models.util.stream_generator(function: Callable, *, attribute_name: str = 'fullname', exclude_before: bool = False, pause_after: Optional[int] = None, skip_existing: bool = False, **function_kwargs: Any) AsyncGenerator[Any, None]

Yield new items from function as they become available.

Parameters
  • function – A callable that returns a ListingGenerator, e.g., Subreddit.comments() or Subreddit.new().

  • attribute_name – The field to use as an ID (default: "fullname").

  • exclude_before – When True does not pass params to function (default: False).

  • pause_after – An integer representing the number of requests that result in no new items before this function yields None, effectively introducing a pause into the stream. A negative value yields None after items from a single response have been yielded, regardless of number of new items obtained in that response. A value of 0 yields None after every response resulting in no new items, and a value of None never introduces a pause (default: None).

  • skip_existing – When True, this does not yield any results from the first request thereby skipping any items that existed in the stream prior to starting the stream (default: False).

Additional keyword arguments will be passed to function.

Note

This function internally uses an exponential delay with jitter between subsequent responses that contain no new results, up to a maximum delay of just over 16 seconds. In practice, that means that the time before pause for pause_after=N+1 is approximately twice the time before pause for pause_after=N.

For example, to create a stream of comment replies, try:

reply_function = reddit.inbox.comment_replies
async for reply in asyncpraw.models.util.stream_generator(reply_function):
    print(reply)

To pause a comment stream after six responses with no new comments, try:

subreddit = await reddit.subreddit("test")
async for comment in subreddit.stream.comments(pause_after=6):
    if comment is None:
        break
    print(comment)

To resume fetching comments after a pause, try:

subreddit = await reddit.subreddit("test")
comment_stream = subreddit.stream.comments(pause_after=5)

async for comment in comment_stream:
    if comment is None:
        break
    print(comment)
# Do any other processing, then try to fetch more data
async for comment in comment_stream:
    if comment is None:
        break
    print(comment)

To bypass the internal exponential backoff, try the following. This approach is useful if you are monitoring a subreddit with infrequent activity, and you want to consistently learn about new items from the stream as soon as possible, rather than up to a delay of just over sixteen seconds.

subreddit = await reddit.subreddit("test")
async for comment in subreddit.stream.comments(pause_after=0):
    if comment is None:
        continue
    print(comment)

Comment Extraction and Parsing

A common use for Reddit’s API is to extract comments from submissions and use them to perform keyword or phrase analysis.

As always, you need to begin by creating an instance of Reddit:

import asyncpraw

reddit = asyncpraw.Reddit(
    client_id="CLIENT_ID",
    client_secret="CLIENT_SECRET",
    password="PASSWORD",
    user_agent="Comment Extraction (by u/USERNAME)",
    username="USERNAME",
)

Note

If you are only analyzing public comments, entering a username and password is optional.

In this document, we will detail the process of finding all the comments for a given submission. If you instead want to process all comments on Reddit, or comments belonging to one or more specific subreddits, please see SubredditStream.comments().

Extracting comments with Async PRAW

Assume we want to process the comments for this submission: https://www.reddit.com/r/funny/comments/3g1jfi/buttons/

We first need to obtain a submission object. We can do that either with the entire URL:

url = "https://www.reddit.com/r/funny/comments/3g1jfi/buttons/"
submission = await reddit.submission(url=url)

or with the submission’s ID which comes after comments/ in the URL:

submission = await reddit.submission("3g1jfi")

With a submission object we can then interact with its CommentForest through the submission’s comments attribute. A CommentForest is a list of top-level comments each of which contains a CommentForest of replies.

If we wanted to output only the body of the top-level comments in the thread we could do:

comments = await submission.comments()
for top_level_comment in comments:
    print(top_level_comment.body)

While running this you will most likely encounter the exception AttributeError: 'MoreComments' object has no attribute 'body'. This submission’s comment forest contains a number of MoreComments objects. These objects represent the “load more comments”, and “continue this thread” links encountered on the website. While we could ignore MoreComments in our code, like so:

from asyncpraw.models import MoreComments

comments - await submission.comments()
for top_level_comment in comments:
    if isinstance(top_level_comment, MoreComments):
        continue
    print(top_level_comment.body)

The replace_more method

In the previous snippet, we used isinstance() to check whether the item in the comment list was a MoreComments so that we could ignore it. But there is a better way: the CommentForest object has a method called replace_more(), which replaces or removes MoreComments objects from the forest.

Each replacement requires one network request, and its response may yield additional MoreComments instances. As a result, by default, replace_more() only replaces at most 32 MoreComments instances – all other instances are simply removed. The maximum number of instances to replace can be configured via the limit parameter. Additionally a threshold parameter can be set to only perform replacement of MoreComments instances that represent a minimum number of comments; it defaults to 0, meaning all MoreComments instances will be replaced up to limit.

A limit of 0 simply removes all MoreComments from the forest. The previous snippet can thus be simplified:

comments = await submission.comments()
await comments.replace_more(limit=0)
for top_level_comment in comments:
    print(top_level_comment.body)

Note

Calling replace_more() is destructive. Calling it again on the same submission instance has no effect.

Meanwhile, a limit of None means that all MoreComments objects will be replaced until there are none left, as long as they satisfy the threshold.

comments = await submission.comments()
await comments.replace_more(limit=None)
for top_level_comment in comments:
    print(top_level_comment.body)

Now we are able to successfully iterate over all the top-level comments. What about their replies? We could output all second-level comments like so:

submission.comments.replace_more(limit=None)
for top_level_comment in submission.comments:
    for second_level_comment in top_level_comment.replies:
        print(second_level_comment.body)

However, the comment forest can be arbitrarily deep, so we’ll want a more robust solution. One way to iterate over a tree, or forest, is via a breadth-first traversal using a queue:

comments = await submission.comments()
await comments.replace_more(limit=None)
comment_queue = comments[:]  # Seed with top-level
while comment_queue:
    comment = comment_queue.pop(0)
    print(comment.body)
    comment_queue.extend(comment.replies)

The above code will output all the top-level comments, followed by second-level, third-level, etc. While it is awesome to be able to do your own breadth-first traversals, CommentForest provides a convenience method, list(), which returns a list of comments traversed in the same order as the code above. Thus the above can be rewritten as:

comments = await submission.comments()
comments.replace_more(limit=None)
all_comments = await comments.list()
for comment in all_comments:
    print(comment.body)

You can now properly extract and parse all (or most) of the comments belonging to a single submission. Combine this with submission iteration and you can build some really cool stuff.

Finally, note that the value of submission.num_comments may not match up 100% with the number of comments extracted via Async PRAW. This discrepancy is normal as that count includes deleted, removed, and spam comments.

Working with Refresh Tokens

Reddit OAuth2 Scopes

Before working with refresh tokens you should decide which scopes your application requires. If you want to use all scopes, you can use the special scope *.

To get an up-to-date listing of all Reddit scopes and their descriptions run the following:

import requests

response = requests.get(
    "https://www.reddit.com/api/v1/scopes.json",
    headers={"User-Agent": "fetch-scopes by u/bboe"},
)

for scope, data in sorted(response.json().items()):
    print(f"{scope:>18s}  {data['description']}")

As of February 2021, the available scopes are:

Scope

Description

account

Update preferences and related account information. Will not have access to your email or password.

creddits

Spend my reddit gold creddits on giving gold to other users.

edit

Edit and delete my comments and submissions.

flair

Select my subreddit flair. Change link flair on my submissions.

history

Access my voting history and comments or submissions I’ve saved or hidden.

identity

Access my reddit username and signup date.

livemanage

Manage settings and contributors of live threads I contribute to.

modconfig

Manage the configuration, sidebar, and CSS of subreddits I moderate.

modcontributors

Add/remove users to approved user lists and ban/unban or mute/unmute users from subreddits I moderate.

modflair

Manage and assign flair in subreddits I moderate.

modlog

Access the moderation log in subreddits I moderate.

modmail

Access and manage modmail via mod.reddit.com.

modothers

Invite or remove other moderators from subreddits I moderate.

modposts

Approve, remove, mark nsfw, and distinguish content in subreddits I moderate.

modself

Accept invitations to moderate a subreddit. Remove myself as a moderator or contributor of subreddits I moderate or contribute to.

modtraffic

Access traffic stats in subreddits I moderate.

modwiki

Change editors and visibility of wiki pages in subreddits I moderate.

mysubreddits

Access the list of subreddits I moderate, contribute to, and subscribe to.

privatemessages

Access my inbox and send private messages to other users.

read

Access posts and comments through my account.

report

Report content for rules violations. Hide & show individual submissions.

save

Save and unsave comments and submissions.

structuredstyles

Edit structured styles for a subreddit I moderate.

submit

Submit links and comments from my account.

subscribe

Manage my subreddit subscriptions. Manage “friends” - users whose content I follow.

vote

Submit and change my votes on comments and submissions.

wikiedit

Edit wiki pages on my behalf

wikiread

Read wiki pages through my account

Obtaining Refresh Tokens

The following program can be used to obtain a refresh token with the desired scopes:

#!/usr/bin/env python

"""This example demonstrates the flow for retrieving a refresh token.



This tool can be used to conveniently create refresh tokens for later use with
your web application OAuth2 credentials.

To create a Reddit application visit the following link while logged into the account
you want to create a refresh token for: https://www.reddit.com/prefs/apps/

Create a "web app" with the redirect uri set to: http://localhost:8080

After the application is created, take note of:

- REDDIT_CLIENT_ID; the line just under "web app" in the upper left of the Reddit
  Application
- REDDIT_CLIENT_SECRET; the value to the right of "secret"

Usage:

    EXPORT praw_client_id=<REDDIT_CLIENT_ID>
    EXPORT praw_client_secret=<REDDIT_CLIENT_SECRET>
    python3 obtain_refresh_token.py

"""
import asyncio
import random
import socket
import sys

import asyncpraw


async def main():
    """Provide the program's entry point when directly executed."""
    scope_input = input(
        "Enter a comma separated list of scopes, or '*' for all scopes: "
    )
    scopes = [scope.strip() for scope in scope_input.strip().split(",")]

    reddit = asyncpraw.Reddit(
        redirect_uri="http://localhost:8080",
        user_agent="obtain_refresh_token/v0 by u/bboe",
    )
    state = str(random.randint(0, 65000))
    url = reddit.auth.url(duration="permanent", scopes=scopes, state=state)
    print(f"Now open this url in your browser: {url}")

    client = receive_connection()
    data = client.recv(1024).decode("utf-8")
    param_tokens = data.split(" ", 2)[1].split("?", 1)[1].split("&")
    params = {
        key: value for (key, value) in [token.split("=") for token in param_tokens]
    }

    if state != params["state"]:
        send_message(
            client,
            f"State mismatch. Expected: {state} Received: {params['state']}",
        )
        return 1
    elif "error" in params:
        send_message(client, params["error"])
        return 1

    refresh_token = await reddit.auth.authorize(params["code"])
    send_message(client, f"Refresh token: {refresh_token}")
    await reddit._http.close()
    return 0


def receive_connection():
    """Wait for and then return a connected socket..

    Opens a TCP connection on port 8080, and waits for a single client.

    """
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("localhost", 8080))
    server.listen(1)
    client = server.accept()[0]
    server.close()
    return client


def send_message(client, message):
    """Send message to client and close the connection."""
    print(message)
    client.send(f"HTTP/1.1 200 OK\r\n\r\n{message}".encode("utf-8"))
    client.close()


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    sys.exit(loop.run_until_complete(main()))

This script assumes you have configured your application’s redirect uri to localhost:8080

When you execute this script interactively:

  1. You will be prompted to provide a comma-separated list of scopes.

  2. You will be given a URL that will take you through the auth flow on Reddit.

  3. When you open the provided link in your browser, Reddit will ask you for permission to grant the application permissions to the scopes requested.

  4. After clicking allow, you will have a new authorized application configured.

  5. You will be redirected to another page (the application’s redirect uri) where your refresh token will be displayed and will be printed to the command line.

You only have to run this script once for each refresh token. The refresh token (along with the application’s client_id, client_secret) are valid credentials until manually revoked by the user.

Submission Stream Reply Bot

Most redditors have seen bots in action on the site. Reddit bots can perform a number of tasks including providing useful information, e.g., an Imperial to Metric units bot; convenience, e.g., a link corrector bot; or analytical information, e.g., redditor analyzer bot for writing complexity.

PRAW provides a simple way to build your own bot using the Python programming language. As a result, it is little surprise that a majority of bots on Reddit are powered by Async PRAW.

With Async PRAW, there is now support for interacting with Reddit inside an asynchronous environment, most commonly, Discord bots.

This tutorial will show you how to build a bot that monitors a particular subreddit, r/AskReddit, for new submissions containing simple questions and replies with an appropriate link to lmgtfy (Let Me Google That For You).

There are three key components we will address to perform this task:

  1. Monitor new submissions.

  2. Analyze the title of each submission to see if it contains a simple question.

  3. Reply with an appropriate lmgtfy link.

LMGTFY Bot

The goal of the LMGTFY Bot is to point users in the right direction when they ask a simple question that is unlikely to be upvoted or answered by other users.

Two examples of such questions are:

  1. “What is the capital of Canada?”

  2. “How many feet are in a yard?”

Once we identify these questions, the LMGTFY Bot will reply to the submission with an appropriate lmgtfy link. For the example questions those links are:

  1. https://lmgtfy.com/?q=What+is+the+capital+of+Canada%3F

  2. https://lmgtfy.com/?q=How+many+feet+are+in+a+yard%3F

Step 1: Getting Started

Access to Reddit’s API requires a set of OAuth2 credentials. Those credentials are obtained by registering an application with Reddit. To register an application and receive a set of OAuth2 credentials please follow only the “First Steps” section of Reddit’s OAuth2 Quick Start Example wiki page.

Once the credentials are obtained we can begin writing the LMGTFY Bot. Start by creating an instance of Reddit:

import asyncpraw

reddit = asyncpraw.Reddit(
    client_id="CLIENT_ID",
    client_secret="CLIENT_SECRET",
    password="PASSWORD",
    user_agent="LMGTFY (by u/USERNAME)",
    username="USERNAME",
)

In addition to the OAuth2 credentials, the username and password of the Reddit account that registered the application are required.

Note

This example demonstrates use of a script type application. For other application types please see Reddit’s wiki page OAuth2 App Types.

Step 2: Monitoring New Submissions to /r/AskReddit

PRAW provides a convenient way to obtain new submissions to a given subreddit. To indefinitely iterate over new submissions to a subreddit add:

subreddit = await reddit.subreddit("test")
async for submission in subreddit.stream.submissions():
    # do something with submission
    ...

Replace "AskReddit" with the name of another subreddit if you want to iterate through its new submissions. Additionally, multiple subreddits can be specified by joining them with pluses (+), for example, "AskReddit+NoStupidQuestions". All subreddits can be specified using the special name "all". Subreddits can be excluded from the special "all" subreddit by joining them with minuses (-), for example "all-excluded_subreddit1-excluded_subreddit2".

Step 3: Analyzing the Submission Titles

Now that we have a stream of new submissions to r/AskReddit, it is time to see if their titles contain a simple question. We naïvely define a simple question as:

  1. It must contain no more than ten words.

  2. It must contain one of the phrases "what is", "what are", or "who is".

Warning

These naïve criteria result in many false positives. It is strongly recommended that you develop more precise heuristics before launching a bot on any popular subreddits.

First we filter out titles that contain more than ten words:

if len(submission.title.split()) > 10:
    return

We then check to see if the submission’s title contains any of the desired phrases:

questions = ["what is", "who is", "what are"]
normalized_title = submission.title.lower()
for question_phrase in questions:
    if question_phrase in normalized_title:
        # do something with a matched submission
        break

String comparison in Python is case sensitive. As a result, we only compare a normalized version of the title to our lower-case question phrases. In this case, “normalized” means only lower-case.

The break at the end prevents us from matching more than once on a single submission. For instance, what would happen without the break if a submission’s title was “Who is or what are buffalo?”?

Step 4: Automatically Replying to the Submission

The LMGTFY Bot is nearly complete. We iterate through submissions and find ones that appear to be simple questions. All that is remaining is to reply to those submissions with an appropriate lmgtfy link.

First we will need to construct a working lmgtfy link. In essence, we want to pass the entire submission title to lmgtfy. However, there are certain characters that are not permitted in URLs or have other meanings. For instance, the space character, `` , is not permitted, and the question mark, ``?, has a special meaning. Thus we will transform those into their URL-safe representation so that a question like “What is the capital of Canada?” is transformed into the link https://lmgtfy.com/?q=What+is+the+capital+of+Canada%3F.

There are a number of ways we could accomplish this task. For starters, we could write a function to replace spaces with pluses (+) and question marks with %3F. However, there is even an easier way; using an existing built-in function to do so.

Add the following code where the “do something with a matched submission” comment is located:

from urllib.parse import quote_plus

reply_template = "[Let me google that for you](https://lmgtfy.com/?q={})"

url_title = quote_plus(submission.title)
reply_text = reply_template.format(url_title)

Now that we have the reply text, replying to the submission is easy:

await submission.reply(reply_text)

If all went well, your comment should have been made. If your bot account is brand new, you will likely run into rate limit issues. These rate limits will persist until that account acquires sufficient karma.

Step 5: Cleaning Up The Code

While we have a working bot, we have added little segments here and there. If we were to continue to do so in this fashion our code would be quite unreadable. Let’s clean it up some.

The first thing we should do is put all of our import statements at the top of the file. It is common to list built-in packages before third-party ones:

#!/usr/bin/env python3
import asyncio
from urllib.parse import quote_plus

import asyncpraw

Next, we extract a few constants that are used in our script:

QUESTIONS = ["what is", "who is", "what are"]
REPLY_TEMPLATE = "[Let me google that for you](https://lmgtfy.com/?q={})"

We then extract the segment of code pertaining to processing a single submission into its own function:

async def process_submission(submission):
    # Ignore titles with more than 10 words as they probably are not simple
    # questions.
    if len(submission.title.split()) > 10:
        return

    normalized_title = submission.title.lower()
    for question_phrase in QUESTIONS:
        if question_phrase in normalized_title:
            url_title = quote_plus(submission.title)
            reply_text = REPLY_TEMPLATE.format(url_title)
            print(f"Replying to: {submission.title}")
            await submission.reply(reply_text)
            # A reply has been made so do not attempt to match other phrases.
            break

Observe that we added some comments and a print() call. The print() addition informs us every time we are about to reply to a submission, which is useful to ensure the script is running.

Next, it is a good practice to not have any top-level executable code in case you want to turn your Python script into a Python module, i.e., import it from another Python script or module. A common way to do that is to move the top-level code to a main function:

async def main():
    reddit = asyncpraw.Reddit(
        client_id="CLIENT_ID",
        client_secret="CLIENT_SECRET",
        password="PASSWORD",
        user_agent="LMGTFY (by u/USERNAME)",
        username="USERNAME",
    )

    subreddit = await reddit.subreddit("AskReddit")
    async for submission in subreddit.stream.submissions():
        await process_submission(submission)

Finally, we need to call main only in the cases that this script is the one being executed:

if __name__ == "__main__":
    asyncio.run(main())
The Complete LMGTFY Bot

The following is the complete LMGTFY Bot:

#!/usr/bin/env python3
import asyncio
from urllib.parse import quote_plus

import asyncpraw

QUESTIONS = ["what is", "who is", "what are"]
REPLY_TEMPLATE = "[Let me google that for you](https://lmgtfy.com/?q={})"


async def main():
    reddit = asyncpraw.Reddit(
        client_id="CLIENT_ID",
        client_secret="CLIENT_SECRET",
        password="PASSWORD",
        user_agent="LMGTFY (by u/USERNAME)",
        username="USERNAME",
    )

    subreddit = await reddit.subreddit("AskReddit")
    async for submission in subreddit.stream.submissions():
        await process_submission(submission)


async def process_submission(submission):
    # Ignore titles with more than 10 words as they probably are not simple
    # questions.
    if len(submission.title.split()) > 10:
        return

    normalized_title = submission.title.lower()
    for question_phrase in QUESTIONS:
        if question_phrase in normalized_title:
            url_title = quote_plus(submission.title)
            reply_text = REPLY_TEMPLATE.format(url_title)
            print(f"Replying to: {submission.title}")
            await submission.reply(reply_text)
            # A reply has been made so do not attempt to match other phrases.
            break


if __name__ == "__main__":
    asyncio.run(main())

Change Log

Async PRAW follows semantic versioning.

Unreleased

7.6.1 (2022/11/28)

Changed

  • Revert edit() positional argument deprecation.

  • Revert edit() positional argument deprecation.

Fixed

  • An issue where ModmailConversation’s messages attribute would only contain the latest message.

7.6.0 (2022/10/23)

Added

Changed

  • Drop support for Python 3.6, which is end-of-life on 2021-12-23.

  • conversations() now returns a ListingGenerator allowing you to page through more than 100 conversations.

Deprecated

  • The after argument for conversations() will now have to be included in params keyword argument.

  • Positional keyword arguments for applicable functions and methods. Starting with Async PRAW 8, most functions and methods will no longer support positional arguments. It will encourage more explicit argument passing, enable arguments to be sorted alphabetically, and prevent breaking changes when adding new arguments to existing methods.

7.5.0 (2021/11/13)

Added

  • Log a warning if a submission’s comment_sort attribute is updated after the submission has already been fetched and a warn_comment_sort config setting to turn off the warning.

  • user_selectable() to get available subreddit link flairs.

  • Automatic RateLimit handling will support errors with millisecond resolution.

  • Draft to represent a submission draft.

  • Draft.delete() to delete drafts.

  • Draft.submit() to submit drafts.

  • Draft.update() to modify drafts.

  • DraftHelper to fetch or create drafts on new Reddit.

  • DraftList to represent a list of Draft objects.

Deprecated

Fixed

  • Fixed return value type of methods returning a listing in Subreddit and its helper classes.

  • An import error when using Async PRAW in environments where libsqlite3-dev is needed to utilize aiosqlite package which depends on the sqlite3 builtin.

Deprecated

  • The keyword argument lazy has been replace by fetch to consolidate the keyword argument used to explicitly perform a fetch when initializing an object.

7.4.0 (2021/07/30)

Added

Changed

Deprecated

  • Reddit keyword argument token_manager.

7.3.1 (2021/07/06)

Changed

  • Reddit will now be shallow copied when a deepcopy is preformed on it as asyncprawcore.Session (more specifically, asyncio.AbstractEventLoop) does not support being deepcopied.

Fixed

  • Fixed an issue where some RedditBase objects would be sent in a request as "None".

7.3.0 (2021/06/18)

Added

Changed

  • moderated() will now objectify all data returned from the API.

  • The wiki_edit endpoint has been changed from r/{subreddit}/api/wiki/edit/ to r/{subreddit}/api/wiki/edit.

  • Redditor.block() no longer needs to retrieve a user’s fullname.

Deprecated

Fixed

  • Fixed bug where WikiPage.edit() and SubredditWiki.create() would fail if passed content and reason parameters that produced a request with a body greater than 500 KiB, even when the parameters did not exceed their respective permitted maximum lengths.

  • Fixed bug where request() could not handle instances of BadRequests when the JSON data contained only the keys “reason” and “message”.

  • Fixed bug where request() could not handle instances of BadRequests when the response did not contain valid JSON data.

  • Fixed bug where fullname() sometimes returned the wrong fullname.

7.2.0 (2021/02/25)

Added

Deprecated

  • The configuration setting refresh_token is deprecated and its use will result in a DeprecationWarning. This deprecation applies in all ways of setting configuration values, i.e., via praw.ini, as a keyword argument when initializing an instance of Reddit, and via the PRAW_REFRESH_TOKEN environment variable. To be prepared for Async PRAW 8, use the new Reddit keyword argument token_manager. See Working with Refresh Tokens in Async PRAW’s documentation for an example.

  • me() will no longer return None when called in read_only mode starting in Async PRAW 8. A DeprecationWarning will be issued. To switch forward to the Async PRAW 8 behavior set praw8_raise_exception_on_me=True in your asyncpraw.Reddit(...) call.

7.1.1 (2021/02/11)

Added

  • Add method Subreddits.premium() to reflect the naming change in Reddit’s API.

  • Ability to submit image galleries with submit_gallery().

  • Ability to pass a gallery url to Reddit.submission().

  • Ability to specify modmail mute duration.

  • Add method invited() to get invited moderators of a subreddit.

  • Ability to submit text/self posts with inline media.

  • Add method Submission.award() and Comment.award() with the ability to specify type of award, anonymity, and message when awarding a submission or comment.

  • Ability to specify subreddits by name using the subreddits parameter in Reddit.info().

  • Added Reddit.close() to close the requestor session.

  • Ability to use Reddit as an asynchronous context manager that automatically closes the requestor session on exit.

Changed

  • BoundedSet will now utilize a Last-Recently-Used (LRU) storing mechanism, which will change the order in which elements are removed from the set.

  • Improved submit_image() and submit_video() performance in slow network environments by removing a race condition when establishing a websocket connection.

Deprecated

Fixed

  • An issue where leaving as a moderator fails if you are using token auth.

  • An issue where an incorrect error was being raised due to invalid submission urls.

  • A bug where if you call .parent() on a comment it clears its replies.

  • An issue where performing a deepcopy on an RedditBase object will fail.

  • Some cases where streams yield the same item multiple times. This cannot be prevented in every case.

  • An issue where streams could get stuck on a deleted item and never pull new items.

  • Fix subreddit style asset uploading.

7.1.0 (2020/07/16)

  • First official Async PRAW release!

7.1.0.pre1 (2020/07/16)

  • Initial Async PRAW pre-release.

For changes in PRAW please see: PRAW Changelog

Contributing to Async PRAW

Async PRAW gladly welcomes new contributions. As with most larger projects, we have an established consistent way of doing things. A consistent style increases readability, decreases bug-potential and makes it faster to understand how everything works together.

Setting Up Your Development Environment

This section will cover the recommended steps to get you started with contributing to Async PRAW.

Create a Virtual Environment

It is strongly recommended to use a virtual environment to isolate your development environment. This is a good idea because it will make managing the needed dependencies and their versions much easier. For more information, see the venv documentation. Assuming you have the minimum Python version required for Async PRAW, you can create a virtual environment with the following commands from the root of the cloned project directory:

python3 -m venv .venv

Next you need to activate the virtual environment. This is done by running the following:

MacOS/Linux:

source .venv/bin/activate

Windows Command Prompt

.venv\Scripts\activate.bat
Install Development Dependencies

Next, you will need to install the dependencies development dependencies. This is done by running the following:

pip install -e .[dev]

Important

If you are using zsh for your shell, you will need to double-quote .[dev] like so:

pip install -e ".[dev]"

Note

The -e tells pip to install Async PRAW in an editable state. This will allow for easier testing and debugging. The [dev] extra will install all development dependencies. This includes the dependencies for both linting and testing.

Code Style

Linting

Async PRAW follows PEP 8 and PEP 257 and some Async PRAW Specific Style Guidelines. pre-commit is used to manage a suite of pre-commit hooks that enforce conformance with these PEPs along with several other checks. Additionally, the pre_push.py script can be used to run the full pre-commit suite and the docs build prior to submitting a pull request.

Note

In order to use the pre-commit hooks and the pre_push.py dependencies, you must either install the development dependencies as outlined in the Install Development Dependencies section above or you must install the [lint] extra manually:

pip install -e .[lint]

To install the pre-commit hooks to automatically run when you commit, run the following:

pre-commit install

To run all the needed checks and to ensure the docs build correctly, run the following:

./pre_push.py
Async PRAW Specific Style Guidelines

The following are Async PRAW-specific guidelines in addition to the PEPs specified in Linting:

  • Within a single file classes are sorted alphabetically where inheritance permits.

  • Within a class, methods are sorted alphabetically within their respective groups with the following as the grouping order:

    • Static methods

    • Class methods

    • Cached properties

    • Properties

    • Instance Methods

  • Use descriptive names for the catch-all keyword argument, e.g., **other_options rather than **kwargs.

  • Methods with more than one argument should have all its arguments sorted alphabetically and marked as keyword only with the * argument. For example:

    class ExampleClass:
        async def example_method(
            self,
            *,
            arg1,
            arg2,
            optional_arg1=None,
        ):
            ...
    

    There is some exceptions to this:

    • If it’s clear without reading documentation what the mandatory positional arguments would be and their order, then they can be positional arguments. For example:

      class ExampleClass:
          def pair(self, left, right):
              ...
      
    • If there is one or two mandatory arguments and some optional arguments, then the mandatory arguments may be positional (as long as it adheres to the previous point), however, the optional arguments must be made keyword only and sorted alphabetically. For example:

      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,
              selftext=None,
              send_replies=True,
              spoiler=False,
              url=None,
          ):
              ...
      

Testing

Contributions to Async PRAW requires 100% test coverage as reported by Coveralls. If you know how to add a feature, but aren’t sure how to write the necessary tests, please open a pull request anyway so we can work with you to write the necessary tests.

Running the Test Suite

GitHub Actions automatically runs all updates to known branches and pull requests. However, it’s useful to be able to run the tests locally. The simplest way is via:

pytest

Without any configuration or modification, all the tests should pass. If they do not, please file a bug report.

Adding and Updating Integration Tests

Async PRAW’s integration tests utilize vcrpy to record an interaction with Reddit. The recorded interaction is then replayed for subsequent test runs.

To safely record a cassette without leaking your account credentials, Async PRAW utilizes a number of environment variables which are replaced with placeholders in the cassettes. The environment variables are (listed in bash export format):

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

By setting these environment variables prior to running pytest, when adding or updating cassettes, instances of mypassword will be replaced by the placeholder text <PASSWORD> and similar for the other environment variables.

To use a refresh token instead of username/password set prawtest_refresh_token instead of prawtest_password and prawtest_username.

When adding or updating a cassette, you will likely want to force requests to occur again rather than using an existing cassette. The simplest way to rebuild a cassette is to first delete it, and then rerun the test suite.

Please always verify that only the requests you expect to be made are contained within your cassette.

Documentation

  • All publicly available functions, classes, and modules should have a docstring.

  • All documentation files and docstrings should be linted and formatted by docstrfmt.

  • Use correct terminology. A subreddit’s fullname is something like t5_xyfc7. The correct term for a subreddit’s “name” like python for r/python is its display name.

Static Checker

Async PRAW’s test suite comes with a checker tool that can warn you of using incorrect documentation styles (using .. code:: instead of .. code-block::, using /r/ instead of r/, etc.). This is run automatically by the pre-commit hooks and the pre_push.py script.

class tools.static_word_checks.StaticChecker(replace: bool)

Run simple checks on the entire document or specific lines.

__init__(replace: bool)

Initialize a StaticChecker instance.

Parameters

replace – Whether to make replacements.

check_for_double_syntax(filename: str, content: str) bool

Checks a file for double-slash statements (/r/ and /u/).

Parameters
  • filename – The name of the file to check & replace.

  • content – The content of the file

Returns

A boolean with the status of the check

check_for_noreturn(filename: str, line_number: int, content: str) bool

Checks a line for NoReturn statements.

Parameters
  • filename – The name of the file to check & replace.

  • line_number – The line number

  • content – The content of the line

Returns

A boolean with the status of the check

run_checks() bool

Scan a directory and run the checks.

The directory is assumed to be the asyncpraw directory located in the parent directory of the file, so if this file exists in ~/asyncpraw/tools/static_word_checks.py, it will check ~/asyncpraw/asyncpraw.

It runs the checks located in the self.full_file_checks and self.line_checks lists, with full file checks being run first.

Full-file checks are checks that can also fix the errors they find, while the line checks can just warn about found errors.

Files to Update

AUTHORS.rst

For your first contribution, please add yourself to the end of the respective list in the AUTHORS.rst file.

CHANGES.rst

For feature additions, bugfixes, or code removal please add an appropriate entry to CHANGES.rst. If the Unreleased section does not exist at the top of CHANGES.rst please add it. See commit 280525c16ba28cdd69cdbb272a0e2764b1c7e6a0 for an example.

See Also

Please also read the Contributing Guidelines

Glossary

  • Access Token: A temporary token to allow access to the Reddit API. Lasts for one hour.

  • Creddit: Back when the only award was Reddit Gold, a creddit was equal to one month of Reddit Gold. Creddits have been converted to Reddit Coins. See this for more info about the old Reddit Gold system.

  • Fullname: The fullname of an object is the object’s type followed by an underscore and its base-36 id. An example would be t3_1h4f3, where the t3 signals that it is a Submission, and the submission ID is 1h4f3.

    Here is a list of the six different types of objects returned from Reddit:

    • t1 These object represent Comments.

    • t4 These object represent Messages.

    • t6 These object represent Awards, such as Reddit Gold or Reddit Silver.

  • Gild: Back when the only award was Reddit Gold, gilding a post meant awarding one month of Reddit Gold. Currently, gilding means awarding one month of Reddit Platinum, or giving a Platinum award.

  • Websocket: A special connection type that supports both a client and a server (the running program and Reddit respectively) sending multiple messages to each other. Reddit uses websockets to notify clients when an image or video submission is completed, as well as certain types of asset uploads, such as subreddit banners.

Migrating to Async PRAW

With the conversion to async, there are few critical changes that had to be made. This page outlines a few those changes.

Network Requests

Async PRAW utilizes aiohttp to make network requests to Reddit’s API. Since aiohttp can only be used in an asynchronous environment, all network requests need to be awaited. Due to this, most Async PRAW methods need to be awaited as well. You can tell if a method needs awaited by looking at the docs. For example, me() has the word await before me(use_cache: bool = True) in the header for that method since that method makes a network request.

Lazy Loading

In PRAW, the majority of objects are lazily loaded and are not fetched until an attribute is accessed. With Async PRAW, objects can be fetched on initialization and some now do this by default. For example:

  • PRAW:

    # 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)
    
  • Async PRAW:

    # 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)
    

Now, lazy loading is not gone completely and can still be done. For example, if you only want to remove a post, you don’t need the object fully fetched to do that.

  • PRAW:

    # object is not fetched and is only removed
    reddit.submission("id").mod.remove()
    
  • Async PRAW:

    # 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()
    

The following objects are still lazily loaded by default:

You can pass fetch=True in their respective helper method to fully load it.

Inversely, the following objects are now fully fetched when initialized:

You can pass fetch=False in their respective helper method if you want to lazily load it.

In addition, there will be a load() method provided for manually fetching/refreshing objects that subclass RedditBase. If you need to later on access an attribute you need to call the .load() method first:

# object is lazily loaded and no requests are made
submission = await reddit.submission("id", fetch=False)
...
# network request is made and item is fully fetched
await submission.load()

# network request is not made as object is already fully fetched
print(submission.score)

Getting items by Indices

In PRAW you could get specific Emoji, LiveUpdate, RemovalReason, Rule, and WikiPage, objects by using string indices. This will no longer work and has been converted to a .get_<item name>(item) method. Also, they are not lazily loaded by default anymore.

  • PRAW:

    # lazily creates a WikiPage instance
    page = subreddit.wiki["page"]
    
    # network request is made and item is fully fetched
    print(page.content_md)
    
  • Async PRAW:

    # 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)
    
    # using slices
    rule = await subreddit.mod.rules.get_rule(slice(-3, None))  # to get the last 3 rules
    

Migrating to PRAW 7.X

Exception Handling

Class APIException has also been renamed to RedditAPIException. Importing APIException will still work, but is deprecated, but will be removed in Async PRAW 8.0.

PRAW 7 introduced a fundamental change in how exceptions are received from Reddit’s API. Reddit can return multiple exceptions for one API action, and as such, the exception RedditAPIException serves as a container for each of the true exception objects. These objects are instances of RedditErrorItem, and they contain the information of one “error” from Reddit’s API. They have the three data attributes that APIException used to contain.

Most code regarding exceptions can be quickly fixed to work under the new system. All of the exceptions are stored in the items attribute of the exception as entries in a list. In the example code below, observe how attributes are accessed.

try:
    subreddit = await reddit.subreddit("test")
    await subreddit.submit("Test Title", url="invalidurl")
except APIException as exception:
    print(exception.error_type)

This can generally be changed to:

try:
    subreddit = await reddit.subreddit("test")
    await subreddit.submit("Test Title", url="invalidurl")
except RedditAPIException as exception:
    print(exception.items[0].error_type)

However, this should not be done, as this will only work for one error. The probability of Reddit’s API returning multiple exceptions, especially on submit actions, should be addressed. Rather, iterate over the exception, and do the action on each item in the iterator.

try:
    subreddit = await reddit.subreddit("test")
    await subreddit.submit("Test Title", url="invalidurl")
except RedditAPIException as exception:
    for subexception in exception.items:
        print(subexception.error_type)

Alternatively, the exceptions are provided to the exception constructor, so printing the exception directly will also allow you to see all the exceptions.

try:
    subreddit = await reddit.subreddit("test")
    await subreddit.submit("Test Title", url="invalidurl")
except RedditAPIException as exception:
    print(exception)

References

Index