NadekoBot/NadekoBot.Modules.Utility/Services/CommandMapService.cs

78 lines
2.8 KiB
C#
Raw Normal View History

2017-07-17 19:42:36 +00:00
using System.Collections.Concurrent;
2017-05-29 23:53:16 +00:00
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Discord;
2017-07-17 19:42:36 +00:00
using NadekoBot.Common.ModuleBehaviors;
2017-05-29 23:53:16 +00:00
using NadekoBot.Extensions;
using NadekoBot.Core.Services;
using NadekoBot.Core.Services.Database.Models;
2017-07-17 19:42:36 +00:00
using NLog;
2017-05-29 23:53:16 +00:00
2017-07-17 19:42:36 +00:00
namespace NadekoBot.Modules.Utility.Services
2017-05-29 23:53:16 +00:00
{
public class CommandMapService : IInputTransformer, INService
2017-05-29 23:53:16 +00:00
{
private readonly Logger _log;
public ConcurrentDictionary<ulong, ConcurrentDictionary<string, string>> AliasMaps { get; } = new ConcurrentDictionary<ulong, ConcurrentDictionary<string, string>>();
//commandmap
public CommandMapService(NadekoBot bot)
2017-05-29 23:53:16 +00:00
{
_log = LogManager.GetCurrentClassLogger();
AliasMaps = new ConcurrentDictionary<ulong, ConcurrentDictionary<string, string>>(
bot.AllGuildConfigs.ToDictionary(
2017-05-29 23:53:16 +00:00
x => x.GuildId,
x => new ConcurrentDictionary<string, string>(x.CommandAliases
.Distinct(new CommandAliasEqualityComparer())
.ToDictionary(ca => ca.Trigger, ca => ca.Mapping))));
}
public async Task<string> TransformInput(IGuild guild, IMessageChannel channel, IUser user, string input)
{
await Task.Yield();
if (guild == null || string.IsNullOrWhiteSpace(input))
return input;
2017-05-29 23:53:16 +00:00
if (guild != null)
{
input = input.ToLowerInvariant();
if (AliasMaps.TryGetValue(guild.Id, out ConcurrentDictionary<string, string> maps))
{
var keys = maps.Keys
.OrderByDescending(x => x.Length);
foreach (var k in keys)
{
string newInput;
if (input.StartsWith(k + " "))
newInput = maps[k] + input.Substring(k.Length, input.Length - k.Length);
else if (input == k)
newInput = maps[k];
else
continue;
_log.Info(@"--Mapping Command--
GuildId: {0}
Trigger: {1}
Mapping: {2}", guild.Id, input, newInput);
try { await channel.SendConfirmAsync($"{input} => {newInput}").ConfigureAwait(false); } catch { }
return newInput;
}
}
}
return input;
}
}
public class CommandAliasEqualityComparer : IEqualityComparer<CommandAlias>
{
public bool Equals(CommandAlias x, CommandAlias y) => x.Trigger == y.Trigger;
public int GetHashCode(CommandAlias obj) => obj.Trigger.GetHashCode();
}
}