From d5d7378e027c5d3f0b9689e9bd18c8b3100167ea Mon Sep 17 00:00:00 2001 From: Christopher Bonnell Date: Thu, 10 Aug 2023 08:19:00 -0500 Subject: [PATCH] [Feature]: ComponentBuilder component removal methods (#2644) * New helper methods * Auto-resolve empty ActionRows * Resolve potential nulls * Add RemoveButtonByURL * split out url method --- .../MessageComponents/ComponentBuilder.cs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/Discord.Net.Core/Entities/Interactions/MessageComponents/ComponentBuilder.cs b/src/Discord.Net.Core/Entities/Interactions/MessageComponents/ComponentBuilder.cs index 29ff80cf2e..33760ca5cf 100644 --- a/src/Discord.Net.Core/Entities/Interactions/MessageComponents/ComponentBuilder.cs +++ b/src/Discord.Net.Core/Entities/Interactions/MessageComponents/ComponentBuilder.cs @@ -81,6 +81,39 @@ internal void AddComponent(IMessageComponent component, int row) } } + /// + /// Removes all components of the given type from the . + /// + /// The to remove. + /// The current builder. + public ComponentBuilder RemoveComponentsOfType(ComponentType t) + { + this.ActionRows.ForEach(ar => ar.Components.RemoveAll(c => c.Type == t)); + return this; + } + + /// + /// Removes a component from the . + /// + /// The custom id of the component. + /// The current builder. + public ComponentBuilder RemoveComponent(string customId) + { + this.ActionRows.ForEach(ar => ar.Components.RemoveAll(c => c.CustomId == customId)); + return this; + } + + /// + /// Removes a Link Button from the based on its URL. + /// + /// The URL of the Link Button. + /// The current builder. + public ComponentBuilder RemoveButtonByURL(string url) + { + this.ActionRows.ForEach(ar => ar.Components.RemoveAll(c => c is ButtonComponent b && b.Url == url)); + return this; + } + /// /// Adds a to the at the specific row. /// If the row cannot accept the component then it will add it to a row that can. @@ -283,6 +316,11 @@ public MessageComponent Build() if (_actionRows?.SelectMany(x => x.Components)?.Any(x => x.Type == ComponentType.TextInput) ?? false) throw new ArgumentException("TextInputComponents are not allowed in messages.", nameof(ActionRows)); + if (_actionRows?.Count > 0) + for (int i = 0; i < _actionRows?.Count; i++) + if (_actionRows[i]?.Components?.Count == 0) + _actionRows.RemoveAt(i); + return _actionRows != null ? new MessageComponent(_actionRows.Select(x => x.Build()).ToList()) : MessageComponent.Empty;