21 Commits
Author SHA1 Message Date
dsql 654c18fece chore: bump to 1.1.0 (logging-discipline audit)
Signed-off-by: disqualifier <dev@disqualifier.me>
2026-08-10 23:00:50 -04:00
dsql 5095953257 fix: drop exc_info on the best-effort cleanup warnings
cache_button refresh and on_timeout delete are best-effort cleanup that swallow the
HTTPException and recover; both logged at WARNING with exc_info=True, dumping a full
traceback on a handled-and-recovered path. exc_info belongs on terminal/unhandled paths -
drop it and fold the exception reason in with %s so the diagnostic is kept without the
traceback noise.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-08-09 02:13:12 -04:00
dsql 438a15813f release: 1.0.0
first stable release. pre-1.0.0 verification complete: all surviving MED regressions and
gaps resolved and independently re-fired, tree audited clean across the suite.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-09 18:53:15 -04:00
dsql b8d7bd728a docs: pin README install to v0.1.8, the newest existing tag
README pinned @v0.1.9 but that tag was never cut (newest is v0.1.8), so the documented
install line fails to resolve - point it at v0.1.8. pyproject stays at 0.1.9 under the
version freeze; the tag is cut at the 1.0.0 decision.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-06 19:38:49 -04:00
dsql d925112752 fix: skip a None content value in a multi-entry page join instead of rendering literal 'None'
the multi-entry content-join f-strung a dict entry's content with no None guard, so a
{'content': None} entry following a text entry produced a literal 'None' line
('hello' + None -> 'hello\nNone'). a None content now contributes nothing to the join.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-06 16:41:19 -04:00
dsql 9b13674440 docs: fix broken antecedent and de-duplicate the cache-button omit note
The omit-cache sentence was spliced mid-paragraph between the raw-id problem
statement and "The cache button fixes that", so "that" resolved to the wrong
antecedent (the omit-cache mechanics instead of the raw-id rendering
problem). The same note already exists standalone later in the section, so
the spliced copy was also a duplicate. Drop it from the lead paragraph and
keep the one standalone copy.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-06 00:12:11 -04:00
dsql 9e55b29e11 fix: multi-entry pages join dict content instead of dropping all but the last
The dict-entry catch-all assigned kwargs["content"] = value directly, so a
per_page > 1 page combining multiple dict entries silently kept only the
last entry's content while embeds/files/buttons from every entry still
accumulated - an asymmetry that dropped text with no error. The dict
branch's content key now routes through the same None-check/newline-join
accumulation the plain-str branch already used, so every entry's content
survives in order.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-03 19:07:24 -04:00
dsql a2cb616667 refactor: derive __version__ from package metadata (single source)
Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-03 16:59:33 -04:00
dsql bdf06b9777 docs: add missing cache_sleep to constructor options list
Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-03 16:23:41 -04:00
dsql 4e4cd0687b docs: compress prose/module docstrings, em-dash->hyphen (de-bloat wave 1)
Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-03 00:13:45 -04:00
dsql 8addecd64f fix: cache button renders on single page; cache_button edit swallows deleted/expired message (v0.1.7)
update_buttons gated the cache button behind the nav row, so a single-page
paginator with a non-empty cache never showed it despite the README promising
otherwise; the cache button now renders whenever self.cache is truthy,
independent of nav, and start() keeps the view alive for that case too.

cache_button's post-sleep message.edit was unguarded, so a message deleted or
expired during cache_sleep raised out of the callback; it now mirrors
on_timeout's NotFound/Forbidden swallow and HTTPException log.

also compresses the module and method docstrings (no behavior change).

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-02 23:23:26 -04:00
dsql bba01fa931 refactor: rename ButtonPaginator -> DPYPaginator (keep ButtonPaginator as alias)
the paginator class is now DPYPaginator, matching the package name (dpy_paginator),
for naming consistency with the suite. ButtonPaginator is kept as a back-compat alias
(ButtonPaginator = DPYPaginator), so existing imports and call sites keep working
unchanged. both names are exported in __all__. mirrors the suite's alias convention
(aioweb Response/aiowebResponse, envelope_crypto EnvelopeCrypto/PCICrypto).

verified against discord.py 2.7.1: both names resolve to the same class, construction
via either name works, the empty-pages ValueError message updated. v0.1.6.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-02 17:50:24 -04:00
dsql 546b9080ef fix: rebuild fresh File per render, convert Attachments in files= list, thread page state through locals
discord.py closes a discord.File's fp after every send/edit, so reusing the
same File object across renders raised ValueError on navigating back to a
file page; reset_files now rebuilds a fresh File from the same source
instead. The dict page 'files' list never converted discord.Attachment to
File (unlike the singular 'file' key), crashing reset_files with
AttributeError; it now converts via to_file() like its sibling. get_page_kwargs
also built render state in instance attributes across real await points,
letting two near-simultaneous interactions interleave into a merged render;
it now builds in locals and threads them through the recursive branch,
publishing self.current_page_buttons only once a page is fully assembled.

Bump to v0.1.5.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-02 17:30:26 -04:00
dsql 66933b1e2e chore: ignore .claude/ dir (CLAUDE.md now lives under .claude/)
Signed-off-by: disqualifier <dev@disqualifier.me>
2026-06-29 21:55:13 -04:00
dsql 18bbde19b6 docs: note cache=None/[] disables the cache button
Signed-off-by: disqualifier <dev@disqualifier.me>
2026-06-29 21:41:37 -04:00
dsql fa5cdf3e1d fix: F3 guard per_page>=1; swallow on_timeout HTTPException
per_page<=0 raised ZeroDivisionError (==0) or yielded a negative max_pages (<0) at the
divmod; now a clear ValueError. on_timeout swallows a transient delete HTTPException (with
a log) so a best-effort cleanup doesn't surface as an unretrieved-task traceback. add the
module logger.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-06-29 21:35:01 -04:00
dsql 1416375e40 fix: cache=[] disables the button (not raises); nav row stays suppressed on re-render (v0.1.4)
M-3: the cache-length guard used 'cache is not None', so cache=[] ([] is not None) hit the
length check and raised at construction — contradicting README/CLAUDE that say a falsy
cache disables the button (matching the render path 'if self.cache:'). guard now uses
'if cache' so [] and None both disable; a non-empty too-short cache still raises.

dpy_paginator-F2: update_buttons() now ANDs nav with max_pages>=2, so a single-page
re-render (update_page -> _build_render_kwargs, default nav=True) no longer resurrects the
nav row over the page's custom buttons. start()'s single-page branch simplified accordingly.

verified by execution with real discord.py: []-disables and None-disables both construct,
real cache renders, too-short still raises; single-page re-render keeps nav suppressed +
custom button, multi-page control still shows nav.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-06-29 20:47:43 -04:00
dsql de572af675 docs: pin install line to release, note unpinned-latest option
Signed-off-by: disqualifier <dev@disqualifier.me>
2026-06-29 18:13:51 -04:00
dsql 234f663f04 docs: show unpinned install line; note tag-pinning for reproducibility
Signed-off-by: disqualifier <dev@disqualifier.me>
2026-06-29 18:07:36 -04:00
dsql 8c3bacb2f2 fix: reject wrong-typed embed/file page keys; author_id is-None check (v0.1.3)
- a dict page with a wrong-typed embed/embeds/file/files key now raises a clear
  paginator-side ValueError instead of forwarding it to discord.py as a conflicting
  kwarg (opaque TypeError) (L12)
- interaction_check uses 'author_id is None' so an author_id of 0 still restricts (nit).

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-06-29 17:58:09 -04:00
dsql 20ea4f9291 fix: single page keeps custom buttons instead of dropping the view (v0.1.2)
a single-page result (max_pages < 2) suppressed the navigation row by dropping the
whole view, which also discarded the consumer's custom per-page buttons. now: if the
page carries custom buttons, keep the view and rebuild with update_buttons(nav=False)
— nav items suppressed, custom buttons kept, and stop() NOT called so their callbacks
still fire. a page with no custom buttons keeps the original drop-the-view behavior.

verified by execution against real discord.py: single page + custom button -> start()
-> callback FIRES on click (view kept, stop() not called); negative control on the old
code drops the button entirely; the no-button single-page case is unregressed.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-06-29 17:26:04 -04:00
5 changed files with 184 additions and 81 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
# claude # claude
CLAUDE.md .claude/
# python # python
__pycache__/ __pycache__/
+32 -9
View File
@@ -9,26 +9,31 @@ buttons) behind previous / jump / next navigation, with an optional cache button
`requirements.txt`: `requirements.txt`:
``` ```
dpy_paginator @ git+ssh://git@git.rethinkstudios.io/rethink-public/dpy_paginator.git@v0.1.1 dpy_paginator @ git+ssh://git@git.rethinkstudios.io/rethink-public/dpy_paginator.git@v1.0.0
``` ```
Direct: Direct:
```bash ```bash
pip install "dpy_paginator @ git+ssh://git@git.rethinkstudios.io/rethink-public/dpy_paginator.git@v0.1.1" pip install "dpy_paginator @ git+ssh://git@git.rethinkstudios.io/rethink-public/dpy_paginator.git@v1.0.0"
``` ```
Requires `discord.py` (pulled transitively). Requires `discord.py` (pulled transitively).
Drop the `@v1.0.0` suffix from the line above to install the latest unpinned.
## Basic usage ## Basic usage
The paginator class is `DPYPaginator`. It is also exported as `ButtonPaginator` (a
back-compat alias) — both names refer to the same class, so either import works.
Plain pages — just navigation: Plain pages — just navigation:
```python ```python
from dpy_paginator import ButtonPaginator from dpy_paginator import DPYPaginator # or: from dpy_paginator import ButtonPaginator
pages = [discord.Embed(title=f"Page {i}") for i in range(5)] pages = [discord.Embed(title=f"Page {i}") for i in range(5)]
await ButtonPaginator(pages, author_id=ctx.author.id).start(ctx) await DPYPaginator(pages, author_id=ctx.author.id).start(ctx)
``` ```
`start()` accepts an `Interaction` or any `Messageable` (a `Context`, channel, etc.). `start()` accepts an `Interaction` or any `Messageable` (a `Context`, channel, etc.).
@@ -39,7 +44,7 @@ Navigation uses plain Unicode by default — no setup, no emoji upload required.
`emojis=` to override with custom application/guild emojis the bot can use: `emojis=` to override with custom application/guild emojis the bot can use:
```python ```python
ButtonPaginator(pages, emojis={ DPYPaginator(pages, emojis={
"previous": "<:icon_back:123...>", "previous": "<:icon_back:123...>",
"next": "<:icon_next:123...>", "next": "<:icon_next:123...>",
"cache": "<:icon_cache:123...>", "cache": "<:icon_cache:123...>",
@@ -52,7 +57,20 @@ Unset keys fall back to the Unicode defaults.
A page may be a `str`, `discord.Embed`, `discord.File`/`Attachment`, a sequence of A page may be a `str`, `discord.Embed`, `discord.File`/`Attachment`, a sequence of
those, or a `dict`. A dict page can carry `content`, `embed`/`embeds`, those, or a `dict`. A dict page can carry `content`, `embed`/`embeds`,
`file`/`files`, and a `buttons` list of custom button configs. `file`/`files`, and a `buttons` list of custom button configs. Both `file` and
`files` accept a `discord.Attachment` and convert it via `to_file()` automatically —
you never need to convert an attachment before passing it in.
With `per_page > 1`, multiple entries render onto one page. `content` from each
entry (whether a plain `str` entry or a dict's `content` key) joins with `\n` in
order, same as `embeds`/`files`/`buttons` accumulate — no entry's content is
dropped in favor of another's.
File pages are safe to navigate back to. discord.py closes a `discord.File`'s
underlying handle after every send/edit, so the paginator never resends your File
object directly — it rebuilds a fresh `discord.File` from the same source (path or
buffer) on every render, so `pages` can hold a `discord.File` once and be paged
back and forth indefinitely.
## Custom per-page buttons ## Custom per-page buttons
@@ -81,7 +99,7 @@ for session in sessions:
], ],
}) })
paginator = ButtonPaginator( paginator = DPYPaginator(
pages, cache=None, timeout=900, delete_message_after=True, pages, cache=None, timeout=900, delete_message_after=True,
mentions_allowed=discord.AllowedMentions.none(), ephemeral=True, mentions_allowed=discord.AllowedMentions.none(), ephemeral=True,
page_text="Session {} of {}", page_text="Session {} of {}",
@@ -112,13 +130,17 @@ for group in groups:
pages.append(build_embed(group)) pages.append(build_embed(group))
cache.append(" ".join(f"<@{uid}>" for uid in group["user_ids"])) cache.append(" ".join(f"<@{uid}>" for uid in group["user_ids"]))
await ButtonPaginator(pages, cache=cache, cache_sleep=1.0).start(ctx) await DPYPaginator(pages, cache=cache, cache_sleep=1.0).start(ctx)
``` ```
Omit `cache` or pass `None`/`[]` and the button never appears. When set, `cache` Omit `cache` or pass `None`/`[]` and the button never appears. When set, `cache`
must have one entry per rendered page — a shorter `cache` raises `ValueError` at must have one entry per rendered page — a shorter `cache` raises `ValueError` at
construction rather than failing with an `IndexError` mid-navigation. construction rather than failing with an `IndexError` mid-navigation.
The cache button renders whenever `cache` is truthy, even on a single page (no
navigation row) — it doesn't depend on there being more than one page to flip
through.
## Constructor options ## Constructor options
- `pages` — sequence of page content - `pages` — sequence of page content
@@ -131,6 +153,7 @@ construction rather than failing with an `IndexError` mid-navigation.
- `ephemeral` — send/edit ephemerally - `ephemeral` — send/edit ephemerally
- `page_text` — format string for the jump button label - `page_text` — format string for the jump button label
- `emojis` — override navigation emojis - `emojis` — override navigation emojis
- `cache_sleep` — seconds to wait after cache-priming before refreshing (default 1.0)
## Subclassing ## Subclassing
@@ -139,4 +162,4 @@ in an embed). It may be sync or async.
## Versioning ## Versioning
Tagged `vX.Y.Z`. Pin the tag in `requirements.txt`. Releases are tagged `vX.Y.Z`. The install line above pins a release; drop the `@vX.Y.Z` suffix to install the latest unpinned. Pin deliberately for reproducible installs.
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project] [project]
name = "dpy_paginator" name = "dpy_paginator"
version = "0.1.1" version = "1.1.0"
description = "Button-navigated paginator for discord.py — config-free, injectable emojis, installable." description = "Button-navigated paginator for discord.py — config-free, injectable emojis, installable."
requires-python = ">=3.10" requires-python = ">=3.10"
dependencies = [ dependencies = [
+9 -2
View File
@@ -1,3 +1,10 @@
from .dpy_paginator import ButtonPaginator, JumpToPageModal, DEFAULT_EMOJIS, Page from importlib.metadata import version, PackageNotFoundError
__all__ = ["ButtonPaginator", "JumpToPageModal", "DEFAULT_EMOJIS", "Page"] from .dpy_paginator import DPYPaginator, ButtonPaginator, JumpToPageModal, DEFAULT_EMOJIS, Page
try:
__version__ = version("dpy_paginator")
except PackageNotFoundError:
__version__ = "0.0.0+unknown"
__all__ = ["DPYPaginator", "ButtonPaginator", "JumpToPageModal", "DEFAULT_EMOJIS", "Page", "__version__"]
+132 -59
View File
@@ -3,32 +3,20 @@ button paginator for discord.py
a discord.ui.View that paginates mixed content (strings, embeds, files, a discord.ui.View that paginates mixed content (strings, embeds, files,
attachments, or dicts of mixed content with custom buttons) behind attachments, or dicts of mixed content with custom buttons) behind
previous / jump / next navigation, with an optional cache button. previous / jump / next navigation, with an optional cache button. config-free;
everything is passed at construction. see README for page-type and button-config
details.
from dpy_paginator import ButtonPaginator file pages get a fresh discord.File rebuilt from the same source on every render,
since discord.py closes a File's handle after each send/edit. get_page_kwargs
pages = [discord.Embed(title=f"Page {i}") for i in range(5)] builds each page's kwargs/buttons in local state and only publishes once fully
await ButtonPaginator(pages, author_id=ctx.author.id).start(ctx) assembled, so concurrent interactions never interleave into a shared render.
emojis: navigation uses plain unicode by default (no setup). pass emojis= to
override with custom application/guild emojis the bot can use:
ButtonPaginator(pages, emojis={
"previous": "<:icon_back:123...>",
"next": "<:icon_next:123...>",
"cache": "<:icon_cache:123...>",
})
page types: a page may be a str, a discord.Embed, a discord.File/Attachment,
a sequence of those, or a dict. a dict page can carry 'content'/'embed(s)'/
'file(s)' plus a 'buttons' list of custom button configs (see README).
config-free: no host config import; everything is passed at construction.
""" """
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
import logging
from typing import ( from typing import (
Any, Any,
Dict, Dict,
@@ -69,6 +57,8 @@ DEFAULT_EMOJIS = {
"cache": "\U0001f5c2\ufe0f", # 🗂️ "cache": "\U0001f5c2\ufe0f", # 🗂️
} }
log = logging.getLogger(__name__)
PageT_co = TypeVar("PageT_co", bound=Page, covariant=True) PageT_co = TypeVar("PageT_co", bound=Page, covariant=True)
@@ -94,7 +84,7 @@ class _CustomButton(discord.ui.Button):
class JumpToPageModal(discord.ui.Modal, title="Jump to Page"): class JumpToPageModal(discord.ui.Modal, title="Jump to Page"):
"""modal that lets a user jump to a specific page""" """modal that lets a user jump to a specific page"""
def __init__(self, paginator: "ButtonPaginator"): def __init__(self, paginator: "DPYPaginator"):
super().__init__() super().__init__()
self.paginator = paginator self.paginator = paginator
self.page_number = discord.ui.TextInput( self.page_number = discord.ui.TextInput(
@@ -122,7 +112,7 @@ class JumpToPageModal(discord.ui.Modal, title="Jump to Page"):
) )
class ButtonPaginator(Generic[PageT_co], discord.ui.View): class DPYPaginator(Generic[PageT_co], discord.ui.View):
"""button-navigated paginator supporting mixed page content and custom buttons""" """button-navigated paginator supporting mixed page content and custom buttons"""
message: Optional[Union[discord.Message, discord.WebhookMessage]] = None message: Optional[Union[discord.Message, discord.WebhookMessage]] = None
@@ -160,7 +150,9 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
""" """
super().__init__(timeout=timeout) super().__init__(timeout=timeout)
if not pages: if not pages:
raise ValueError("ButtonPaginator requires at least one page") raise ValueError("DPYPaginator requires at least one page")
if per_page < 1:
raise ValueError("per_page must be >= 1")
self.author_id: Optional[int] = author_id self.author_id: Optional[int] = author_id
self.delete_message_after: bool = delete_message_after self.delete_message_after: bool = delete_message_after
self.mentions_allowed = mentions_allowed or discord.AllowedMentions.all() self.mentions_allowed = mentions_allowed or discord.AllowedMentions.all()
@@ -176,12 +168,11 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
total_pages, left_over = divmod(len(self.pages), self.per_page) total_pages, left_over = divmod(len(self.pages), self.per_page)
self.max_pages: int = total_pages + (1 if left_over else 0) self.max_pages: int = total_pages + (1 if left_over else 0)
if cache is not None and len(cache) < self.max_pages: if cache and len(cache) < self.max_pages:
raise ValueError( raise ValueError(
f"cache has {len(cache)} entries but there are {self.max_pages} pages; " f"cache has {len(cache)} entries but there are {self.max_pages} pages; "
"cache needs one entry per page" "cache needs one entry per page"
) )
self._page_kwargs: Dict[str, Any] = self._fresh_kwargs()
def _fresh_kwargs(self) -> Dict[str, Any]: def _fresh_kwargs(self) -> Dict[str, Any]:
"""a clean page-kwargs dict""" """a clean page-kwargs dict"""
@@ -200,7 +191,7 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
async def interaction_check(self, interaction: Interaction) -> bool: async def interaction_check(self, interaction: Interaction) -> bool:
"""restrict interaction to author_id when set""" """restrict interaction to author_id when set"""
if not self.author_id or self.author_id == interaction.user.id: if self.author_id is None or self.author_id == interaction.user.id:
return True return True
await interaction.response.send_message("You cannot interact with this menu.", ephemeral=True) await interaction.response.send_message("You cannot interact with this menu.", ephemeral=True)
return False return False
@@ -224,19 +215,40 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
async def get_page_kwargs( async def get_page_kwargs(
self, page: Union[PageT_co, Sequence[PageT_co]], skip_formatting: bool = False self, page: Union[PageT_co, Sequence[PageT_co]], skip_formatting: bool = False
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""build the send/edit kwargs for a page, extracting any custom buttons""" """build the send/edit kwargs for a page, extracting any custom buttons
concurrency-safe: publishes self.current_page_buttons only once the page
is fully assembled, so an interleaved concurrent call never observes a
partially-built page.
"""
kwargs, buttons = await self._get_page_kwargs(page, skip_formatting=skip_formatting)
self.current_page_buttons = buttons
return kwargs
async def _get_page_kwargs(
self,
page: Union[PageT_co, Sequence[PageT_co]],
skip_formatting: bool = False,
kwargs: Optional[Dict[str, Any]] = None,
buttons: Optional[List[discord.ui.Button]] = None,
) -> Tuple[Dict[str, Any], List[discord.ui.Button]]:
"""recursive worker: builds kwargs/buttons in locals, never touching instance
attributes mid-build, so concurrent calls hold their own state until
get_page_kwargs publishes the result"""
if kwargs is None:
kwargs = self._fresh_kwargs()
if buttons is None:
buttons = []
if not skip_formatting: if not skip_formatting:
self._page_kwargs = self._fresh_kwargs()
formatted_page = await discord.utils.maybe_coroutine(self.format_page, page) formatted_page = await discord.utils.maybe_coroutine(self.format_page, page)
else: else:
formatted_page = page formatted_page = page
self.current_page_buttons = []
if isinstance(formatted_page, dict): if isinstance(formatted_page, dict):
formatted_page = dict(formatted_page) formatted_page = dict(formatted_page)
for config in formatted_page.pop("buttons", []): for config in formatted_page.pop("buttons", []):
self.current_page_buttons.append( buttons.append(
_CustomButton( _CustomButton(
label=config.get("label", "Button"), label=config.get("label", "Button"),
style=config.get("style", discord.ButtonStyle.gray), style=config.get("style", discord.ButtonStyle.gray),
@@ -250,40 +262,61 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
for key, value in formatted_page.items(): for key, value in formatted_page.items():
if key == "embeds" and isinstance(value, list): if key == "embeds" and isinstance(value, list):
self._page_kwargs["embeds"].extend(value) kwargs["embeds"].extend(value)
elif key == "embed" and isinstance(value, discord.Embed): elif key == "embed" and isinstance(value, discord.Embed):
self._page_kwargs["embeds"].append(value) kwargs["embeds"].append(value)
elif key == "files" and isinstance(value, list): elif key == "files" and isinstance(value, list):
self._page_kwargs["files"].extend(value) for item in value:
if isinstance(item, discord.Attachment):
item = await item.to_file()
kwargs["files"].append(item)
elif key == "file" and isinstance(value, (discord.File, discord.Attachment)): elif key == "file" and isinstance(value, (discord.File, discord.Attachment)):
if isinstance(value, discord.Attachment): if isinstance(value, discord.Attachment):
value = await value.to_file() value = await value.to_file()
self._page_kwargs["files"].append(value) kwargs["files"].append(value)
elif key in ("embed", "embeds", "file", "files"):
# wrong-typed value would collide with base embeds=[]/files=[]; reject early
raise ValueError(
f"page key {key!r} has unexpected type {type(value).__name__}"
)
elif key == "content":
if value is None:
continue
existing = kwargs["content"]
kwargs["content"] = value if existing is None else f"{existing}\n{value}"
else: else:
self._page_kwargs[key] = value kwargs[key] = value
elif isinstance(formatted_page, str): elif isinstance(formatted_page, str):
content = self._page_kwargs["content"] content = kwargs["content"]
self._page_kwargs["content"] = ( kwargs["content"] = (
formatted_page if content is None else f"{content}\n{formatted_page}" formatted_page if content is None else f"{content}\n{formatted_page}"
) )
elif isinstance(formatted_page, discord.Embed): elif isinstance(formatted_page, discord.Embed):
self._page_kwargs["embeds"].append(formatted_page) kwargs["embeds"].append(formatted_page)
elif isinstance(formatted_page, (discord.File, discord.Attachment)): elif isinstance(formatted_page, (discord.File, discord.Attachment)):
if isinstance(formatted_page, discord.Attachment): if isinstance(formatted_page, discord.Attachment):
formatted_page = await formatted_page.to_file() formatted_page = await formatted_page.to_file()
self._page_kwargs["files"].append(formatted_page) kwargs["files"].append(formatted_page)
elif isinstance(formatted_page, (tuple, list)): elif isinstance(formatted_page, (tuple, list)):
for item in formatted_page: for item in formatted_page:
await self.get_page_kwargs(item, skip_formatting=True) await self._get_page_kwargs(item, skip_formatting=True, kwargs=kwargs, buttons=buttons)
else: else:
raise TypeError("page content must be str, discord.Embed, file/attachment, sequence, or dict") raise TypeError("page content must be str, discord.Embed, file/attachment, sequence, or dict")
return self._page_kwargs return kwargs, buttons
def update_buttons(self) -> None: def update_buttons(self, nav: bool = True) -> None:
"""rebuild the action row for the current page state""" """rebuild the action row for the current page state
nav=False (or a single page, max_pages < 2) drops prev/jump/next but keeps
custom and cache buttons; the cache button renders independent of nav
whenever self.cache is truthy.
"""
self.clear_items() self.clear_items()
nav = nav and self.max_pages >= 2
if nav:
self.previous_page.emoji = self.emojis["previous"] self.previous_page.emoji = self.emojis["previous"]
self.previous_page.disabled = self.current_page <= 0 self.previous_page.disabled = self.current_page <= 0
self.add_item(self.previous_page) self.add_item(self.previous_page)
@@ -298,6 +331,7 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
self.cache_button.emoji = self.emojis["cache"] self.cache_button.emoji = self.emojis["cache"]
self.add_item(self.cache_button) self.add_item(self.cache_button)
if nav:
self.next_page.emoji = self.emojis["next"] self.next_page.emoji = self.emojis["next"]
self.next_page.disabled = self.current_page >= self.max_pages - 1 self.next_page.disabled = self.current_page >= self.max_pages - 1
self.add_item(self.next_page) self.add_item(self.next_page)
@@ -332,13 +366,11 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
async def cache_button(self, interaction: discord.Interaction, _: discord.ui.Button) -> None: async def cache_button(self, interaction: discord.Interaction, _: discord.ui.Button) -> None:
"""prime the viewer's client mention cache, then refresh the current view """prime the viewer's client mention cache, then refresh the current view
discord clients render <@id> as a raw id until the user object is cached. a mention-cache primer, not a data cache: posts the page's mentions in a
this posts the page's mentions in a throwaway ephemeral message so the client throwaway ephemeral message (allowed_mentions=none(), tags render but no
resolves them, waits cache_sleep seconds, then re-edits the message so the ping fires) to force client resolution, waits cache_sleep seconds, then
mentions display as names — no manual page-flip needed. re-edits so mentions display as names. expected discord failures (deleted
message, no permission) are swallowed, like on_timeout.
allowed_mentions is none() on purpose: the <@id> tags still render (which is
what primes the cache) but no actual ping/notification fires.
""" """
await interaction.response.send_message( await interaction.response.send_message(
content=self.cache[self.current_page], content=self.cache[self.current_page],
@@ -349,7 +381,14 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
await asyncio.sleep(self.cache_sleep) await asyncio.sleep(self.cache_sleep)
kwargs = await self._build_render_kwargs() kwargs = await self._build_render_kwargs()
if self.message: if self.message:
try:
await self.message.edit(**kwargs) await self.message.edit(**kwargs)
except (discord.NotFound, discord.Forbidden):
pass
except discord.HTTPException as exc:
# swallowed best-effort cleanup that recovers - no traceback (exc_info belongs
# on terminal/unhandled paths); the reason is folded in for diagnosis.
log.warning("paginator cache_button: failed to refresh message: %s", exc)
@discord.ui.button(style=discord.ButtonStyle.blurple) @discord.ui.button(style=discord.ButtonStyle.blurple)
async def next_page(self, interaction: Interaction, _: discord.ui.Button[Self]) -> None: async def next_page(self, interaction: Interaction, _: discord.ui.Button[Self]) -> None:
@@ -358,32 +397,57 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
await self.update_page(interaction) await self.update_page(interaction)
def reset_files(self, page_kwargs: Dict[str, Any]) -> None: def reset_files(self, page_kwargs: Dict[str, Any]) -> None:
"""rewind file pointers so they can be sent again""" """swap in a fresh discord.File per render so a re-render never reuses a sent one
for file in page_kwargs.get("files", []):
file.reset() discord.py closes a File's fp after every send/edit; file.reset() raises
once a path-backed File is actually closed, so rebuild from source instead.
"""
files = page_kwargs.get("files")
if not files:
return
page_kwargs["files"] = [self._fresh_file(file) for file in files]
@staticmethod
def _fresh_file(file: discord.File) -> discord.File:
"""build a new discord.File from an existing one's source: a path-backed
File (_owner=True) reopens from fp.name; a buffer-backed File (_owner=False)
is never closed by discord.py, so its buffer is rewound and reused"""
if file._owner:
source = file.fp.name
else:
source = file.fp
source.seek(file._original_pos)
return discord.File(
source,
filename=file.filename,
spoiler=file.spoiler,
description=file.description,
)
async def start( async def start(
self, obj: Union[Interaction, Messageable], **send_kwargs: Any self, obj: Union[Interaction, Messageable], **send_kwargs: Any
) -> Optional[Union[discord.Message, discord.WebhookMessage]]: ) -> Optional[Union[discord.Message, discord.WebhookMessage]]:
"""send the first page; obj is an Interaction or a Messageable""" """send the first page; obj is an Interaction or a Messageable"""
kwargs = await self.get_page_kwargs(self.get_page(self.current_page)) kwargs = await self.get_page_kwargs(self.get_page(self.current_page))
# single page: update_buttons drops nav but keeps custom/cache buttons live;
# only drop the view entirely below if neither is present
self.update_buttons() self.update_buttons()
if self.max_pages < 2: if self.max_pages < 2 and not self.current_page_buttons and not self.cache:
self.stop() self.stop()
kwargs.pop("view", None) kwargs.pop("view", None)
self.reset_files(kwargs) self.reset_files(kwargs)
if isinstance(obj, discord.Interaction): if isinstance(obj, discord.Interaction):
# ephemeral is an interaction-response concept; only these paths accept it # ephemeral only applies to interaction-response paths
if obj.response.is_done(): if obj.response.is_done():
self.message = await obj.followup.send(**kwargs, ephemeral=self.ephemeral, **send_kwargs) self.message = await obj.followup.send(**kwargs, ephemeral=self.ephemeral, **send_kwargs)
else: else:
await obj.response.send_message(**kwargs, ephemeral=self.ephemeral, **send_kwargs) await obj.response.send_message(**kwargs, ephemeral=self.ephemeral, **send_kwargs)
self.message = await obj.original_response() self.message = await obj.original_response()
elif isinstance(obj, Messageable): elif isinstance(obj, Messageable):
# Messageable.send (a raw channel) has no ephemeral param never pass it # a raw channel's send has no ephemeral param; never pass it
self.message = await obj.send(**kwargs, **send_kwargs) self.message = await obj.send(**kwargs, **send_kwargs)
else: else:
raise TypeError(f"expected Interaction or Messageable, got {obj.__class__.__name__}") raise TypeError(f"expected Interaction or Messageable, got {obj.__class__.__name__}")
@@ -393,8 +457,8 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
async def on_timeout(self) -> None: async def on_timeout(self) -> None:
"""delete the message on timeout when delete_message_after is set """delete the message on timeout when delete_message_after is set
only the expected discord failures (already deleted, or no permission) are only expected discord failures (already deleted, no permission) are
swallowed; an unexpected error surfaces rather than being silently dropped. swallowed; unexpected errors surface.
""" """
if not self.delete_message_after or self.message is None: if not self.delete_message_after or self.message is None:
return return
@@ -402,3 +466,12 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
await self.message.delete() await self.message.delete()
except (discord.NotFound, discord.Forbidden): except (discord.NotFound, discord.Forbidden):
pass pass
except discord.HTTPException as exc:
# best-effort cleanup task; log rather than raise into an unretrieved task. no
# traceback (exc_info belongs on terminal/unhandled paths) - fold the reason in.
log.warning("paginator on_timeout: failed to delete message: %s", exc)
# back-compat alias: the class was originally named ButtonPaginator; DPYPaginator is
# the canonical name (matching the package), both refer to the same class
ButtonPaginator = DPYPaginator