From 8561953222c29248e1c7755e8add398852b5b5c4 Mon Sep 17 00:00:00 2001 From: DA-344 <108473820+DA-344@users.noreply.github.com> Date: Mon, 10 Mar 2025 20:54:33 +0100 Subject: [PATCH] chore: Add container add/remove/clear_item(s) --- discord/ui/container.py | 60 +++++++++++++++++++++++++++++++++++++++++ discord/ui/section.py | 2 +- 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/discord/ui/container.py b/discord/ui/container.py index 8218e1de6..fd9dd0c49 100644 --- a/discord/ui/container.py +++ b/discord/ui/container.py @@ -233,3 +233,63 @@ class Container(Item[V]): spoiler=component.spoiler, id=component.id, ) + + def add_item(self, item: Item[Any]) -> Self: + """Adds an item to this container. + + This function returns the class instance to allow for fluent-style + chaining. + + Parameters + ---------- + item: :class:`Item` + The item to append. + + Raises + ------ + TypeError + An :class:`Item` was not passed. + ValueError + Maximum number of children has been exceeded (10). + """ + + if len(self._children) >= 10: + raise ValueError('maximum number of children exceeded') + + if not isinstance(item, Item): + raise TypeError(f'expected Item not {item.__class__.__name__}') + + self._children.append(item) + + if item.is_dispatchable(): + if getattr(item, '__discord_ui_section__', False): + self.__dispatchable.append(item.accessory) # type: ignore + + return self + + def remove_item(self, item: Item[Any]) -> Self: + """Removes an item from this container. + + This function returns the class instance to allow for fluent-style + chaining. + + Parameters + ---------- + item: :class:`TextDisplay` + The item to remove from the section. + """ + + try: + self._children.remove(item) + except ValueError: + pass + return self + + def clear_items(self) -> Self: + """Removes all the items from the container. + + This function returns the class instance to allow for fluent-style + chaining. + """ + self._children.clear() + return self diff --git a/discord/ui/section.py b/discord/ui/section.py index 981d06e93..16b5fb6c5 100644 --- a/discord/ui/section.py +++ b/discord/ui/section.py @@ -121,7 +121,7 @@ class Section(Item[V]): Parameters ---------- item: Union[:class:`str`, :class:`Item`] - The items to append, if it is a string it automatically wrapped around + The item to append, if it is a string it automatically wrapped around :class:`TextDisplay`. Raises