How to use the praw.errors 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 praw-dev / praw / scripts / init_test_environment.py View on Github external
def make_submissions(r):
    for sub_info in SUBMISSIONS:
        r.login(sub_info['username'], PASSWORD)
        del sub_info['username']
        try:
            r.submit(**sub_info)
            print('Make submission: {0}'.format(sub_info['title']))
        except praw.errors.AlreadySubmitted:
            pass
github praw-dev / praw / tests / test_unauthenticated_reddit.py View on Github external
def test_create_and_delete_redditor(self):
        # This test has to be updated everytime the cassette needs to be
        # updated because we have to use consistent values for saved-runs
        # but it needs to be unique each time we actually hit reddit's
        # servers.
        key = '10'
        username = 'PyAPITestUser{0}'.format(key)
        password = 'pass{0}'.format(key)

        self.assertRaises(errors.UsernameExists, self.r.create_redditor,
                          self.other_user_name, self.other_user_pswd)

        self.r.create_redditor(username, password)
        self.r.login(username, password, disable_warning=True)
        self.assertTrue(self.r.is_logged_in())

        self.assertRaises(errors.InvalidUserPass, self.r.delete, 'bad_pswd')

        self.r.delete(password)
        self.r.clear_authentication()
        self.assertRaises(errors.InvalidUserPass, self.r.login, username,
                          password, disable_warning=True)
github praw-dev / praw / tests / test_flair.py View on Github external
def test_flair_csv_requires_user(self):
        flair_mapping = [{'flair_text': 'hsdf'}]
        self.assertRaises(errors.ClientException,
                          self.subreddit.set_flair_csv, flair_mapping)
github Anorov / reddit-commenter / commenter.py View on Github external
def _make_comment(self, content, comment):
        if not content or content.id in self.already_replied or not comment:
            return "**[SKIPPED DUE TO UNSUITABLE CONTENT SELECTION]**"

        while True:
            # Loop to re-try commenting if rate limit is hit
            try:
                self._add_comment(content, comment)
                self.already_replied.add(content.id)
                return comment
            except praw.errors.RateLimitExceeded as e:
                self._log("[RATE LIMITED] Sleeping %d seconds...\n" % e.sleep_time)
                time.sleep(e.sleep_time)
            except praw.errors.APIException as e:
                self._log("[API Error] %s\n" % e)
                return "**[SKIPPED DUE TO API ERROR]**"
            except requests.exceptions.HTTPError as e:
                if e.response.status_code == 403:
                    subreddit = content.subreddit.display_name
                    self._log("!!![BANNED FROM SUBREDDIT: %s]!!!" % subreddit)
                    self._remove_subreddit(subreddit)
                    return "**[SKIPPED DUE TO BAN: REMOVED SUBREDDIT]**"
                else:
                    return "**[SKIPPED DUE TO UNKNOWN HTTP ERROR]**"
            except Exception as e:
                self._log("**[EXCEPTION] %s\n" % e)
                return "**[SKIPPED DUE TO UNKNOWN EXCEPTION]**"
github arjunblj / slack-reddit / app.py View on Github external
def fetch_posts(subreddit, sort='hot', top_num=5):
    """Fetch post information from a subreddit given the options.
    """
    try:
        sub = Reddit.get_subreddit(subreddit)
        resp = getattr(sub, SORT_TYPES[sort])(limit=top_num)
        data = _get_post_header(subreddit, sort, top_num)
        for i, post in enumerate(resp):
            post_number = i + 1
            data += ('%s. *[%s]* <%s|%s>\n' %
                     (post_number, post.score, post.url, post.title))
        return _create_response(data)
    except praw.errors.InvalidSubreddit:
        return _create_response('Specify a subreddit that exists!')
github Wyboth / isReactionaryBot / isReactionaryBot.py View on Github external
raise SystemExit()
        try:
            if user == 'isreactionarybot':  # For smartasses.
                request.reply('Nice try.')
                sqlCursor.execute('INSERT INTO Identifiers VALUES (?)', (request.id,))
                logger.info('Received request to check self.')
            else:
                request.reply(calculate_reactionariness(user))
                sqlCursor.execute('INSERT INTO Identifiers VALUES (?)', (request.id,))
                logger.info('Received and successfully processed request to check user {0}'.format(user))
        except praw.errors.NotFound:
            request.reply('User {0} not found.\n\n---\n\nI am a bot. Only the past 1,000 posts and comments are '
                          'fetched. Questions? Suggestions? Visit /r/isReactionaryBot!'.format(user))
            sqlCursor.execute('INSERT INTO Identifiers VALUES (?)', (request.id,))
            logger.info('Received request to check user {0}. Failed to find user.'.format(user))
        except praw.errors.Forbidden:
            sqlCursor.execute('INSERT INTO Identifiers VALUES (?)', (request.id,))
            logger.info('Received request to check user {0}. Received 403 (probably banned).'.format(user))
        sqlConnection.commit()
github albertjo / User_History_Bot / Bot.py View on Github external
print 'success'
        message.mark_as_read()


def main():
    running = True
    while (running):
        run_bot()       
        time.sleep(10)


if __name__ == '__main__':
    try:
        REDDIT_INTERFACE = praw.Reddit(user_agent = USER_AGENT)
        REDDIT_INTERFACE.login(REDDIT_USERNAME, REDDIT_PASSWORD) 
    except praw.errors.InvalidUser:
        print("remember to log error that user is invalid")     
    except praw.errors.InvalidUserPass:
        print("remember to log error that password is invalid")
    main()
github SmBe19 / praw-OAuth2Util / OAuth2Util / OAuth2Util.py View on Github external
self._get_value(CONFIGKEY_SCOPE, set, split_val=','),
						self._get_value(CONFIGKEY_REFRESHABLE, as_boolean=True))

		self._start_webserver(url)
		if not self._get_value(CONFIGKEY_SERVER_MODE, as_boolean=True):
			webbrowser.open(url)
		else:
			print("Webserver is waiting for you :D. Please open {0}:{1}/{2} "
					"in your browser"
				.format(SERVER_URL, SERVER_PORT, SERVER_LINK_PATH))
		self._wait_for_response()

		try:
			access_information = self.r.get_access_information(
				self.server.response_code)
		except praw.errors.OAuthException:
			self._log("Can not authenticate, maybe the app infos (e.g. secret) are wrong.", logging.ERROR)
			raise

		self._change_value(CONFIGKEY_TOKEN, access_information["access_token"])
		self._change_value(CONFIGKEY_REFRESH_TOKEN, access_information["refresh_token"])
		self._change_value(CONFIGKEY_VALID_UNTIL, time.time() + TOKEN_VALID_DURATION)
github xl0 / LittleHelperRobot / littlehelperbot.py View on Github external
text = "Non-mobile: [%s](%s)\n\n" % (links[0]['text'], links[0]['href'])
		else: # len(links) > 1
			text = "Non-mobile:\n\n"
			for link in links:
				if link['text'] == link['href'] and link['text'][0:4] == 'http':
					text += "* %s\n" % link['href']
				else:
					text += " * [%s](%s)\n" % (link['text'], link['href'])
			text += "\n"
		text += "^That's ^why ^I'm ^here, ^I ^don't ^judge ^you. ^PM ^/u/xl0 ^if ^I'm ^causing ^any ^trouble. [^WUT?](https://github.com/xl0/LittleHelperRobot/wiki/What's-this-all-about%3F)"

		print "I'm commenting:\n", text.encode('utf-8')
		try:
			c = comment.reply(text);
			print c.permalink.encode('utf-8')
		except praw.errors.RateLimitExceeded as e:
			print "Nope, rate limit exceded:", str(e)
		except praw.errors.APIException as e:
			print "Some other exception:", str(e)
		except requests.exceptions.HTTPError as e:
			print "Looks like we are banned here"
github rossem / RedditStorage / RedditStorage.py View on Github external
def loginMod(username, password, subreddit):
    trying = True
    while trying:
        try:
            _login(username,password)
            trying = False
        except praw.errors.InvalidUserPass:
            postMessage.SetLabel("Wrong Password")
            postMessage1.SetLabel("Wrong Password")
    while checkForMod(username, subreddit):
        postMessage.SetLabel("Not a Moderator of the Subreddit")
        postMessage1.SetLabel("Not a Moderator of the Subreddit")