Fix send_to_discord and add more excepts

This commit is contained in:
2022-12-06 10:18:33 +01:00
parent b5c3edf871
commit c8e76291a5
2 changed files with 48 additions and 24 deletions

View File

@ -24,12 +24,15 @@ Exceptions:
from discord_webhook import DiscordWebhook from discord_webhook import DiscordWebhook
from pydantic import BaseModel from pydantic import BaseModel
from reader import ( from reader import (
EntryNotFoundError,
FeedExistsError, FeedExistsError,
FeedNotFoundError, FeedNotFoundError,
InvalidFeedURLError, InvalidFeedURLError,
ParseError, ParseError,
StorageError, StorageError,
TagNotFoundError,
) )
from reader.types import EntryLike
from requests import Response from requests import Response
from discord_rss_bot.settings import logger, reader from discord_rss_bot.settings import logger, reader
@ -127,19 +130,17 @@ def check_feeds() -> None:
if it was successful. if it was successful.
""" """
reader.update_feeds() reader.update_feeds()
entries = reader.get_entries(read=False) send_to_discord()
for entry in entries:
send_to_discord(entry)
def send_to_discord(entry) -> Response: def send_to_discord(feed=None):
""" """
Send entries to Discord. Send entries to Discord.
If response was not ok, we will log the error and mark the entry as unread, so it will be sent again next time. If response was not ok, we will log the error and mark the entry as unread, so it will be sent again next time.
Args: Args:
entry: The entry to send. feed: The entry to send.
Raises: Raises:
NoWebhookFoundError: If no webhook is found. NoWebhookFoundError: If no webhook is found.
@ -147,23 +148,47 @@ def send_to_discord(entry) -> Response:
Returns: Returns:
Response: The response from the webhook. Response: The response from the webhook.
""" """
if feed is None:
entries = reader.get_entries(read=False)
else:
entries = reader.get_entries(feed=feed, read=False)
reader.set_entry_read(entry) if not entries:
logger.debug(f"New entry: {entry.title}") logger.info("No entries to send")
return
webhook_url = str(reader.get_tag(entry.feed.url, "webhook")) for entry in entries:
if not webhook_url: logger.debug(f"Sending entry {entry} to Discord")
logger.error(f"No webhook found for feed: {entry.feed.url}") try:
raise NoWebhookFoundError(f"No webhook found for feed: {entry.feed.url}") reader.set_entry_read(entry, True)
logger.debug(f"New entry: {entry.title}")
except EntryNotFoundError:
logger.error("Entry not found", exc_info=True)
raise
except StorageError:
logger.error("Storage error", exc_info=True)
raise
logger.debug(f"Sending to webhook: {webhook_url}") try:
webhook_message = f":robot: :mega: {entry.title}\n{entry.link}" webhook_url = str(reader.get_tag(entry.feed.url, "webhook"))
webhook = DiscordWebhook(url=webhook_url, content=webhook_message, rate_limit_retry=True) except TagNotFoundError:
response = webhook.execute() logger.error("Tag not found", exc_info=True)
if not response.ok: raise
logger.error(f"Error: {response.status_code} {response.reason}") except StorageError:
reader.set_entry_read(entry, False) logger.error("Storage error", exc_info=True)
return response raise
if not webhook_url:
logger.error(f"No webhook found for feed: {entry.feed.url}")
raise NoWebhookFoundError(f"No webhook found for feed: {entry.feed.url}")
logger.debug(f"Sending to webhook: {webhook_url}")
webhook_message = f":robot: :mega: {entry.title}\n{entry.link}"
webhook = DiscordWebhook(url=webhook_url, content=webhook_message, rate_limit_retry=True)
response = webhook.execute()
if not response.ok:
logger.error(f"Error: {response.status_code} {response.reason}")
reader.set_entry_read(entry, False)
def update_feed(feed_url: str, webhook: str) -> IfFeedError: def update_feed(feed_url: str, webhook: str) -> IfFeedError:

View File

@ -37,7 +37,7 @@ from fastapi import FastAPI, Form, HTTPException, Request
from fastapi.responses import FileResponse, HTMLResponse from fastapi.responses import FileResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates from fastapi.templating import Jinja2Templates
from reader import Entry, EntryCounts, Feed, FeedCounts, ResourceNotFoundError from reader import EntryCounts, Feed, FeedCounts, ResourceNotFoundError
from tomlkit.toml_document import TOMLDocument from tomlkit.toml_document import TOMLDocument
from discord_rss_bot.feeds import IfFeedError, add_feed, send_to_discord, update_feed from discord_rss_bot.feeds import IfFeedError, add_feed, send_to_discord, update_feed
@ -53,8 +53,7 @@ templates: Jinja2Templates = Jinja2Templates(directory="templates")
def check_feed(request: Request, feed_url: str = Form()): def check_feed(request: Request, feed_url: str = Form()):
"""Check all feeds""" """Check all feeds"""
reader.update_feeds() reader.update_feeds()
entry: Iterable[Entry] = reader.get_entries(feed=feed_url, read=False) send_to_discord(feed_url)
send_to_discord(entry)
logger.info(f"Get feed: {feed_url}") logger.info(f"Get feed: {feed_url}")
feed: Feed = reader.get_feed(feed_url) feed: Feed = reader.get_feed(feed_url)
@ -94,8 +93,8 @@ async def create_feed(feed_url: str = Form(), webhook_dropdown: str = Form()) ->
# Check if set_hook_by_name() was successful. # Check if set_hook_by_name() was successful.
if isinstance( if isinstance(
set_hook_by_name(name=webhook_dropdown, feed_url=feed_url), set_hook_by_name(name=webhook_dropdown, feed_url=feed_url),
ResourceNotFoundError, ResourceNotFoundError,
): ):
return set_hook_by_name(name=webhook_dropdown, feed_url=feed_url) return set_hook_by_name(name=webhook_dropdown, feed_url=feed_url)