From 1e4d64013ceab74337e8583dea4a6bac96b93a90 Mon Sep 17 00:00:00 2001 From: kingston Date: Mon, 5 Oct 2026 21:01:53 -0500 Subject: [PATCH] Add AlbumOfTheDay cog (1001 Albums Generator album of the day, timezone-aware daily post) --- README.md | 40 ++++ albumoftheday/__init__.py | 16 ++ albumoftheday/albumoftheday.py | 322 +++++++++++++++++++++++++++++++++ albumoftheday/info.json | 24 +++ 4 files changed, 402 insertions(+) create mode 100644 albumoftheday/__init__.py create mode 100644 albumoftheday/albumoftheday.py create mode 100644 albumoftheday/info.json diff --git a/README.md b/README.md index 92489ca..669e84d 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,9 @@ Homepage: https://homepage.kingstons-scrapyard.net/ **Deadman** - [Deadman](#deadman) +**AlbumOfTheDay** +- [AlbumOfTheDay](#albumoftheday) + **AutoRoom** - [Installation](#installation) - [AutoRoom](#autoroom) @@ -83,6 +86,43 @@ When the switch is armed, each listed user is DM'd to confirm they were added. I --- +## AlbumOfTheDay + +Posts your [1001 Albums Generator](https://1001albumsgenerator.com) group's album of the day to a Discord channel, with group stats, genres, and streaming links. This is the in-bot equivalent of the album-notifier GitHub Actions project: instead of a cron workflow and a webhook, it runs inside the bot, stores config per server, and schedules the daily post itself. + +Install: + +``` +[p]cog install scrapyard albumoftheday +[p]load albumoftheday +``` + +Setup (per server): + +1. Find your group API URL. Take your group page URL `https://1001albumsgenerator.com/groups/your-slug` and insert `/api/v1` before `/groups`: `https://1001albumsgenerator.com/api/v1/groups/your-slug` +2. Configure: + +``` +[p]aotd seturl https://1001albumsgenerator.com/api/v1/groups/your-slug +[p]aotd setchannel #album-of-the-day +[p]aotd settime 8 0 +``` + +3. Test immediately with `[p]aotd now`. + +**Commands:** +- `[p]aotd now` - post today's album in the current channel (anyone). +- `[p]aotd seturl ` - set the group API URL (admin / Manage Server). +- `[p]aotd setchannel [#channel]` - set the daily post channel (defaults to current). +- `[p]aotd settime [minute]` - daily post time, 24-hour, in the server timezone. +- `[p]aotd settz ` - set the timezone (default `America/Chicago`, US Central). +- `[p]aotd settings` - show current config. +- `[p]aotd clear` - clear config and stop daily posting. + +The schedule is timezone-aware and defaults to US Central (CST/CDT). A time you set stays fixed in local terms year-round, with daylight saving handled automatically. The daily post is guarded against double-posting within one local day, even across bot restarts. + +--- + ## AutoRoom Automatic voice channel management. When a member joins an AutoRoom Source (voice channel), a brand new AutoRoom is created that they have control over. Once everyone leaves the AutoRoom, it is automatically deleted. diff --git a/albumoftheday/__init__.py b/albumoftheday/__init__.py new file mode 100644 index 0000000..21e5308 --- /dev/null +++ b/albumoftheday/__init__.py @@ -0,0 +1,16 @@ +"""Package for AlbumOfTheDay cog.""" + +import json +from pathlib import Path + +from redbot.core.bot import Red + +from .albumoftheday import AlbumOfTheDay + +with Path(__file__).parent.joinpath("info.json").open() as fp: + __red_end_user_data_statement__ = json.load(fp)["end_user_data_statement"] + + +async def setup(bot: Red) -> None: + """Load AlbumOfTheDay cog.""" + await bot.add_cog(AlbumOfTheDay(bot)) diff --git a/albumoftheday/albumoftheday.py b/albumoftheday/albumoftheday.py new file mode 100644 index 0000000..66a4ab3 --- /dev/null +++ b/albumoftheday/albumoftheday.py @@ -0,0 +1,322 @@ +"""AlbumOfTheDay - a Red-DiscordBot cog. + +Pulls your group's "album of the day" from the 1001 Albums Generator public +API and posts a rich embed (group stats, genres, streaming links). Replaces the +GitHub Actions + webhook flow of bturney/album-notifier with an in-bot cog: +per-guild config via Red Config, a once-a-day scheduled post via tasks.loop, +and on-demand commands. + +API shape and embed content are ported from album-notifier/notify.py. +""" + +import datetime +import logging +from typing import Optional +from zoneinfo import ZoneInfo, available_timezones + +import aiohttp +import discord +from discord.ext import tasks +from redbot.core import Config, commands +from redbot.core.bot import Red + +log = logging.getLogger("red.albumoftheday") + +# Default scheduling timezone. America/Chicago observes CST (UTC-6) in winter and +# CDT (UTC-5) in summer, so a fixed local post time stays fixed year-round. +DEFAULT_TZ = "America/Chicago" + +DEFAULT_GUILD = { + "api_url": None, # https://1001albumsgenerator.com/api/v1/groups/ + "channel_id": None, # channel to post the daily album in + "post_hour": 8, # hour 0-23 in the guild's timezone + "post_minute": 0, # minute 0-59 + "timezone": DEFAULT_TZ, # IANA timezone name the post time is interpreted in + "last_posted": None, # ISO date "YYYY-MM-DD" (in the guild tz) guarding double posts +} + +EMBED_COLOR = 0x3498DB +REQUEST_TIMEOUT = 15 + + +class AlbumOfTheDay(commands.Cog): + """Post the 1001 Albums Generator album of the day.""" + + def __init__(self, bot: Red): + self.bot = bot + self.config = Config.get_conf(self, identifier=0xA1B0_0FDA, force_registration=True) + self.config.register_guild(**DEFAULT_GUILD) + self.session = aiohttp.ClientSession() + self.daily_check.start() + + def cog_unload(self): + self.daily_check.cancel() + self.bot.loop.create_task(self.session.close()) + + # ------------------------------------------------------------------ # + # Data fetch + embed build (ported from notify.py) + # ------------------------------------------------------------------ # + async def fetch_album_data(self, api_url: str) -> dict: + """GET the group API. Raises ValueError with a user-facing message on failure.""" + try: + async with self.session.get( + api_url, timeout=aiohttp.ClientTimeout(total=REQUEST_TIMEOUT) + ) as resp: + if resp.status != 200: + raise ValueError( + f"API returned status {resp.status}. Check the API URL points to a valid group." + ) + try: + data = await resp.json() + except (aiohttp.ContentTypeError, ValueError): + raise ValueError("API returned malformed JSON.") + except aiohttp.ClientConnectionError: + raise ValueError("Could not connect to the API. Check the bot's internet connection and the API URL.") + except (aiohttp.ServerTimeoutError, TimeoutError): + raise ValueError(f"API request timed out after {REQUEST_TIMEOUT} seconds.") + except aiohttp.ClientError as e: + raise ValueError(f"API request failed: {e}") + + if "currentAlbum" not in data: + raise ValueError("API response missing 'currentAlbum'. Check the API URL points to a valid group.") + return data + + def build_album_embed(self, data: dict) -> discord.Embed: + album = data["currentAlbum"] + favorites = data.get("highestRatedAlbums", []) + worsts = data.get("lowestRatedAlbums", []) + favorite_genres = data.get("favoriteGenres", []) + worst_genres = data.get("worstGenres", []) + stats = { + "albums": data.get("numberOfGeneratedAlbums", "?"), + "votes": data.get("totalVotes", "?"), + "avg": data.get("averageRating", "?"), + } + + if favorites: + fav = favorites[0] + fav_str = f"*{fav['name']}* - {fav['artist']} ({fav['averageRating']:.1f}/5)" + else: + fav_str = "No favorites yet" + + if worsts: + worst = worsts[0] + worst_str = f"*{worst['name']}* - {worst['artist']} ({worst['averageRating']:.1f}/5)" + else: + worst_str = "No least favorites yet" + + if favorite_genres: + fg = favorite_genres[0] + fav_genre_str = f"{fg['genre'].replace('-', ' ').title()} ({fg['rating']:.1f}/5 avg)" + else: + fav_genre_str = "No favorite genre yet" + + if worst_genres: + wg = worst_genres[0] + worst_genre_str = f"{wg['genre'].replace('-', ' ').title()} ({wg['rating']:.1f}/5 avg)" + else: + worst_genre_str = "No least favorite genre yet" + + links = [f"[Reviews]({album['globalReviewsUrl']})"] if album.get("globalReviewsUrl") else [] + if album.get("wikipediaUrl"): + links.append(f"[Wikipedia]({album['wikipediaUrl']})") + if album.get("spotifyId"): + links.append(f"[Spotify](https://open.spotify.com/album/{album['spotifyId']})") + if album.get("appleMusicId"): + links.append(f"[Apple Music](https://music.apple.com/album/{album['appleMusicId']})") + links_str = " | ".join(links) + + genres = [g.replace("-", " ").title() for g in album.get("genres", [])] + genres_str = ", ".join(genres) if genres else "Unknown" + + title = f"{album['name']} - {album['artist']}" + release = album.get("releaseDate", "") + if release: + title += f" ({release})" + + description = f"**Genre(s):** {genres_str}" + if links_str: + description += f"\n{links_str}" + + embed = discord.Embed(title=title, description=description, color=EMBED_COLOR) + embed.add_field(name="All-Time Favorite", value=fav_str, inline=False) + embed.add_field(name="Least Favorite", value=worst_str, inline=False) + embed.add_field(name="Favorite Genre", value=fav_genre_str, inline=True) + embed.add_field(name="Worst Genre", value=worst_genre_str, inline=True) + embed.set_footer( + text=f"{stats['albums']} albums rated, {stats['votes']} votes cast. " + f"Group average: {stats['avg']}/5" + ) + + images = album.get("images") or [] + if images and images[0].get("url"): + embed.set_thumbnail(url=images[0]["url"]) + return embed + + async def _post_album(self, channel: discord.TextChannel, api_url: str) -> discord.Embed: + """Fetch and post the album embed to a channel. Raises ValueError on data failure.""" + data = await self.fetch_album_data(api_url) + embed = self.build_album_embed(data) + await channel.send(content="Today's Album of the Day", embed=embed) + return embed + + # ------------------------------------------------------------------ # + # Scheduled daily post + # ------------------------------------------------------------------ # + @commands.Cog.listener() + async def on_ready(self): + # Harmless if already running; ensures the loop survives a reconnect. + if not self.daily_check.is_running(): + self.daily_check.start() + + @tasks.loop(minutes=1) + async def daily_check(self): + """Runs every minute; posts once per guild when the configured local time is reached.""" + all_guilds = await self.config.all_guilds() + for guild_id, conf in all_guilds.items(): + api_url = conf.get("api_url") + channel_id = conf.get("channel_id") + if not api_url or not channel_id: + continue + + tz_name = conf.get("timezone", DEFAULT_TZ) + try: + tz = ZoneInfo(tz_name) + except Exception: + log.warning("AlbumOfTheDay: bad timezone %r in guild %s, using %s", tz_name, guild_id, DEFAULT_TZ) + tz = ZoneInfo(DEFAULT_TZ) + now = datetime.datetime.now(tz) + today = now.date().isoformat() + + if now.hour != conf.get("post_hour", 8) or now.minute != conf.get("post_minute", 0): + continue + if conf.get("last_posted") == today: + continue # already posted today + + guild = self.bot.get_guild(guild_id) + if guild is None: + continue + channel = guild.get_channel(channel_id) + if channel is None: + log.warning("AlbumOfTheDay: configured channel %s missing in guild %s", channel_id, guild_id) + continue + try: + await self._post_album(channel, api_url) + await self.config.guild_from_id(guild_id).last_posted.set(today) + except ValueError as e: + log.warning("AlbumOfTheDay: scheduled post failed in guild %s: %s", guild_id, e) + except discord.DiscordException as e: + log.warning("AlbumOfTheDay: Discord send failed in guild %s: %s", guild_id, e) + + @daily_check.before_loop + async def before_daily_check(self): + await self.bot.wait_until_red_ready() + + # ------------------------------------------------------------------ # + # Commands + # ------------------------------------------------------------------ # + @commands.group(name="albumoftheday", aliases=["aotd"]) + @commands.guild_only() + async def albumoftheday(self, ctx: commands.Context): + """Album of the Day controls.""" + + @albumoftheday.command(name="now") + async def aotd_now(self, ctx: commands.Context): + """Post today's album right now in this channel.""" + api_url = await self.config.guild(ctx.guild).api_url() + if not api_url: + await ctx.send( + f"No API URL set. An admin can set it with `{ctx.clean_prefix}aotd seturl `." + ) + return + async with ctx.typing(): + try: + await self._post_album(ctx.channel, api_url) + except ValueError as e: + await ctx.send(f"Could not fetch the album: {e}") + + @albumoftheday.command(name="seturl") + @commands.admin_or_permissions(manage_guild=True) + async def aotd_seturl(self, ctx: commands.Context, api_url: str): + """Set the 1001 Albums Generator API URL for this server. + + Take your group URL (https://1001albumsgenerator.com/groups/your-slug) + and insert /api/v1 before /groups: + https://1001albumsgenerator.com/api/v1/groups/your-slug + """ + if not api_url.startswith("https://"): + await ctx.send("The API URL must start with `https://`.") + return + await self.config.guild(ctx.guild).api_url.set(api_url) + await ctx.send( + "API URL saved. Test it now with " + f"`{ctx.clean_prefix}aotd now`." + ) + + @albumoftheday.command(name="setchannel") + @commands.admin_or_permissions(manage_guild=True) + async def aotd_setchannel(self, ctx: commands.Context, channel: Optional[discord.TextChannel] = None): + """Set the channel for the daily post (defaults to the current channel).""" + channel = channel or ctx.channel + await self.config.guild(ctx.guild).channel_id.set(channel.id) + await ctx.send(f"Daily album will be posted in {channel.mention}.") + + @albumoftheday.command(name="settime") + @commands.admin_or_permissions(manage_guild=True) + async def aotd_settime(self, ctx: commands.Context, hour: int, minute: int = 0): + """Set the daily post time in the server's timezone (24-hour). Example: settime 8 0 = 8:00am. + + The time is interpreted in the configured timezone (default America/Chicago, + CST/CDT), which auto-adjusts for daylight saving. Change the zone with settz. + """ + if not (0 <= hour <= 23) or not (0 <= minute <= 59): + await ctx.send("Hour must be 0-23 and minute 0-59.") + return + await self.config.guild(ctx.guild).post_hour.set(hour) + await self.config.guild(ctx.guild).post_minute.set(minute) + tz_name = await self.config.guild(ctx.guild).timezone() + await ctx.send(f"Daily album will post at {hour:02d}:{minute:02d} {tz_name} time.") + + @albumoftheday.command(name="settz", aliases=["settimezone"]) + @commands.admin_or_permissions(manage_guild=True) + async def aotd_settz(self, ctx: commands.Context, tz_name: str): + """Set the timezone the post time is interpreted in (IANA name). + + Example: settz America/Chicago (US Central, CST/CDT). The default is + already America/Chicago. Daylight saving is handled automatically. + """ + if tz_name not in available_timezones(): + await ctx.send( + "Unknown timezone. Use an IANA name like `America/Chicago`, " + "`America/New_York`, or `Europe/London`." + ) + return + await self.config.guild(ctx.guild).timezone.set(tz_name) + await ctx.send(f"Timezone set to {tz_name}. The daily post time is now in this zone.") + + @albumoftheday.command(name="settings", aliases=["status"]) + @commands.admin_or_permissions(manage_guild=True) + async def aotd_settings(self, ctx: commands.Context): + """Show the current configuration for this server.""" + conf = await self.config.guild(ctx.guild).all() + channel = ctx.guild.get_channel(conf["channel_id"]) if conf["channel_id"] else None + tz_name = conf.get("timezone", DEFAULT_TZ) + try: + now_local = datetime.datetime.now(ZoneInfo(tz_name)).strftime("%H:%M") + except Exception: + now_local = "?" + lines = [ + f"**API URL:** {conf['api_url'] or 'not set'}", + f"**Channel:** {channel.mention if channel else 'not set'}", + f"**Daily time:** {conf['post_hour']:02d}:{conf['post_minute']:02d} ({tz_name})", + f"**Timezone now:** {now_local} {tz_name}", + f"**Last posted:** {conf['last_posted'] or 'never'}", + ] + await ctx.send("\n".join(lines)) + + @albumoftheday.command(name="clear") + @commands.admin_or_permissions(manage_guild=True) + async def aotd_clear(self, ctx: commands.Context): + """Clear this server's configuration (stops the daily post).""" + await self.config.guild(ctx.guild).clear() + await ctx.send("Configuration cleared. Daily posting is off.") diff --git a/albumoftheday/info.json b/albumoftheday/info.json new file mode 100644 index 0000000..be6cf79 --- /dev/null +++ b/albumoftheday/info.json @@ -0,0 +1,24 @@ +{ + "name": "AlbumOfTheDay", + "author": [ + "Scrapyard Cogworks" + ], + "short": "Posts the 1001 Albums Generator album of the day on a daily schedule.", + "description": "Pulls your group's album of the day from the 1001 Albums Generator API and posts a rich embed with group stats, genres, and streaming links. Supports an on-demand command and a timezone-aware daily scheduled post per guild (default US Central, CST/CDT).", + "install_msg": "Thanks for installing AlbumOfTheDay from Scrapyard Cogworks! Set it up with [p]aotd seturl, [p]aotd setchannel, and [p]aotd settime. Visit us at https://homepage.kingstons-scrapyard.net/", + "requirements": [], + "tags": [ + "music", + "1001albums", + "notifier", + "schedule", + "daily" + ], + "min_bot_version": "3.5.0", + "min_python_version": [ + 3, + 11, + 0 + ], + "end_user_data_statement": "This cog stores per-server configuration only: the 1001 Albums Generator API URL, the target channel ID, the scheduled post time and timezone, and the date of the last post. It does not store message content or any personal user data." +}