Compare commits
10
Commits
8addecd64f
...
v1.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
654c18fece | ||
|
|
5095953257 | ||
|
|
438a15813f | ||
|
|
b8d7bd728a | ||
|
|
d925112752 | ||
|
|
9b13674440 | ||
|
|
9e55b29e11 | ||
|
|
a2cb616667 | ||
|
|
bdf06b9777 | ||
|
|
4e4cd0687b |
@@ -9,18 +9,18 @@ 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.7
|
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.7"
|
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 `@v0.1.7` suffix from the line above to install the latest unpinned.
|
Drop the `@v1.0.0` suffix from the line above to install the latest unpinned.
|
||||||
|
|
||||||
## Basic usage
|
## Basic usage
|
||||||
|
|
||||||
@@ -61,6 +61,11 @@ those, or a `dict`. A dict page can carry `content`, `embed`/`embeds`,
|
|||||||
`files` accept a `discord.Attachment` and convert it via `to_file()` automatically —
|
`files` accept a `discord.Attachment` and convert it via `to_file()` automatically —
|
||||||
you never need to convert an attachment before passing it in.
|
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
|
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
|
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
|
object directly — it rebuilds a fresh `discord.File` from the same source (path or
|
||||||
@@ -110,8 +115,6 @@ echoes its `data`.
|
|||||||
## Cache button (mention priming)
|
## Cache button (mention priming)
|
||||||
|
|
||||||
Discord clients render `<@id>` as a raw id until the user object is cached locally.
|
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
|
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>"`).
|
entry is a string of the user mentions on that page (`"<@111> <@222> <@333>"`).
|
||||||
|
|
||||||
@@ -150,6 +153,7 @@ through.
|
|||||||
- `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
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "dpy_paginator"
|
name = "dpy_paginator"
|
||||||
version = "0.1.7"
|
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 = [
|
||||||
|
|||||||
@@ -1,3 +1,10 @@
|
|||||||
|
from importlib.metadata import version, PackageNotFoundError
|
||||||
|
|
||||||
from .dpy_paginator import DPYPaginator, ButtonPaginator, JumpToPageModal, DEFAULT_EMOJIS, Page
|
from .dpy_paginator import DPYPaginator, ButtonPaginator, JumpToPageModal, DEFAULT_EMOJIS, Page
|
||||||
|
|
||||||
__all__ = ["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__"]
|
||||||
|
|||||||
@@ -3,29 +3,14 @@ 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 DPYPaginator # or ButtonPaginator, an alias
|
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 DPYPaginator(pages, author_id=ctx.author.id).start(ctx)
|
assembled, so concurrent interactions never interleave into a shared render.
|
||||||
|
|
||||||
emojis: unicode by default; override via emojis={"previous"/"next"/"cache": ...}.
|
|
||||||
|
|
||||||
page types: str, discord.Embed, discord.File/Attachment, a sequence of those, or a
|
|
||||||
dict carrying 'content'/'embed(s)'/'file(s)' plus a 'buttons' list of custom button
|
|
||||||
configs (see README). both 'file' and 'files' accept a discord.Attachment and
|
|
||||||
convert it via to_file() automatically.
|
|
||||||
|
|
||||||
file pages: discord.py closes a discord.File's handle after every send/edit, so a
|
|
||||||
fresh discord.File is rebuilt from the same source on every render (including the
|
|
||||||
first) instead of resending the consumer's object.
|
|
||||||
|
|
||||||
concurrency: get_page_kwargs builds each page's kwargs/buttons in local state and
|
|
||||||
only publishes them once the whole page is fully assembled, so near-simultaneous
|
|
||||||
interactions (e.g. rapid button clicks) never interleave into a shared render.
|
|
||||||
|
|
||||||
config-free: no host config import; everything is passed at construction.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -128,11 +113,7 @@ class JumpToPageModal(discord.ui.Modal, title="Jump to Page"):
|
|||||||
|
|
||||||
|
|
||||||
class DPYPaginator(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"""
|
||||||
|
|
||||||
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
|
message: Optional[Union[discord.Message, discord.WebhookMessage]] = None
|
||||||
|
|
||||||
@@ -187,7 +168,6 @@ class DPYPaginator(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)
|
||||||
# falsy cache (None/[]) disables the cache button; non-empty needs one entry per page
|
|
||||||
if cache 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; "
|
||||||
@@ -237,9 +217,9 @@ class DPYPaginator(Generic[PageT_co], discord.ui.View):
|
|||||||
) -> 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
|
||||||
|
|
||||||
builds into local state (see _get_page_kwargs) and publishes
|
concurrency-safe: publishes self.current_page_buttons only once the page
|
||||||
self.current_page_buttons only once the page is fully assembled, so an
|
is fully assembled, so an interleaved concurrent call never observes a
|
||||||
interleaved concurrent call never observes a partially-built page.
|
partially-built page.
|
||||||
"""
|
"""
|
||||||
kwargs, buttons = await self._get_page_kwargs(page, skip_formatting=skip_formatting)
|
kwargs, buttons = await self._get_page_kwargs(page, skip_formatting=skip_formatting)
|
||||||
self.current_page_buttons = buttons
|
self.current_page_buttons = buttons
|
||||||
@@ -252,11 +232,9 @@ class DPYPaginator(Generic[PageT_co], discord.ui.View):
|
|||||||
kwargs: Optional[Dict[str, Any]] = None,
|
kwargs: Optional[Dict[str, Any]] = None,
|
||||||
buttons: Optional[List[discord.ui.Button]] = None,
|
buttons: Optional[List[discord.ui.Button]] = None,
|
||||||
) -> Tuple[Dict[str, Any], List[discord.ui.Button]]:
|
) -> Tuple[Dict[str, Any], List[discord.ui.Button]]:
|
||||||
"""recursive worker: builds kwargs/buttons in locals threaded through recursion
|
"""recursive worker: builds kwargs/buttons in locals, never touching instance
|
||||||
|
attributes mid-build, so concurrent calls hold their own state until
|
||||||
instance attributes are never touched mid-build, so concurrent interactions
|
get_page_kwargs publishes the result"""
|
||||||
each hold their own state until get_page_kwargs publishes the result.
|
|
||||||
"""
|
|
||||||
if kwargs is None:
|
if kwargs is None:
|
||||||
kwargs = self._fresh_kwargs()
|
kwargs = self._fresh_kwargs()
|
||||||
if buttons is None:
|
if buttons is None:
|
||||||
@@ -297,11 +275,15 @@ class DPYPaginator(Generic[PageT_co], discord.ui.View):
|
|||||||
value = await value.to_file()
|
value = await value.to_file()
|
||||||
kwargs["files"].append(value)
|
kwargs["files"].append(value)
|
||||||
elif key in ("embed", "embeds", "file", "files"):
|
elif key in ("embed", "embeds", "file", "files"):
|
||||||
# wrong-typed value would otherwise collide with base embeds=[]/files=[]
|
# wrong-typed value would collide with base embeds=[]/files=[]; reject early
|
||||||
# and raise an opaque TypeError from inside discord.py — reject it here
|
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"page key {key!r} has unexpected type {type(value).__name__}"
|
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:
|
||||||
kwargs[key] = value
|
kwargs[key] = value
|
||||||
elif isinstance(formatted_page, str):
|
elif isinstance(formatted_page, str):
|
||||||
@@ -327,9 +309,8 @@ class DPYPaginator(Generic[PageT_co], discord.ui.View):
|
|||||||
"""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
|
nav=False (or a single page, max_pages < 2) drops prev/jump/next but keeps
|
||||||
the page's custom buttons and the cache button — cache renders whenever
|
custom and cache buttons; the cache button renders independent of nav
|
||||||
self.cache is truthy, independent of the nav row, so a single-page result
|
whenever self.cache is truthy.
|
||||||
with a cache still gets its cache button.
|
|
||||||
"""
|
"""
|
||||||
self.clear_items()
|
self.clear_items()
|
||||||
|
|
||||||
@@ -385,14 +366,11 @@ class DPYPaginator(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
|
||||||
|
|
||||||
this is a mention-cache primer, not a data cache: discord clients render
|
a mention-cache primer, not a data cache: posts the page's mentions in a
|
||||||
<@id> as a raw id until the user is cached, so this posts the page's
|
throwaway ephemeral message (allowed_mentions=none(), tags render but no
|
||||||
mentions in a throwaway ephemeral message (allowed_mentions=none() — tags
|
ping fires) to force client resolution, waits cache_sleep seconds, then
|
||||||
render, no ping fires) to force resolution, waits cache_sleep seconds, then
|
re-edits so mentions display as names. expected discord failures (deleted
|
||||||
re-edits the message so mentions display as names.
|
message, no permission) are swallowed, like on_timeout.
|
||||||
|
|
||||||
expected discord failures (deleted message, no permission) are swallowed
|
|
||||||
like on_timeout — an expired/deleted message must not raise here.
|
|
||||||
"""
|
"""
|
||||||
await interaction.response.send_message(
|
await interaction.response.send_message(
|
||||||
content=self.cache[self.current_page],
|
content=self.cache[self.current_page],
|
||||||
@@ -407,8 +385,10 @@ class DPYPaginator(Generic[PageT_co], discord.ui.View):
|
|||||||
await self.message.edit(**kwargs)
|
await self.message.edit(**kwargs)
|
||||||
except (discord.NotFound, discord.Forbidden):
|
except (discord.NotFound, discord.Forbidden):
|
||||||
pass
|
pass
|
||||||
except discord.HTTPException:
|
except discord.HTTPException as exc:
|
||||||
log.warning("paginator cache_button: failed to refresh message", exc_info=True)
|
# 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:
|
||||||
@@ -419,9 +399,8 @@ class DPYPaginator(Generic[PageT_co], discord.ui.View):
|
|||||||
def reset_files(self, page_kwargs: Dict[str, Any]) -> None:
|
def reset_files(self, page_kwargs: Dict[str, Any]) -> None:
|
||||||
"""swap in a fresh discord.File per render so a re-render never reuses a sent one
|
"""swap in a fresh discord.File per render so a re-render never reuses a sent one
|
||||||
|
|
||||||
discord.py closes a File's fp after every send/edit, making it single-use;
|
discord.py closes a File's fp after every send/edit; file.reset() raises
|
||||||
file.reset() raises once a path-backed File is actually closed, so rebuild a
|
once a path-backed File is actually closed, so rebuild from source instead.
|
||||||
new discord.File from the same source instead — cheap, and safe either way.
|
|
||||||
"""
|
"""
|
||||||
files = page_kwargs.get("files")
|
files = page_kwargs.get("files")
|
||||||
if not files:
|
if not files:
|
||||||
@@ -430,13 +409,9 @@ class DPYPaginator(Generic[PageT_co], discord.ui.View):
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _fresh_file(file: discord.File) -> discord.File:
|
def _fresh_file(file: discord.File) -> discord.File:
|
||||||
"""build a new discord.File from an existing one's source
|
"""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)
|
||||||
a path-backed File (_owner=True) is reopened from fp.name, which stays
|
is never closed by discord.py, so its buffer is rewound and reused"""
|
||||||
readable after discord.py closes the handle. a buffer-backed File
|
|
||||||
(_owner=False) is never closed by discord.py, so its buffer is rewound and
|
|
||||||
reused directly.
|
|
||||||
"""
|
|
||||||
if file._owner:
|
if file._owner:
|
||||||
source = file.fp.name
|
source = file.fp.name
|
||||||
else:
|
else:
|
||||||
@@ -454,9 +429,8 @@ class DPYPaginator(Generic[PageT_co], discord.ui.View):
|
|||||||
) -> 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 (max_pages < 2): update_buttons already drops the nav row but
|
# single page: update_buttons drops nav but keeps custom/cache buttons live;
|
||||||
# keeps custom/cache buttons — so a single page with either still renders
|
# only drop the view entirely below if neither is present
|
||||||
# them (live callbacks); only drop the view entirely if neither is present
|
|
||||||
self.update_buttons()
|
self.update_buttons()
|
||||||
|
|
||||||
if self.max_pages < 2 and not self.current_page_buttons and not self.cache:
|
if self.max_pages < 2 and not self.current_page_buttons and not self.cache:
|
||||||
@@ -466,14 +440,14 @@ class DPYPaginator(Generic[PageT_co], discord.ui.View):
|
|||||||
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__}")
|
||||||
@@ -483,8 +457,8 @@ class DPYPaginator(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
|
||||||
@@ -492,10 +466,10 @@ class DPYPaginator(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:
|
except discord.HTTPException as exc:
|
||||||
# fire-and-forget task; a transient failure must not surface as an
|
# best-effort cleanup task; log rather than raise into an unretrieved task. no
|
||||||
# unretrieved-task traceback on a best-effort cleanup
|
# traceback (exc_info belongs on terminal/unhandled paths) - fold the reason in.
|
||||||
log.warning("paginator on_timeout: failed to delete message", exc_info=True)
|
log.warning("paginator on_timeout: failed to delete message: %s", exc)
|
||||||
|
|
||||||
|
|
||||||
# back-compat alias: the class was originally named ButtonPaginator; DPYPaginator is
|
# back-compat alias: the class was originally named ButtonPaginator; DPYPaginator is
|
||||||
|
|||||||
Reference in New Issue
Block a user