6 Commits
Author SHA1 Message Date
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
5 changed files with 163 additions and 51 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
# claude
CLAUDE.md
.claude/
# python
__pycache__/
+22 -9
View File
@@ -9,28 +9,31 @@ buttons) behind previous / jump / next navigation, with an optional cache button
`requirements.txt`:
```
dpy_paginator @ git+ssh://git@git.rethinkstudios.io/rethink-public/dpy_paginator.git@v0.1.3
dpy_paginator @ git+ssh://git@git.rethinkstudios.io/rethink-public/dpy_paginator.git@v0.1.6
```
Direct:
```bash
pip install "dpy_paginator @ git+ssh://git@git.rethinkstudios.io/rethink-public/dpy_paginator.git@v0.1.3"
pip install "dpy_paginator @ git+ssh://git@git.rethinkstudios.io/rethink-public/dpy_paginator.git@v0.1.6"
```
Requires `discord.py` (pulled transitively).
Drop the `@v0.1.3` suffix from the line above to install the latest unpinned.
Drop the `@v0.1.6` suffix from the line above to install the latest unpinned.
## 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:
```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)]
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.).
@@ -41,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:
```python
ButtonPaginator(pages, emojis={
DPYPaginator(pages, emojis={
"previous": "<:icon_back:123...>",
"next": "<:icon_next:123...>",
"cache": "<:icon_cache:123...>",
@@ -54,7 +57,15 @@ Unset keys fall back to the Unicode defaults.
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`,
`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.
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
@@ -83,7 +94,7 @@ for session in sessions:
],
})
paginator = ButtonPaginator(
paginator = DPYPaginator(
pages, cache=None, timeout=900, delete_message_after=True,
mentions_allowed=discord.AllowedMentions.none(), ephemeral=True,
page_text="Session {} of {}",
@@ -99,6 +110,8 @@ echoes its `data`.
## Cache button (mention priming)
Discord clients render `<@id>` as a raw id until the user object is cached locally.
Omit `cache` (or pass `None` / `[]`) and the button never appears; a non-empty cache
must have one entry per page or construction raises.
The cache button fixes that: pass `cache=[...]` with one entry per page, where each
entry is a string of the user mentions on that page (`"<@111> <@222> <@333>"`).
@@ -114,7 +127,7 @@ for group in groups:
pages.append(build_embed(group))
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`
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "dpy_paginator"
version = "0.1.3"
version = "0.1.6"
description = "Button-navigated paginator for discord.py — config-free, injectable emojis, installable."
requires-python = ">=3.10"
dependencies = [
+2 -2
View File
@@ -1,3 +1,3 @@
from .dpy_paginator import ButtonPaginator, JumpToPageModal, DEFAULT_EMOJIS, Page
from .dpy_paginator import DPYPaginator, ButtonPaginator, JumpToPageModal, DEFAULT_EMOJIS, Page
__all__ = ["ButtonPaginator", "JumpToPageModal", "DEFAULT_EMOJIS", "Page"]
__all__ = ["DPYPaginator", "ButtonPaginator", "JumpToPageModal", "DEFAULT_EMOJIS", "Page"]
+137 -38
View File
@@ -5,15 +5,15 @@ a discord.ui.View that paginates mixed content (strings, embeds, files,
attachments, or dicts of mixed content with custom buttons) behind
previous / jump / next navigation, with an optional cache button.
from dpy_paginator import ButtonPaginator
from dpy_paginator import DPYPaginator # or ButtonPaginator, an alias
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)
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={
DPYPaginator(pages, emojis={
"previous": "<:icon_back:123...>",
"next": "<:icon_next:123...>",
"cache": "<:icon_cache:123...>",
@@ -21,7 +21,21 @@ override with custom application/guild emojis the bot can use:
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).
'file(s)' plus a 'buttons' list of custom button configs (see README). both
the singular 'file' and plural 'files' dict keys accept a discord.Attachment
and convert it via to_file() — neither key requires the caller to convert
first.
file pages are re-rendered safely: discord.py closes a discord.File's
underlying handle after every send/edit, so the paginator never resends a
consumer-supplied File object directly — it rebuilds a fresh discord.File
from the same source (path or buffer) on every render, including the first.
concurrency: get_page_kwargs builds each page's kwargs/buttons in local
state and only publishes them once the whole page (including any awaited
format_page or Attachment.to_file() conversions) is fully assembled, so two
near-simultaneous interactions (e.g. rapid button clicks) never interleave
into a merged or shared render.
config-free: no host config import; everything is passed at construction.
"""
@@ -29,6 +43,7 @@ config-free: no host config import; everything is passed at construction.
from __future__ import annotations
import asyncio
import logging
from typing import (
Any,
Dict,
@@ -69,6 +84,8 @@ DEFAULT_EMOJIS = {
"cache": "\U0001f5c2\ufe0f", # 🗂️
}
log = logging.getLogger(__name__)
PageT_co = TypeVar("PageT_co", bound=Page, covariant=True)
@@ -94,7 +111,7 @@ class _CustomButton(discord.ui.Button):
class JumpToPageModal(discord.ui.Modal, title="Jump to Page"):
"""modal that lets a user jump to a specific page"""
def __init__(self, paginator: "ButtonPaginator"):
def __init__(self, paginator: "DPYPaginator"):
super().__init__()
self.paginator = paginator
self.page_number = discord.ui.TextInput(
@@ -122,8 +139,12 @@ class JumpToPageModal(discord.ui.Modal, title="Jump to Page"):
)
class ButtonPaginator(Generic[PageT_co], discord.ui.View):
"""button-navigated paginator supporting mixed page content and custom buttons"""
class DPYPaginator(Generic[PageT_co], discord.ui.View):
"""button-navigated paginator supporting mixed page content and custom buttons
also importable as `ButtonPaginator` (a back-compat alias defined below); both
names refer to this same class.
"""
message: Optional[Union[discord.Message, discord.WebhookMessage]] = None
@@ -160,7 +181,11 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
"""
super().__init__(timeout=timeout)
if not pages:
raise ValueError("ButtonPaginator requires at least one page")
raise ValueError("DPYPaginator requires at least one page")
if per_page < 1:
# per_page <= 0 would ZeroDivisionError (==0) or yield a negative max_pages
# (<0) at the divmod below; fail loud like the other construction guards
raise ValueError("per_page must be >= 1")
self.author_id: Optional[int] = author_id
self.delete_message_after: bool = delete_message_after
self.mentions_allowed = mentions_allowed or discord.AllowedMentions.all()
@@ -176,12 +201,13 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
total_pages, left_over = divmod(len(self.pages), self.per_page)
self.max_pages: int = total_pages + (1 if left_over else 0)
if cache is not None and len(cache) < self.max_pages:
# a falsy cache (None or []) disables the cache button (see the render path's
# `if self.cache:`); only a non-empty cache must have one entry per page
if cache and len(cache) < self.max_pages:
raise ValueError(
f"cache has {len(cache)} entries but there are {self.max_pages} pages; "
"cache needs one entry per page"
)
self._page_kwargs: Dict[str, Any] = self._fresh_kwargs()
def _fresh_kwargs(self) -> Dict[str, Any]:
"""a clean page-kwargs dict"""
@@ -224,19 +250,44 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
async def get_page_kwargs(
self, page: Union[PageT_co, Sequence[PageT_co]], skip_formatting: bool = False
) -> 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
builds into local state and publishes self.current_page_buttons only once
the whole page (including any nested recursion and awaited conversions) is
fully assembled, so an interleaved concurrent call never observes or
mutates a partially-built page (see _get_page_kwargs).
"""
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: build kwargs/buttons in locals, threaded through recursion
instance attributes are never read or written mid-build, so concurrent
interactions each hold their own kwargs/buttons until get_page_kwargs
publishes the finished result.
"""
if kwargs is None:
kwargs = self._fresh_kwargs()
if buttons is None:
buttons = []
if not skip_formatting:
self._page_kwargs = self._fresh_kwargs()
formatted_page = await discord.utils.maybe_coroutine(self.format_page, page)
else:
formatted_page = page
self.current_page_buttons = []
if isinstance(formatted_page, dict):
formatted_page = dict(formatted_page)
for config in formatted_page.pop("buttons", []):
self.current_page_buttons.append(
buttons.append(
_CustomButton(
label=config.get("label", "Button"),
style=config.get("style", discord.ButtonStyle.gray),
@@ -250,15 +301,18 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
for key, value in formatted_page.items():
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):
self._page_kwargs["embeds"].append(value)
kwargs["embeds"].append(value)
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)):
if isinstance(value, discord.Attachment):
value = await value.to_file()
self._page_kwargs["files"].append(value)
kwargs["files"].append(value)
elif key in ("embed", "embeds", "file", "files"):
# a wrong-typed embed/file would otherwise fall to the catch-all and
# be forwarded verbatim, colliding with the base embeds=[]/files=[]
@@ -268,25 +322,25 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
f"page key {key!r} has unexpected type {type(value).__name__}"
)
else:
self._page_kwargs[key] = value
kwargs[key] = value
elif isinstance(formatted_page, str):
content = self._page_kwargs["content"]
self._page_kwargs["content"] = (
content = kwargs["content"]
kwargs["content"] = (
formatted_page if content is None else f"{content}\n{formatted_page}"
)
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)):
if isinstance(formatted_page, discord.Attachment):
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)):
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:
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, nav: bool = True) -> None:
"""rebuild the action row for the current page state
@@ -294,9 +348,13 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
nav=False rebuilds with only the page's custom buttons and no navigation
items (prev/jump/cache/next) — a single-page result that still carries
custom buttons keeps them (and their live callbacks) without a nav row.
the nav row is also suppressed for a single page (max_pages < 2) even when
nav is left at its default, so a re-render (update_page) never resurrects it.
"""
self.clear_items()
nav = nav and self.max_pages >= 2
if nav:
self.previous_page.emoji = self.emojis["previous"]
self.previous_page.disabled = self.current_page <= 0
@@ -373,26 +431,58 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
await self.update_page(interaction)
def reset_files(self, page_kwargs: Dict[str, Any]) -> None:
"""rewind file pointers so they can be sent again"""
for file in page_kwargs.get("files", []):
file.reset()
"""swap in a fresh discord.File per render so a re-render never reuses a sent one
discord.py closes a File's underlying fp after every send/edit
(MultipartParameters.__exit__ -> file.close()), so the SAME File object is
single-use. Rather than call file.reset() (which raises 'seek of closed
file' the moment a path-backed File has actually been closed), rebuild a
new discord.File from the same source for every entry — cheap, and safe
whether or not the previous render already consumed it.
"""
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 (fp opened internally, _owner=True) is reopened from
fp.name, the path it was constructed with — fp.name stays readable even
after discord.py has closed the handle, so this works whether or not the
previous render already consumed it. a buffer-backed File (caller passed
an io object, _owner=False) is never closed by discord.py (see
File.close(), which only closes _owner=True files) so its buffer is
rewound to its starting position and reused directly.
"""
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(
self, obj: Union[Interaction, Messageable], **send_kwargs: Any
) -> Optional[Union[discord.Message, discord.WebhookMessage]]:
"""send the first page; obj is an Interaction or a Messageable"""
kwargs = await self.get_page_kwargs(self.get_page(self.current_page))
# update_buttons already suppresses the nav row for a single page (max_pages < 2),
# keeping only the page's custom buttons — so a single page with custom buttons
# renders them (live callbacks) with no nav row
self.update_buttons()
if self.max_pages < 2:
if self.current_page_buttons:
# single page WITH custom buttons: keep the view live so the
# buttons' callbacks still fire; strip only the navigation row
self.update_buttons(nav=False)
else:
# single page, no custom buttons: no interactive row at all
self.stop()
kwargs.pop("view", None)
if self.max_pages < 2 and not self.current_page_buttons:
# single page, no custom buttons: no interactive row at all, drop the view
self.stop()
kwargs.pop("view", None)
self.reset_files(kwargs)
@@ -423,3 +513,12 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
await self.message.delete()
except (discord.NotFound, discord.Forbidden):
pass
except discord.HTTPException:
# on_timeout runs as a fire-and-forget task; a transient delete failure must
# not surface as an unretrieved-task traceback on a best-effort cleanup
log.warning("paginator on_timeout: failed to delete message", exc_info=True)
# 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