diff --git a/BrackeysBot/ArgumentConverters/TimeSpanArgumentConverter.cs b/BrackeysBot/ArgumentConverters/TimeSpanArgumentConverter.cs new file mode 100644 index 0000000..ed613cf --- /dev/null +++ b/BrackeysBot/ArgumentConverters/TimeSpanArgumentConverter.cs @@ -0,0 +1,71 @@ +using System; +using System.Threading.Tasks; +using DisCatSharp.CommandsNext; +using DisCatSharp.CommandsNext.Converters; +using DisCatSharp.Entities; + +namespace BrackeysBot.ArgumentConverters; + +/// +/// Represents a converter which converts a command argument to . +/// +internal sealed class TimeSpanArgumentConverter : IArgumentConverter +{ + /// + public Task> ConvertAsync(string value, CommandContext ctx) + { + TimeSpan result = TimeSpan.Zero; + var unitValue = 0; + + for (var index = 0; index < value.Length; index++) + { + char current = value[index]; + switch (current) + { + case var digitChar when char.IsDigit(digitChar): + var digit = (int) char.GetNumericValue(digitChar); + unitValue = unitValue * 10 + digit; + break; + + case 'y': + result += TimeSpan.FromDays(unitValue * 365); + unitValue = 0; + break; + + case 'm': + if (index < value.Length - 1 && value[index + 1] == 'o') + { + index++; + result += TimeSpan.FromDays(unitValue * 30); + } + else + result += TimeSpan.FromMinutes(unitValue); + + unitValue = 0; + break; + + case 'w': + result += TimeSpan.FromDays(unitValue * 7); + unitValue = 0; + break; + + case 'd': + result += TimeSpan.FromDays(unitValue); + unitValue = 0; + break; + + case 'h': + result += TimeSpan.FromHours(unitValue); + unitValue = 0; + break; + + case 's': + result += TimeSpan.FromSeconds(unitValue); + unitValue = 0; + break; + } + } + + return Task.FromResult>(result); + } +} diff --git a/BrackeysBot/Plugins/SimplePluginManager.cs b/BrackeysBot/Plugins/SimplePluginManager.cs index a780b2e..6255bd9 100644 --- a/BrackeysBot/Plugins/SimplePluginManager.cs +++ b/BrackeysBot/Plugins/SimplePluginManager.cs @@ -6,10 +6,12 @@ using System.Threading; using BrackeysBot.API.Exceptions; using BrackeysBot.API.Plugins; +using BrackeysBot.ArgumentConverters; using BrackeysBot.Configuration; using BrackeysBot.Resources; using DisCatSharp; using DisCatSharp.CommandsNext; +using DisCatSharp.CommandsNext.Converters; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; @@ -287,6 +289,9 @@ public IPlugin LoadPlugin(string name) CommandsNextExtension? commandsNext = plugin.DiscordClient?.GetCommandsNext(); if (commandsNext is not null) { + commandsNext.UnregisterConverter(); + commandsNext.RegisterConverter(new TimeSpanArgumentConverter()); + string[] commandNames = commandsNext.RegisteredCommands.Keys.ToArray(); Logger.Info(string.Format(LoggerMessages.PluginRegisteredCommands, pluginInfo.Name, commandNames.Length, string.Join(", ", commandNames)));