diff --git a/reddit.py b/reddit.py index dd668ec..8bd76b5 100644 --- a/reddit.py +++ b/reddit.py @@ -25,6 +25,34 @@ def get_reddit_instance(): ) +def get_reddit_post(sub, is_image_post=False): + reddit_instance = get_reddit_instance() + + try: + sub = reddit_instance.subreddit(sub) + post = sub.random() + + except exceptions.NotFound: + return "Geile, gib gültiges Sub" + except exceptions.Forbidden: + return "Geile, gib freies Sub" + except Exception as e: + return e + + if post == None: + return "Random geht in diesem Sub leider nicht :(" + + if is_image_post: + tries = 0 + while "image" not in get_post_type(post.url) and tries < 5: + post = sub.random() + tries += 1 + if tries >= 5: + return "Geile, gib Sub mit Bildern (über 5 Fehlversuche)" + + return post.url + + def wrong_dog(bot, update): reddit(bot, update, ['whatswrongwithyourdog']) @@ -37,40 +65,14 @@ def reddit(bot, update, args): if not args: update.message.reply_text("Geile, sag sub") return - sub = args[0] - reddit_instance = get_reddit_instance() - post = reddit_instance.subreddit(sub).random() - update.message.reply_text(post.url) + sub = args[0] + update.message.reply_text(get_reddit_post(sub)) def reddit_img(bot, update, args): if not args: update.message.reply_text("Geile, sag sub") return - desired_sub = args[0] - reddit_instance = get_reddit_instance() - - try: - sub = reddit_instance.subreddit(desired_sub) - post = sub.random() - print(post.url) - except exceptions.NotFound: - update.message.reply_text("Geile, gib gültiges Sub") - return - except exceptions.Forbidden: - update.message.reply_text("Geile, gib freies Sub") - return - except Exception as e: - update.message.reply_text(e) - return - - tries = 0 - while "image" not in get_post_type(post.url) and tries < 5: - post = sub.random() - tries += 1 - if tries >= 5: - update.message.reply_text("Geile, gib Sub mit Bildern (über 5 Fehlversuche)") - return - - bot.send_photo(chat_id=update.message.chat_id, photo=post.url) + sub = args[0] + bot.send_photo(chat_id=update.message.chat_id, photo=get_reddit_post(sub, True))