from __future__ import annotations import builtins from collections.abc import Callable, Sequence import os from pathlib import Path from typing import cast from albedo_api import Host, HostMedia, PythonApi, Record, Text host: Host active_media_cell: Callable[[], str] | None = None attach_host_media: Callable[[str, HostMedia, float | None], str] | None = None MAX_FILES = 10 MAX_FILE_BYTES = 10 * 1024 * 1024 def written(value: str | int | None) -> str | None: return None if value is None else str(value) def attachments( files: str | os.PathLike[str] | Sequence[str | os.PathLike[str]] | None, ) -> builtins.list[str]: if files is None: return [] items = [files] if isinstance(files, (str, os.PathLike)) else list(files) if len(items) > MAX_FILES: raise ValueError(f"Discord accepts at most {MAX_FILES} files per message") resolved: builtins.list[str] = [] for item in items: path = Path(item).expanduser().resolve() if not path.exists(): raise FileNotFoundError(str(item)) if not path.is_file(): raise IsADirectoryError(f"{item!s} is not a file") if path.stat().st_size > MAX_FILE_BYTES: raise ValueError(f"{path.name} exceeds Discord's 10 MiB limit") resolved.append(str(path)) return resolved class Discord: async def send( self, channel: str, text: str = "", reply_to: str | int | None = None, files: str | os.PathLike[str] | Sequence[str | os.PathLike[str]] | None = None, ) -> Record: """Post in a channel by handle ("c3") or name, optionally replying to a message number or attaching files (a path or list of up to 10 paths, each at most 10 MiB). Text past 2000 characters is split; returns Record(messages, channel): the numbers posted and the handle.""" paths = attachments(files) if not text and not paths: raise ValueError("send needs text or files") value = cast( dict[str, object], await host( "discord.send", { "channel": channel, "text": text, "reply_to": written(reply_to), "files": paths, }, ), ) return Record(value) async def dm( self, user: str, text: str = "", files: str | os.PathLike[str] | Sequence[str | os.PathLike[str]] | None = None, ) -> Record: """DM the bot's owner or an allowed person, optionally attaching files; returns Record(messages, channel).""" paths = attachments(files) if not text and not paths: raise ValueError("dm needs text or files") return Record( cast( dict[str, object], await host("discord.dm", {"user": user, "text": text, "files": paths}), ) ) async def history( self, channel: str, limit: int = 20, before: str | int | None = None ) -> builtins.list[Record]: """Recent messages, oldest first: Record(number, author, username, bot, content, timestamp, reply_to, attachments, sticker_items, emotes). Use their media refs with `show_media`. `before` is a message number.""" items = await host( "discord.history", {"channel": channel, "limit": limit, "before": written(before)}, ) return [Record(item) for item in cast(builtins.list[dict], items)] async def show_media(self, ref: str, *, fps: float | None = None) -> Text: """Attach one Discord media ref to the running cell's result, without downloading it into Python. Use a ref from a Discord event or history, not a URL. fps is for videos and only on models that take it. A saved nested cell keeps the attachment on its own result, not its caller's. If this cell is full, show the ref again in another cell. """ if active_media_cell is None or attach_host_media is None: raise RuntimeError("this kernel does not support discord media previews") cell_id = active_media_cell() media = cast( HostMedia, await host("discord.show_media", {"cell_id": cell_id, "ref": ref}), ) return Text(attach_host_media(cell_id, media, fps)) async def react(self, channel: str, message: str | int, emoji: str) -> None: """React to a message number with a unicode emoji, or name:id for a custom one.""" await host( "discord.react", {"channel": channel, "message": str(message), "emoji": emoji}, ) async def channels(self) -> builtins.list[Record]: """Channels the bot sees: handle, name, guild, delivery, mentions_only.""" items = await host("discord.channels", {}) return [Record(item) for item in cast(builtins.list[dict], items)] async def status(self) -> Record: """The bot's name, state, detail, user, owner and invite_url.""" return Record(cast(dict[str, object], await host("discord.status", {}))) def setup(api: PythonApi) -> dict[str, object]: global host, active_media_cell, attach_host_media host = api.host active_media_cell = api.active_media_cell attach_host_media = api.attach_host_media return {"discord": Discord(), "DiscordError": api.HostError}