From a9c79a7a9411290f72ef64359c3de35013d947c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joakim=20Hells=C3=A9n?= Date: Sat, 28 Jan 2023 19:28:28 +0100 Subject: [PATCH] Add the webhook to existing feed if it doesn't have a webhook --- discord_rss_bot/feeds.py | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/discord_rss_bot/feeds.py b/discord_rss_bot/feeds.py index 954f8b2..71f01a2 100644 --- a/discord_rss_bot/feeds.py +++ b/discord_rss_bot/feeds.py @@ -2,7 +2,7 @@ from typing import Iterable from discord_webhook import DiscordEmbed, DiscordWebhook from fastapi import HTTPException -from reader import Entry, Feed, Reader +from reader import Entry, Feed, FeedExistsError, Reader, TagNotFoundError from requests import Response from discord_rss_bot import custom_message, settings @@ -192,21 +192,8 @@ def create_feed(reader: Reader, feed_url: str, webhook_dropdown: str) -> None: HTTPException: If webhook_dropdown does not equal a webhook or default_custom_message not found. """ clean_feed_url: str = feed_url.strip() - - # TODO: Check if the feed is valid, if not return an error or fix it. - # For example, if the feed is missing the protocol, add it. - reader.add_feed(clean_feed_url) - reader.update_feed(clean_feed_url) - - # Mark every entry as read, so we don't send all the old entries to Discord. - entries: Iterable[Entry] = reader.get_entries(feed=clean_feed_url, read=False) - for entry in entries: - reader.set_entry_read(entry, True) - - hooks = reader.get_tag((), "webhooks", []) - webhook_url: str = "" - if hooks: + if hooks := reader.get_tag((), "webhooks", []): # Get the webhook URL from the dropdown. for hook in hooks: if hook["name"] == webhook_dropdown: # type: ignore @@ -217,6 +204,23 @@ def create_feed(reader: Reader, feed_url: str, webhook_dropdown: str) -> None: # TODO: Show this error on the page. raise HTTPException(status_code=404, detail="Webhook not found") + try: + # TODO: Check if the feed is valid + reader.add_feed(clean_feed_url) + except FeedExistsError: + # Add the webhook to an already added feed if it doesn't have a webhook instead of trying to create a new. + try: + reader.get_tag(clean_feed_url, "webhook") + except TagNotFoundError: + reader.set_tag(clean_feed_url, "webhook", webhook_url) # type: ignore + + reader.update_feed(clean_feed_url) + + # Mark every entry as read, so we don't send all the old entries to Discord. + entries: Iterable[Entry] = reader.get_entries(feed=clean_feed_url, read=False) + for entry in entries: + reader.set_entry_read(entry, True) + if not default_custom_message: # TODO: Show this error on the page. raise HTTPException(status_code=404, detail="Default custom message couldn't be found.")