本文整理匯總了Python中praw.Reddit方法的典型用法代碼示例。如果您正苦於以下問題:Python praw.Reddit方法的具體用法?Python praw.Reddit怎麽用?Python praw.Reddit使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類praw
的用法示例。
在下文中一共展示了praw.Reddit方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: main
# 需要導入模塊: import praw [as 別名]
# 或者: from praw import Reddit [as 別名]
def main():
parser = argparse.ArgumentParser(description="Import flairs to subreddit")
parser.add_argument("-f", "--file", dest="filename", help="input file", metavar="FILE", type=extant_file, required=True)
parser.add_argument("-t", "--type", dest="filetype", help="json or csv", metavar="TYPE", type=str, choices=['json', 'csv'], required=True)
args = parser.parse_args()
r = praw.Reddit(client_id=app_key,
client_secret=app_secret,
username=username,
password=password,
user_agent=username)
if args.filetype == "json":
r.subreddit(subreddit).flair.update(load_json(args.filename))
elif args.filetype == "csv":
r.subreddit(subreddit).flair.update(load_csv(args.filename))
示例2: get_reddit_object
# 需要導入模塊: import praw [as 別名]
# 或者: from praw import Reddit [as 別名]
def get_reddit_object(token):
try:
reddit = praw.Reddit(user_agent='reddit_utils web app by Roman Kuleshov',
client_id=token['client_id'],
client_secret=token['client_secret'],
username=token['username'],
password=token['password'])
reddit.user.me()
return {'status': 'success', 'data': reddit}
except OAuthException as err:
return {'status': 'error', 'data': 'Error: Unable to get API access, please make sure API credentials are correct and try again (check the username and password first)'}
except ResponseException as err:
return {'status': 'error', 'data': 'Error: ResponseException: ' + str(err)}
except Exception as err:
return {'status': 'error', 'data': 'Unexpected Error: ' + str(err)}
示例3: _getAllComments
# 需要導入模塊: import praw [as 別名]
# 或者: from praw import Reddit [as 別名]
def _getAllComments(self, curComments):
"""
Get all the comments of a Reddit submission in a nice, JSON-formatted hierarchy of comments and replies.
Uses recursion to get the comment hierarchy.
:type curComments: list
:rtype: dict
"""
comments = {}
for comment in curComments:
if isinstance(comment, praw.objects.Comment): # Make sure it isn't a MoreComments object
author = comment.author
if author is None:
author = "[Deleted]"
else:
author = author.name
if comments.get(
author) is not None: # We make this a list in case the author comments multiple times in the submission on the same level of the comment tree
comments[author].append({'Body': comment.body, 'Replies': self._getAllComments(comment.replies)})
else:
comments[author] = [{'Body': comment.body, 'Replies': self._getAllComments(comment.replies)}]
return comments
示例4: login
# 需要導入模塊: import praw [as 別名]
# 或者: from praw import Reddit [as 別名]
def login(reddit_oauth_credentials_path):
####################################################################################################################
# Log into my application.
####################################################################################################################
user_agent, client_id, client_secret, redirect_uri = read_oauth_credentials(reddit_oauth_credentials_path)
reddit = praw.Reddit(user_agent=user_agent)
reddit.set_oauth_app_info(client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri)
# We do this in order to also keep the json files for storage
reddit.config.store_json_result = True
return reddit
示例5: load_log
# 需要導入模塊: import praw [as 別名]
# 或者: from praw import Reddit [as 別名]
def load_log():
"""Reads the processed posts log file and creates it if it doesn't exist.
Returns
-------
list
A list of Reddit posts ids.
"""
try:
with open(POSTS_LOG, "r", encoding="utf-8") as log_file:
return log_file.read().splitlines()
except FileNotFoundError:
with open(POSTS_LOG, "a", encoding="utf-8") as log_file:
return []
示例6: submissions_top
# 需要導入模塊: import praw [as 別名]
# 或者: from praw import Reddit [as 別名]
def submissions_top(redditor):
top_s = []
for submission in redditor.submissions.top('all', limit=10):
sub = {}
sub['Title'] = submission.title.encode('utf-8')
sub['URL'] = submission.url.encode('utf-8')
sub['Subreddit'] = str(submission.subreddit)
sub['Created Date'] = datetime.fromtimestamp(submission.created).strftime("%D %H:%M")
sub['Score'] = submission.score
sub['Comments'] = submission.num_comments
sub['Crossposts'] = submission.num_crossposts
sub['Mature Content'] = submission.over_18
if submission.media:
if 'oembed' in submission.media:
if 'url' in submission.media['oembed']:
sub['Embedded Media Description'] = submission.media['oembed']['description']
if 'url' in submission.media['oembed']:
sub['Embedded Media URL'] = submission.media['oembed']['url']
if 'reddit_video' in submission.media:
if 'fallback_url' in submission.media['reddit_video']:
sub['Reddit Video URL'] = submission.media['reddit_video']['fallback_url']
top_s.append(sub)
return top_s
示例7: main
# 需要導入模塊: import praw [as 別名]
# 或者: from praw import Reddit [as 別名]
def main(username):
user_stats = {}
reddit_id = vault.get_key('reddit_id')
reddit_secret = vault.get_key('reddit_secret')
user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'
reddit = praw.Reddit(client_id=reddit_id, client_secret=reddit_secret,
user_agent=user_agent)
redditor = reddit.redditor(username)
try:
user_stats['Redditor Stats'] = redditor_stats(redditor)
user_stats['Top 10 Submitted to Subreddits'] = submission_stats(redditor)
user_stats['Top 10 Commented in Subreddits'] = comment_stats(redditor)
if EXTRA_VERBOSE:
user_stats['Top Submissions'] = submissions_top(redditor)
user_stats['Top Comments'] = comments_top(redditor)
user_stats['Contriversial Posts'] = controversial_stats(redditor)
except NotFound as e:
user_stats['Error'] = str(e)
pass
return user_stats
示例8: main
# 需要導入模塊: import praw [as 別名]
# 或者: from praw import Reddit [as 別名]
def main():
match_text = "INSERT TEXT HERE"
r = praw.Reddit(
user_agent=config.USER_AGENT,
client_id=config.R_CLIENT_ID,
client_secret=config.R_CLIENT_SECRET,
username=config.R_USERNAME,
password=config.R_PASSWORD,
)
user = r.redditor(config.R_USERNAME)
comments = list(user.comments.new())
count = 0
for c in comments:
if match_text in c.body:
c.delete()
count += 1
print "Comments deleted: {}".format(count)
示例9: log
# 需要導入模塊: import praw [as 別名]
# 或者: from praw import Reddit [as 別名]
def log(message, alert=False):
"""Log messages along with a timestamp in a log file. If the alert
option is set to true, send a message to the admin's reddit inbox.
"""
t = time.strftime('%y-%m-%d %H:%M:%S', time.localtime())
message = "{}: {}\n".format(t, message)
message = message.encode('utf8', 'replace')
if config.LOG_FILE:
with open(config.LOG_FILE, 'a') as f:
f.write(message)
else:
print(message, end='')
if alert and config.ADMIN:
r = praw.Reddit(config.USER_AGENT)
r.login(config.R_USERNAME, config.R_PASSWORD)
admin_alert = message
subject = "CompileBot Alert"
r.redditor(config.ADMIN).message(subject, admin_alert)
示例10: main
# 需要導入模塊: import praw [as 別名]
# 或者: from praw import Reddit [as 別名]
def main():
r = praw.Reddit(
user_agent=config.USER_AGENT,
client_id=config.R_CLIENT_ID,
client_secret=config.R_CLIENT_SECRET,
username=config.R_USERNAME,
password=config.R_PASSWORD,
)
if config.SUBREDDIT:
config.BANNED_USERS
config.BANNED_USERS = get_banned(r)
# Iterate though each new comment/message in the inbox and
# process it appropriately.
inbox = r.inbox.unread()
for new in inbox:
try:
process_unread(new, r)
except:
tb = traceback.format_exc()
# Notify admin of any errors
log("Error processing comment {c.id}\n"
"{traceback}".format(c=new, traceback=code_block(tb)), alert=True)
finally:
new.mark_read()
示例11: start
# 需要導入模塊: import praw [as 別名]
# 或者: from praw import Reddit [as 別名]
def start():
"""Start the sneakpeek application."""
logging.info("Starting application")
logging.info("Instantiating Reddit instance")
reddit = praw.Reddit(
client_id=config.CLIENT["ID"],
client_secret=config.CLIENT["SECRET"],
user_agent=config.USER_AGENT,
username=config.USERNAME,
password=config.PASSWORD)
try:
scan(reddit.subreddit(config.SUBREDDIT))
except Exception as exception:
# This should never happen,
# because it breaks the infinite subreddit monitoring
# provided by subreddit.stream.submissions()
logging.critical("Exception occurred while scanning. This should never happen.")
logging.critical(exception)
示例12: search_subreddit
# 需要導入模塊: import praw [as 別名]
# 或者: from praw import Reddit [as 別名]
def search_subreddit(name, query, sort="relevance", limit=500, filter_nsfw=True):
if has_reddit_access():
try:
submissions = list(
get_subreddit(name).search(query, sort=sort, limit=limit)
)
if filter_nsfw:
submissions = [
submission for submission in submissions if not submission.over_18
]
return submissions
except ResponseException as err:
logger.error("Exception with accessing Reddit: {}".format(err))
except RequestException as err:
logger.error("Exception with accessing Reddit: {}".format(err))
else:
logger.warning("WARNING: No reddit access!")
示例13: createPrawConfig
# 需要導入模塊: import praw [as 別名]
# 或者: from praw import Reddit [as 別名]
def createPrawConfig(client_id, client_secret,
praw_path='praw.ini'):
"""
Create praw.ini file for Reddit credentials.
Parameters
----------
client_id: str
Reddit app client id.
client_secret: str
Reddit app client secret.
praw_path: str
Path to praw.ini.
"""
r_config = ConfigParser()
r_config['bot1'] = {
'client_id': client_id,
'client_secret': client_secret,
'user_agent': 'FreshScript'
}
with open(praw_path, 'w') as p:
r_config.write(p)
示例14: setupCron
# 需要導入模塊: import praw [as 別名]
# 或者: from praw import Reddit [as 別名]
def setupCron(self):
cron = CronTab()
cron_setting = textwrap.dedent("""\
┌───────────── minute (0 - 59)
│ ┌───────────── hour (0 - 23)
│ │ ┌───────────── day of month (1 - 31)
│ │ │ ┌───────────── month (1 - 12)
│ │ │ │ ┌───────────── day of week (0 - 6) (Sunday to Saturday;
│ │ │ │ │ 7 is also Sunday on some systems)
│ │ │ │ │
│ │ │ │ │
* * * * * command to execute
""")
choice = input(cron_setting)
# Reddit class
示例15: get_reddit_posts
# 需要導入模塊: import praw [as 別名]
# 或者: from praw import Reddit [as 別名]
def get_reddit_posts(subreddit_info):
post_dict = {}
print('[ OK ] Getting posts from Reddit...')
for submission in subreddit_info.hot(limit=POST_LIMIT):
if (submission.over_18 and NSFW_POSTS_ALLOWED is False):
# Skip over NSFW posts if they are disabled in the config file
print('[ OK ] Skipping', submission.id, 'because it is marked as NSFW')
continue
elif (submission.is_self and SELF_POSTS_ALLOWED is False):
# Skip over NSFW posts if they are disabled in the config file
print('[ OK ] Skipping', submission.id, 'because it is a self post')
continue
elif (submission.spoiler and SPOILERS_ALLOWED is False):
# Skip over posts marked as spoilers if they are disabled in the config file
print('[ OK ] Skipping', submission.id, 'because it is marked as a spoiler')
continue
elif (submission.stickied):
print('[ OK ] Skipping', submission.id, 'because it is stickied')
continue
else:
# Create dict
post_dict[submission.id] = submission
return post_dict