Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 408
bot.py
from __future__ import annotations
import asyncio
import json
import logging
import os
import re
from pathlib import Path
from typing import Any, Optional
import aiohttp
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(
level=os.getenv("LOG_LEVEL", "INFO").upper(),
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("youtube-notifier")
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY")
COMMAND_PREFIX = os.getenv("COMMAND_PREFIX", "!")
POLL_INTERVAL = max(30, int(os.getenv("POLL_INTERVAL", "60")))
DATA_FILE = Path(os.getenv("DATA_FILE", "data/subscriptions.json"))
YOUTUBE_CHANNEL_ID = re.compile(r"^UC[A-Za-z0-9_-]{22}$")
class SubscriptionStore:
def __init__(self, path: Path) -> None:
self.path = path
self.data: dict[str, Any] = {"subscriptions": {}}
self._load()
def _load(self) -> None:
if not self.path.exists():
return
try:
with self.path.open("r", encoding="utf-8") as file:
loaded = json.load(file)
if isinstance(loaded, dict) and isinstance(loaded.get("subscriptions"), dict):
self.data = loaded
except (OSError, json.JSONDecodeError):
logger.exception("Could not read %s; starting with no subscriptions", self.path)
def _save(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
temporary_path = self.path.with_suffix(".tmp")
with temporary_path.open("w", encoding="utf-8") as file:
json.dump(self.data, file, ensure_ascii=False, indent=2)
temporary_path.replace(self.path)
@staticmethod
def key(guild_id: int, youtube_channel_id: str) -> str:
return f"{guild_id}:{youtube_channel_id}"
def upsert(
self,
guild_id: int,
youtube_channel_id: str,
discord_channel_id: int,
) -> None:
key = self.key(guild_id, youtube_channel_id)
existing = self.data["subscriptions"].get(key, {})
self.data["subscriptions"][key] = {
"guild_id": guild_id,
"youtube_channel_id": youtube_channel_id,
"discord_channel_id": discord_channel_id,
"last_live_video_id": existing.get("last_live_video_id"),
}
self._save()
def remove(self, guild_id: int, youtube_channel_id: str) -> bool:
key = self.key(guild_id, youtube_channel_id)
removed = self.data["subscriptions"].pop(key, None) is not None
if removed:
self._save()
return removed
def for_guild(self, guild_id: int) -> list[dict[str, Any]]:
return [
subscription
for subscription in self.data["subscriptions"].values()
if subscription.get("guild_id") == guild_id
]
def all(self) -> list[dict[str, Any]]:
return list(self.data["subscriptions"].values())
def update_last_live(self, subscription: dict[str, Any], video_id: Optional[str]) -> None:
subscription["last_live_video_id"] = video_id
key = self.key(subscription["guild_id"], subscription["youtube_channel_id"])
if key in self.data["subscriptions"]:
self.data["subscriptions"][key]["last_live_video_id"] = video_id
self._save()
class YouTubeMonitor:
endpoint = "https://www.googleapis.com/youtube/v3/search"
def __init__(self, bot: commands.Bot, store: SubscriptionStore) -> None:
self.bot = bot
self.store = store
self.session: Optional[aiohttp.ClientSession] = None
self.task: Optional[asyncio.Task[None]] = None
async def start(self) -> None:
self.session = aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=20),
headers={"User-Agent": "YouTube-Discord-Notifier/1.0"},
)
self.task = asyncio.create_task(self._run(), name="youtube-monitor")
async def close(self) -> None:
if self.task is not None:
self.task.cancel()
await asyncio.gather(self.task, return_exceptions=True)
if self.session is not None:
await self.session.close()
async def _run(self) -> None:
await self.bot.wait_until_ready()
while not self.bot.is_closed():
try:
await self.poll_once()
except asyncio.CancelledError:
raise
except Exception:
logger.exception("Unexpected error while polling YouTube")
await asyncio.sleep(POLL_INTERVAL)
async def fetch_active_live(
self, youtube_channel_id: str
) -> tuple[bool, Optional[dict[str, str]]]:
if self.session is None or not YOUTUBE_API_KEY:
return False, None
params = {
"key": YOUTUBE_API_KEY,
"part": "snippet",
"channelId": youtube_channel_id,
"eventType": "live",
"type": "video",
"maxResults": "1",
}
try:
async with self.session.get(self.endpoint, params=params) as response:
if response.status != 200:
body = await response.text()
logger.warning(
"YouTube API returned %s for %s: %s",
response.status,
youtube_channel_id,
body[:300],
)
return False, None
payload = await response.json()
except (aiohttp.ClientError, asyncio.TimeoutError):
logger.exception("Could not contact YouTube for %s", youtube_channel_id)
return False, None
items = payload.get("items", [])
if not items:
return True, None
item = items[0]
video_id = item.get("id", {}).get("videoId")
snippet = item.get("snippet", {})
if not video_id:
return True, None
return True, {
"video_id": video_id,
"title": snippet.get("title", "Đang phát trực tiếp trên YouTube"),
"channel_title": snippet.get("channelTitle", "YouTube"),
"thumbnail": snippet.get("thumbnails", {}).get("high", {}).get("url", ""),
}
async def poll_once(self) -> None:
subscriptions = self.store.all()
if not subscriptions:
return
if not YOUTUBE_API_KEY:
logger.warning("YOUTUBE_API_KEY is not configured; live monitoring is paused")
return
results: dict[str, tuple[bool, Optional[dict[str, str]]]] = {}
for subscription in subscriptions:
youtube_channel_id = subscription["youtube_channel_id"]
if youtube_channel_id not in results:
results[youtube_channel_id] = await self.fetch_active_live(youtube_channel_id)
for subscription in subscriptions:
success, live = results[subscription["youtube_channel_id"]]
if not success: