Files
.gitignore
bot.py
database.py
README.md
requirements.txt
Code
5 464
bot.py
import asyncio
import logging
import os
import re
import xml.etree.ElementTree as ET
import aiohttp
import discord
from discord import app_commands
from discord.ext import commands, tasks
from dotenv import load_dotenv
from database import Database
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("video-notifier")
ATOM_NS = {
"atom": "http://www.w3.org/2005/Atom",
"yt": "http://www.youtube.com/xml/schemas/2015",
}
def parse_video_feed(xml_text: str) -> list[dict[str, str]]:
root = ET.fromstring(xml_text)
videos = []
for entry in root.findall("atom:entry", ATOM_NS):
video_id = entry.findtext("yt:videoId", default="", namespaces=ATOM_NS)
title = entry.findtext("atom:title", default="Untitled video", namespaces=ATOM_NS)
published = entry.findtext("atom:published", default="", namespaces=ATOM_NS)
link_element = entry.find("atom:link[@rel='alternate']", ATOM_NS)
if not video_id:
continue
videos.append(
{
"id": video_id,
"title": title,
"published": published,
"url": (
link_element.get("href")
if link_element is not None
else f"https://www.youtube.com/watch?v={video_id}"
),
}
)
return videos
class VideoNotifier(commands.Bot):
def __init__(self) -> None:
intents = discord.Intents.default()
super().__init__(command_prefix="!", intents=intents)
self.database = Database(os.getenv("DATABASE_PATH", "data/video_notifier.db"))
self.http_session: aiohttp.ClientSession | None = None
self.notification_mention = os.getenv("NOTIFICATION_MENTION", "").strip()
async def setup_hook(self) -> None:
await self.database.initialize()
self.http_session = aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=20),
headers={"User-Agent": "DiscordVideoNotifier/1.0"},
)
guild_id = os.getenv("DISCORD_GUILD_ID", "").strip()
if guild_id:
guild = discord.Object(id=int(guild_id))
self.tree.copy_global_to(guild=guild)
await self.tree.sync(guild=guild)
logger.info("Synced commands to guild %s", guild_id)
else:
await self.tree.sync()
logger.info("Synced global commands")
poll_interval = max(30, int(os.getenv("POLL_INTERVAL_SECONDS", "300")))
self.poll_videos.change_interval(seconds=poll_interval)
self.poll_videos.start()
async def close(self) -> None:
self.poll_videos.cancel()
if self.http_session is not None:
await self.http_session.close()
await super().close()
async def on_ready(self) -> None:
logger.info("Logged in as %s (%s)", self.user, self.user.id if self.user else "unknown")
async def fetch_videos(self, youtube_channel_id: str) -> list[dict[str, str]]:
if self.http_session is None:
raise RuntimeError("HTTP session is not ready")
feed_url = f"https://www.youtube.com/feeds/videos.xml?channel_id={youtube_channel_id}"
async with self.http_session.get(feed_url) as response:
if response.status != 200:
raise RuntimeError(f"YouTube returned HTTP {response.status}")
xml_text = await response.text()
try:
videos = parse_video_feed(xml_text)
except ET.ParseError as error:
raise RuntimeError("YouTube returned an invalid feed") from error
if not videos:
raise RuntimeError("No videos were found for that channel ID")
return videos
async def get_notification_channel(self, channel_id: int) -> discord.abc.Messageable:
channel = self.get_channel(channel_id)
if channel is None:
channel = await self.fetch_channel(channel_id)
if not isinstance(channel, discord.abc.Messageable):
raise RuntimeError("The configured channel cannot receive messages")
return channel
def mention_settings(self) -> tuple[str | None, discord.AllowedMentions]:
if not self.notification_mention:
return None, discord.AllowedMentions.none()
if self.notification_mention == "@everyone":
return self.notification_mention, discord.AllowedMentions(everyone=True)
role_match = re.fullmatch(r"<@&(\d+)>", self.notification_mention)
if role_match:
role = discord.Object(id=int(role_match.group(1)))
return self.notification_mention, discord.AllowedMentions(roles=[role])
return self.notification_mention, discord.AllowedMentions.none()
async def poll_config(self, config: dict) -> int:
videos = await self.fetch_videos(config["youtube_channel_id"])
video_ids = [video["id"] for video in videos]
if not config["initialized"]:
await self.database.mark_seen(config["guild_id"], video_ids)
await self.database.mark_initialized(config["guild_id"])
return 0
seen_ids = await self.database.get_seen_ids(config["guild_id"])
new_videos = [video for video in reversed(videos) if video["id"] not in seen_ids]
channel = await self.get_notification_channel(config["discord_channel_id"])
mention, allowed_mentions = self.mention_settings()
sent_count = 0
for video in new_videos:
embed = discord.Embed(
title=video["title"],
url=video["url"],
description="A new video has been posted on YouTube.",
color=discord.Color.red(),
)
if video["published"]:
embed.timestamp = discord.utils.parse_time(video["published"])
embed.set_footer(text="YouTube video notification")
await channel.send(
content=mention,
embed=embed,
allowed_mentions=allowed_mentions,
)
await self.database.mark_seen(config["guild_id"], [video["id"]])
sent_count += 1
return sent_count
@tasks.loop(seconds=300)
async def poll_videos(self) -> None:
for config in await self.database.get_enabled_configs():
try:
sent_count = await self.poll_config(config)
if sent_count:
logger.info(
"Sent %d video notification(s) for guild %s",
sent_count,
config["guild_id"],
)
except (aiohttp.ClientError, RuntimeError, discord.DiscordException) as error:
logger.warning(
"Could not poll guild %s: %s",
config["guild_id"],
error,
)
except Exception:
logger.exception("Unexpected error while polling guild %s", config["guild_id"])
@poll_videos.before_loop
async def before_poll_videos(self) -> None:
await self.wait_until_ready()
bot = VideoNotifier()