From 884a4b126c21ef2bdcbf1d78ba484cdf6d9f433f Mon Sep 17 00:00:00 2001 From: Rikitav Date: Sun, 24 Aug 2025 22:35:44 +0400 Subject: [PATCH] Added TextContainsWordAttribute --- .../MessageTextFilterAttributes.cs | 11 +++++ Telegrator/Filters/MessageTextFilters.cs | 47 +++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/Telegrator/Annotations/MessageTextFilterAttributes.cs b/Telegrator/Annotations/MessageTextFilterAttributes.cs index c73affe..22509a7 100644 --- a/Telegrator/Annotations/MessageTextFilterAttributes.cs +++ b/Telegrator/Annotations/MessageTextFilterAttributes.cs @@ -44,4 +44,15 @@ namespace Telegrator.Annotations public class HasTextAttribute() : MessageFilterAttribute(new TextNotNullOrEmptyFilter()) { } + + /// + /// 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. + /// + /// + /// + /// + public class TextContainsWordAttribute(string word, StringComparison comparison = StringComparison.InvariantCulture, int startIndex = 0) + : MessageFilterAttribute(new TextContainsWordFilter(word, comparison, startIndex)) + { } } diff --git a/Telegrator/Filters/MessageTextFilters.cs b/Telegrator/Filters/MessageTextFilters.cs index bb29042..ecc9b09 100644 --- a/Telegrator/Filters/MessageTextFilters.cs +++ b/Telegrator/Filters/MessageTextFilters.cs @@ -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 _) => !string.IsNullOrEmpty(Text); } + + /// + /// 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. + /// + public class TextContainsWordFilter(string word, StringComparison comparison = StringComparison.InvariantCulture, int startIndex = 0) : MessageTextFilter + { + /// + /// The content to check if the message text equals. + /// + protected readonly string Word = word; + + /// + /// The string comparison type to use for the check. + /// + protected readonly StringComparison Comparison = comparison; + + /// + /// The search starting position. + /// + protected readonly int StartIndex = startIndex; + + /// + protected override bool CanPassNext(FilterExecutionContext 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; + } + } }