INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Delete the currently authenticated redditor.
WARNING!
This action is IRREVERSIBLE. Use only if you're okay with NEVER
accessing this reddit account again.
:param password: password for currently authenticated account
:param message: optional 'reason for deletion' message.
... | def delete(self, password, message=""):
"""Delete the currently authenticated redditor.
WARNING!
This action is IRREVERSIBLE. Use only if you're okay with NEVER
accessing this reddit account again.
:param password: password for currently authenticated account
:param me... |
Create or edit a wiki page with title `page` for `subreddit`.
:returns: The json response from the server. | def edit_wiki_page(self, subreddit, page, content, reason=''):
"""Create or edit a wiki page with title `page` for `subreddit`.
:returns: The json response from the server.
"""
data = {'content': content,
'page': page,
'r': six.text_type(subreddit),
... |
Return the access information for an OAuth2 authorization grant.
:param code: the code received in the request from the OAuth2 server
:param update_session: Update the current session with the retrieved
token(s).
:returns: A dictionary with the key/value pairs for access_token,
... | def get_access_information(self, code, # pylint: disable=W0221
update_session=True):
"""Return the access information for an OAuth2 authorization grant.
:param code: the code received in the request from the OAuth2 server
:param update_session: Update the current... |
Return available flair choices and current flair.
:param link: If link is given, return the flair options for this
submission. Not normally given directly, but instead set by calling
the flair_choices method for Submission objects.
Use the default for the session's user.
... | def get_flair_choices(self, subreddit, link=None):
"""Return available flair choices and current flair.
:param link: If link is given, return the flair options for this
submission. Not normally given directly, but instead set by calling
the flair_choices method for Submission ob... |
Return a UserList of Redditors with whom the user is friends. | def get_friends(self, **params):
"""Return a UserList of Redditors with whom the user is friends."""
url = self.config['friends']
return self.request_json(url, params=params)[0] |
Return a LoggedInRedditor object.
Note: This function is only intended to be used with an 'identity'
providing OAuth2 grant. | def get_me(self):
"""Return a LoggedInRedditor object.
Note: This function is only intended to be used with an 'identity'
providing OAuth2 grant.
"""
response = self.request_json(self.config['me'])
user = objects.Redditor(self, response['name'], response)
user.__... |
Return True if OAuth2 authorized for the passed in scope(s). | def has_scope(self, scope):
"""Return True if OAuth2 authorized for the passed in scope(s)."""
if not self.is_oauth_session():
return False
if '*' in self._authentication:
return True
if isinstance(scope, six.string_types):
scope = [scope]
retu... |
Login to a reddit site.
**DEPRECATED**. Will be removed in a future version of PRAW.
https://www.reddit.com/comments/2ujhkr/
https://www.reddit.com/comments/37e2mv/
Look for username first in parameter, then praw.ini and finally if both
were empty get it from stdin. Look for p... | def login(self, username=None, password=None, **kwargs):
"""Login to a reddit site.
**DEPRECATED**. Will be removed in a future version of PRAW.
https://www.reddit.com/comments/2ujhkr/
https://www.reddit.com/comments/37e2mv/
Look for username first in parameter, then praw.ini ... |
Return updated access information for an OAuth2 authorization grant.
:param refresh_token: The refresh token used to obtain the updated
information. When not provided, use the stored refresh_token.
:param update_session: Update the session with the returned data.
:returns: A diction... | def refresh_access_information(self, # pylint: disable=W0221
refresh_token=None,
update_session=True):
"""Return updated access information for an OAuth2 authorization grant.
:param refresh_token: The refresh token used to obtain th... |
Select user flair or link flair on subreddits.
This can only be used for assigning your own name flair or link flair
on your own submissions. For assigning other's flairs using moderator
access, see :meth:`~praw.__init__.ModFlairMixin.set_flair`.
:param item: A string, Subreddit object... | def select_flair(self, item, flair_template_id='', flair_text=''):
"""Select user flair or link flair on subreddits.
This can only be used for assigning your own name flair or link flair
on your own submissions. For assigning other's flairs using moderator
access, see :meth:`~praw.__ini... |
Set the credentials used for OAuth2 authentication.
Calling this function will overwrite any currently existing access
credentials.
:param scope: A set of reddit scopes the tokens provide access to
:param access_token: the access token of the authentication
:param refresh_token... | def set_access_credentials(self, scope, access_token, refresh_token=None,
update_user=True):
"""Set the credentials used for OAuth2 authentication.
Calling this function will overwrite any currently existing access
credentials.
:param scope: A set of redd... |
Create a new subreddit.
:returns: The json response from the server.
This function may result in a captcha challenge. PRAW will
automatically prompt you for a response. See :ref:`handling-captchas`
if you want to manually handle captchas. | def create_subreddit(self, name, title, description='', language='en',
subreddit_type='public', content_options='any',
over_18=False, default_set=True, show_media=False,
domain='', wikimode='disabled', captcha=None,
**kw... |
Delete an image from the subreddit.
:param name: The name of the image if removing a CSS image.
:param header: When true, delete the subreddit header.
:returns: The json response from the server. | def delete_image(self, subreddit, name=None, header=False):
"""Delete an image from the subreddit.
:param name: The name of the image if removing a CSS image.
:param header: When true, delete the subreddit header.
:returns: The json response from the server.
"""
subredd... |
Set the settings for the given subreddit.
:param subreddit: Must be a subreddit object.
:returns: The json response from the server. | def set_settings(self, subreddit, title, public_description='',
description='', language='en', subreddit_type='public',
content_options='any', over_18=False, default_set=True,
show_media=False, domain='', domain_css=False,
domain_sideba... |
Set stylesheet for the given subreddit.
:returns: The json response from the server. | def set_stylesheet(self, subreddit, stylesheet):
"""Set stylesheet for the given subreddit.
:returns: The json response from the server.
"""
subreddit = six.text_type(subreddit)
data = {'r': subreddit,
'stylesheet_contents': stylesheet,
'op': 'sa... |
Upload an image to the subreddit.
:param image_path: A path to the jpg or png image you want to upload.
:param name: The name to provide the image. When None the name will be
filename less any extension.
:param header: When True, upload the image as the subreddit header.
:pa... | def upload_image(self, subreddit, image_path, name=None,
header=False, upload_as=None):
"""Upload an image to the subreddit.
:param image_path: A path to the jpg or png image you want to upload.
:param name: The name to provide the image. When None the name will be
... |
Update only the given settings for the given subreddit.
The settings to update must be given by keyword and match one of the
parameter names in `set_settings`.
:returns: The json response from the server. | def update_settings(self, subreddit, **kwargs):
"""Update only the given settings for the given subreddit.
The settings to update must be given by keyword and match one of the
parameter names in `set_settings`.
:returns: The json response from the server.
"""
settings ... |
Add a flair template to the given subreddit.
:returns: The json response from the server. | def add_flair_template(self, subreddit, text='', css_class='',
text_editable=False, is_link=False):
"""Add a flair template to the given subreddit.
:returns: The json response from the server.
"""
data = {'r': six.text_type(subreddit),
'text':... |
Clear flair templates for the given subreddit.
:returns: The json response from the server. | def clear_flair_templates(self, subreddit, is_link=False):
"""Clear flair templates for the given subreddit.
:returns: The json response from the server.
"""
data = {'r': six.text_type(subreddit),
'flair_type': 'LINK_FLAIR' if is_link else 'USER_FLAIR'}
return s... |
Configure the flair setting for the given subreddit.
:returns: The json response from the server. | def configure_flair(self, subreddit, flair_enabled=False,
flair_position='right',
flair_self_assign=False,
link_flair_enabled=False,
link_flair_position='left',
link_flair_self_assign=False):
... |
Delete the flair for the given user on the given subreddit.
:returns: The json response from the server. | def delete_flair(self, subreddit, user):
"""Delete the flair for the given user on the given subreddit.
:returns: The json response from the server.
"""
data = {'r': six.text_type(subreddit),
'name': six.text_type(user)}
return self.request_json(self.config['del... |
Return a get_content generator of flair mappings.
:param subreddit: Either a Subreddit object or the name of the
subreddit to return the flair list for.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url`, `root_field`, `thing_field`, and
... | def get_flair_list(self, subreddit, *args, **kwargs):
"""Return a get_content generator of flair mappings.
:param subreddit: Either a Subreddit object or the name of the
subreddit to return the flair list for.
The additional parameters are passed directly into
:meth:`.get_c... |
Set flair for the user in the given subreddit.
`item` can be a string, Redditor object, or Submission object.
If `item` is a string it will be treated as the name of a Redditor.
This method can only be called by a subreddit moderator with flair
permissions. To set flair on yourself or ... | def set_flair(self, subreddit, item, flair_text='', flair_css_class=''):
"""Set flair for the user in the given subreddit.
`item` can be a string, Redditor object, or Submission object.
If `item` is a string it will be treated as the name of a Redditor.
This method can only be called b... |
Return a get_content generator for moderation log items.
:param subreddit: Either a Subreddit object or the name of the
subreddit to return the modlog for.
:param mod: If given, only return the actions made by this moderator.
Both a moderator name or Redditor object can be used ... | def get_mod_log(self, subreddit, mod=None, action=None, *args, **kwargs):
"""Return a get_content generator for moderation log items.
:param subreddit: Either a Subreddit object or the name of the
subreddit to return the modlog for.
:param mod: If given, only return the actions made... |
Return a get_content generator of banned users for the subreddit.
:param subreddit: The subreddit to get the banned user list for.
:param user_only: When False, the generator yields a dictionary of data
associated with the server response for that user. In such cases,
the Reddit... | def get_banned(self, subreddit, user_only=True, *args, **kwargs):
"""Return a get_content generator of banned users for the subreddit.
:param subreddit: The subreddit to get the banned user list for.
:param user_only: When False, the generator yields a dictionary of data
associated ... |
Set flair for a group of users in the given subreddit.
flair_mapping should be a list of dictionaries with the following keys:
`user`: the user name,
`flair_text`: the flair text for the user (optional),
`flair_css_class`: the flair css class for the user (optional)
:retu... | def set_flair_csv(self, subreddit, flair_mapping):
"""Set flair for a group of users in the given subreddit.
flair_mapping should be a list of dictionaries with the following keys:
`user`: the user name,
`flair_text`: the flair text for the user (optional),
`flair_css_clas... |
Return a get_content generator of contributors for the given subreddit.
If it's a public subreddit, then authentication as a
moderator of the subreddit is required. For protected/private
subreddits only access is required. See issue #246. | def get_contributors(self, subreddit, *args, **kwargs):
"""
Return a get_content generator of contributors for the given subreddit.
If it's a public subreddit, then authentication as a
moderator of the subreddit is required. For protected/private
subreddits only access is requir... |
Return a get_content generator of edited items.
:param subreddit: Either a Subreddit object or the name of the
subreddit to return the edited items for. Defaults to `mod` which
includes items for all the subreddits you moderate.
The additional parameters are passed directly int... | def get_edited(self, subreddit='mod', *args, **kwargs):
"""Return a get_content generator of edited items.
:param subreddit: Either a Subreddit object or the name of the
subreddit to return the edited items for. Defaults to `mod` which
includes items for all the subreddits you m... |
Return the stylesheet and images for the given subreddit. | def get_stylesheet(self, subreddit, **params):
"""Return the stylesheet and images for the given subreddit."""
url = self.config['stylesheet'].format(
subreddit=six.text_type(subreddit))
return self.request_json(url, params=params)['data'] |
Abdicate moderator status in a subreddit. Use with care.
:param subreddit: The name of the subreddit to leave `status` from.
:returns: the json response from the server. | def leave_moderator(self, subreddit):
"""Abdicate moderator status in a subreddit. Use with care.
:param subreddit: The name of the subreddit to leave `status` from.
:returns: the json response from the server.
"""
self.evict(self.config['my_mod_subreddits'])
return sel... |
Abdicate status in a subreddit.
:param subreddit: The name of the subreddit to leave `status` from.
:param statusurl: The API URL which will be used in the leave request.
Please use :meth:`leave_contributor` or :meth:`leave_moderator`
rather than setting this directly.
... | def _leave_status(self, subreddit, statusurl):
"""Abdicate status in a subreddit.
:param subreddit: The name of the subreddit to leave `status` from.
:param statusurl: The API URL which will be used in the leave request.
Please use :meth:`leave_contributor` or :meth:`leave_moderator... |
Copy a multireddit.
:param from_redditor: The username or Redditor object for the user
who owns the original multireddit
:param from_name: The name of the multireddit, belonging to
from_redditor
:param to_name: The name to copy the multireddit as. If None, uses
... | def copy_multireddit(self, from_redditor, from_name, to_name=None,
*args, **kwargs):
"""Copy a multireddit.
:param from_redditor: The username or Redditor object for the user
who owns the original multireddit
:param from_name: The name of the multireddit, be... |
Create a new multireddit.
:param name: The name of the new multireddit.
:param description_md: Optional description for the multireddit,
formatted in markdown.
:param icon_name: Optional, choose an icon name from this list: ``art
and design``, ``ask``, ``books``, ``busin... | def create_multireddit(self, name, description_md=None, icon_name=None,
key_color=None, subreddits=None, visibility=None,
weighting_scheme=None, overwrite=False,
*args, **kwargs): # pylint: disable=W0613
"""Create a new multireddi... |
Delete a Multireddit.
Any additional parameters are passed directly into
:meth:`~praw.__init__.BaseReddit.request` | def delete_multireddit(self, name, *args, **kwargs):
"""Delete a Multireddit.
Any additional parameters are passed directly into
:meth:`~praw.__init__.BaseReddit.request`
"""
url = self.config['multireddit_about'].format(user=self.user.name,
... |
Edit a multireddit, or create one if it doesn't already exist.
See :meth:`create_multireddit` for accepted parameters. | def edit_multireddit(self, *args, **kwargs):
"""Edit a multireddit, or create one if it doesn't already exist.
See :meth:`create_multireddit` for accepted parameters.
"""
return self.create_multireddit(*args, overwrite=True, **kwargs) |
Return a Multireddit object for the author and name specified.
:param redditor: The username or Redditor object of the user
who owns the multireddit.
:param multi: The name of the multireddit to fetch.
The additional parameters are passed directly into the
:class:`.Multired... | def get_multireddit(self, redditor, multi, *args, **kwargs):
"""Return a Multireddit object for the author and name specified.
:param redditor: The username or Redditor object of the user
who owns the multireddit.
:param multi: The name of the multireddit to fetch.
The addi... |
Return a list of multireddits belonging to a redditor.
:param redditor: The username or Redditor object to find multireddits
from.
:returns: The json response from the server
The additional parameters are passed directly into
:meth:`~praw.__init__.BaseReddit.request_json`
... | def get_multireddits(self, redditor, *args, **kwargs):
"""Return a list of multireddits belonging to a redditor.
:param redditor: The username or Redditor object to find multireddits
from.
:returns: The json response from the server
The additional parameters are passed dire... |
Rename a Multireddit.
:param current_name: The name of the multireddit to rename
:param new_name: The new name to assign to this multireddit
The additional parameters are passed directly into
:meth:`~praw.__init__.BaseReddit.request_json` | def rename_multireddit(self, current_name, new_name, *args, **kwargs):
"""Rename a Multireddit.
:param current_name: The name of the multireddit to rename
:param new_name: The new name to assign to this multireddit
The additional parameters are passed directly into
:meth:`~praw... |
Return a get_content generator of subreddits.
The Subreddits generated are those where the session's user is a
contributor.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered. | def get_my_contributions(self, *args, **kwargs):
"""Return a get_content generator of subreddits.
The Subreddits generated are those where the session's user is a
contributor.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter can... |
Return a get_content generator of subreddits.
The Subreddits generated are those where the session's user is a
moderator.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered. | def get_my_moderation(self, *args, **kwargs):
"""Return a get_content generator of subreddits.
The Subreddits generated are those where the session's user is a
moderator.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot b... |
Return a get_content generator of subreddits.
The subreddits generated are those that hat the session's user is
subscribed to.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered. | def get_my_subreddits(self, *args, **kwargs):
"""Return a get_content generator of subreddits.
The subreddits generated are those that hat the session's user is
subscribed to.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter can... |
Mark each of the supplied thing_ids as (un)read.
:returns: The json response from the server. | def _mark_as_read(self, thing_ids, unread=False):
"""Mark each of the supplied thing_ids as (un)read.
:returns: The json response from the server.
"""
data = {'id': ','.join(thing_ids)}
key = 'unread_message' if unread else 'read_message'
response = self.request_json(se... |
Return a get_content generator for inboxed comment replies.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered. | def get_comment_replies(self, *args, **kwargs):
"""Return a get_content generator for inboxed comment replies.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered.
"""
return self.get_content(self.config['comment_... |
Return a get_content generator for inbox (messages and comments).
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered. | def get_inbox(self, *args, **kwargs):
"""Return a get_content generator for inbox (messages and comments).
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered.
"""
return self.get_content(self.config['inbox'], *ar... |
Return a Message object corresponding to the given ID.
:param message_id: The ID or Fullname for a Message
The additional parameters are passed directly into
:meth:`~praw.objects.Message.from_id` of Message, and subsequently into
:meth:`.request_json`. | def get_message(self, message_id, *args, **kwargs):
"""Return a Message object corresponding to the given ID.
:param message_id: The ID or Fullname for a Message
The additional parameters are passed directly into
:meth:`~praw.objects.Message.from_id` of Message, and subsequently into
... |
Return a get_content generator for inboxed submission replies.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered. | def get_post_replies(self, *args, **kwargs):
"""Return a get_content generator for inboxed submission replies.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered.
"""
return self.get_content(self.config['post_rep... |
Return a get_content generator for sent messages.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered. | def get_sent(self, *args, **kwargs):
"""Return a get_content generator for sent messages.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered.
"""
return self.get_content(self.config['sent'], *args, **kwargs) |
Return a get_content generator for unread messages.
:param unset_has_mail: When True, clear the has_mail flag (orangered)
for the user.
:param update_user: If both `unset_has_mail` and `update user` is True,
set the `has_mail` attribute of the logged-in user to False.
T... | def get_unread(self, unset_has_mail=False, update_user=False, *args,
**kwargs):
"""Return a get_content generator for unread messages.
:param unset_has_mail: When True, clear the has_mail flag (orangered)
for the user.
:param update_user: If both `unset_has_mail` ... |
Return a get_content generator for username mentions.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered. | def get_mentions(self, *args, **kwargs):
"""Return a get_content generator for username mentions.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered.
"""
return self.get_content(self.config['mentions'], *args, **... |
Send a message to a redditor or a subreddit's moderators (mod mail).
:param recipient: A Redditor or Subreddit instance to send a message
to. A string can also be used in which case the string is treated
as a redditor unless it is prefixed with either '/r/' or '#', in
which ... | def send_message(self, recipient, subject, message, from_sr=None,
captcha=None, **kwargs):
"""Send a message to a redditor or a subreddit's moderators (mod mail).
:param recipient: A Redditor or Subreddit instance to send a message
to. A string can also be used in which... |
Hide one or multiple objects in the context of the logged in user.
:param thing_id: A single fullname or list of fullnames,
representing objects which will be hidden.
:param _unhide: If True, unhide the object(s) instead. Use
:meth:`~praw.__init__.ReportMixin.unhide` rather than... | def hide(self, thing_id, _unhide=False):
"""Hide one or multiple objects in the context of the logged in user.
:param thing_id: A single fullname or list of fullnames,
representing objects which will be hidden.
:param _unhide: If True, unhide the object(s) instead. Use
:... |
Comment on the given thing with the given text.
:returns: A Comment object for the newly created comment. | def _add_comment(self, thing_id, text):
"""Comment on the given thing with the given text.
:returns: A Comment object for the newly created comment.
"""
def add_comment_helper(self, thing_id, text):
data = {'thing_id': thing_id,
'text': text}
... |
Submit a new link to the given subreddit.
Accepts either a Subreddit object or a str containing the subreddit's
display name.
:param resubmit: If True, submit the link even if it has already been
submitted.
:param save: If True the new Submission will be saved after creatio... | def submit(self, subreddit, title, text=None, url=None, captcha=None,
save=None, send_replies=None, resubmit=None, **kwargs):
"""Submit a new link to the given subreddit.
Accepts either a Subreddit object or a str containing the subreddit's
display name.
:param resubmit:... |
Subscribe to the given subreddit.
:param subreddit: Either the subreddit name or a subreddit object.
:param unsubscribe: When True, unsubscribe.
:returns: The json response from the server. | def subscribe(self, subreddit, unsubscribe=False):
"""Subscribe to the given subreddit.
:param subreddit: Either the subreddit name or a subreddit object.
:param unsubscribe: When True, unsubscribe.
:returns: The json response from the server.
"""
data = {'action': 'uns... |
Some custom patches on top of the python webbrowser module to fix
user reported bugs and limitations of the module. | def patch_webbrowser():
"""
Some custom patches on top of the python webbrowser module to fix
user reported bugs and limitations of the module.
"""
# https://bugs.python.org/issue31014
# https://github.com/michael-lazar/rtv/issues/588
def register_patch(name, klass, instance=None, update_tr... |
Setup terminal and initialize curses. Most of this copied from
curses.wrapper in order to convert the wrapper into a context manager. | def curses_session():
"""
Setup terminal and initialize curses. Most of this copied from
curses.wrapper in order to convert the wrapper into a context manager.
"""
try:
# Curses must wait for some time after the Escape key is pressed to
# check if it is the beginning of an escape se... |
Move the cursor up or down by the given increment.
Params:
direction (int): `1` will move the cursor down one item and `-1`
will move the cursor up one item.
n_windows (int): The number of items that are currently being drawn
on the screen.
Retur... | def move(self, direction, n_windows):
"""
Move the cursor up or down by the given increment.
Params:
direction (int): `1` will move the cursor down one item and `-1`
will move the cursor up one item.
n_windows (int): The number of items that are currently... |
Move the page down (positive direction) or up (negative direction).
Paging down:
The post on the bottom of the page becomes the post at the top of
the page and the cursor is moved to the top.
Paging up:
The post at the top of the page becomes the post at the bottom o... | def move_page(self, direction, n_windows):
"""
Move the page down (positive direction) or up (negative direction).
Paging down:
The post on the bottom of the page becomes the post at the top of
the page and the cursor is moved to the top.
Paging up:
T... |
Flip the orientation of the page. | def flip(self, n_windows):
"""
Flip the orientation of the page.
"""
assert n_windows >= 0
self.page_index += (self.step * n_windows)
self.cursor_index = n_windows
self.inverted = not self.inverted
self.top_item_height = None |
Parse a key represented by a string and return its character code. | def parse(cls, key):
"""
Parse a key represented by a string and return its character code.
"""
try:
if isinstance(key, int):
return key
elif re.match('[<]KEY_.*[>]', key):
# Curses control character
return getattr(... |
Guess based on the file extension.
Args:
url (text): Web url that was linked to by a reddit submission.
Returns:
modified_url (text): The url (or filename) that will be used when
constructing the command to run.
content_type (text): The mime-type tha... | def get_mimetype(url):
"""
Guess based on the file extension.
Args:
url (text): Web url that was linked to by a reddit submission.
Returns:
modified_url (text): The url (or filename) that will be used when
constructing the command to run.
... |
Re-download all submissions and reset the page index | def refresh_content(self, order=None, name=None):
"""
Re-download all submissions and reset the page index
"""
order = order or self.content.order
# Preserve the query if staying on the current page
if name is None:
query = self.content.query
else:
... |
Open a prompt to search the given subreddit | def search_subreddit(self, name=None):
"""
Open a prompt to search the given subreddit
"""
name = name or self.content.name
query = self.term.prompt_input('Search {0}: '.format(name))
if not query:
return
with self.term.loader('Searching'):
... |
If on a subreddit, remember it and head back to the front page.
If this was pressed on the front page, go back to the last subreddit. | def show_frontpage(self):
"""
If on a subreddit, remember it and head back to the front page.
If this was pressed on the front page, go back to the last subreddit.
"""
if self.content.name != '/r/front':
target = '/r/front'
self.toggled_subreddit = self.c... |
Select the current submission to view posts. | def open_submission(self, url=None):
"""
Select the current submission to view posts.
"""
if url is None:
data = self.get_selected_item()
url = data['permalink']
if data.get('url_type') == 'selfpost':
self.config.history.add(data['url_f... |
Open a link with the webbrowser | def open_link(self):
"""
Open a link with the webbrowser
"""
data = self.get_selected_item()
if data['url_type'] == 'selfpost':
self.open_submission()
elif data['url_type'] == 'x-post subreddit':
self.refresh_content(order='ignore', name=data['xpo... |
Post a new submission to the given subreddit. | def post_submission(self):
"""
Post a new submission to the given subreddit.
"""
# Check that the subreddit can be submitted to
name = self.content.name
if '+' in name or name in ('/r/all', '/r/front', '/r/me', '/u/saved'):
self.term.show_notification("Can't p... |
Re-download comments and reset the page index | def refresh_content(self, order=None, name=None):
"""
Re-download comments and reset the page index
"""
order = order or self.content.order
url = name or self.content.name
# Hack to allow an order specified in the name by prompt_subreddit() to
# override the curr... |
Toggle the selected comment tree between visible and hidden | def toggle_comment(self):
"""
Toggle the selected comment tree between visible and hidden
"""
current_index = self.nav.absolute_index
self.content.toggle(current_index)
# This logic handles a display edge case after a comment toggle. We
# want to make sure that w... |
Open the link contained in the selected item.
If there is more than one link contained in the item, prompt the user
to choose which link to open. | def open_link(self):
"""
Open the link contained in the selected item.
If there is more than one link contained in the item, prompt the user
to choose which link to open.
"""
data = self.get_selected_item()
if data['type'] == 'Submission':
link = self... |
Open the selected comment with the URL viewer | def comment_urlview(self):
"""
Open the selected comment with the URL viewer
"""
data = self.get_selected_item()
comment = data.get('body') or data.get('text') or data.get('url_full')
if comment:
self.term.open_urlview(comment)
else:
self.t... |
Open the selected item with the system's pager | def open_pager(self):
"""
Open the selected item with the system's pager
"""
n_rows, n_cols = self.term.stdscr.getmaxyx()
if self.config['max_pager_cols'] is not None:
n_cols = min(n_cols, self.config['max_pager_cols'])
data = self.get_selected_item()
... |
Move the cursor up to the comment's parent. If the comment is
top-level, jump to the previous top-level comment. | def move_parent_up(self):
"""
Move the cursor up to the comment's parent. If the comment is
top-level, jump to the previous top-level comment.
"""
cursor = self.nav.absolute_index
if cursor > 0:
level = max(self.content.get(cursor)['level'], 1)
whi... |
Jump to the next comment that's at the same level as the selected
comment and shares the same parent. | def move_sibling_next(self):
"""
Jump to the next comment that's at the same level as the selected
comment and shares the same parent.
"""
cursor = self.nav.absolute_index
if cursor >= 0:
level = self.content.get(cursor)['level']
try:
... |
Return function to generate Redditor listings. | def _get_redditor_listing(subpath=''):
"""Return function to generate Redditor listings."""
def _listing(self, sort='new', time='all', *args, **kwargs):
"""Return a get_content generator for some RedditContentObject type.
:param sort: Specify the sort order of the results if applicable
... |
Return function to generate specific subreddit Submission listings. | def _get_sorter(subpath='', **defaults):
"""Return function to generate specific subreddit Submission listings."""
@restrict_access(scope='read')
def _sorted(self, *args, **kwargs):
"""Return a get_content generator for some RedditContentObject type.
The additional parameters are passed dir... |
Return a function for relationship modification.
Used to support friending (user-to-user), as well as moderating,
contributor creating, and banning (user-to-subreddit). | def _modify_relationship(relationship, unlink=False, is_sub=False):
"""Return a function for relationship modification.
Used to support friending (user-to-user), as well as moderating,
contributor creating, and banning (user-to-subreddit).
"""
# The API uses friend and unfriend to manage all of th... |
Return a requests Request object that can be "prepared". | def _prepare_request(reddit_session, url, params, data, auth, files,
method=None):
"""Return a requests Request object that can be "prepared"."""
# Requests using OAuth for authorization must switch to using the oauth
# domain.
if getattr(reddit_session, '_use_oauth', False):
... |
Return the new url or None if there are no redirects.
Raise exceptions if appropriate. | def _raise_redirect_exceptions(response):
"""Return the new url or None if there are no redirects.
Raise exceptions if appropriate.
"""
if response.status_code not in [301, 302, 307]:
return None
new_url = urljoin(response.url, response.headers['location'])
if 'reddits/search' in new_u... |
Raise specific errors on some status codes. | def _raise_response_exceptions(response):
"""Raise specific errors on some status codes."""
if not response.ok and 'www-authenticate' in response.headers:
msg = response.headers['www-authenticate']
if 'insufficient_scope' in msg:
raise OAuthInsufficientScope('insufficient_scope', res... |
Return an argument converted to a reddit-formatted list.
The returned format is a comma deliminated list. Each element is a string
representation of an object. Either given as a string or as an object that
is then converted to its string representation. | def _to_reddit_list(arg):
"""Return an argument converted to a reddit-formatted list.
The returned format is a comma deliminated list. Each element is a string
representation of an object. Either given as a string or as an object that
is then converted to its string representation.
"""
if (isin... |
Prompt user for captcha solution and return a prepared result. | def _get_captcha(reddit_session, captcha_id):
"""Prompt user for captcha solution and return a prepared result."""
url = urljoin(reddit_session.config['captcha'],
captcha_id + '.png')
sys.stdout.write('Captcha URL: {0}\nCaptcha: '.format(url))
sys.stdout.flush()
raw = sys.stdin.rea... |
Return a decorator that enforces API request limit guidelines.
We are allowed to make a API request every api_request_delay seconds as
specified in praw.ini. This value may differ from reddit to reddit. For
reddit.com it is 2. Any function decorated with this will be forced to
delay _ra... | def rate_limit(function):
"""Return a decorator that enforces API request limit guidelines.
We are allowed to make a API request every api_request_delay seconds as
specified in praw.ini. This value may differ from reddit to reddit. For
reddit.com it is 2. Any function decorated with thi... |
Responsible for dispatching the request and returning the result.
Network level exceptions should be raised and only
``requests.Response`` should be returned.
:param request: A ``requests.PreparedRequest`` object containing all
the data necessary to perform the request.
:pa... | def request(self, request, proxies, timeout, verify, **_):
"""Responsible for dispatching the request and returning the result.
Network level exceptions should be raised and only
``requests.Response`` should be returned.
:param request: A ``requests.PreparedRequest`` object containing ... |
Return a decorator that interacts with a handler's cache.
This decorator must be applied to a DefaultHandler class method or
instance method as it assumes `cache`, `ca_lock` and `timeouts` are
available. | def with_cache(function):
"""Return a decorator that interacts with a handler's cache.
This decorator must be applied to a DefaultHandler class method or
instance method as it assumes `cache`, `ca_lock` and `timeouts` are
available.
"""
@wraps(function)
def wrap... |
Remove items from cache matching URLs.
Return the number of items removed. | def evict(cls, urls):
"""Remove items from cache matching URLs.
Return the number of items removed.
"""
if isinstance(urls, text_type):
urls = [urls]
urls = set(normalize_url(url) for url in urls)
retval = 0
with cls.ca_lock:
for key in l... |
Send the request through the server and return the HTTP response. | def _relay(self, **kwargs):
"""Send the request through the server and return the HTTP response."""
retval = None
delay_time = 2 # For connection retries
read_attempts = 0 # For reading from socket
while retval is None: # Evict can return False
sock = socket.socket... |
Attempt to load settings from various praw.ini files. | def _load_configuration():
"""Attempt to load settings from various praw.ini files."""
config = configparser.RawConfigParser()
module_dir = os.path.dirname(sys.modules[__name__].__file__)
if 'APPDATA' in os.environ: # Windows
os_config_path = os.environ['APPDATA']
elif 'XDG_CONFIG_HOME' in ... |
Bind the theme's colors to curses's internal color pair map.
This method must be called once (after curses has been initialized)
before any element attributes can be accessed. Color codes and other
special attributes will be mixed bitwise into a single value that
can be passed into curs... | def bind_curses(self):
"""
Bind the theme's colors to curses's internal color pair map.
This method must be called once (after curses has been initialized)
before any element attributes can be accessed. Color codes and other
special attributes will be mixed bitwise into a single... |
Returns the curses attribute code for the given element. | def get(self, element, selected=False):
"""
Returns the curses attribute code for the given element.
"""
if self._attribute_map is None:
raise RuntimeError('Attempted to access theme attribute before '
'calling initialize_curses_theme()')
... |
Compile all of the themes configuration files in the search path. | def list_themes(cls, path=THEMES):
"""
Compile all of the themes configuration files in the search path.
"""
themes, errors = [], OrderedDict()
def load_themes(path, source):
"""
Load all themes in the given path.
"""
if os.path.is... |
Prints a human-readable summary of the installed themes to stdout.
This is intended to be used as a command-line utility, outside of the
main curses display loop. | def print_themes(cls, path=THEMES):
"""
Prints a human-readable summary of the installed themes to stdout.
This is intended to be used as a command-line utility, outside of the
main curses display loop.
"""
themes, errors = cls.list_themes(path=path + '/')
print... |
Search for the given theme on the filesystem and attempt to load it.
Directories will be checked in a pre-determined order. If the name is
provided as an absolute file path, it will be loaded directly. | def from_name(cls, name, path=THEMES):
"""
Search for the given theme on the filesystem and attempt to load it.
Directories will be checked in a pre-determined order. If the name is
provided as an absolute file path, it will be loaded directly.
"""
if os.path.isfile(nam... |
Load a theme from the specified configuration file.
Parameters:
filename: The name of the filename to load.
source: A description of where the theme was loaded from. | def from_file(cls, filename, source):
"""
Load a theme from the specified configuration file.
Parameters:
filename: The name of the filename to load.
source: A description of where the theme was loaded from.
"""
_logger.info('Loading theme %s', filename)
... |
Parse a single line from a theme file.
Format:
<element>: <foreground> <background> <attributes> | def _parse_line(cls, element, line, filename=None):
"""
Parse a single line from a theme file.
Format:
<element>: <foreground> <background> <attributes>
"""
items = line.split()
if len(items) == 2:
fg, bg, attrs = items[0], items[1], ''
e... |
Helper function used to set the fallback attributes of an element when
they are defined by the configuration as "None" or "-". | def _set_fallback(elements, src_field, fallback, dest_field=None):
"""
Helper function used to set the fallback attributes of an element when
they are defined by the configuration as "None" or "-".
"""
if dest_field is None:
dest_field = src_field
if isinstan... |
Converts hex RGB to the 6x6x6 xterm color space
Args:
color (str): RGB color string in the format "#RRGGBB"
Returns:
str: ansi color string in the format "ansi_n", where n
is between 16 and 230
Reference:
https://github.com/chadj2/bash-ui/bl... | def rgb_to_ansi(color):
"""
Converts hex RGB to the 6x6x6 xterm color space
Args:
color (str): RGB color string in the format "#RRGGBB"
Returns:
str: ansi color string in the format "ansi_n", where n
is between 16 and 230
Reference:
... |
Traverse the list in the given direction and return the next theme | def _step(self, theme, direction):
"""
Traverse the list in the given direction and return the next theme
"""
if not self.themes:
self.reload()
# Try to find the starting index
key = (theme.source, theme.name)
for i, val in enumerate(self.themes):
... |
The entry point from the praw-multiprocess utility. | def run():
"""The entry point from the praw-multiprocess utility."""
parser = OptionParser(version='%prog {0}'.format(__version__))
parser.add_option('-a', '--addr', default='localhost',
help=('The address or host to listen on. Specify -a '
'0.0.0.0 to liste... |
Mute tracebacks of common errors. | def handle_error(_, client_addr):
"""Mute tracebacks of common errors."""
exc_type, exc_value, _ = sys.exc_info()
if exc_type is socket.error and exc_value[0] == 32:
pass
elif exc_type is cPickle.UnpicklingError:
sys.stderr.write('Invalid connection from {0}\n'
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.