Moved .convert and .calc to Utility, updated descriptions to match prefix

This commit is contained in:
Kwoth 2016-10-10 03:02:42 +02:00
parent fbd2beb348
commit 482d1a8fb4
6 changed files with 10 additions and 282 deletions

View File

@ -1,67 +0,0 @@
using Discord;
using Discord.Commands;
using NadekoBot.Attributes;
using NadekoBot.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Searches
{
[Group]
public partial class Searches
{
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public static async Task Calculate(IUserMessage msg, [Remainder] string expression)
{
try
{
var expr = new NCalc.Expression(expression, NCalc.EvaluateOptions.IgnoreCase);
expr.EvaluateParameter += Expr_EvaluateParameter;
var result = expr.Evaluate();
await msg.Reply(string.Format("Your expression evaluated to: {0}", expr.Error ?? result));
}
catch (Exception e)
{
await msg.Reply($"Your expression failed to evaluate: {e.Message} ");
}
}
private static void Expr_EvaluateParameter(string name, NCalc.ParameterArgs args)
{
switch (name.ToLowerInvariant()) {
case "pi": args.Result= Math.PI;
break;
case "e": args.Result = Math.E;
break;
}
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task CalcOps(IUserMessage msg)
{
StringBuilder builder = new StringBuilder();
var selection = typeof(Math).GetTypeInfo().GetMethods().Except(typeof(object).GetTypeInfo().GetMethods()).Select(x =>
{
var name = x.Name;
if (x.GetParameters().Any())
{
name += " (" + string.Join(", ", x.GetParameters().Select(y => y.IsOptional ? $"[{y.ParameterType.Name + " " + y.Name }]" : y.ParameterType.Name + " " + y.Name)) + ")";
}
return name;
});
foreach (var method in selection) builder.AppendLine(method);
await msg.ReplyLong(builder.ToString());
}
}
class ExpressionContext
{
public double Pi { get; set; } = Math.PI;
}
}

View File

@ -1,11 +0,0 @@
using System.Collections.Generic;
namespace NadekoBot.Modules.Searches.Commands.Models
{
public class MeasurementUnit
{
public List<string> Triggers { get; set; }
public string UnitType { get; set; }
public decimal Modifier { get; set; }
}
}

View File

@ -1,14 +0,0 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace NadekoBot.Modules.Searches.Commands.Models
{
public class Rates
{
public string Base { get; set; }
public DateTime Date { get; set; }
[JsonProperty("rates")]
public Dictionary<string, decimal> ConversionRates { get; set; }
}
}

View File

@ -1,180 +0,0 @@
using Discord;
using Discord.Commands;
using NadekoBot.Attributes;
using NadekoBot.Extensions;
using NadekoBot.Modules.Searches.Commands.Models;
using NadekoBot.Services;
using NadekoBot.Services.Database.Models;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
namespace NadekoBot.Modules.Searches
{
public partial class Searches
{
[Group]
public class UnitConverterCommands
{
private Logger _log;
private static Timer _timer;
public static TimeSpan Span = new TimeSpan(12, 0, 0);
public UnitConverterCommands()
{
_log = LogManager.GetCurrentClassLogger();
try
{
using (var uow = DbHandler.UnitOfWork())
{
//need to do this the first time
if (uow.ConverterUnits.Empty())
{
var content = JsonConvert.DeserializeObject<List<MeasurementUnit>>(File.ReadAllText("units.json")).Select(u => new ConvertUnit()
{
Modifier = u.Modifier,
UnitType = u.UnitType,
InternalTrigger = string.Join("|", u.Triggers)
});
uow.ConverterUnits.AddRange(content.ToArray());
uow.Complete();
}
Units = uow.ConverterUnits.GetAll().ToList();
}
}
catch (Exception e)
{
_log.Warn("Could not load units: " + e.Message);
}
_timer = new Timer(new TimerCallback(UpdateCurrency), null, 0,(int)Span.TotalMilliseconds);
}
public void UpdateCurrency(object stateInfo)
{
var currencyRates = UpdateCurrencyRates().Result;
var unitTypeString = "currency";
using (var uow = DbHandler.UnitOfWork())
{
var toRemove = Units.Where(u => u.UnitType == unitTypeString);
Units.RemoveAll(u => u.UnitType == unitTypeString);
uow.ConverterUnits.RemoveRange(toRemove.ToArray());
var baseType = new ConvertUnit()
{
Triggers = new[] { currencyRates.Base },
Modifier = decimal.One,
UnitType = unitTypeString
};
uow.ConverterUnits.Add(baseType);
Units.Add(baseType);
var range = currencyRates.ConversionRates.Select(u => new ConvertUnit()
{
InternalTrigger = u.Key,
Modifier = u.Value,
UnitType = unitTypeString
}).ToArray();
uow.ConverterUnits.AddRange(range);
Units.AddRange(range);
uow.Complete();
}
_log.Info("Updated Currency");
}
public List<ConvertUnit> Units { get; set; }
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task ConvertList(IUserMessage msg)
{
var sb = new StringBuilder("Units that can be used by the converter: \n");
var res = Units.GroupBy(x => x.UnitType);
foreach (var group in res)
{
sb.AppendLine($"{group.Key}: ```xl");
sb.AppendLine(string.Join(",", group.Select(x => x.Triggers.FirstOrDefault()).OrderBy(x => x)));
sb.AppendLine("```");
}
await msg.ReplyLong(sb.ToString(), breakOn: new[] { "```xl\n", "\n" });
}
[NadekoCommand, Usage, Description, Aliases]
public async Task Convert(IUserMessage msg, string origin, string target, decimal value)
{
var originUnit = Units.Find(x => x.Triggers.Select(y => y.ToLowerInvariant()).Contains(origin.ToLowerInvariant()));
var targetUnit = Units.Find(x => x.Triggers.Select(y => y.ToLowerInvariant()).Contains(target.ToLowerInvariant()));
if (originUnit == null || targetUnit == null)
{
await msg.Reply(string.Format("Cannot convert {0} to {1}: units not found", origin, target));
return;
}
if (originUnit.UnitType != targetUnit.UnitType)
{
await msg.Reply(string.Format("Cannot convert {0} to {1}: types of unit are not equal", originUnit.Triggers.First(), targetUnit.Triggers.First()));
return;
}
decimal res;
if (originUnit.Triggers == targetUnit.Triggers) res = value;
else if (originUnit.UnitType == "temperature")
{
//don't really care too much about efficiency, so just convert to Kelvin, then to target
switch (originUnit.Triggers.First().ToUpperInvariant())
{
case "C":
res = value + 273.15m; //celcius!
break;
case "F":
res = (value + 459.67m) * (5 / 9);
break;
default:
res = value;
break;
}
//from Kelvin to target
switch (targetUnit.Triggers.First())
{
case "C":
res = value - 273.15m; //celcius!
break;
case "F":
res = res * (9 / 5) - 458.67m;
break;
default:
break;
}
}
else
{
if (originUnit.UnitType == "currency")
{
res = (value * targetUnit.Modifier) / originUnit.Modifier;
}
else
res = (value * originUnit.Modifier) / targetUnit.Modifier;
}
res = Math.Round(res, 2);
await msg.Reply(string.Format("{0} {1} is equal to {2} {3}", value, (originUnit.Triggers.First() + "s").SnPl(value.IsInteger() ? (int)value : 2), res, (targetUnit.Triggers.First() + "s").SnPl(res.IsInteger() ? (int)res : 2)));
}
}
public static async Task<Rates> UpdateCurrencyRates()
{
using (var http = new HttpClient())
{
var res = await http.GetStringAsync("http://api.fixer.io/latest").ConfigureAwait(false);
return JsonConvert.DeserializeObject<Rates>(res);
}
}
}
}

View File

@ -807,7 +807,7 @@ namespace NadekoBot.Resources {
}
/// <summary>
/// Looks up a localized string similar to `~calcops`.
/// Looks up a localized string similar to `.calcops`.
/// </summary>
public static string calcops_usage {
get {
@ -834,7 +834,7 @@ namespace NadekoBot.Resources {
}
/// <summary>
/// Looks up a localized string similar to `~calc 1+1`.
/// Looks up a localized string similar to `.calc 1+1`.
/// </summary>
public static string calculate_usage {
get {
@ -1554,7 +1554,7 @@ namespace NadekoBot.Resources {
}
/// <summary>
/// Looks up a localized string similar to Convert quantities. Use `~convertlist` to see supported dimensions and currencies..
/// Looks up a localized string similar to Convert quantities. Use `.convertlist` to see supported dimensions and currencies..
/// </summary>
public static string convert_desc {
get {
@ -1563,7 +1563,7 @@ namespace NadekoBot.Resources {
}
/// <summary>
/// Looks up a localized string similar to `~convert m km 1000`.
/// Looks up a localized string similar to `.convert m km 1000`.
/// </summary>
public static string convert_usage {
get {
@ -1590,7 +1590,7 @@ namespace NadekoBot.Resources {
}
/// <summary>
/// Looks up a localized string similar to `~convertlist`.
/// Looks up a localized string similar to `.convertlist`.
/// </summary>
public static string convertlist_usage {
get {

View File

@ -1921,10 +1921,10 @@
<value>convert</value>
</data>
<data name="convert_desc" xml:space="preserve">
<value>Convert quantities. Use `~convertlist` to see supported dimensions and currencies.</value>
<value>Convert quantities. Use `.convertlist` to see supported dimensions and currencies.</value>
</data>
<data name="convert_usage" xml:space="preserve">
<value>`~convert m km 1000`</value>
<value>`.convert m km 1000`</value>
</data>
<data name="convertlist_cmd" xml:space="preserve">
<value>convertlist</value>
@ -1933,7 +1933,7 @@
<value>List of the convertible dimensions and currencies.</value>
</data>
<data name="convertlist_usage" xml:space="preserve">
<value>`~convertlist`</value>
<value>`.convertlist`</value>
</data>
<data name="wowjoke_cmd" xml:space="preserve">
<value>wowjoke</value>
@ -1951,7 +1951,7 @@
<value>Evaluate a mathematical expression.</value>
</data>
<data name="calculate_usage" xml:space="preserve">
<value>`~calc 1+1`</value>
<value>`.calc 1+1`</value>
</data>
<data name="osu_cmd" xml:space="preserve">
<value>osu</value>
@ -2515,7 +2515,7 @@
<value>Shows all available operations in .calc command</value>
</data>
<data name="calcops_usage" xml:space="preserve">
<value>`~calcops`</value>
<value>`.calcops`</value>
</data>
<data name="calcops_cmd" xml:space="preserve">
<value>calcops</value>