Add a function for getting webhook for a entry

This commit is contained in:
2022-12-29 15:29:34 +01:00
parent e598455836
commit e3b44fd34e
2 changed files with 30 additions and 10 deletions

View File

@ -24,9 +24,10 @@ Exceptions:
from typing import Iterable
from discord_webhook import DiscordWebhook
from reader import Entry, Reader, TagNotFoundError
from reader import Entry, Reader
from requests import Response
from discord_rss_bot import settings
from discord_rss_bot.blacklist import should_be_skipped
from discord_rss_bot.settings import get_reader
from discord_rss_bot.whitelist import has_white_tags, should_be_sent
@ -54,22 +55,15 @@ def send_to_discord(custom_reader: Reader | None = None, feed=None, do_once=Fals
# If feed is not None we will only get the entries for that feed.
if feed is None:
# Get all the entries, we will loop through them and check if they should be sent.
entries: Iterable[Entry] = reader.get_entries(read=False)
else:
# Get all the entries, we will loop through them and check if they should be sent.
entries: Iterable[Entry] = reader.get_entries(feed=feed, read=False)
for entry in entries:
# Set the webhook to read, so we don't send it again.
reader.set_entry_read(entry, True) # type: ignore
# Get the webhook from the feed.
try:
webhook_url: str = str(reader.get_tag(entry.feed_url, "webhook"))
except TagNotFoundError:
print(f"Webhook not found for feed {entry.feed_url}")
continue
webhook_url = settings.get_webhook_for_entry(reader, entry)
webhook_message: str = f":robot: :mega: {entry.title}\n{entry.link}"
webhook: DiscordWebhook = DiscordWebhook(url=webhook_url, content=webhook_message, rate_limit_retry=True)

View File

@ -16,7 +16,7 @@ import logging
import os
from platformdirs import user_data_dir
from reader import Reader, make_reader
from reader import Entry, Reader, TagNotFoundError, make_reader
logging_format: str = "[%(asctime)s] [%(funcName)s:%(lineno)d] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=logging_format)
@ -24,6 +24,32 @@ data_dir: str = user_data_dir(appname="discord_rss_bot", appauthor="TheLovinator
os.makedirs(data_dir, exist_ok=True)
def get_webhook_for_entry(custom_reader: Reader, entry: Entry) -> str | None:
"""
Get the webhook from the database.
Args:
custom_reader: If we should use a custom reader, or the default one.
entry: The entry to get the webhook for.
Returns:
Webhook URL if it has one, returns None if not or error.
"""
# Get the default reader if we didn't get a custom one.
reader: Reader = get_reader() if custom_reader is None else custom_reader
# Get the webhook from the feed.
# Is None if not found or error.
webhook_url: str | None
try:
webhook_url = str(reader.get_tag(entry.feed_url, "webhook"))
except TagNotFoundError:
print(f"Webhook not found for feed {entry.feed_url}")
webhook_url = None
return webhook_url
def get_db_location(custom_location: str = "") -> str:
"""Where we store the database file.