本文整理汇总了Python中praw.Reddit.subreddit方法的典型用法代码示例。如果您正苦于以下问题:Python Reddit.subreddit方法的具体用法?Python Reddit.subreddit怎么用?Python Reddit.subreddit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类praw.Reddit
的用法示例。
在下文中一共展示了Reddit.subreddit方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: say_something_sciencey
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import subreddit [as 别名]
def say_something_sciencey():
r = Reddit('bot1', user_agent='Phteven')
subreddits = ['shittyaskscience', "showerthoughts"]
chosen_subreddit = random.choice(subreddits)
submissions = r.subreddit(chosen_subreddit)
posts = submissions.hot(limit=100)
self_posts = [p for p in posts if p.domain.lower() == 'self.%s'.lower() % chosen_subreddit]
return random.choice(self_posts).title
示例2: get_nude
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import subreddit [as 别名]
def get_nude(api_key, session):
if not session.get([]):
reddit = Reddit(client_id='UrExvPI1zjBAiQ',
client_secret=api_key,
user_agent='python:desubot URL: http://github.com/Motoko11/desubot:v2.0')
subreddit = reddit.subreddit('gonewild')
submissions = subreddit.top(limit=64)
links = [submission.url for submission in submissions if not submission.stickied]
shuffle(links)
session.set(links)
return session.get([]).pop(0)
示例3: ModUtils
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import subreddit [as 别名]
class ModUtils(object):
"""Class that provides all the modutils functionality."""
def __init__(self, subreddit, site=None, verbose=None):
"""Initialize the ModUtils class by passing in config options."""
self.reddit = Reddit(site, check_for_updates=False, user_agent=AGENT)
self.sub = self.reddit.subreddit(subreddit)
self.verbose = verbose
self._current_flair = None
def add_users(self, category):
"""Add users to 'banned', 'contributor', or 'moderator'."""
mapping = {'banned': 'ban', 'contributor': 'make_contributor',
'moderator': 'make_moderator'}
if category not in mapping:
print('{!r} is not a valid option for --add'.format(category))
return
func = getattr(self.sub, mapping[category])
print('Enter user names (any separation should suffice):')
data = sys.stdin.read().strip()
for name in re.split('[^A-Za-z0-9_]+', data):
func(name)
print('Added {!r} to {}'.format(name, category))
def clear_empty(self):
"""Remove flair that is not visible or has been set to empty."""
for flair in self.current_flair():
if not flair['flair_text'] and not flair['flair_css_class']:
print(self.reddit.flair.update(flair['user']))
print('Removed flair for {0}'.format(flair['user']))
def current_flair(self):
"""Generate the flair, by user, for the subreddit."""
if self._current_flair is None:
self._current_flair = []
if self.verbose:
print('Fetching flair list for {}'.format(self.sub))
for flair in self.sub.flair:
self._current_flair.append(flair)
yield flair
else:
for item in self._current_flair:
yield item
def flair_template_sync(self, editable, limit, # pylint: disable=R0912
static, sort, use_css, use_text):
"""Synchronize templates with flair that already exists on the site.
:param editable: Indicates that all the options should be editable.
:param limit: The minimum number of users that must share the flair
before it is added as a template.
:param static: A list of flair templates that will always be added.
:param sort: The order to sort the flair templates.
:param use_css: Include css in the templates.
:param use_text: Include text in the templates.
"""
# Parameter verification
if not use_text and not use_css:
raise Exception('At least one of use_text or use_css must be True')
sorts = ('alpha', 'size')
if sort not in sorts:
raise Exception('Sort must be one of: {}'.format(', '.join(sorts)))
# Build current flair list along with static values
counter = {}
if static:
for key in static:
if use_css and use_text:
parts = tuple(x.strip() for x in key.split(','))
if len(parts) != 2:
raise Exception('--static argument {!r} must have two '
'parts (comma separated) when using '
'both text and css.'.format(parts))
key = parts
counter[key] = limit
if self.verbose:
sys.stdout.write('Retrieving current flair\n')
sys.stdout.flush()
for flair in self.current_flair():
if self.verbose:
sys.stdout.write('.')
sys.stdout.flush()
if use_text and use_css:
key = (flair['flair_text'], flair['flair_css_class'])
elif use_text:
key = flair['flair_text']
else:
key = flair['flair_css_class']
if key in counter:
counter[key] += 1
else:
counter[key] = 1
if self.verbose:
print()
# Sort flair list items according to the specified sort
if sort == 'alpha':
items = sorted(counter.items())
#.........这里部分代码省略.........
示例4: print
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import subreddit [as 别名]
the THREADTIME that thread is posted to the sub as the bottom sticky
"""
print("Getting weekly thread...")
title = "| {} {}".format(thread["title"], strftime("%Y-%m-%d"))
print("\tPosting", title, "thread")
thread = sub.submit(title, selftext=thread["body"]).mod.sticky(bottom=True)
thread.comment_sort = 'new'
print("\tDone!")
# RUNNING BOT
while True:
try:
print("\nRunning at", strftime("%Y-%m-%d %H:%M:%S"))
subreddit = r.subreddit(SUBREDDIT)
posts = subreddit.new(limit=MAXPOSTS)
day = strftime("%a")
if strftime("%H:%M") == THREADTIME and day in THREADS:
weekly_thread(subreddit, THREADS[day])
try:
with open("oldposts", "r") as file:
oldposts = [line.strip() for line in file]
except FileNotFoundError:
oldposts = []
for post in posts:
if post.id not in oldposts and post.approved_by is None:
actions(post)
示例5: SubRedditStats
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import subreddit [as 别名]
class SubRedditStats(object):
"""Contain all the functionality of the subreddit_stats command."""
post_prefix = tt('Subreddit Stats:')
post_header = tt('---\n###{}\n')
post_footer = tt('>Generated with [BBoe](/u/bboe)\'s [Subreddit Stats]'
'(https://github.com/praw-dev/prawtools) \n{}'
'SRS Marker: {}')
re_marker = re.compile('SRS Marker: (\d+)')
@staticmethod
def _previous_max(submission):
return float(SubRedditStats.re_marker.findall(submission.selftext)[-1])
@staticmethod
def _permalink(item):
if isinstance(item, Submission):
return tt('/comments/{}').format(item.id)
else: # comment
return tt('/comments/{}//{}?context=1').format(item.submission.id,
item.id)
@staticmethod
def _pts(points):
return '1 pt' if points == 1 else '{} pts'.format(points)
@staticmethod
def _user(user):
if user is None:
return '_deleted_'
elif isinstance(user, Redditor):
user = str(user)
return tt('[{}](/user/{})').format(user.replace('_', '\_'), user)
def __init__(self, subreddit, site, verbosity, distinguished):
"""Initialize the SubRedditStats instance with config options."""
self.reddit = Reddit(site, disable_update_check=True,
user_agent='prawtools/{}'.format(__version__))
self.subreddit = self.reddit.subreddit(subreddit)
self.verbosity = verbosity
self.distinguished = distinguished
self.submissions = []
self.comments = []
self.submitters = defaultdict(list)
self.commenters = defaultdict(list)
self.min_date = 0
self.max_date = time.time() - DAYS_IN_SECONDS * 3
self.prev_srs = None
def msg(self, msg, level, overwrite=False):
"""Output a messaage to the screen if the verbosity is sufficient."""
if self.verbosity and self.verbosity >= level:
sys.stdout.write(msg)
if overwrite:
sys.stdout.write('\r')
sys.stdout.flush()
else:
sys.stdout.write('\n')
def prev_stat(self, prev_id):
"""Load the previous subreddit stat."""
self.prev_srs = self.reddit.submission(prev_id)
self.min_date = self._previous_max(self.prev_srs)
def fetch_recent_submissions(self, max_duration, after, exclude_self,
exclude_link, since_last=True):
"""Fetch recent submissions in subreddit with boundaries.
Does not include posts within the last three days as their scores may
not be representative.
:param max_duration: When set, specifies the number of days to include
:param after: When set, fetch all submission after this submission id.
:param exclude_self: When true, don't include self posts.
:param exclude_link: When true, don't include links.
:param since_last: When true use info from last submission to determine
the stop point
:returns: True if any submissions were found.
"""
if exclude_self and exclude_link:
raise TypeError('Cannot set both exclude_self and exclude_link.')
if max_duration:
self.min_date = self.max_date - DAYS_IN_SECONDS * max_duration
params = {'after': after} if after else None
self.msg('DEBUG: Fetching submissions', 1)
for submission in self.subreddit.new(limit=None, params=params):
if submission.created_utc <= self.min_date:
break
if since_last and submission.title.startswith(self.post_prefix) \
and submission.author == self.reddit.config.username:
# Use info in this post to update the min_date
# And don't include this post
self.msg(tt('Found previous: {}')
.format(safe_title(submission)), 2)
if self.prev_srs is None: # Only use the most recent
self.min_date = max(self.min_date,
self._previous_max(submission))
self.prev_srs = submission
continue
#.........这里部分代码省略.........