How to use the praw.exceptions function in praw

To help you get started, we’ve selected a few praw examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ArthurG / PleaseRepayMe / backend / app / prediction / pipeline.py View on Github external
def make_prediction(thread_url):

    start_time = time.time()
    r = praw.Reddit(user_agent='BorrowR | https://github.com/guoarthur/reddit-queries',
      client_id=CLIENT_ID, client_secret=CLIENT_SECRET, 
      username=USERNAME, password=PASSWORD)

    submission = None
    try:
        submission = r.submission(url=thread_url)
    except praw.exceptions.ClientException:
        logger.warning('make_prediction recieved non /r/borrow URL', url=thread_url)
        return ({"error": "Please only enter posts from the /r/borrow/ subreddit"}, 400)

    if not submission.subreddit.display_name == "borrow":
        logger.warning('make_prediction recieved non /r/borrow URL', url=thread_url)
        return ({"error": "Please only enter posts from the /r/borrow/ subreddit"}, 400)

    if not "[REQ]" in submission.title:
        logger.warning('make_prediction recieved non [REQ] post', url=thread_url)
        return ({"error": "Please only enter [REQ] posts from the /r/borrow/ subreddit"}, 400)

    usernameStr = submission.author.name
    logger.info('make_prediction received a valid url, starting prediction', url=thread_url)

    predictive_data = get_predictive_data(usernameStr)
    predictions = predict_user_repayment2(predictive_data)
github mattdaviscodes / reddit-blackjack-bot / reddit_blackjack_bot.py View on Github external
sub = reddit.subreddit(subreddit)
                for post in sub.new():
                    # TODO: Check if the post itself contains a summon
                    for comment in post.comments:
                        for summon in config.SUMMON_STRINGS:
                            if summon in comment.body.lower():
                                # TODO: Check if bot has already responded to this comment
                                print("Summoned by {} in thread {}. Comment ID: {}".format(comment.author, post.title,
                                                                                           comment.id))
                                d = Game()
                                d.deal()
                                reply = d.get_reddit_reply()
                                comment.reply(reply)
        except KeyboardInterrupt:
            sys.exit()
        except praw.exceptions.APIException as e:
            # TODO: Investigate if this catches only rate limit exceptions, or more
            print(e)
            print("Rate limit exceeded. Sleeping for 10 minutes.")
            time.sleep(60)
        except Exception as e:
            print("EXCEPTION: {}".format(e))
github pmdevita / GifReversingBot / core / reply.py View on Github external
comment = comment.reply(consts.reply_template.format(message))
        if context.distinguish:
            comment.mod.distinguish(sticky=True)

        print("Successfully reversed and replied!")
    except praw.exceptions.APIException as err:
        error = vars(err)
        if err.error_type == "RATELIMIT":
            errtokens = error['message'].split()
            print("Oops! Hit the rate limit! Gotta wait " + errtokens[len(errtokens) - 2] + " " + errtokens[
                len(errtokens) - 1])
    except prawcore.exceptions.Forbidden:
        # Probably banned, message the gif to them
        comment.author.message(consts.reply_ban_subject, consts.reply_ban_template.format(url))
        print("Successfully reversed and messaged!")
    except praw.exceptions.APIException as e:
        print(e, dir(e))
        raise e
github JosephLai241 / Universal-Reddit-Scraper / pentscraper.py View on Github external
def main():
    ### Login loop    
    while True:
    	try:
            reddit = praw.Reddit(client_id = c_id, \
                             	client_secret = c_secret, \
                             	user_agent = u_a, \
                             	username = usrnm, \
                             	password = passwd)    # Connect to reddit
            break

    	except praw.exceptions.APIException:    # Catch Reddit API error. REVIEW PARAMS
    		print("Unable to connect to server. Try again.")
    	
    	except praw.exceptions.ClientException:    # Catch client login error
    		print("Unable to log in. Try again.")

    ### Scraping loop
    while True:
        index,cat_i,search_for,submissions = get_subreddit()                # Get subreddit name
        
        collected = get_posts(reddit,index,cat_i,search_for,submissions)    # Get posts in subreddit
        overview = sort_posts(collected)                                    # Sort posts from scrape, return dictionary
                             
        write_csv(index,cat_i,search_for,overview)                          # Create CSV
        
        print("\nCSV created.")
github MrPowerScripts / reddit-karma-farming-bot / src / reddit.py View on Github external
# Check if there's any items in the submissions list. If not display error
    if rand_sub:
        try:
            # Check if the we're reposting a selfpost or a link post.
            # Set the required params accodingly, and reuse the content
            # from the old post
            log.info("submission title: " + rand_sub.title)
            log.info("posting to: {}".format(rand_sub.subreddit.name))
            if rand_sub.is_self:
                params = {"title": rand_sub.title, "selftext": rand_sub.selftext}
            else:
                params = {"title": rand_sub.title, "url": rand_sub.url}

            # Submit the same content to the same subreddit. Prepare your salt picks
            api.subreddit(rand_sub.subreddit.display_name).submit(**params)
        except praw.exceptions.APIException as e:
            raise e
        except Exception as e:
            log.info(e)
    else:
        log.error("something broke")
github mattdaviscodes / reddit-blackjack-bot / bot.py View on Github external
user_agent=config.USER_AGENT,
                         username=config.USERNAME,
                         password=config.PASSWORD)
    bot = Bot(reddit, sql)

    loops = 0
    logging.info('Begin main loop')
    while True:
        loops += 1
        if loops % 100 == 0:
            logging.info("Loop {}".format(loops))
        try:
            bot.parse_mentions()
        except KeyboardInterrupt:
            sys.exit()
        except praw.exceptions.APIException as e:
            # TODO: Investigate if this catches only rate limit exceptions, or more
            logging.warn(e)
            logging.warn("Rate limit exceeded. Sleeping for 1 minute.")
            time.sleep(60)
        except Exception as e:
            logging.error(traceback.format_exc())
github petrarch1603 / MapPornBot / votingpost.py View on Github external
shortlink = submission.shortlink

    my_urls_list = []  # List of urls of all maps being submitted, used to make grid collage

    # Post each map as a comment
    for obj in cont_db.live_list:
        submission.reply('[' + str(obj.map_name) + '](' + str(obj.url) + ')   \n'
                         '' + str(obj.desc) + '\n\n----\n\n^^^^' + str(obj.raw_id))

        # Send a message to each contestant letting them know it's live.
        try:
            r.redditor(obj.author).message('The monthly map contest is live!',
                                           'Thank you for contributing a map. '
                                           '[The voting on the monthly contest is '
                                           'open now at this link.](' + shortlink + ')    \n' + botDisclaimerText)
        except praw.exceptions.APIException as e:
            print('Could not send message to ' + obj.author + '   \n' + str(e))
        try:
            cont_db.add_date_to_submission(raw_id=obj.raw_id, yearmonth=yyyymm)
        except Exception as e:
            functions.send_reddit_message_to_self(title='Voting post error',
                                                  message="could not add contest date "
                                                          "to {}\n    {}".format(obj.raw_id, e))
        my_urls_list.append(obj.url)  # Add URL to list for getting the grid collage

    # General Comment Thread so people don't post top level comments
    generalcomment = submission.reply('General Comment Thread')
    generalcomment.mod.distinguish(sticky=True)
    generalcomment.reply('**What is with the ^^^small characters?**    \n'
                         'This contest is automated with a bot. The bot uses these random characters to index the maps '
                         'and to calculate the winner at the end of the contest.\n\n----\n\n'
                         '^^^[Github](https://github.com/petrarch1603/MapPornBot)')
github trambelus / UserSim / usim.py View on Github external
if target[:3] == '/u/':
		target = target[3:]
	if target == 'YOURUSERNAMEHERE':
		log("Corrected 'YOURUSERNAMEHERE' to %s" % author)
		target = author
	#log('%s: Started %s for %s on %s' % (id, target, author, time.strftime("%Y-%m-%d %X",time.localtime(com.created_utc))))
	try:
		if (target[:3] != '/r/'):
			next(r.redditor(target).comments.new(limit=1))
	except prawcore.exceptions.NotFound:
		if levenshteinDistance(target, author) <3:
			log("Corrected spelling from %s to %s" % (target, author))
			target = author
	except StopIteration:
		pass
	except praw.exceptions.APIException:
		time.sleep(1)
	(model, sentence_avg) = get_markov(r, id, target)
	try:
		if isinstance(model, str):
			try_reply(com,(model % target) + FOOTER)
			log('%s: (%d) %s by %s in %s on %s:\n%s' % (id, index, target, author, sub, ctime, model % target), additional='\n')
		else:
			if sentence_avg == 0:
				try_reply(com,"Couldn't simulate %s: maybe this user is a bot, or has too few unique comments.%s" % (target,FOOTER))
				return
			reply_r = []
			for _ in range(random.randint(1,sentence_avg)):
				tmp_s = model.make_sentence(tries=TRIES)
				if tmp_s == None:
					try_reply(com,"Couldn't simulate %s: maybe this user is a bot, or has too few unique comments.%s" % (target,FOOTER))
					return
github PurelyApplied / roll_one_for_me / rofm / classes / reddit / endpoint.py View on Github external
def try_to_follow_link(cls, href):
        try:
            logging.debug("Attempting to follow href to comment: {}".format(href))
            return cls.r.comment(href)
        except praw.exceptions.PRAWException:
            logging.debug("Comment failed.  Attempting to follow href to submission: {]".format(href))
            return cls.r.submission(None, href)
github zonination / oc-bot / ocbot2.py View on Github external
else:
                        print('  Flair: \'{0}\' ({1})\n'.format(submission.author_flair_text, submission.author_flair_css_class))
                    
                
            # Perform Secondary Objectives (check inbox)
            chkinbox()
            time.sleep(5)
            
        reflairing = reflair()
        if reflairing:
            print('Reflairing complete.\n')
        else:
            print('Restarting reflairing session...\n')
        
    # Exception list for when Reddit inevitably screws up
    except praw.exceptions.APIException:
        print('\nAn API exception happened.\nTaking a coffee break.\n')
        time.sleep(30)
    except prawcore.exceptions.ServerError:
        print('\nReddit\'s famous 503 error occurred.\nTaking a coffee break.\n')
        time.sleep(180)
    except prawcore.exceptions.InvalidToken:
        print('\n401 error: Token needs refreshing.\nTaking a coffee break.\n')
        time.sleep(30)
    # Probably another goddamn Snoosletter that the bot can't reply to.
    except prawcore.exceptions.Forbidden:
        print('  Unable to respond. Marking as read.\n')
        for item in r.inbox.unread(limit=100):
            if item in r.inbox.messages(limit=100):
                item.mark_read()
    except (KeyboardInterrupt, SystemExit):
        raise