87 lines
3.1 KiB
C#
87 lines
3.1 KiB
C#
using System;
|
|
using System.Text;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace DeukBot4.MessageHandlers.CommandHandler.RequestStructure
|
|
{
|
|
public static class ParameterMatcher
|
|
{
|
|
public enum ParameterType
|
|
{
|
|
Word,
|
|
Number,
|
|
Remainder,
|
|
User,
|
|
Timespan,
|
|
}
|
|
|
|
public static string[] GenerateRegex(Command command)
|
|
{
|
|
var arr = new string[command.ParameterTypes.Length];
|
|
for (var index = 0; index < command.ParameterTypes.Length; index++)
|
|
{
|
|
var commandParameterType = command.ParameterTypes[index];
|
|
|
|
var builder = new StringBuilder();
|
|
for (var i = 0; i < commandParameterType.Length; i++)
|
|
{
|
|
var parameterType = commandParameterType[i];
|
|
builder.Append(GetParameterRegex(parameterType, i + 1));
|
|
}
|
|
|
|
arr[index] = builder.ToString();
|
|
}
|
|
return arr;
|
|
}
|
|
|
|
private static string GetParameterRegex(ParameterType type, int index)
|
|
{
|
|
switch (type)
|
|
{
|
|
case ParameterType.Word:
|
|
return $" *(?<{index}>\\w+)";
|
|
case ParameterType.Number:
|
|
return $" *(?<{index}>\\d+)(?:$| |\n)";
|
|
case ParameterType.Remainder:
|
|
return $" *(?<{index}>.*)";
|
|
case ParameterType.User:
|
|
return $" *(?:<@!*(?<{index}>\\d+)>|(?<{index}>\\d+)|(?<{index}>\\w+)(?:$| |\n))";
|
|
case ParameterType.Timespan:
|
|
return $" *(?<{index}>\\d+\\.*\\d*[smhd])";
|
|
default:
|
|
throw new ArgumentOutOfRangeException(nameof(type), type, null);
|
|
}
|
|
}
|
|
|
|
public static RequestParameter[] GetParameterValues(Command command, string parameterString)
|
|
{
|
|
for (var index = 0; index < command.ParametersMatchers.Length; index++)
|
|
{
|
|
var parameterTypes = command.ParameterTypes[index];
|
|
var pattern = command.ParametersMatchers[index];
|
|
Match matches;
|
|
try
|
|
{
|
|
matches = Regex.Match(parameterString, pattern);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Logger.Main.LogError(e.ToString());
|
|
return command.RequireParameterMatch ? null : new RequestParameter[0];
|
|
}
|
|
if (matches.Success)
|
|
{
|
|
var arr = new RequestParameter[matches.Groups.Count - 1];
|
|
for (var i = 1; i < matches.Groups.Count; i++)
|
|
{
|
|
var group = matches.Groups[i];
|
|
arr[i - 1] = new RequestParameter(group.Value, parameterTypes[i - 1]);
|
|
}
|
|
return arr;
|
|
}
|
|
}
|
|
|
|
return command.RequireParameterMatch ? null : new RequestParameter[0];
|
|
}
|
|
}
|
|
} |