本文整理汇总了Python中praw.Reddit类的典型用法代码示例。如果您正苦于以下问题:Python Reddit类的具体用法?Python Reddit怎么用?Python Reddit使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Reddit类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_mark_as_read
def test_mark_as_read(self):
oth = Reddit(USER_AGENT)
oth.login('PyApiTestUser3', '1111')
# pylint: disable-msg=E1101
msg = six_next(oth.user.get_unread(limit=1))
msg.mark_as_read()
self.assertTrue(msg not in oth.user.get_unread(limit=5))
示例2: authorized
def authorized():
reddit_state = request.args.get('state', '')
reddit_code = request.args.get('code', '')
if not reddit_state or not reddit_code:
return redirect(url_for('index'))
r = Reddit(app.config['REDDIT_USER_AGENT'], handler=handler)
r.set_oauth_app_info(app.config['REDDIT_CLIENT_ID'], app.config['REDDIT_CLIENT_SECRET'], app.config['REDDIT_REDIRECT_URI'])
reddit_info = r.get_access_information(reddit_code)
reddit_user = r.get_me()
next_path = session['last_path']
if reddit_state != session['oauth_state']:
flash("Invalid state given, please try again.", 'danger')
return redirect(next_path or url_for('index'))
user = user_by_nickname(reddit_user.name)
if user is None:
nickname = reddit_user.name
user = User(nickname = nickname, role = 'u',
accessToken = reddit_info['access_token'],
refreshToken = reddit_info['refresh_token'])
else:
user.accessToken = reddit_info['access_token']
user.refreshToken = reddit_info['refresh_token']
db.session.add(user)
db.session.commit()
remember_me = False
if 'remember_me' in session:
remember_me = session['remember_me']
session.pop('remember_me', None)
login_user(user, remember = remember_me)
# update_flair(user)
return redirect(next_path or url_for('index'))
示例3: reset_image_pool
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: make_config
def make_config(filename):
"""
Make a new config file.
"""
here = os.path.dirname(os.path.abspath(__file__))
template_file = os.path.join(here, CONFIG_TEMPLATE)
with open(template_file, 'r') as f:
config = json.load(f)
print('Generating a new config, press [Enter] to accept default value.')
_ask_config(config)
bot_class = get_bot_class(config['bot_class'])
r = Reddit('praw/oauth_access_info_setup 1.0')
r.set_oauth_app_info(**config['oauth_info'])
url = r.get_authorize_url('uniqueKey', bot_class.get_scope(), True)
print('Go to this url: =====\n\n{}\n\n====='.format(url))
code = input('and enter the authorization code: ')
assert code, "No authorization code supplied."
access_info = r.get_access_information(code)
access_info.pop('scope', None)
config['access_info'] = access_info
with open(filename, 'w') as f:
json.dump(config, f, indent=2)
print('Wrote config {!r}!'.format(filename))
return config
示例5: reddit_titles
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)
示例6: say_something_sciencey
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
示例7: reddit_parser
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)
示例8: login
def login():
next = request.args.get('next')
from uuid import uuid1
state = str(uuid1())
session['oauth_state'] = state
session['last_path'] = next
r = Reddit(app.config['REDDIT_USER_AGENT'], handler=handler)
r.set_oauth_app_info(app.config['REDDIT_CLIENT_ID'], app.config['REDDIT_CLIENT_SECRET'], app.config['REDDIT_REDIRECT_URI'])
authorize_url = r.get_authorize_url(state,refreshable=True)
return redirect(authorize_url)
示例9: update_reddit
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'])
示例10: get_nude
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)
示例11: test_mark_as_unread
def test_mark_as_unread(self):
oth = Reddit(USER_AGENT)
oth.login('PyApiTestUser3', '1111')
found = None
for msg in oth.user.get_inbox():
if not msg.new:
found = msg
msg.mark_as_unread()
break
else:
self.fail('Could not find a read message.')
self.assertTrue(found in oth.user.get_unread())
示例12: test_mark_multiple_as_read
def test_mark_multiple_as_read(self):
oth = Reddit(USER_AGENT)
oth.login('PyApiTestUser3', '1111')
messages = []
for msg in oth.user.get_unread(limit=None):
if msg.author != oth.user.name:
messages.append(msg)
if len(messages) >= 2:
return
self.assertEqual(2, len(messages))
self.r.user.mark_as_read(messages)
unread = oth.user.get_unread(limit=5)
for msg in messages:
self.assertTrue(msg not in unread)
示例13: get
def get(self, *args, **kwargs):
username = self.kwargs['username']
api = Reddit(user_agent=settings.USER_AGENT)
exists = False
redditor = None
try:
redditor = api.get_redditor(username)
exists = True
except HTTPError:
exists = False
data = {'exists': exists}
if redditor:
data['redditor'] = redditor.fullname
return Response(data)
示例14: main
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 = []
示例15: update_countdown
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)