RikoBot-Sharp/RegexHandler.cs

49 lines
1.6 KiB
C#
Raw Normal View History

2020-01-30 20:57:41 +01:00
using System;
using System.Text.RegularExpressions;
using Telegram.Bot.Types;
namespace RSSBot {
/// <summary>
2020-11-05 19:34:45 +01:00
/// RegexHandler for Telegram Bots.
2020-01-30 20:57:41 +01:00
/// </summary>
public class RegexHandler {
2020-11-05 19:34:45 +01:00
private readonly Action<Message, GroupCollection> CallbackFunction;
private readonly string Pattern;
2020-01-30 20:57:41 +01:00
/// <summary>
2020-11-05 19:34:45 +01:00
/// Constructor for the RegexHandler.
2020-01-30 20:57:41 +01:00
/// </summary>
/// <param name="pattern">Regex pattern</param>
/// <param name="callback">Callback function to call when the update should be processed</param>
2020-11-05 19:34:45 +01:00
public RegexHandler(string pattern, Action<Message, GroupCollection> callback)
{
2020-01-30 20:57:41 +01:00
Pattern = pattern;
CallbackFunction = callback;
}
/// <summary>
2020-11-05 19:34:45 +01:00
/// Checks whether the update should be handled by this handler.
2020-01-30 20:57:41 +01:00
/// </summary>
/// <param name="message">Telegram Message object</param>
/// <returns>true if the update should be handled</returns>
2020-11-05 19:34:45 +01:00
public bool HandleUpdate(Message message)
{
2020-01-30 20:57:41 +01:00
return Regex.IsMatch(message.Text,
Pattern,
RegexOptions.IgnoreCase);
}
/// <summary>
2020-11-05 19:34:45 +01:00
/// Calls the assoicated callback function.
2020-01-30 20:57:41 +01:00
/// </summary>
/// <param name="message">Telegram Message object</param>
2020-11-05 19:34:45 +01:00
public void ProcessUpdate(Message message)
{
2020-01-30 20:57:41 +01:00
GroupCollection matches = Regex.Match(message.Text,
Pattern,
RegexOptions.IgnoreCase
).Groups;
CallbackFunction(message, matches);
}
}
}