This repository has been archived by the owner on Jun 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Replace default TimeSpanConverter with custom TimeSpanArgumentConverter
- Loading branch information
1 parent
da1a9f3
commit 696d60f
Showing
2 changed files
with
76 additions
and
0 deletions.
There are no files selected for viewing
71 changes: 71 additions & 0 deletions
71
BrackeysBot/ArgumentConverters/TimeSpanArgumentConverter.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
using System; | ||
using System.Threading.Tasks; | ||
using DisCatSharp.CommandsNext; | ||
using DisCatSharp.CommandsNext.Converters; | ||
using DisCatSharp.Entities; | ||
|
||
namespace BrackeysBot.ArgumentConverters; | ||
|
||
/// <summary> | ||
/// Represents a converter which converts a command argument to <see cref="TimeSpan" />. | ||
/// </summary> | ||
internal sealed class TimeSpanArgumentConverter : IArgumentConverter<TimeSpan> | ||
{ | ||
/// <inheritdoc /> | ||
public Task<Optional<TimeSpan>> 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<Optional<TimeSpan>>(result); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters