Add content_length method to LayoutView and container items

This commit is contained in:
Rapptz 2025-08-18 14:33:15 -04:00
parent e00bb0b0f3
commit f08c042217
4 changed files with 27 additions and 0 deletions

View File

@ -219,6 +219,12 @@ class ActionRow(Item[V]):
for child in self.children: for child in self.children:
yield child yield child
def content_length(self) -> int:
""":class:`int`: Returns the total length of all text content in this action row."""
from .text_display import TextDisplay
return sum(len(item.content) for item in self._children if isinstance(item, TextDisplay))
def add_item(self, item: Item[Any]) -> Self: def add_item(self, item: Item[Any]) -> Self:
"""Adds an item to this action row. """Adds an item to this action row.

View File

@ -281,6 +281,12 @@ class Container(Item[V]):
if child._has_children(): if child._has_children():
yield from child.walk_children() # type: ignore yield from child.walk_children() # type: ignore
def content_length(self) -> int:
""":class:`int`: Returns the total length of all text content in this container."""
from .text_display import TextDisplay
return sum(len(item.content) for item in self.walk_children() if isinstance(item, TextDisplay))
def add_item(self, item: Item[Any]) -> Self: def add_item(self, item: Item[Any]) -> Self:
"""Adds an item to this container. """Adds an item to this container.

View File

@ -128,6 +128,12 @@ class Section(Item[V]):
def _has_children(self): def _has_children(self):
return True return True
def content_length(self) -> int:
""":class:`int`: Returns the total length of all text content in this section."""
from .text_display import TextDisplay
return sum(len(item.content) for item in self._children if isinstance(item, TextDisplay))
def add_item(self, item: Union[str, Item[Any]]) -> Self: def add_item(self, item: Union[str, Item[Any]]) -> Self:
"""Adds an item to this section. """Adds an item to this section.

View File

@ -327,6 +327,15 @@ class BaseView:
"""List[:class:`Item`]: The list of children attached to this view.""" """List[:class:`Item`]: The list of children attached to this view."""
return self._children.copy() return self._children.copy()
def content_length(self) -> int:
""":class:`int`: Returns the total length of all text content in the view's items.
A view is allowed to have a maximum of 4000 display characters across all its items.
"""
from .text_display import TextDisplay
return sum(len(item.content) for item in self.walk_children() if isinstance(item, TextDisplay))
@classmethod @classmethod
def from_message(cls, message: Message, /, *, timeout: Optional[float] = 180.0) -> Union[View, LayoutView]: def from_message(cls, message: Message, /, *, timeout: Optional[float] = 180.0) -> Union[View, LayoutView]:
"""Converts a message's components into a :class:`View` """Converts a message's components into a :class:`View`