NadekoBot/src/NadekoBot/Modules/CustomReactions/Extensions.cs

84 lines
3.0 KiB
C#
Raw Normal View History

using Discord;
using NadekoBot.Services;
using NadekoBot.Services.Database.Models;
using System;
using System.Collections.Generic;
2016-12-13 15:17:40 +00:00
using System.Text.RegularExpressions;
namespace NadekoBot.Modules.CustomReactions
{
public static class Extensions
{
2016-10-16 03:22:54 +00:00
public static Dictionary<string, Func<IUserMessage, string, string>> responsePlaceholders = new Dictionary<string, Func<IUserMessage, string, string>>()
{
{"%target%", (ctx, trigger) => { return ctx.Content.Substring(trigger.Length).Trim(); } }
2016-10-16 03:22:54 +00:00
};
public static Dictionary<string, Func<IUserMessage, string>> placeholders = new Dictionary<string, Func<IUserMessage, string>>()
{
{"%mention%", (ctx) => { return $"<@{NadekoBot.Client.GetCurrentUser().Id}>"; } },
{"%user%", (ctx) => { return ctx.Author.Mention; } },
2016-12-13 15:17:40 +00:00
//{"%rng%", (ctx) => { return new NadekoRandom().Next(0,10).ToString(); } }
};
private static readonly Regex rngRegex = new Regex("%rng(?:(?<from>(?:-)?\\d+)-(?<to>(?:-)?\\d+))?%", RegexOptions.Compiled);
private static readonly NadekoRandom rng = new NadekoRandom();
public static Dictionary<Regex, MatchEvaluator> regexPlaceholders = new Dictionary<Regex, MatchEvaluator>()
{
{ rngRegex, (match) => {
int from = 0;
int.TryParse(match.Groups["from"].ToString(), out from);
int to = 0;
int.TryParse(match.Groups["to"].ToString(), out to);
if(from == 0 && to == 0)
{
return rng.Next(0, 11).ToString();
}
if(from >= to)
return "";
return rng.Next(from,to+1).ToString();
} }
};
2016-10-16 03:22:54 +00:00
private static string ResolveTriggerString(this string str, IUserMessage ctx)
{
foreach (var ph in placeholders)
{
2016-10-16 03:22:54 +00:00
str = str.ToLowerInvariant().Replace(ph.Key, ph.Value(ctx));
}
return str;
}
private static string ResolveResponseString(this string str, IUserMessage ctx, string resolvedTrigger)
{
foreach (var ph in placeholders)
{
str = str.Replace(ph.Key.ToLowerInvariant(), ph.Value(ctx));
2016-10-16 03:22:54 +00:00
}
foreach (var ph in responsePlaceholders)
{
str = str.Replace(ph.Key.ToLowerInvariant(), ph.Value(ctx, resolvedTrigger));
}
2016-12-13 15:17:40 +00:00
foreach (var ph in regexPlaceholders)
{
str = ph.Key.Replace(str, ph.Value);
}
return str;
}
public static string TriggerWithContext(this CustomReaction cr, IUserMessage ctx)
2016-10-16 03:22:54 +00:00
=> cr.Trigger.ResolveTriggerString(ctx);
public static string ResponseWithContext(this CustomReaction cr, IUserMessage ctx)
2016-10-16 03:22:54 +00:00
=> cr.Response.ResolveResponseString(ctx, cr.Trigger.ResolveTriggerString(ctx));
}
}