-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathBotMath.cs
55 lines (51 loc) · 1.97 KB
/
BotMath.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System.Globalization;
using org.mariuszgromada.math.mxparser;
using License = org.mariuszgromada.math.mxparser.License;
namespace CompatBot.Commands;
internal static class BotMath
{
static BotMath()
{
License.iConfirmNonCommercialUse("RPCS3");
}
[Command("calculate")]
[Description("Math; there you go, Juhn")]
public static async ValueTask Calc(SlashCommandContext ctx, [Description("Math expression or `help` for syntax link")] string expression)
{
var ephemeral = !ctx.Channel.IsSpamChannel();
if (expression.Equals("help", StringComparison.OrdinalIgnoreCase))
{
await ctx.RespondAsync("Help for all the features and built-in constants and functions could be found at [mXparser website](<https://mathparser.org/mxparser-math-collection/>)", ephemeral);
return;
}
var result = """
Something went wrong ¯\\\_(ツ)\_/¯
Math is hard, yo
""";
try
{
mXparser.resetCancelCurrentCalculationFlag();
var expr = new Expression(expression);
const int timeout = 1_000;
var cts = new CancellationTokenSource(timeout);
// ReSharper disable once MethodSupportsCancellation
var delayTask = Task.Delay(timeout);
var calcTask = Task.Run(() => expr.calculate().ToString(CultureInfo.InvariantCulture), cts.Token);
await Task.WhenAny(calcTask, delayTask).ConfigureAwait(false);
if (calcTask.IsCompletedSuccessfully)
{
result = await calcTask;
}
else
{
mXparser.cancelCurrentCalculation();
result = "Calculation took too much time and all operations were cancelled";
}
}
catch (Exception e)
{
Config.Log.Warn(e, "Math failed");
}
await ctx.RespondAsync(result, ephemeral).ConfigureAwait(false);
}
}