Remove logger

This commit is contained in:
2022-12-08 13:46:13 +01:00
parent 32fd7fddc8
commit 15543bea72
3 changed files with 10 additions and 60 deletions

View File

@ -29,7 +29,7 @@ from reader import (
) )
from requests import Response from requests import Response
from discord_rss_bot.settings import logger, reader from discord_rss_bot.settings import reader
def send_to_discord(feed=None) -> None: def send_to_discord(feed=None) -> None:
@ -54,23 +54,12 @@ def send_to_discord(feed=None) -> None:
reader.update_feed(feed) reader.update_feed(feed)
entries: Iterable[Entry] = reader.get_entries(feed=feed, read=False) entries: Iterable[Entry] = reader.get_entries(feed=feed, read=False)
if not entries:
logger.info("No entries to send")
return
for entry in entries: for entry in entries:
logger.debug(f"Sending entry {entry} to Discord")
reader.set_entry_read(entry, True) reader.set_entry_read(entry, True)
logger.debug(f"Entry {entry.title} marked as read")
webhook_url: str = str(reader.get_tag(entry.feed_url, "webhook")) webhook_url: str = str(reader.get_tag(entry.feed_url, "webhook"))
logger.debug(f"Sending to webhook: {webhook_url}")
webhook_message: str = f":robot: :mega: {entry.title}\n{entry.link}" webhook_message: str = f":robot: :mega: {entry.title}\n{entry.link}"
webhook: DiscordWebhook = DiscordWebhook(url=webhook_url, content=webhook_message, rate_limit_retry=True) webhook: DiscordWebhook = DiscordWebhook(url=webhook_url, content=webhook_message, rate_limit_retry=True)
response: Response = webhook.execute() response: Response = webhook.execute()
if not response.ok: if not response.ok:
logger.error(f"Error: {response.status_code} {response.reason}")
reader.set_entry_read(entry, False) reader.set_entry_read(entry, False)
logger.debug(f"Entry {entry.title} marked as unread")

View File

@ -36,16 +36,12 @@ 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 ( from reader import Entry, EntryCounts, Feed, FeedCounts
EntryCounts,
Feed,
FeedCounts,
)
from starlette.templating import _TemplateResponse from starlette.templating import _TemplateResponse
from tomlkit.toml_document import TOMLDocument from tomlkit.toml_document import TOMLDocument
from discord_rss_bot.feeds import send_to_discord from discord_rss_bot.feeds import send_to_discord
from discord_rss_bot.settings import logger, read_settings_file, reader from discord_rss_bot.settings import read_settings_file, reader
app: FastAPI = FastAPI() app: FastAPI = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static") app.mount("/static", StaticFiles(directory="static"), name="static")
@ -56,8 +52,6 @@ templates: Jinja2Templates = Jinja2Templates(directory="templates")
def check_feed(request: Request, feed_url: str = Form()) -> _TemplateResponse: def check_feed(request: Request, feed_url: str = Form()) -> _TemplateResponse:
"""Check all feeds""" """Check all feeds"""
send_to_discord(feed_url) send_to_discord(feed_url)
logger.info(f"Get feed: {feed_url}")
feed: Feed = reader.get_feed(feed_url) feed: Feed = reader.get_feed(feed_url)
return templates.TemplateResponse("feed.html", {"request": request, "feed": feed}) return templates.TemplateResponse("feed.html", {"request": request, "feed": feed})
@ -75,26 +69,20 @@ async def create_feed(feed_url: str = Form(), webhook_dropdown: str = Form()) ->
Returns: Returns:
dict: The feed that was added. dict: The feed that was added.
""" """
# Remove spaces from feed_url
feed_url = feed_url.strip() feed_url = feed_url.strip()
logger.debug(f"Stripped feed_url: {feed_url}")
logger.info(f"Adding feed {feed_url} for {webhook_dropdown}")
reader.add_feed(feed_url) reader.add_feed(feed_url)
reader.update_feed(feed_url) reader.update_feed(feed_url)
# Mark every entry as read, so we don't send all the old entries to Discord. # Mark every entry as read, so we don't send all the old entries to Discord.
entries = reader.get_entries(feed=feed_url, read=False) entries = reader.get_entries(feed=feed_url, read=False)
for entry in entries: for entry in entries:
logger.debug(f"Marking {entry.title} as read")
reader.set_entry_read(entry, True) reader.set_entry_read(entry, True)
settings: TOMLDocument = read_settings_file() settings: TOMLDocument = read_settings_file()
logger.debug(f"Webhook name: {webhook_dropdown} with URL: {settings['webhooks'][webhook_dropdown]}")
webhook_url: str = str(settings["webhooks"][webhook_dropdown]) webhook_url: str = str(settings["webhooks"][webhook_dropdown])
reader.set_tag(feed_url, "webhook", webhook_url) reader.set_tag(feed_url, "webhook", webhook_url)
reader.get_tag(feed_url, "webhook")
# TODO: Go to the feed page. # TODO: Go to the feed page.
return {"feed_url": str(feed_url), "status": "added"} return {"feed_url": str(feed_url), "status": "added"}
@ -102,14 +90,11 @@ async def create_feed(feed_url: str = Form(), webhook_dropdown: str = Form()) ->
def create_list_of_webhooks() -> list[dict[str, str]]: def create_list_of_webhooks() -> list[dict[str, str]]:
"""List with webhooks.""" """List with webhooks."""
logger.info("Creating list with webhooks.")
settings: TOMLDocument = read_settings_file() settings: TOMLDocument = read_settings_file()
list_of_webhooks = [] list_of_webhooks = []
for hook in settings["webhooks"]: for hook in settings["webhooks"]:
logger.info(f"Webhook name: {hook} with URL: {settings['webhooks'][hook]}")
list_of_webhooks.append({"name": hook, "url": settings["webhooks"][hook]}) list_of_webhooks.append({"name": hook, "url": settings["webhooks"][hook]})
logger.debug(f"Hook: {hook}, URL: {settings['webhooks'][hook]}")
logger.info(f"List of webhooks: {list_of_webhooks}")
return list_of_webhooks return list_of_webhooks
@ -147,13 +132,10 @@ async def get_feed(feed_url: str, request: Request) -> _TemplateResponse:
Returns: Returns:
HTMLResponse: The HTML response. HTMLResponse: The HTML response.
""" """
# Convert the URL to a valid URL.
logger.info(f"Got feed: {feed_url}")
feed: Feed = reader.get_feed(feed_url) feed: Feed = reader.get_feed(feed_url)
# Get entries from the feed. # Get entries from the feed.
entries: Iterable[EntryCounts] = reader.get_entries(feed=feed_url) entries: Iterable[Entry] = reader.get_entries(feed=feed_url)
# Get the entries in the feed. # Get the entries in the feed.
feed_counts: FeedCounts = reader.get_feed_counts(feed=feed_url) feed_counts: FeedCounts = reader.get_feed_counts(feed=feed_url)
@ -194,7 +176,6 @@ def make_context_index(request) -> dict:
feed_list = [] feed_list = []
feeds: Iterable[Feed] = reader.get_feeds() feeds: Iterable[Feed] = reader.get_feeds()
for feed in feeds: for feed in feeds:
logger.debug(f"Feed: {feed}")
hook = reader.get_tag(feed.url, "webhook") hook = reader.get_tag(feed.url, "webhook")
feed_list.append({"feed": feed, "webhook": hook}) feed_list.append({"feed": feed, "webhook": hook})
@ -225,7 +206,6 @@ async def remove_feed(request: Request, feed_url: str = Form()):
reader.delete_feed(feed_url) reader.delete_feed(feed_url)
logger.info(f"Deleted feed: {feed_url}")
context = make_context_index(request) context = make_context_index(request)
return templates.TemplateResponse("index.html", context) return templates.TemplateResponse("index.html", context)
@ -238,11 +218,7 @@ def startup() -> None:
settings: TOMLDocument = read_settings_file() settings: TOMLDocument = read_settings_file()
if not settings["webhooks"]: if not settings["webhooks"]:
logger.critical("No webhooks found in settings file.") sys.exit("No webhooks found in settings file.")
sys.exit()
webhooks = settings["webhooks"]
for key in webhooks:
logger.info(f"Webhook name: {key} with URL: {settings['webhooks'][key]}")
scheduler: BackgroundScheduler = BackgroundScheduler() scheduler: BackgroundScheduler = BackgroundScheduler()

View File

@ -11,8 +11,6 @@ Functions:
Variables: Variables:
data_dir: data_dir:
Where we store the database and settings file. Where we store the database and settings file.
logger:
The logger for this program.
""" """
import logging import logging
import os import os
@ -24,8 +22,6 @@ from tomlkit.items import Table
from tomlkit.toml_document import TOMLDocument from tomlkit.toml_document import TOMLDocument
logging.basicConfig(level=logging.DEBUG, format="[%(asctime)s] [%(funcName)s:%(lineno)d] %(message)s") logging.basicConfig(level=logging.DEBUG, format="[%(asctime)s] [%(funcName)s:%(lineno)d] %(message)s")
logger: logging.Logger = logging.getLogger(__name__)
data_dir: str = user_data_dir(appname="discord_rss_bot", appauthor="TheLovinator", roaming=True) data_dir: str = user_data_dir(appname="discord_rss_bot", appauthor="TheLovinator", roaming=True)
os.makedirs(data_dir, exist_ok=True) os.makedirs(data_dir, exist_ok=True)
@ -39,8 +35,6 @@ def create_settings_file(settings_file_location) -> None:
Returns: Returns:
None None
""" """
logger.debug(f"{settings_file_location=}")
webhooks: Table = table() webhooks: Table = table()
webhooks.add(comment('"First webhook" = "https://discord.com/api/webhooks/1234567890/abcdefghijklmnopqrstuvwxyz"')) webhooks.add(comment('"First webhook" = "https://discord.com/api/webhooks/1234567890/abcdefghijklmnopqrstuvwxyz"'))
webhooks.add(comment('"Second webhook" = "https://discord.com/api/webhooks/1234567890/abcdefghijklmnopqrstuvwxyz"')) webhooks.add(comment('"Second webhook" = "https://discord.com/api/webhooks/1234567890/abcdefghijklmnopqrstuvwxyz"'))
@ -66,10 +60,7 @@ def get_db_location(custom_name: str = "db.sqlite") -> str:
Returns: Returns:
The database location. The database location.
""" """
db_name = os.path.join(data_dir, custom_name) return os.path.join(data_dir, custom_name)
logger.debug(f"{db_name=}{f', with custom db name {custom_name!r}' if custom_name != 'db.sqlite' else ''}")
return db_name
def read_settings_file(custom_name: str = "settings.toml") -> TOMLDocument: def read_settings_file(custom_name: str = "settings.toml") -> TOMLDocument:
@ -81,15 +72,9 @@ def read_settings_file(custom_name: str = "settings.toml") -> TOMLDocument:
Returns: Returns:
dict: The settings file as a dict. dict: The settings file as a dict.
""" """
settings_file = os.path.join(data_dir, custom_name) settings_file = os.path.join(data_dir, custom_name)
logger.debug(f"{settings_file=}{f', with custom db name {custom_name!r}' if custom_name != 'db.sqlite' else ''}")
with open(settings_file, encoding="utf-8") as f: with open(settings_file, encoding="utf-8") as f:
contents: TOMLDocument = parse(f.read()) return parse(f.read())
logger.debug(f"{contents=}")
return contents
db_location: str = get_db_location() db_location: str = get_db_location()