Skip to content

Commit d5d7378

Browse files
authored
[Feature]: ComponentBuilder component removal methods (#2644)
* New helper methods * Auto-resolve empty ActionRows * Resolve potential nulls * Add RemoveButtonByURL * split out url method
1 parent 166d40f commit d5d7378

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/Discord.Net.Core/Entities/Interactions/MessageComponents/ComponentBuilder.cs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,39 @@ internal void AddComponent(IMessageComponent component, int row)
8181
}
8282
}
8383

84+
/// <summary>
85+
/// Removes all components of the given type from the <see cref="ComponentBuilder"/>.
86+
/// </summary>
87+
/// <param name="t">The <see cref="ComponentType"/> to remove.</param>
88+
/// <returns>The current builder.</returns>
89+
public ComponentBuilder RemoveComponentsOfType(ComponentType t)
90+
{
91+
this.ActionRows.ForEach(ar => ar.Components.RemoveAll(c => c.Type == t));
92+
return this;
93+
}
94+
95+
/// <summary>
96+
/// Removes a component from the <see cref="ComponentBuilder"/>.
97+
/// </summary>
98+
/// <param name="customId">The custom id of the component.</param>
99+
/// <returns>The current builder.</returns>
100+
public ComponentBuilder RemoveComponent(string customId)
101+
{
102+
this.ActionRows.ForEach(ar => ar.Components.RemoveAll(c => c.CustomId == customId));
103+
return this;
104+
}
105+
106+
/// <summary>
107+
/// Removes a Link Button from the <see cref="ComponentBuilder"/> based on its URL.
108+
/// </summary>
109+
/// <param name="url">The URL of the Link Button.</param>
110+
/// <returns>The current builder.</returns>
111+
public ComponentBuilder RemoveButtonByURL(string url)
112+
{
113+
this.ActionRows.ForEach(ar => ar.Components.RemoveAll(c => c is ButtonComponent b && b.Url == url));
114+
return this;
115+
}
116+
84117
/// <summary>
85118
/// Adds a <see cref="SelectMenuBuilder"/> to the <see cref="ComponentBuilder"/> at the specific row.
86119
/// If the row cannot accept the component then it will add it to a row that can.
@@ -283,6 +316,11 @@ public MessageComponent Build()
283316
if (_actionRows?.SelectMany(x => x.Components)?.Any(x => x.Type == ComponentType.TextInput) ?? false)
284317
throw new ArgumentException("TextInputComponents are not allowed in messages.", nameof(ActionRows));
285318

319+
if (_actionRows?.Count > 0)
320+
for (int i = 0; i < _actionRows?.Count; i++)
321+
if (_actionRows[i]?.Components?.Count == 0)
322+
_actionRows.RemoveAt(i);
323+
286324
return _actionRows != null
287325
? new MessageComponent(_actionRows.Select(x => x.Build()).ToList())
288326
: MessageComponent.Empty;

0 commit comments

Comments
 (0)