Added TextContainsWordAttribute

This commit is contained in:
2025-08-24 22:35:44 +04:00
parent 576dd5013f
commit 884a4b126c
2 changed files with 58 additions and 0 deletions
@@ -44,4 +44,15 @@ namespace Telegrator.Annotations
public class HasTextAttribute()
: MessageFilterAttribute(new TextNotNullOrEmptyFilter())
{ }
/// <summary>
/// Attribute for filtering messages where the text contains a 'word'.
/// 'Word' must be a separate member of the text, and not have any alphabetic characters next to it.
/// </summary>
/// <param name="word"></param>
/// <param name="comparison"></param>
/// <param name="startIndex"></param>
public class TextContainsWordAttribute(string word, StringComparison comparison = StringComparison.InvariantCulture, int startIndex = 0)
: MessageFilterAttribute(new TextContainsWordFilter(word, comparison, startIndex))
{ }
}
+47
View File
@@ -1,5 +1,6 @@
using Telegram.Bot.Types;
using Telegrator.Filters.Components;
using static System.Net.Mime.MediaTypeNames;
namespace Telegrator.Filters
{
@@ -155,4 +156,50 @@ namespace Telegrator.Filters
protected override bool CanPassNext(FilterExecutionContext<Message> _)
=> !string.IsNullOrEmpty(Text);
}
/// <summary>
/// Filter that checks if the message text contains a 'word'.
/// 'Word' must be a separate member of the text, and not have any alphabetic characters next to it.
/// </summary>
public class TextContainsWordFilter(string word, StringComparison comparison = StringComparison.InvariantCulture, int startIndex = 0) : MessageTextFilter
{
/// <summary>
/// The content to check if the message text equals.
/// </summary>
protected readonly string Word = word;
/// <summary>
/// The string comparison type to use for the check.
/// </summary>
protected readonly StringComparison Comparison = comparison;
/// <summary>
/// The search starting position.
/// </summary>
protected readonly int StartIndex = startIndex;
/// <inheritdoc/>
protected override bool CanPassNext(FilterExecutionContext<Message> context)
{
int index = Text.IndexOf(Word, StartIndex, Comparison);
if (index == -1)
return false;
if (index > 0)
{
char prev = Text[index - 1];
if (char.IsLetter(prev))
return false;
}
if (index + Word.Length < Text.Length)
{
char post = Text[index + Word.Length];
if (char.IsLetter(post))
return false;
}
return true;
}
}
}