Add Paginator utility and tests (#92)
Some checks failed
Deploy MkDocs / deploy (push) Has been cancelled

This commit is contained in:
Slipstream 2025-06-15 18:12:10 -06:00 committed by GitHub
parent 8be234c1f0
commit c1c5cfb41a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 63 additions and 0 deletions

View File

@ -71,3 +71,42 @@ async def message_pager(
remaining -= 1 remaining -= 1
if remaining == 0: if remaining == 0:
return return
class Paginator:
"""Helper to split text into pages under a character limit."""
def __init__(self, limit: int = 2000) -> None:
self.limit = limit
self._pages: list[str] = []
self._current = ""
def add_line(self, line: str) -> None:
"""Add a line of text to the paginator."""
if len(line) > self.limit:
if self._current:
self._pages.append(self._current)
self._current = ""
for i in range(0, len(line), self.limit):
chunk = line[i : i + self.limit]
if len(chunk) == self.limit:
self._pages.append(chunk)
else:
self._current = chunk
return
if not self._current:
self._current = line
elif len(self._current) + 1 + len(line) <= self.limit:
self._current += "\n" + line
else:
self._pages.append(self._current)
self._current = line
@property
def pages(self) -> list[str]:
"""Return the accumulated pages."""
pages = list(self._pages)
if self._current:
pages.append(self._current)
return pages

View File

@ -14,6 +14,7 @@ A Python library for interacting with the Discord API, with a focus on bot devel
- Built-in caching layer - Built-in caching layer
- Experimental voice support - Experimental voice support
- Helpful error handling utilities - Helpful error handling utilities
- Paginator utility for splitting long messages
## Installation ## Installation

23
tests/test_paginator.py Normal file
View File

@ -0,0 +1,23 @@
from disagreement.utils import Paginator
def test_paginator_single_page():
p = Paginator(limit=10)
p.add_line("hi")
p.add_line("there")
assert p.pages == ["hi\nthere"]
def test_paginator_splits_pages():
p = Paginator(limit=10)
p.add_line("12345")
p.add_line("67890")
assert p.pages == ["12345", "67890"]
p.add_line("xyz")
assert p.pages == ["12345", "67890\nxyz"]
def test_paginator_handles_long_line():
p = Paginator(limit=5)
p.add_line("abcdef")
assert p.pages == ["abcde", "f"]