How to use the prawcore.exceptions.Redirect function in prawcore

To help you get started, we’ve selected a few prawcore 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 jrittenh / JustNoSinclair / justnosinclair.py View on Github external
try:
                            print("SINCLAIR", "[" + subreddit + "]", submission.title, submission.url)
                            submission.reply(comment)
                            posts_replied_to.append(submission.id)
                            with open("posts_replied_to", "a") as f:
                                f.write(submission.id + "\n")
                        except exceptions.Forbidden:
                            remove_subreddit(local_subreddits, subreddit, "banned")
                        except Exception as e:
                            print(type(e))
                            print(e)
        except exceptions.Forbidden:
            remove_subreddit(local_subreddits, subreddit, "private")
        except exceptions.NotFound:
            remove_subreddit(local_subreddits, subreddit, "invalid")
        except exceptions.Redirect:
            remove_subreddit(local_subreddits, subreddit, "not_found")
        except KeyError:
            remove_subreddit(local_subreddits, subreddit, "removed")
except Exception as e:
    print(type(e))
    print(e)
github MalloyDelacroix / DownloaderForReddit / DownloaderForReddit / Core / DownloadRunner.py View on Github external
def validate_users_and_subreddits(self):
        """See validate_users"""
        for sub in self.subreddit_list:
            if self.run:
                try:
                    subreddit = self._r.subreddit(sub.name)
                    self.validated_subreddits.append(subreddit.display_name)
                    self.queue.put('%s is valid' % subreddit.display_name)
                except (prawcore.exceptions.Redirect, prawcore.exceptions.NotFound, AttributeError):
                    self.handle_invalid_reddit_object(sub)
                except prawcore.RequestException:
                    self.handle_failed_connection()

        if self.run:
            for user in self.user_list:
                redditor = self._r.redditor(user.name)
                try:
                    test = redditor.fullname
                    self.queue.put('%s is valid' % user.name)
                    user.new_submissions = self.get_user_submissions_from_subreddits(redditor, user)
                    self.validated_objects.put(user)
                    user.check_save_directory()
                    self.update_progress_bar()
                except (prawcore.exceptions.Redirect, prawcore.exceptions.NotFound, AttributeError):
                    self.handle_invalid_reddit_object(user)
github MalloyDelacroix / DownloaderForReddit / DownloaderForReddit / Utils / RedditUtils.py View on Github external
def check_user_name(self, name):
        user = self.r.redditor(name)
        try:
            test = user.fullname
            self.name_validation.emit((name, True))
        except (prawcore.exceptions.NotFound, prawcore.exceptions.Redirect, AttributeError):
            self.name_validation.emit((name, False))
        except:
            self.logger.error('Unable to validate user name', extra={'user_name': name}, exc_info=True)
github Watchful1 / UpdateMeBot / scripts / migrate_subreddits.py View on Github external
dbConn = sqlite3.connect(static.DB_TO_MIGRATE_FROM)
c = dbConn.cursor()
log.info(f"Starting subreddits")

for row in c.execute('''
	SELECT Subreddit, Status, DefaultSubscribe, NextNotice, AlwaysPM, Filter, PostsPerDay, LastProfiled
	FROM subredditWhitelist
'''):
	subreddit_name = row[0]
	if subreddit_name in blacklist:
		continue
	reddit_subreddit = r.subreddit(subreddit_name)
	try:
		reddit_subreddit._fetch()
	except (prawcore.exceptions.Redirect, prawcore.exceptions.NotFound):
		log.info(f"Subreddit r/{subreddit_name} doesn't exist")
		continue
	except prawcore.exceptions.Forbidden:
		log.info(f"Subreddit r/{subreddit_name} forbidden")
		continue
	subreddit = new_db.get_or_add_subreddit(reddit_subreddit.display_name)
	subreddit.is_enabled = row[1] == 1
	if subreddit.is_enabled:
		subreddit.last_scanned = utils.datetime_now()
		subreddit.date_enabled = utils.datetime_now()
	subreddit.default_recurring = row[2]
	subreddit.no_comment = row[4]
	if subreddit_name == 'hfy':
		subreddit.flair_blacklist = 'meta,wp,video,misc,text'
		subreddit.prompt_type = SubredditPromptType.ALL
	elif subreddit_name == 'written4reddit':
github tylerbrockett / Alert-Bot-Reddit / src / bot_modules / reddit_handler.py View on Github external
def check_invalid_subreddits(self, subreddits):
        invalid = []
        for subreddit in subreddits:
            try:
                for submission in self.reddit.subreddit(subreddit).new(limit=1):
                    print('subreddit is valid')
            except Redirect:  # was praw.errors.InvalidSubreddit without 'len()' around call in the try block
                Logger.log(traceback.format_exc(), Color.RED)
                invalid.append(subreddit)
        return invalid
github mcandocia / TreeGrabForReddit / get_subreddit_list.py View on Github external
def validate_subreddits(opts, scraper, initial):
    opts.traversed_subreddits.update([x.lower() for x in opts.subreddits])
    for subreddit_text in opts.searching_subreddits:
        if subreddit_text in opts.traversed_subreddits:
            continue
        if subreddit_text in opts.exclude_subreddits:
            continue
        print('searching /r/%s' % subreddit_text)
        try:
            subreddit = scraper.subreddit(subreddit_text)
            num_subscribers = subreddit.subscribers
            proper_name = subreddit.display_name
        except Forbidden:
            print('%s is restricted' % subreddit_text)
            continue
        except (NotFound, Redirect):
            print('%s is not found' % subreddit_text)
            continue
        except BadRequest:
            print('%s is a bad request' % subreddit_text)
            print(sys.exc_info())
            continue
        if num_subscribers >= opts.min_subscribers and \
           (num_subscribers <= opts.max_subscribers):
            opts.proper_subreddit_set.add(proper_name)
    opts.subreddits = list(opts.proper_subreddit_set)
github mcandocia / TreeGrabForReddit / subreddit_scrape.py View on Github external
def validate_subreddit(entry, opts, scraper):
    try:
        if entry['related_subreddit'] in opts.RELATED_SUBREDDIT_SET:
            return None
        subreddit = scraper.subreddit(entry['related_subreddit'])
        #need to force update of display_name
        num_subscribers = subreddit.subscribers
        display_name = subreddit.display_name
        return subreddit
    except Forbidden:
        #at this time display_name is not updated, so just ignore it
        return None
    except (NotFound, Redirect):
        return None
    except BadRequest:
        return None
github MalloyDelacroix / DownloaderForReddit / DownloaderForReddit / UserFinder / UserFinder.py View on Github external
the supplied user name.
        :type name: str
        :type selected_posts: list
        """
        try:
            redditor = self._r.redditor(name)
            user = UserFinderUser(redditor.link_karma, redditor.created, None, name, None,
                                  self.settings_manager.user_finder_post_limit, True,
                                  self.settings_manager.download_videos, self.settings_manager.download_images,
                                  self.settings_manager.nsfw_filter, self.settings_manager.name_downloads_by, None)
            self.add_selected_posts(user, selected_posts)
            posts = self.extract_user_pots(redditor)
            self.add_posts_to_user(user, posts)
            user.last_post_date = self.get_last_post_date(redditor, user.new_submissions)
            self.valid_user_list.append(user)
        except (prawcore.exceptions.Redirect, prawcore.exceptions.NotFound, AttributeError):
            pass
github JaredHays / copy-kun / copykun.py View on Github external
def get_correct_reddit_object(self, link):
        match = re.search(link_regex, link, re.IGNORECASE)
        if not match:
            raise CannotCopyError("Failure parsing link for: \"" + link + "\"")
        try:
            # Link is to comment
            if match.group("comment_id"):
                return reddit.comment(match.group("comment_id"))
            # Link is to post
            elif match.group("id"):
                return reddit.submission(match.group("id"))
            # Link is to neither
            else:
                raise CannotCopyError("Link was not post or comment: \"" + link + "\"")
        # PRAW can throw a KeyError if it can't parse response JSON or a RedirectException for certain non-post reddit links
        except (KeyError, prawcore.exceptions.Redirect) as e:
            raise CannotCopyError("Failure parsing JSON for: \"" + orig_url + "\" (safe to ignore if URL is a non-submission reddit link)")
        except (TypeError, praw.exceptions.APIException) as e:
            logger.exception("Failure fetching url: \"" + orig_url + "\"")
            return None
github Watchful1 / UpdateMeBot / src / subreddits.py View on Github external
def subreddit_posts_per_hour(reddit, subreddit_name):
	count = 0
	oldest_submission = utils.datetime_now()
	try:
		for submission in reddit.get_subreddit_submissions(subreddit_name):
			count += 1
			submission_created = datetime.utcfromtimestamp(submission.created_utc)
			if submission_created < oldest_submission:
				oldest_submission = submission_created
			if count >= 50:
				break
	except (prawcore.exceptions.Redirect, prawcore.exceptions.NotFound):
		log.warning(f"Subreddit r/{subreddit_name} doesn't exist when profiling")
		return 1
	except prawcore.exceptions.Forbidden:
		log.warning(f"Subreddit r/{subreddit_name} forbidden when profiling")
		return 1

	if count == 0:
		return 1

	hours = math.trunc((utils.datetime_now() - oldest_submission).total_seconds() / (60 * 60))
	if hours == 0:
		posts_per_hour = count
	else:
		posts_per_hour = int(math.ceil(count / hours))

	return posts_per_hour