本文整理汇总了Python中praw.Reddit.get_subreddit方法的典型用法代码示例。如果您正苦于以下问题:Python Reddit.get_subreddit方法的具体用法?Python Reddit.get_subreddit怎么用?Python Reddit.get_subreddit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类praw.Reddit
的用法示例。
在下文中一共展示了Reddit.get_subreddit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_reddit
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_subreddit [as 别名]
def update_reddit(self):
#Initialize PRAW and login
r = Reddit(user_agent='/r/reddevils bot by /u/Hubwub')
r.login(self.username,self.password)
#Grab the current settings
settings = r.get_subreddit(self.subreddit).get_settings()
#Update the sidebar
#print sidebar
settings['description'] = sidebar
settings = r.get_subreddit(self.subreddit).update_settings(description=settings['description'])
示例2: __init__
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_subreddit [as 别名]
class GenericRedditLink:
def __init__(self,parent):
self.r=Reddit(user_agent="PollBotBestBot")
self.parent=parent
def __call__(self,msg):
if msg["body"].lower().startswith("!r/"):
m=msg["body"].lstrip("!r/")
spli=m.split(":")
subreddit=spli[0]
print subreddit
if subreddit in config.banned_subreddits:
self.parent.scheduler.add("punishment:"+msg["mucnick"],0.1,self.parent.punishment,args=(msg["mucnick"],),repeat=True)
self.parent.send_message(mto=self.parent.channel,mbody="Nope, not touching that.",mtype="groupchat")
return
body=self.get_hot(subreddit,msg)
if body!=None:
self.parent.send_message(mto=self.parent.channel,mbody=body,mtype="groupchat")
if msg["body"].lower().startswith("!block ") and msg["mucnick"] in config.admins:
m=m.spli(" ")
subreddit=spli[1]
config.banned_subreddits.append(subreddit)
def get_hot(self,subreddit,msg):
if msg["type"]=="groupchat":
subreddit=self.r.get_subreddit(subreddit)
try:
if subreddit.over18:
pass
except (HTTPError, errors.InvalidSubreddit) as E:
self.parent.send_message(mto=self.parent.channel,mbody="Learn to Reddit please, "+msg["mucnick"],mtype="groupchat")
return None
if subreddit.over18:
#self.parent.send_message(mto=self.parent.channel,mbody="NSFW content is currently blocked. Direct complaints to mods and admins.",mtype="groupchat")
extra=" :nws: "
else:
extra=""
submissions=subreddit.get_hot(limit=10)
a=None
a1=None
limit=random.randint(0,9)
while limit>0:
a1=a
print a1
try:
a=next(submissions)
except StopIteration:
a=a1
break
print a
limit-=1
try:
return "\n"+extra+str(a.title)+extra+"\n"+extra+str(a.url)+extra
except AttributeError:
return "Reddit API is currently not accepting connections. Please wait ~30 seconds before retrying."
示例3: reset_image_pool
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_subreddit [as 别名]
def reset_image_pool(self, num_pictures):
""" Retrieves the links to all the images that we want. """
reddit = Reddit(user_agent=PROGRAM_NAME)
images_downloaded = 0
sr_dict = {
sr_name : reddit.get_subreddit(sr_name).get_top()
for sr_name in self.subreddit_pool
}
# randomly pick a number of pictures from the subreddits.
# skip the ones that aren't actually pictures.
while images_downloaded < num_pictures:
subreddit = random.choice([key for key in sr_dict.keys()])
try:
submission = next(sr_dict[subreddit])
except StopIteration:
# remove subreddits which run out of content
del sr_dict[subreddit]
# quit if we've run out of subreddits
if len(sr_dict.keys()) > 0: continue;
else: break;
link = submission.url
if utils.is_image_link(link):
print('({num_pics} of {total_pics}) Image found at {url}. Downloading...'.format(num_pics=images_downloaded+1, total_pics=num_pictures, url=link))
self.download_image(link, self.get_file_name(link))
images_downloaded += 1
示例4: reddit_titles
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_subreddit [as 别名]
def reddit_titles(sub):
from praw import Reddit
r = Reddit(user_agent="my_useragent")
news = r.get_subreddit(sub).get_hot(limit=10)
news = list(news)
#num = 3
for i in news:
print(i.title)
示例5: reddit_parser
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_subreddit [as 别名]
def reddit_parser():
args = build_reddit_parser().parse_args()
db_connection = create_connection(args.db_host, args.db_password)
reddit = Reddit(user_agent=args.user_agent)
subreddit = reddit.get_subreddit(args.subreddit)
if args.username:
password = getpass("Enter reddit password: ")
reddit.login(args.username, password)
single_threaded_impl(subreddit, db_connection, args.sub_limit, args.method)
示例6: ban_users
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_subreddit [as 别名]
def ban_users(reddit: praw.Reddit, users):
"""
Ban the users on reddit.
"""
print("Updating DB objects...")
# First pass, update database objects.
for user, subs in users.items():
if user in config.EXEMPT_USERS:
# Ignore these guys. They're cool/bots.
continue
if not db.session.query(exists().where(db.BannedUser.username == user)).scalar():
# Update.
u = db.BannedUser(username=user, reason="AutoCensor automatic ban - Subreddits: {}".format(",").join(subs))
db.session.add(u)
# Commit session.
db.session.commit()
print("Building many-to-many entries...")
# Second pass, check for users and subreddits, and update many-to-many entires.
for user in users:
if user in config.EXEMPT_USERS:
# Ignore these guys. They're cool/bots.
continue
try:
u_object = db.session.query(db.BannedUser).filter(db.BannedUser.username == user).one()
except sqlalchemy.orm.exc.NoResultFound:
continue
for managing_sub in db.session.query(db.ManagingSubreddit).all():
if u_object not in managing_sub.users:
managing_sub.users.append(u_object)
db.session.add(managing_sub)
db.session.commit()
print("Banning users...")
banned = 0
# Last pass, ban them on our subreddits.
for subobject in db.session.query(db.ManagingSubreddit).all():
# Get the subreddit.
sub = reddit.get_subreddit(subobject.name)
# Get the users.
for user in subobject.users:
# Begin the bans!
try:
sub.add_ban(
user.username,
ban_reason="Automatically banned for posting in these subreddits: {}".format(user.reason),
note="Automatically banned for posting in these subreddits: {}".format(user.reason),
)
banned += 1
except:
# whatever
continue
return banned
示例7: __init__
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_subreddit [as 别名]
class Snitch:
def __init__(self, username, passwd, url, subreddit):
self.rh = Reddit('Release the Snitch v 0.1 by Kolpa')
self.rh.login(username, passwd)
self.css = self.__load_css()
self.desc = self.__load_desc()
self.url = url
self.subreddit = subreddit
def __load_css(self):
with open('raw.css', 'r') as f:
return f.read()
def __load_desc(self):
with open('descripiton.txt', 'r') as f:
return f.read()
def __get_last_id(self):
with open('current', 'r') as f:
return f.read()
def __set_new_id(self):
id = randrange(0, 999999)
with open('current', 'w') as f:
f.write(str(id))
return id
def _get_random_pos(self):
return randrange(0, 100, 10), randrange(0, 100, 10)
def __update_desc(self, desc):
self.rh.update_settings(self.rh.get_subreddit(self.subreddit), description=desc)
def can_move(self, id):
if not os.path.exists('current'):
return True
return id == self.__get_last_id()
def move(self, id):
try:
if self.can_move(id):
new_id = self.__set_new_id()
desc = self.desc.format(new_id)
x, y = self._get_random_pos()
css = self.css.format(x, y, self.url)
self.rh.set_stylesheet(self.subreddit, css)
self.__update_desc(desc)
return True
except Exception:
return False
示例8: main
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_subreddit [as 别名]
def main():
parser = argparse.ArgumentParser(
prog='modbot.py',
description="Subreddit automoderating script")
parser.add_argument('subreddit')
parser.add_argument('-r', '--rulesdir', default='./rules')
parser.add_argument('-u', '--user')
parser.add_argument('-p', '--password')
args = parser.parse_args()
rh = RuleHandler(args.rulesdir, '*.rule')
logging.config.fileConfig('logging.conf')
reddit = Reddit('%s/%s' % (NAME, VERSION))
try:
reddit.login(args.user, args.password)
except praw.errors.InvalidUserPass:
logging.critical("Login failure")
sys.exit(1)
sub = reddit.get_subreddit(args.subreddit)
read_thinglists()
comments_ph = None
submissions_ph = None
while True:
logging.debug("Loop start")
loopstart = time.time()
try:
modqueue_items = sub.get_mod_queue(limit=100)
except Exception, e:
modqueue_items = []
num = 0
for modqueue_item in modqueue_items:
num += 1
matchrules(modqueue_item, rh.rules, is_modqueue=True)
logging.info("Checked %d modqueue items" % num)
try:
if comments_ph == None:
comments = sub.get_comments(limit=100)
else:
comments = sub.get_comments(place_holder=comments_ph,
limit=500)
except Exception, e:
comments = []
示例9: update_countdown
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_subreddit [as 别名]
def update_countdown(username, password, subreddit_name, target):
user_agent = '/r/{0} countdown'.format(subreddit_name)
reddit = Reddit(user_agent)
reddit.login(username, password, disable_warning=True)
# reddit access
subreddit = reddit.get_subreddit(subreddit_name)
settings = subreddit.get_settings()
description = HTMLParser().unescape(settings['description'])
# time matches
countdown_delta = target - datetime.now()
days_left = countdown_delta.days
hours_left = countdown_delta.seconds // 3600
# regex and strings
# countdownSearch = re.compile("(\[\d?\d?\]\([#][a-z]*\)\s[a-z]*[!]?\s?)+", re.I) # old regex
countdownSearch = re.compile("((\s([a-z]{4})*)*\s?\[\d?\d?\]\([#][a-z]*\)\s[a-z]*[!]?\s?)+", re.I)
origStr = " less than [](#days) days [](#hours) hours\n"
noDaysStr = " less than [](#hours) hours\n"
noHoursStr = " less than [](#minutes) minutes\n"
raceLiveStr = " [](#days) Racing [](#hours) is [](#minutes) live\n"
updatemeStr = " [](#days) Current [](#hours) event [](#minutes) ended\n"
# make sure our event hasn't happened yet
if target > datetime.now():
if days_left > 0:
description = re.sub(countdownSearch, origStr, description)
elif hours_left > 0 and days_left == 0:
description = re.sub(countdownSearch, noDaysStr, description)
else:
description = re.sub(countdownSearch, noHoursStr, description)
for key, value in compute_time_ago_params(target).iteritems():
pattern = "\\[[^\\]]*\\]\\(#{0}\\)".format(key) # replace [<anything>](#<key>)
repl = "[{0}](#{1})".format(value, key) # with [<value>](#<key>)
description = re.sub(pattern, repl, description)
# if race is happening, show raceLiveStr, else race is over, show updatemeStr
else:
countdownSearch.search(description)
if target.hour > datetime.now().hour - 3:
description = re.sub(countdownSearch, raceLiveStr, description)
else:
description = re.sub(countdownSearch, updatemeStr, description)
subreddit.update_settings(description=description)
示例10: update_countdown
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_subreddit [as 别名]
def update_countdown(username, password, subreddit_name, target):
user_agent = '/r/{0} countdown bot'.format(subreddit_name)
reddit = Reddit(user_agent)
reddit.login(username, password)
subreddit = reddit.get_subreddit(subreddit_name)
settings = subreddit.get_settings()
description = HTMLParser().unescape(settings['description'])
for key, value in compute_time_ago_params(target).iteritems():
pattern = "\\[[^\\]]*\\]\\(#{0}\\)".format(key) # replace [<anything>](#<key>)
repl = "[{0}](#{1})".format(value, key) # with [<value>](#<key>)
description = re.sub(pattern, repl, description)
print(description)
subreddit.update_settings(description=description)
示例11: create_sidebar
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_subreddit [as 别名]
def create_sidebar(self):
h = HTMLParser.HTMLParser()
#Initialize PRAW and login
r = Reddit(user_agent='/r/reddevils bot by /u/Hubwub')
r.login(self.username,self.password)
#Grab the sidebar template from the wiki
sidebar = r.get_subreddit(self.subreddit).get_wiki_page('edit_sidebar').content_md
#Create list from sidebar by splitting at ####
sidebar_list = sidebar.split('####')
#Sidebar
#print sidebar_list
#sidebar = (sidebar_list[0]+league+sidebar_list[1])
sidebar = (sidebar_list[0]+league+rfixtures+goals+sidebar_list[1])
#Fix characters in sidebar
sidebar = h.unescape(sidebar)
return sidebar
示例12: test_report
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_subreddit [as 别名]
def test_report(self):
# login as new user to report submission
oth = Reddit(USER_AGENT)
oth.login('PyApiTestUser3', '1111')
subreddit = oth.get_subreddit(self.sr)
submission = None
for submission in subreddit.get_new_by_date():
if not submission.hidden:
break
else:
self.fail('Could not find a non-reported submission.')
submission.report()
# check if submission was reported
for report in self.r.get_subreddit(self.sr).get_reports():
if report.id == submission.id:
break
else:
self.fail('Could not find reported submission.')
示例13: scrape
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_subreddit [as 别名]
def scrape(subreddit_name, backfill_to=None):
"""
Scrape a subreddit.
:type subreddit_name: str
:type backfill_to: datetime.datetime
"""
subreddit_name = subreddit_name.lower()
imgur_client = ImgurClient(
settings.IMGUR_CLIENT_ID, settings.IMGUR_CLIENT_SECRET)
reddit = Reddit(user_agent=settings.REDDIT_USER_AGENT)
subreddit = reddit.get_subreddit(subreddit_name)
with session_manager() as session:
if backfill_to is not None:
_backfill(
session, subreddit, subreddit_name, imgur_client, backfill_to)
else:
_scrape(session, subreddit, subreddit_name, imgur_client)
示例14: scrape
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_subreddit [as 别名]
def scrape(reddit: praw.Reddit) -> dict:
"""
Begin a scraping pass.
Uses the subreddits defined in config.EDGELORD_SUBREDDITS.
:param reddit: The reddit object to use.
:return: A dict containing users and a list of subreddits.
"""
banning = {}
for sub in config.EDGELORD_SUBREDDITS:
# Get sub.
print("Scraping subreddit {}".format(sub))
try:
subreddit = reddit.get_subreddit(sub)
hot_posts = subreddit.get_hot(limit=30)
for i, post in enumerate(hot_posts):
print("{} - [{}/30] - Scraping comments of".format(sub, i + 1), post)
# Get submitter name.
assert isinstance(post, praw.objects.Submission)
# TODO: Figure out way to get submitters name.
# Otherwise, loop over comments, plucking the submitter off.
for comment in praw.helpers.flatten_tree(post.comments):
if isinstance(comment, praw.objects.MoreComments):
# TODO: Add MoreComments parsing.
continue
if should_ban(comment):
if comment.author is not None:
print("{} - [{}/30] - Adding to ban list: {}".format(sub, i + 1, comment.author))
if not comment.author.name in banning:
banning[comment.author.name] = []
if sub in banning[comment.author.name]:
continue
else:
banning[comment.author.name].append(sub)
except Exception as e:
print("Error happened - {}".format(e))
print("Skipping to next sub.")
return banning
示例15: random_reddit_image
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_subreddit [as 别名]
def random_reddit_image(self, caption=None, bot=None, update=None):
"""
Find and send a random image from a random subreddit containing
images.
"""
if not (bot and update):
return
bot.send_chat_action(update.message.chat.id)
# choose a random subreddit to pull image from
subreddit = choice(self.subreddits)
# grab submissions from the subreddit
reddit = Reddit(user_agent=self.reddit_user_agent)
submissions = reddit.get_subreddit(subreddit).get_hot(limit=50)
# skip non-imgur links, animated images, and choose a random submission
submission = choice([sub.url for sub in submissions
if 'imgur.com' in sub.url])
# find all the image links in the submission, and choose a random one
try:
image_url = choice(get_image_links_from_imgur(submission))
except (IndexError, ValueError):
# no image found, so try again
return self.random_reddit_image(caption=caption, bot=bot,
update=update)
# get the image content
logger.info('"/{command}" from {user}: posting image at {url}'.format(
command=' '.join([update.command] + update.command_args),
user=update.message.user.username,
url=image_url,
))
response = requests.get(image_url)
if response.status_code != 200:
bot.send_message(update.message.chat.id, self.error_message)
return
# image_content = make_thumbnail(response.content)
image_content = response.content
bot.send_photo(update.message.chat.id, image_content,
reply_to_message_id=update.message.id,
caption=image_url)