UserSubreddit¶
- class praw.models.UserSubreddit(reddit, *args, **kwargs)¶
A class for
UserSubreddits.To obtain an instance of this class execute:
subreddit = reddit.user.me().subreddit
Typical Attributes
Note
This table describes attributes that typically belong to objects of this class. PRAW dynamically provides the attributes that Reddit returns via the API. Since those attributes are subject to change on Reddit’s end, 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_flairWhether users can assign their own link flair.
can_assign_user_flairWhether users can assign their own user flair.
created_utcTime the subreddit was created, represented in Unix Time.
descriptionSubreddit description, in Markdown.
description_htmlSubreddit description, in HTML.
display_nameName of the subreddit.
idID of the subreddit.
nameFullname of the subreddit.
over18Whether the subreddit is NSFW.
public_descriptionDescription of the subreddit, shown in searches and on the “You must be invited to visit this community” page (if applicable).
spoilers_enabledWhether the spoiler tag feature is enabled.
subscribersCount of subscribers. This will be
0unless unless the authenticated user is a moderator.user_is_bannedWhether the authenticated user is banned.
user_is_moderatorWhether the authenticated user is a moderator.
user_is_subscriberWhether the authenticated user is subscribed.
- Parameters:
reddit (praw.Reddit)
args (Any)
kwargs (Any)
- __init__(reddit, *args, **kwargs)¶
Initialize an
UserSubredditinstance.Note
This class should not be initialized directly. Instead, obtain an instance via:
reddit.user.me().subredditorreddit.redditor("redditor_name").subreddit.
- banned()¶
Provide an instance of
SubredditRelationship.For example, to ban a user try:
reddit.subreddit("test").banned.add("spez", ban_reason="...")
To list the banned users along with any notes, try:
for ban in reddit.subreddit("test").banned(): print(f"{ban}: {ban.note}")
- Return type:
- collections()¶
Provide an instance of
SubredditCollections.To see the permalinks of all
Collections that belong to a subreddit, try:for collection in reddit.subreddit("test").collections: print(collection.permalink)
To get a specific
Collectionby its UUID or permalink, use one of the following:collection = reddit.subreddit("test").collections("some_uuid") collection = reddit.subreddit("test").collections( permalink="https://reddit.com/r/SUBREDDIT/collection/some_uuid" )
- Return type:
- comments()¶
Provide an instance of
CommentHelper.For example, to output the author of the 25 most recent comments of r/test execute:
for comment in reddit.subreddit("test").comments(limit=25): print(comment.author)
- Return type:
- contributor()¶
Provide an instance of
ContributorRelationship.Contributors are also known as approved submitters.
To add a contributor try:
reddit.subreddit("test").contributor.add("spez")
- Return type:
- controversial(*, time_filter='all', **generator_kwargs)¶
Return a
ListingGeneratorfor controversial items.- Parameters:
- Raises:
ValueErroriftime_filteris invalid.- Return type:
Additional keyword arguments are passed in the initialization of
ListingGenerator.This method can be used like:
reddit.domain("imgur.com").controversial(time_filter="week") reddit.multireddit(redditor="samuraisam", name="programming").controversial( time_filter="day" ) reddit.redditor("spez").controversial(time_filter="month") reddit.redditor("spez").comments.controversial(time_filter="year") reddit.redditor("spez").submissions.controversial(time_filter="all") reddit.subreddit("all").controversial(time_filter="hour")
- emoji()¶
Provide an instance of
SubredditEmoji.This attribute can be used to discover all emoji for a subreddit:
for emoji in reddit.subreddit("test").emoji: print(emoji)
A single emoji can be lazily retrieved via:
reddit.subreddit("test").emoji["emoji_name"]
Note
Attempting to access attributes of a nonexistent emoji will result in a
ClientException.- Return type:
- filters()¶
Provide an instance of
SubredditFilters.For example, to add a filter, run:
reddit.subreddit("all").filters.add("test")
- Return type:
- flair()¶
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 theflairmoderator permission on try:for flair in reddit.subreddit("test").flair(): print(flair)
Flair templates can be interacted with through this attribute via:
for template in reddit.subreddit("test").flair.templates: print(template)
- Return type:
- property fullname: str¶
Return the object’s fullname.
A fullname is an object’s kind mapping like
t3followed by an underscore and the object’s base36 ID, e.g.,t1_c5s96e0.
- hot(**generator_kwargs)¶
Return a
ListingGeneratorfor hot items.Additional keyword arguments are passed in the initialization of
ListingGenerator.This method can be used like:
reddit.domain("imgur.com").hot() reddit.multireddit(redditor="samuraisam", name="programming").hot() reddit.redditor("spez").hot() reddit.redditor("spez").comments.hot() reddit.redditor("spez").submissions.hot() reddit.subreddit("all").hot()
- message(*, from_subreddit=None, message, subject)¶
Send a message to a
Redditoror aSubreddit’s moderators (modmail).- Parameters:
from_subreddit (
Subreddit|str|None) –A
Subredditinstance 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
mailmoderator permission.message (
str) – The message content.subject (
str) – The subject of the message.
- Return type:
For example, to send a private message to u/spez, try:
reddit.redditor("spez").message(subject="TEST", message="test message from PRAW")
To send a message to u/spez from the moderators of r/test try:
reddit.redditor("spez").message( subject="TEST", message="test message from r/test", from_subreddit="test" )
To send a message to the moderators of r/test, try:
reddit.subreddit("test").message(subject="TEST", message="test PM from PRAW")
- mod()¶
Provide an instance of
UserSubredditModeration.For example, to update the authenticated user’s display name:
reddit.user.me().subreddit.mod.update(title="New display name")
- Return type:
- moderator()¶
Provide an instance of
ModeratorRelationship.For example, to add a moderator try:
reddit.subreddit("test").moderator.add("spez")
To list the moderators along with their permissions try:
for moderator in reddit.subreddit("test").moderator(): print(f"{moderator}: {moderator.mod_permissions}")
- Return type:
- 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":reddit.subreddit("test").modmail.create(subject="test", body="hello", recipient="spez")
- Return type:
- muted()¶
Provide an instance of
SubredditRelationship.For example, muted users can be iterated through like so:
for mute in reddit.subreddit("test").muted(): print(f"{mute}: {mute.date}")
- Return type:
- new(**generator_kwargs)¶
Return a
ListingGeneratorfor new items.Additional keyword arguments are passed in the initialization of
ListingGenerator.This method can be used like:
reddit.domain("imgur.com").new() reddit.multireddit(redditor="samuraisam", name="programming").new() reddit.redditor("spez").new() reddit.redditor("spez").comments.new() reddit.redditor("spez").submissions.new() reddit.subreddit("all").new()
- classmethod parse(data, reddit)¶
Return an instance of
clsfromdata.
- post_requirements()¶
Get the post requirements for a subreddit.
The returned dict contains the following keys:
domain_blacklistbody_restriction_policydomain_whitelisttitle_regexesbody_blacklisted_stringsbody_required_stringstitle_text_min_lengthis_flair_requiredtitle_text_max_lengthbody_regexeslink_repost_agebody_text_min_lengthlink_restriction_policybody_text_max_lengthtitle_required_stringstitle_blacklisted_stringsguidelines_textguidelines_display_policy
For example, to fetch the post requirements for r/test:
print(reddit.subreddit("test").post_requirements)
- quaran()¶
Provide an instance of
SubredditQuarantine.This property is named
quaranbecausequarantineis a subreddit attribute returned by Reddit to indicate whether or not a subreddit is quarantined.To opt-in into a quarantined subreddit:
reddit.subreddit("test").quaran.opt_in()
- Return type:
- rising(**generator_kwargs)¶
Return a
ListingGeneratorfor rising submissions.Additional keyword arguments are passed in the initialization of
ListingGenerator.For example, to get rising submissions for r/test:
for submission in reddit.subreddit("test").rising(): print(submission.title)
- rules()¶
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:
for rule in reddit.subreddit("test").rules: print(rule)
Moderators can also add rules to the subreddit. For example, to make a rule called
"No spam"in r/test:reddit.subreddit("test").rules.mod.add( short_name="No spam", kind="all", description="Do not spam. Spam bad" )
- Return type:
- search(query, *, sort='relevance', syntax='lucene', time_filter='all', **generator_kwargs)¶
Return a
ListingGeneratorfor items that matchquery.- Parameters:
query (
str) – The query string to search for.sort (
str) – Can be one of:"relevance","hot","top","new", or"comments". (default:"relevance").syntax (
str) – Can be one of:"cloudsearch","lucene", or"plain"(default:"lucene").time_filter (
str) – Can be one of:"all","day","hour","month","week", or"year"(default:"all").generator_kwargs (Any)
- Return type:
For more information on building a search query see: https://www.reddit.com/wiki/search
For example, to search all subreddits for
"praw"try:for submission in reddit.subreddit("all").search("praw"): print(submission.title)
- sticky(*, number=1)¶
Return a
Submissionobject for a sticky of the subreddit.- Parameters:
number (
int) – Specify which sticky to return. 1 appears at the top (default:1).- Raises:
prawcore.NotFoundif the sticky does not exist.- Return type:
For example, to get the stickied post on r/test:
reddit.subreddit("test").sticky()
- stream()¶
Provide an instance of
SubredditStream.Streams can be used to indefinitely retrieve new comments made to a subreddit, like:
for comment in reddit.subreddit("test").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:
for submission in reddit.subreddit("all").stream.submissions(): print(submission)
- Return type:
- stylesheet()¶
Provide an instance of
SubredditStylesheet.For example, to add the css data
.test{color:blue}to the existing stylesheet:subreddit = reddit.subreddit("test") stylesheet = subreddit.stylesheet() stylesheet.stylesheet += ".test{color:blue}" subreddit.stylesheet.update(stylesheet.stylesheet)
- Return type:
- submit(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)¶
Add a submission to the
Subreddit.- Parameters:
title (
str) – The title of the submission.collection_id (
str|None) – The UUID of aCollectionto add the newly-submitted post to.discussion_type (
str|None) – Set to"CHAT"to enable live discussion instead of traditional comments (default:None).flair_id (
str|None) – The flair template to select (default:None).flair_text (
str|None) – If the template’sflair_text_editablevalue isTrue, this value will set a custom text (default:None).flair_idis required whenflair_textis provided.inline_media (
dict[str,InlineMedia] |None) – A dict ofInlineMediaobjects where the key is the placeholder name inselftext. Link post selftext does not support inline media.nsfw (
bool) – Whether the submission should be marked NSFW (default:False).resubmit (
bool) – WhenFalse, an error will occur if the URL has already been submitted (default:True).selftext (
str|None) – The Markdown formatted content for atextsubmission or an optional post body forlinksubmissions. Use an empty string,"", to make a title-only submission.send_replies (
bool) – WhenTrue, messages will be sent to the submission author when comments are made to the submission (default:True).spoiler (
bool) – Whether the submission should be marked as a spoiler (default:False).
- Return type:
- Returns:
A
Submissionobject for the newly created submission.
Provide
selftextalone for atextsubmission.selftextcan accompany aurlfor alinksubmission.selftextthat accompanies alinksubmission is optional.selftextforlinksubmissions does not supportinline_media.For example, to submit a URL to r/test do:
title = "PRAW documentation" url = "https://praw.readthedocs.io" reddit.subreddit("test").submit(title, url=url)
For example, to submit a self post with inline media do:
from praw.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} reddit.subreddit("test").submit("title", inline_media=media, selftext=selftext)
Note
Inserted media will have a padding of
\\n\\nautomatically 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  an image  and video  inline
Note
To submit a post to a subreddit with the
"news"flair, you can get the flair id like this:choices = list(subreddit.flair.link_templates.user_selectable()) template_id = next(x for x in choices if x["flair_text"] == "news")["flair_template_id"] subreddit.submit("title", flair_id=template_id, url="https://www.news.com/")
See also
submit_gallery()to submit more than one image in the same postsubmit_image()to submit imagessubmit_poll()to submit pollssubmit_video()to submit videos and videogifs
- submit_gallery(title, images, *, collection_id=None, discussion_type=None, flair_id=None, flair_text=None, nsfw=False, selftext=None, send_replies=True, spoiler=False)¶
Add an image gallery submission to the subreddit.
- Parameters:
title (
str) – The title of the submission.images (
list[dict[str,str]]) – The images to post in dict with the following structure:{"image_path": "path", "caption": "caption", "outbound_url": "url"}, onlyimage_pathis required.collection_id (
str|None) – The UUID of aCollectionto add the newly-submitted post to.discussion_type (
str|None) – Set to"CHAT"to enable live discussion instead of traditional comments (default:None).flair_id (
str|None) – The flair template to select (default:None).flair_text (
str|None) – If the template’sflair_text_editablevalue isTrue, this value will set a custom text (default:None).flair_idis required whenflair_textis provided.nsfw (
bool) – Whether the submission should be marked NSFW (default:False).selftext (
str|None) – Optional Markdown-formatted post body content (default:None).send_replies (
bool) – WhenTrue, messages will be sent to the submission author when comments are made to the submission (default:True).spoiler (
bool) – Whether the submission should be marked asa spoiler (default:False).
- Return type:
- Returns:
A
Submissionobject for the newly created submission.- Raises:
ClientExceptionifimage_pathinimagesrefers 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", }, ] reddit.subreddit("test").submit_gallery(title, images)
See also
submit()to submit url posts and selftextssubmit_image()to submit single imagessubmit_poll()to submit pollssubmit_video()to submit videos and videogifs
- submit_image(title, image_path, *, collection_id=None, discussion_type=None, flair_id=None, flair_text=None, nsfw=False, resubmit=True, selftext=None, send_replies=True, spoiler=False, timeout=10, without_websockets=False)¶
Add an image submission to the subreddit.
- Parameters:
collection_id (
str|None) – The UUID of aCollectionto add the newly-submitted post to.discussion_type (
str|None) – Set to"CHAT"to enable live discussion instead of traditional comments (default:None).flair_id (
str|None) – The flair template to select (default:None).flair_text (
str|None) – If the template’sflair_text_editablevalue isTrue, this value will set a custom text (default:None).flair_idis required whenflair_textis provided.image_path (
str) – The path to an image, to upload and post.nsfw (
bool) – Whether the submission should be marked NSFW (default:False).resubmit (
bool) – WhenFalse, an error will occur if the URL has already been submitted (default:True).selftext (
str|None) – Optional Markdown-formatted post body content (default:None).send_replies (
bool) – WhenTrue, messages will be sent to the submission author when comments are made to the submission (default:True).spoiler (
bool) – Whether the submission should be marked as a spoiler (default:False).timeout (
int) – Specifies a particular timeout, in seconds. Use to avoid “Websocket error” exceptions (default:10).title (
str) – The title of the submission.without_websockets (
bool) – Set toTrueto disable use of WebSockets (see note below for an explanation). IfTrue, this method doesn’t return anything (default:False).
- Return type:
- Returns:
A
Submissionobject for the newly created submission, unlesswithout_websocketsisTrue.- Raises:
ClientExceptionifimage_pathrefers 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 thetimeoutparameter to a value above 10.To disable the use of WebSockets, set
without_websockets=True. This will make the method returnNone, 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" reddit.subreddit("test").submit_image(title, image)
See also
submit()to submit url posts and selftextssubmit_gallery()to submit more than one image in the same postsubmit_poll()to submit pollssubmit_video()to submit videos and videogifs
- submit_poll(title, *, collection_id=None, discussion_type=None, duration, flair_id=None, flair_text=None, nsfw=False, options, resubmit=True, selftext, send_replies=True, spoiler=False)¶
Add a poll submission to the subreddit.
- Parameters:
title (
str) – The title of the submission.collection_id (
str|None) – The UUID of aCollectionto add the newly-submitted post to.discussion_type (
str|None) – Set to"CHAT"to enable live discussion instead of traditional comments (default:None).duration (
int) – The number of days the poll should accept votes, as anint. Valid values are between1and7, inclusive.flair_id (
str|None) – The flair template to select (default:None).flair_text (
str|None) – If the template’sflair_text_editablevalue isTrue, this value will set a custom text (default:None).flair_idis required whenflair_textis provided.nsfw (
bool) – Whether the submission should be marked NSFW (default:False).options (
list[str]) – A list of two to six poll options asstr.resubmit (
bool) – WhenFalse, an error will occur if the URL has already been submitted (default:True).selftext (
str) – The Markdown formatted content for the submission. Use an empty string,"", to make a submission with no text contents.send_replies (
bool) – WhenTrue, messages will be sent to the submission author when comments are made to the submission (default:True).spoiler (
bool) – Whether the submission should be marked as a spoiler (default:False).
- Return type:
- Returns:
A
Submissionobject for the newly created submission.
For example, to submit a poll to r/test do:
title = "Do you like PRAW?" reddit.subreddit("test").submit_poll( title, selftext="", options=["Yes", "No"], duration=3 )
See also
submit()to submit url posts and selftextssubmit_gallery()to submit more than one image in the same postsubmit_image()to submit single imagessubmit_video()to submit videos and videogifs
- submit_video(title, video_path, *, collection_id=None, discussion_type=None, flair_id=None, flair_text=None, nsfw=False, resubmit=True, selftext=None, send_replies=True, spoiler=False, thumbnail_path=None, timeout=10, videogif=False, without_websockets=False)¶
Add a video or videogif submission to the subreddit.
- Parameters:
title (
str) – The title of the submission.video_path (
str) – The path to a video, to upload and post.collection_id (
str|None) – The UUID of aCollectionto add the newly-submitted post to.discussion_type (
str|None) – Set to"CHAT"to enable live discussion instead of traditional comments (default:None).flair_id (
str|None) – The flair template to select (default:None).flair_text (
str|None) – If the template’sflair_text_editablevalue isTrue, this value will set a custom text (default:None).flair_idis required whenflair_textis provided.nsfw (
bool) – Whether the submission should be marked NSFW (default:False).resubmit (
bool) – WhenFalse, an error will occur if the URL has already been submitted (default:True).selftext (
str|None) – Optional Markdown-formatted post body content (default:None).send_replies (
bool) – WhenTrue, messages will be sent to the submission author when comments are made to the submission (default:True).spoiler (
bool) – Whether the submission should be marked as a spoiler (default:False).thumbnail_path (
str|None) – 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 (
int) – Specifies a particular timeout, in seconds. Use to avoid “Websocket error” exceptions (default:10).videogif (
bool) – IfTrue, the video is uploaded as a videogif, which is essentially a silent video (default:False).without_websockets (
bool) – Set toTrueto disable use of WebSockets (see note below for an explanation). IfTrue, this method doesn’t return anything (default:False).
- Return type:
- Returns:
A
Submissionobject for the newly created submission, unlesswithout_websocketsisTrue.- Raises:
ClientExceptionifvideo_pathrefers 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 thetimeoutparameter to a value above 10.To disable the use of WebSockets, set
without_websockets=True. This will make the method returnNone, 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" reddit.subreddit("test").submit_video(title, video)
See also
submit()to submit url posts and selftextssubmit_image()to submit imagessubmit_gallery()to submit more than one image in the same postsubmit_poll()to submit polls
- subscribe(*, other_subreddits=None)¶
Subscribe to the subreddit.
- Parameters:
other_subreddits (
list[Subreddit] |None) – When provided, also subscribe to the provided list of subreddits.- Return type:
For example, to subscribe to r/test:
reddit.subreddit("test").subscribe()
- top(*, time_filter='all', **generator_kwargs)¶
Return a
ListingGeneratorfor top items.- Parameters:
- Raises:
ValueErroriftime_filteris invalid.- Return type:
Additional keyword arguments are passed in the initialization of
ListingGenerator.This method can be used like:
reddit.domain("imgur.com").top(time_filter="week") reddit.multireddit(redditor="samuraisam", name="programming").top(time_filter="day") reddit.redditor("spez").top(time_filter="month") reddit.redditor("spez").comments.top(time_filter="year") reddit.redditor("spez").submissions.top(time_filter="all") reddit.subreddit("all").top(time_filter="hour")
- traffic()¶
Return a dictionary of the
Subreddit’s traffic statistics.- Raises:
prawcore.NotFoundwhen 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.- Return type:
The traffic method returns a dict with three keys. The keys are
day,hourandmonth. 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 thedaykey, start of the hour for thehourkey, etc.). The second, third, and fourth values indicate the unique pageviews, total pageviews, and subscribers, respectively.Note
The
hourkey does not contain subscribers, and therefore each sub-list contains three values.For example, to get the traffic stats for r/test:
stats = reddit.subreddit("test").traffic()
- unsubscribe(*, other_subreddits=None)¶
Unsubscribe from the subreddit.
- Parameters:
other_subreddits (
list[Subreddit] |None) – When provided, also unsubscribe from the provided list of subreddits.- Return type:
To unsubscribe from r/test:
reddit.subreddit("test").unsubscribe()
- widgets()¶
Provide an instance of
SubredditWidgets.Example usage
Get all sidebar widgets:
for widget in reddit.subreddit("test").widgets.sidebar: print(widget)
Get ID card widget:
print(reddit.subreddit("test").widgets.id_card)
- Return type:
- wiki()¶
Provide an instance of
SubredditWiki.This attribute can be used to discover all wikipages for a subreddit:
for wikipage in reddit.subreddit("test").wiki: print(wikipage)
To fetch the content for a given wikipage try:
wikipage = reddit.subreddit("test").wiki["proof"] print(wikipage.content_md)
- Return type: