|
|
|
@@ -3,32 +3,20 @@ button paginator for discord.py
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
pages = [discord.Embed(title=f"Page {i}") for i in range(5)]
|
|
|
|
|
await ButtonPaginator(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={
|
|
|
|
|
"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.
|
|
|
|
|
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
|
|
|
|
|
builds each page's kwargs/buttons in local state and only publishes once fully
|
|
|
|
|
assembled, so concurrent interactions never interleave into a shared render.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import asyncio
|
|
|
|
|
import logging
|
|
|
|
|
from typing import (
|
|
|
|
|
Any,
|
|
|
|
|
Dict,
|
|
|
|
@@ -69,6 +57,8 @@ DEFAULT_EMOJIS = {
|
|
|
|
|
"cache": "\U0001f5c2\ufe0f", # 🗂️
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
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"):
|
|
|
|
|
"""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,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"""
|
|
|
|
|
|
|
|
|
|
message: Optional[Union[discord.Message, discord.WebhookMessage]] = None
|
|
|
|
@@ -160,7 +150,9 @@ 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:
|
|
|
|
|
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 +168,11 @@ 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:
|
|
|
|
|
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"""
|
|
|
|
@@ -200,7 +191,7 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
|
|
|
|
|
|
|
|
|
|
async def interaction_check(self, interaction: Interaction) -> bool:
|
|
|
|
|
"""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
|
|
|
|
|
await interaction.response.send_message("You cannot interact with this menu.", ephemeral=True)
|
|
|
|
|
return False
|
|
|
|
@@ -224,19 +215,40 @@ 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
|
|
|
|
|
|
|
|
|
|
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:
|
|
|
|
|
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,46 +262,67 @@ 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"):
|
|
|
|
|
# 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:
|
|
|
|
|
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) -> None:
|
|
|
|
|
"""rebuild the action row for the current page state"""
|
|
|
|
|
def update_buttons(self, nav: bool = True) -> None:
|
|
|
|
|
"""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.previous_page.emoji = self.emojis["previous"]
|
|
|
|
|
self.previous_page.disabled = self.current_page <= 0
|
|
|
|
|
self.add_item(self.previous_page)
|
|
|
|
|
nav = nav and self.max_pages >= 2
|
|
|
|
|
|
|
|
|
|
self.jump_button.label = self.page_text.format(self.current_page + 1, self.max_pages)
|
|
|
|
|
self.add_item(self.jump_button)
|
|
|
|
|
if nav:
|
|
|
|
|
self.previous_page.emoji = self.emojis["previous"]
|
|
|
|
|
self.previous_page.disabled = self.current_page <= 0
|
|
|
|
|
self.add_item(self.previous_page)
|
|
|
|
|
|
|
|
|
|
self.jump_button.label = self.page_text.format(self.current_page + 1, self.max_pages)
|
|
|
|
|
self.add_item(self.jump_button)
|
|
|
|
|
|
|
|
|
|
for button in self.current_page_buttons:
|
|
|
|
|
self.add_item(button)
|
|
|
|
@@ -298,9 +331,10 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
|
|
|
|
|
self.cache_button.emoji = self.emojis["cache"]
|
|
|
|
|
self.add_item(self.cache_button)
|
|
|
|
|
|
|
|
|
|
self.next_page.emoji = self.emojis["next"]
|
|
|
|
|
self.next_page.disabled = self.current_page >= self.max_pages - 1
|
|
|
|
|
self.add_item(self.next_page)
|
|
|
|
|
if nav:
|
|
|
|
|
self.next_page.emoji = self.emojis["next"]
|
|
|
|
|
self.next_page.disabled = self.current_page >= self.max_pages - 1
|
|
|
|
|
self.add_item(self.next_page)
|
|
|
|
|
|
|
|
|
|
async def _build_render_kwargs(self) -> Dict[str, Any]:
|
|
|
|
|
"""build the edit-ready kwargs for the current page (buttons + attachments)"""
|
|
|
|
@@ -332,13 +366,11 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
|
|
|
|
|
async def cache_button(self, interaction: discord.Interaction, _: discord.ui.Button) -> None:
|
|
|
|
|
"""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.
|
|
|
|
|
this posts the page's mentions in a throwaway ephemeral message so the client
|
|
|
|
|
resolves them, waits cache_sleep seconds, then re-edits the message so the
|
|
|
|
|
mentions display as names — no manual page-flip needed.
|
|
|
|
|
|
|
|
|
|
allowed_mentions is none() on purpose: the <@id> tags still render (which is
|
|
|
|
|
what primes the cache) but no actual ping/notification fires.
|
|
|
|
|
a mention-cache primer, not a data cache: posts the page's mentions in a
|
|
|
|
|
throwaway ephemeral message (allowed_mentions=none(), tags render but no
|
|
|
|
|
ping fires) to force client resolution, waits cache_sleep seconds, then
|
|
|
|
|
re-edits so mentions display as names. expected discord failures (deleted
|
|
|
|
|
message, no permission) are swallowed, like on_timeout.
|
|
|
|
|
"""
|
|
|
|
|
await interaction.response.send_message(
|
|
|
|
|
content=self.cache[self.current_page],
|
|
|
|
@@ -349,7 +381,14 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
|
|
|
|
|
await asyncio.sleep(self.cache_sleep)
|
|
|
|
|
kwargs = await self._build_render_kwargs()
|
|
|
|
|
if self.message:
|
|
|
|
|
await self.message.edit(**kwargs)
|
|
|
|
|
try:
|
|
|
|
|
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)
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
|
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 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(
|
|
|
|
|
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))
|
|
|
|
|
# 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()
|
|
|
|
|
|
|
|
|
|
if self.max_pages < 2:
|
|
|
|
|
if self.max_pages < 2 and not self.current_page_buttons and not self.cache:
|
|
|
|
|
self.stop()
|
|
|
|
|
kwargs.pop("view", None)
|
|
|
|
|
|
|
|
|
|
self.reset_files(kwargs)
|
|
|
|
|
|
|
|
|
|
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():
|
|
|
|
|
self.message = await obj.followup.send(**kwargs, ephemeral=self.ephemeral, **send_kwargs)
|
|
|
|
|
else:
|
|
|
|
|
await obj.response.send_message(**kwargs, ephemeral=self.ephemeral, **send_kwargs)
|
|
|
|
|
self.message = await obj.original_response()
|
|
|
|
|
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)
|
|
|
|
|
else:
|
|
|
|
|
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:
|
|
|
|
|
"""delete the message on timeout when delete_message_after is set
|
|
|
|
|
|
|
|
|
|
only the expected discord failures (already deleted, or no permission) are
|
|
|
|
|
swallowed; an unexpected error surfaces rather than being silently dropped.
|
|
|
|
|
only expected discord failures (already deleted, no permission) are
|
|
|
|
|
swallowed; unexpected errors surface.
|
|
|
|
|
"""
|
|
|
|
|
if not self.delete_message_after or self.message is None:
|
|
|
|
|
return
|
|
|
|
@@ -402,3 +466,12 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
|
|
|
|
|
await self.message.delete()
|
|
|
|
|
except (discord.NotFound, discord.Forbidden):
|
|
|
|
|
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
|
|
|
|
|