|
|
@@ -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,
|
|
|
|
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)'/
|
|
|
|
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.
|
|
|
|
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
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
|
|
import asyncio
|
|
|
|
import asyncio
|
|
|
|
|
|
|
|
import logging
|
|
|
|
from typing import (
|
|
|
|
from typing import (
|
|
|
|
Any,
|
|
|
|
Any,
|
|
|
|
Dict,
|
|
|
|
Dict,
|
|
|
@@ -69,6 +84,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)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -161,6 +178,10 @@ 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("ButtonPaginator 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.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 +197,13 @@ 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:
|
|
|
|
# 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(
|
|
|
|
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 +222,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 +246,44 @@ 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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:
|
|
|
|
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,35 +297,46 @@ 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"):
|
|
|
|
|
|
|
|
# a wrong-typed embed/file would otherwise fall to the catch-all and
|
|
|
|
|
|
|
|
# be forwarded verbatim, colliding with the base embeds=[]/files=[]
|
|
|
|
|
|
|
|
# and raising an opaque TypeError from inside discord.py — reject it
|
|
|
|
|
|
|
|
# here with a clear, paginator-side message
|
|
|
|
|
|
|
|
raise ValueError(
|
|
|
|
|
|
|
|
f"page key {key!r} has unexpected type {type(value).__name__}"
|
|
|
|
|
|
|
|
)
|
|
|
|
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, nav: bool = True) -> 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
|
|
|
@@ -286,9 +344,13 @@ class ButtonPaginator(Generic[PageT_co], discord.ui.View):
|
|
|
|
nav=False rebuilds with only the page's custom buttons and no navigation
|
|
|
|
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
|
|
|
|
items (prev/jump/cache/next) — a single-page result that still carries
|
|
|
|
custom buttons keeps them (and their live callbacks) without a nav row.
|
|
|
|
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()
|
|
|
|
self.clear_items()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
nav = nav and self.max_pages >= 2
|
|
|
|
|
|
|
|
|
|
|
|
if nav:
|
|
|
|
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
|
|
|
@@ -365,24 +427,56 @@ 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 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(
|
|
|
|
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))
|
|
|
|
|
|
|
|
# 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()
|
|
|
|
self.update_buttons()
|
|
|
|
|
|
|
|
|
|
|
|
if self.max_pages < 2:
|
|
|
|
if self.max_pages < 2 and not self.current_page_buttons:
|
|
|
|
if self.current_page_buttons:
|
|
|
|
# single page, no custom buttons: no interactive row at all, drop the view
|
|
|
|
# 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()
|
|
|
|
self.stop()
|
|
|
|
kwargs.pop("view", None)
|
|
|
|
kwargs.pop("view", None)
|
|
|
|
|
|
|
|
|
|
|
@@ -415,3 +509,7 @@ 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:
|
|
|
|
|
|
|
|
# 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)
|
|
|
|