mirror of
https://github.com/Jetsparrow/antiantiswearingbot.git
synced 2026-01-20 23:16:08 +03:00
Switching to NET6
This commit is contained in:
parent
a17f40c5f7
commit
354876985d
@ -1,7 +1,7 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>netcoreapp3.0</TargetFramework>
|
<TargetFramework>net6.0</TargetFramework>
|
||||||
|
|
||||||
<IsPackable>false</IsPackable>
|
<IsPackable>false</IsPackable>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|||||||
@ -1,96 +1,97 @@
|
|||||||
using System;
|
using System.Text.RegularExpressions;
|
||||||
using System.Linq;
|
using System.Threading;
|
||||||
using System.Net;
|
|
||||||
using System.Text;
|
|
||||||
using System.Text.RegularExpressions;
|
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using AntiAntiSwearingBot.Commands;
|
|
||||||
using Telegram.Bot;
|
using Telegram.Bot;
|
||||||
using Telegram.Bot.Args;
|
using Telegram.Bot.Exceptions;
|
||||||
|
using Telegram.Bot.Extensions.Polling;
|
||||||
using Telegram.Bot.Types;
|
using Telegram.Bot.Types;
|
||||||
using Telegram.Bot.Types.Enums;
|
using Telegram.Bot.Types.Enums;
|
||||||
|
using AntiAntiSwearingBot.Commands;
|
||||||
|
|
||||||
namespace AntiAntiSwearingBot
|
namespace AntiAntiSwearingBot;
|
||||||
|
|
||||||
|
public class AntiAntiSwearingBot
|
||||||
{
|
{
|
||||||
public class AntiAntiSwearingBot : IDisposable
|
Config Config { get; }
|
||||||
|
SearchDictionary Dict { get; }
|
||||||
|
Unbleeper Unbleeper { get; }
|
||||||
|
|
||||||
|
public AntiAntiSwearingBot(Config cfg, SearchDictionary dict)
|
||||||
{
|
{
|
||||||
Config Config { get; }
|
Config = cfg;
|
||||||
SearchDictionary Dict { get; }
|
Dict = dict;
|
||||||
Unbleeper Unbleeper { get; }
|
Unbleeper = new Unbleeper(dict, cfg.Unbleeper);
|
||||||
|
}
|
||||||
|
|
||||||
public AntiAntiSwearingBot(Config cfg, SearchDictionary dict)
|
TelegramBotClient TelegramBot { get; set; }
|
||||||
|
ChatCommandRouter Router { get; set; }
|
||||||
|
public User Me { get; private set; }
|
||||||
|
|
||||||
|
public async Task Init()
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(Config.ApiKey))
|
||||||
|
return;
|
||||||
|
|
||||||
|
TelegramBot = new TelegramBotClient(Config.ApiKey);
|
||||||
|
|
||||||
|
Me = await TelegramBot.GetMeAsync();
|
||||||
|
|
||||||
|
|
||||||
|
Router = new ChatCommandRouter(Me.Username);
|
||||||
|
Router.Add(new LearnCommand(Dict), "learn");
|
||||||
|
Router.Add(new UnlearnCommand(Dict), "unlearn");
|
||||||
|
|
||||||
|
var receiverOptions = new ReceiverOptions { AllowedUpdates = new[] { UpdateType.Message } };
|
||||||
|
TelegramBot.StartReceiving(
|
||||||
|
HandleUpdateAsync,
|
||||||
|
HandleErrorAsync,
|
||||||
|
receiverOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var ErrorMessage = exception switch
|
||||||
{
|
{
|
||||||
Config = cfg;
|
ApiRequestException apiRequestException => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
|
||||||
Dict = dict;
|
_ => exception.ToString()
|
||||||
Unbleeper = new Unbleeper(dict, cfg.Unbleeper);
|
};
|
||||||
}
|
Console.WriteLine(ErrorMessage);
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
TelegramBotClient Client { get; set; }
|
async Task HandleUpdateAsync(ITelegramBotClient sender, Update update, CancellationToken cancellationToken)
|
||||||
ChatCommandRouter Router { get; set; }
|
{
|
||||||
public User Me { get; private set; }
|
if (update.Type != UpdateType.Message || update?.Message?.Type != MessageType.Text)
|
||||||
|
return;
|
||||||
public async Task Init()
|
var msg = update.Message!;
|
||||||
|
try
|
||||||
{
|
{
|
||||||
var httpProxy = new WebProxy($"{Config.Proxy.Url}:{Config.Proxy.Port}")
|
|
||||||
{
|
|
||||||
Credentials = new NetworkCredential(Config.Proxy.Login, Config.Proxy.Password)
|
|
||||||
};
|
|
||||||
|
|
||||||
Client = new TelegramBotClient(Config.ApiKey, httpProxy);
|
|
||||||
Me = await Client.GetMeAsync();
|
|
||||||
Router = new ChatCommandRouter(Me.Username);
|
|
||||||
Router.Add(new LearnCommand(Dict), "learn");
|
|
||||||
Router.Add(new UnlearnCommand(Dict), "unlearn");
|
|
||||||
|
|
||||||
Client.OnMessage += BotOnMessageReceived;
|
|
||||||
Client.StartReceiving();
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task Stop()
|
|
||||||
{
|
|
||||||
Dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
#region service
|
|
||||||
|
|
||||||
void BotOnMessageReceived(object sender, MessageEventArgs args)
|
|
||||||
{
|
|
||||||
var msg = args.Message;
|
|
||||||
if (msg == null || msg.Type != MessageType.Text)
|
|
||||||
return;
|
|
||||||
|
|
||||||
string commandResponse = null;
|
string commandResponse = null;
|
||||||
|
|
||||||
try { commandResponse = Router.Execute(sender, args); }
|
try { commandResponse = Router.Execute(sender, update); }
|
||||||
catch { }
|
catch { }
|
||||||
|
|
||||||
if (commandResponse != null)
|
if (commandResponse != null)
|
||||||
{
|
{
|
||||||
Client.SendTextMessageAsync(
|
await TelegramBot.SendTextMessageAsync(
|
||||||
args.Message.Chat.Id,
|
msg.Chat.Id,
|
||||||
commandResponse,
|
commandResponse,
|
||||||
replyToMessageId: args.Message.MessageId);
|
replyToMessageId: msg.MessageId);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
var unbleepResponse = Unbleeper.UnbleepSwears(msg.Text);
|
var unbleepResponse = Unbleeper.UnbleepSwears(msg.Text);
|
||||||
if (unbleepResponse != null)
|
if (unbleepResponse != null)
|
||||||
Client.SendTextMessageAsync(
|
await TelegramBot.SendTextMessageAsync(
|
||||||
args.Message.Chat.Id,
|
msg.Chat.Id,
|
||||||
unbleepResponse,
|
unbleepResponse,
|
||||||
replyToMessageId: args.Message.MessageId);
|
replyToMessageId: msg.MessageId);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
catch (Exception e)
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region IDisposable
|
|
||||||
|
|
||||||
public void Dispose()
|
|
||||||
{
|
{
|
||||||
Client.StopReceiving();
|
Console.WriteLine(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>Exe</OutputType>
|
<OutputType>Exe</OutputType>
|
||||||
<TargetFramework>netcoreapp3.0</TargetFramework>
|
<TargetFramework>net6.0</TargetFramework>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
@ -10,8 +10,8 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
||||||
<PackageReference Include="Telegram.Bot" Version="14.10.0" />
|
<PackageReference Include="Telegram.Bot.Extensions.Polling" Version="2.0.0-alpha.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@ -1,47 +1,44 @@
|
|||||||
using System;
|
using Telegram.Bot.Types;
|
||||||
using System.Collections.Generic;
|
|
||||||
using Telegram.Bot.Args;
|
|
||||||
using AntiAntiSwearingBot.Commands;
|
using AntiAntiSwearingBot.Commands;
|
||||||
|
|
||||||
namespace AntiAntiSwearingBot
|
namespace AntiAntiSwearingBot;
|
||||||
|
|
||||||
|
public interface IChatCommand
|
||||||
{
|
{
|
||||||
public interface IChatCommand
|
string Execute(CommandString cmd, Update messageEventArgs);
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ChatCommandRouter
|
||||||
|
{
|
||||||
|
string Username { get; }
|
||||||
|
Dictionary<string, IChatCommand> Commands { get; }
|
||||||
|
|
||||||
|
public ChatCommandRouter(string username)
|
||||||
{
|
{
|
||||||
string Execute(CommandString cmd, MessageEventArgs messageEventArgs);
|
Username = username;
|
||||||
|
Commands = new Dictionary<string, IChatCommand>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public class ChatCommandRouter
|
public string Execute(object sender, Update args)
|
||||||
{
|
{
|
||||||
string Username { get; }
|
var text = args.Message.Text;
|
||||||
Dictionary<string, IChatCommand> Commands { get; }
|
if (CommandString.TryParse(text, out var cmd))
|
||||||
|
|
||||||
public ChatCommandRouter(string username)
|
|
||||||
{
|
{
|
||||||
Username = username;
|
if (cmd.Username != null && cmd.Username != Username)
|
||||||
Commands = new Dictionary<string, IChatCommand>();
|
return null;
|
||||||
|
if (Commands.ContainsKey(cmd.Command))
|
||||||
|
return Commands[cmd.Command].Execute(cmd, args);
|
||||||
}
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
public string Execute(object sender, MessageEventArgs args)
|
public void Add(IChatCommand c, params string[] cmds)
|
||||||
|
{
|
||||||
|
foreach (var cmd in cmds)
|
||||||
{
|
{
|
||||||
var text = args.Message.Text;
|
if (Commands.ContainsKey(cmd))
|
||||||
if (CommandString.TryParse(text, out var cmd))
|
throw new ArgumentException($"collision for {cmd}, commands {Commands[cmd].GetType()} and {c.GetType()}");
|
||||||
{
|
Commands[cmd] = c;
|
||||||
if (cmd.UserName != null && cmd.UserName != Username)
|
|
||||||
return null;
|
|
||||||
if (Commands.ContainsKey(cmd.Command))
|
|
||||||
return Commands[cmd.Command].Execute(cmd, args);
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Add(IChatCommand c, params string[] cmds)
|
|
||||||
{
|
|
||||||
foreach (var cmd in cmds)
|
|
||||||
{
|
|
||||||
if (Commands.ContainsKey(cmd))
|
|
||||||
throw new ArgumentException($"collision for {cmd}, commands {Commands[cmd].GetType()} and {c.GetType()}");
|
|
||||||
Commands[cmd] = c;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,44 +1,40 @@
|
|||||||
using System;
|
using System.Text.RegularExpressions;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Text;
|
|
||||||
using System.Text.RegularExpressions;
|
|
||||||
|
|
||||||
namespace AntiAntiSwearingBot.Commands
|
namespace AntiAntiSwearingBot.Commands;
|
||||||
|
|
||||||
|
public class CommandString
|
||||||
{
|
{
|
||||||
public class CommandString
|
public CommandString(string command, string username, params string[] parameters)
|
||||||
{
|
{
|
||||||
public CommandString(string command, string username, params string[] parameters)
|
Command = command;
|
||||||
{
|
Username = username;
|
||||||
Command = command;
|
Parameters = parameters;
|
||||||
Parameters = parameters;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public string Command { get; }
|
public string Command { get; }
|
||||||
public string UserName { get; }
|
public string Username { get; }
|
||||||
public string[] Parameters { get; }
|
public string[] Parameters { get; }
|
||||||
|
|
||||||
static readonly char[] WS_CHARS = new[] { ' ', '\r', '\n', '\n' };
|
static readonly char[] WS_CHARS = new[] { ' ', '\r', '\n', '\n' };
|
||||||
|
|
||||||
public static bool TryParse(string s, out CommandString result)
|
public static bool TryParse(string s, out CommandString result)
|
||||||
{
|
{
|
||||||
result = null;
|
result = null;
|
||||||
if (string.IsNullOrWhiteSpace(s) || s[0] != '/')
|
if (string.IsNullOrWhiteSpace(s) || s[0] != '/')
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
string[] words = s.Split(WS_CHARS, StringSplitOptions.RemoveEmptyEntries);
|
string[] words = s.Split(WS_CHARS, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
|
||||||
var cmdRegex = new Regex(@"/(?<cmd>\w+)(@(?<name>\w+))?");
|
var cmdRegex = new Regex(@"/(?<cmd>\w+)(@(?<name>\w+))?");
|
||||||
var match = cmdRegex.Match(words.First());
|
var match = cmdRegex.Match(words.First());
|
||||||
if (!match.Success)
|
if (!match.Success)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
string cmd = match.Groups["cmd"].Captures[0].Value;
|
string cmd = match.Groups["cmd"].Captures[0].Value;
|
||||||
string username = match.Groups["name"].Captures.Count > 0 ? match.Groups["name"].Captures[0].Value : null;
|
string username = match.Groups["name"].Captures.Count > 0 ? match.Groups["name"].Captures[0].Value : null;
|
||||||
string[] parameters = words.Skip(1).ToArray();
|
string[] parameters = words.Skip(1).ToArray();
|
||||||
|
|
||||||
result = new CommandString(cmd, username, parameters);
|
result = new CommandString(cmd, username, parameters);
|
||||||
return true;
|
return true;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,29 +1,26 @@
|
|||||||
using System.Linq;
|
using System.Text.RegularExpressions;
|
||||||
using System.Text.RegularExpressions;
|
using Telegram.Bot.Types;
|
||||||
using Telegram.Bot.Args;
|
|
||||||
|
|
||||||
namespace AntiAntiSwearingBot.Commands
|
namespace AntiAntiSwearingBot.Commands;
|
||||||
|
public class LearnCommand : IChatCommand
|
||||||
{
|
{
|
||||||
public class LearnCommand : IChatCommand
|
SearchDictionary Dict { get; }
|
||||||
|
|
||||||
|
public LearnCommand(SearchDictionary dict)
|
||||||
{
|
{
|
||||||
SearchDictionary Dict { get; }
|
Dict = dict;
|
||||||
|
}
|
||||||
|
|
||||||
public LearnCommand(SearchDictionary dict)
|
public string Execute(CommandString cmd, Update args)
|
||||||
{
|
{
|
||||||
Dict = dict;
|
var word = cmd.Parameters.FirstOrDefault();
|
||||||
}
|
if (string.IsNullOrWhiteSpace(word))
|
||||||
|
return null;
|
||||||
|
|
||||||
public string Execute(CommandString cmd, MessageEventArgs args)
|
if (!Regex.IsMatch(word, @"[а-яА-Я]+"))
|
||||||
{
|
return null;
|
||||||
var word = cmd.Parameters.FirstOrDefault();
|
|
||||||
if (string.IsNullOrWhiteSpace(word))
|
|
||||||
return null;
|
|
||||||
|
|
||||||
if (!Regex.IsMatch(word, @"[а-яА-Я]+"))
|
bool newWord = Dict.Learn(word);
|
||||||
return null;
|
return newWord ? $"Принято слово \"{word}\"" : $"Поднял рейтинг слову \"{word}\"";
|
||||||
|
|
||||||
bool newWord = Dict.Learn(word);
|
|
||||||
return newWord ? $"Принято слово \"{word}\"" : $"Поднял рейтинг слову \"{word}\"";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,30 +1,27 @@
|
|||||||
using System.Linq;
|
using System.Text.RegularExpressions;
|
||||||
using System.Text.RegularExpressions;
|
using Telegram.Bot.Types;
|
||||||
using Telegram.Bot.Args;
|
|
||||||
|
|
||||||
namespace AntiAntiSwearingBot.Commands
|
namespace AntiAntiSwearingBot.Commands;
|
||||||
|
public class UnlearnCommand : IChatCommand
|
||||||
{
|
{
|
||||||
public class UnlearnCommand : IChatCommand
|
SearchDictionary Dict { get; }
|
||||||
|
|
||||||
|
public UnlearnCommand(SearchDictionary dict)
|
||||||
{
|
{
|
||||||
SearchDictionary Dict { get; }
|
Dict = dict;
|
||||||
|
}
|
||||||
|
|
||||||
public UnlearnCommand(SearchDictionary dict)
|
public string Execute(CommandString cmd, Update args)
|
||||||
{
|
{
|
||||||
Dict = dict;
|
var word = cmd.Parameters.FirstOrDefault();
|
||||||
}
|
if (string.IsNullOrWhiteSpace(word))
|
||||||
|
return null;
|
||||||
|
|
||||||
public string Execute(CommandString cmd, MessageEventArgs args)
|
if (!Regex.IsMatch(word, @"[а-яА-Я]+"))
|
||||||
{
|
return null;
|
||||||
var word = cmd.Parameters.FirstOrDefault();
|
if (Dict.Unlearn(word))
|
||||||
if (string.IsNullOrWhiteSpace(word))
|
return $"Удалил слово \"{word}\"";
|
||||||
return null;
|
else
|
||||||
|
return $"Не нашел слово \"{word}\"";
|
||||||
if (!Regex.IsMatch(word, @"[а-яА-Я]+"))
|
|
||||||
return null;
|
|
||||||
if (Dict.Unlearn(word))
|
|
||||||
return $"Удалил слово \"{word}\"";
|
|
||||||
else
|
|
||||||
return $"Не нашел слово \"{word}\"";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,32 +1,29 @@
|
|||||||
namespace AntiAntiSwearingBot
|
namespace AntiAntiSwearingBot;
|
||||||
|
|
||||||
|
public class Config : ConfigBase
|
||||||
{
|
{
|
||||||
public class Config : ConfigBase
|
public string ApiKey { get; private set; }
|
||||||
{
|
public ProxySettings Proxy { get; private set; }
|
||||||
public string ApiKey { get; private set; }
|
public SearchDictionarySettings SearchDictionary { get; private set; }
|
||||||
public ProxySettings Proxy { get; private set; }
|
public UnbleeperSettings Unbleeper { get; private set; }
|
||||||
public SearchDictionarySettings SearchDictionary { get; private set; }
|
|
||||||
public UnbleeperSettings Unbleeper { get; private set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public struct UnbleeperSettings
|
|
||||||
{
|
|
||||||
public string BleepedSwearsRegex { get; private set; }
|
|
||||||
public int MinAmbiguousWordLength { get; private set; }
|
|
||||||
public int MinWordLength { get; private set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public struct SearchDictionarySettings
|
|
||||||
{
|
|
||||||
public string DictionaryPath { get; private set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public struct ProxySettings
|
|
||||||
{
|
|
||||||
public string Url { get; private set; }
|
|
||||||
public int Port { get; private set; }
|
|
||||||
public string Login { get; private set; }
|
|
||||||
public string Password { get; private set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public struct UnbleeperSettings
|
||||||
|
{
|
||||||
|
public string BleepedSwearsRegex { get; private set; }
|
||||||
|
public int MinAmbiguousWordLength { get; private set; }
|
||||||
|
public int MinWordLength { get; private set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct SearchDictionarySettings
|
||||||
|
{
|
||||||
|
public string DictionaryPath { get; private set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct ProxySettings
|
||||||
|
{
|
||||||
|
public string Url { get; private set; }
|
||||||
|
public int Port { get; private set; }
|
||||||
|
public string Login { get; private set; }
|
||||||
|
public string Password { get; private set; }
|
||||||
|
}
|
||||||
|
|||||||
@ -1,76 +1,75 @@
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
|
using System.Reflection;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using Newtonsoft.Json.Linq;
|
using Newtonsoft.Json.Linq;
|
||||||
using System.Reflection;
|
|
||||||
using Newtonsoft.Json.Serialization;
|
using Newtonsoft.Json.Serialization;
|
||||||
|
|
||||||
namespace AntiAntiSwearingBot
|
namespace AntiAntiSwearingBot;
|
||||||
|
|
||||||
|
public abstract class ConfigBase
|
||||||
{
|
{
|
||||||
public abstract class ConfigBase
|
public static T Load<T>(params string[] paths) where T : ConfigBase, new()
|
||||||
{
|
{
|
||||||
public static T Load<T>(params string[] paths) where T : ConfigBase, new()
|
var result = new T();
|
||||||
|
var configJson = new JObject();
|
||||||
|
var mergeSettings = new JsonMergeSettings
|
||||||
{
|
{
|
||||||
var result = new T();
|
MergeArrayHandling = MergeArrayHandling.Union
|
||||||
var configJson = new JObject();
|
};
|
||||||
var mergeSettings = new JsonMergeSettings
|
|
||||||
|
foreach (var path in paths)
|
||||||
|
{
|
||||||
|
try { configJson.Merge(JObject.Parse(File.ReadAllText(path)), mergeSettings);}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
using (var sr = configJson.CreateReader())
|
||||||
|
{
|
||||||
|
var settings = new JsonSerializerSettings
|
||||||
{
|
{
|
||||||
MergeArrayHandling = MergeArrayHandling.Union
|
ContractResolver = new PrivateSetterContractResolver()
|
||||||
};
|
};
|
||||||
|
JsonSerializer.CreateDefault(settings).Populate(sr, result);
|
||||||
foreach (var path in paths)
|
|
||||||
{
|
|
||||||
try { configJson.Merge(JObject.Parse(File.ReadAllText(path)), mergeSettings);}
|
|
||||||
catch { }
|
|
||||||
}
|
|
||||||
|
|
||||||
using (var sr = configJson.CreateReader())
|
|
||||||
{
|
|
||||||
var settings = new JsonSerializerSettings
|
|
||||||
{
|
|
||||||
ContractResolver = new PrivateSetterContractResolver()
|
|
||||||
};
|
|
||||||
JsonSerializer.CreateDefault(settings).Populate(sr, result);
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public class PrivateSetterContractResolver : DefaultContractResolver
|
return result;
|
||||||
{
|
}
|
||||||
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
|
}
|
||||||
{
|
|
||||||
var jProperty = base.CreateProperty(member, memberSerialization);
|
public class PrivateSetterContractResolver : DefaultContractResolver
|
||||||
if (jProperty.Writable)
|
{
|
||||||
return jProperty;
|
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
|
||||||
|
{
|
||||||
jProperty.Writable = member.IsPropertyWithSetter();
|
var jProperty = base.CreateProperty(member, memberSerialization);
|
||||||
|
if (jProperty.Writable)
|
||||||
return jProperty;
|
return jProperty;
|
||||||
}
|
|
||||||
}
|
jProperty.Writable = member.IsPropertyWithSetter();
|
||||||
|
|
||||||
public class PrivateSetterCamelCasePropertyNamesContractResolver : CamelCasePropertyNamesContractResolver
|
return jProperty;
|
||||||
{
|
}
|
||||||
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
|
}
|
||||||
{
|
|
||||||
var jProperty = base.CreateProperty(member, memberSerialization);
|
public class PrivateSetterCamelCasePropertyNamesContractResolver : CamelCasePropertyNamesContractResolver
|
||||||
if (jProperty.Writable)
|
{
|
||||||
return jProperty;
|
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
|
||||||
|
{
|
||||||
jProperty.Writable = member.IsPropertyWithSetter();
|
var jProperty = base.CreateProperty(member, memberSerialization);
|
||||||
|
if (jProperty.Writable)
|
||||||
return jProperty;
|
return jProperty;
|
||||||
}
|
|
||||||
}
|
jProperty.Writable = member.IsPropertyWithSetter();
|
||||||
|
|
||||||
internal static class MemberInfoExtensions
|
return jProperty;
|
||||||
{
|
}
|
||||||
internal static bool IsPropertyWithSetter(this MemberInfo member)
|
}
|
||||||
{
|
|
||||||
var property = member as PropertyInfo;
|
internal static class MemberInfoExtensions
|
||||||
|
{
|
||||||
return property?.GetSetMethod(true) != null;
|
internal static bool IsPropertyWithSetter(this MemberInfo member)
|
||||||
}
|
{
|
||||||
|
var property = member as PropertyInfo;
|
||||||
|
|
||||||
|
return property?.GetSetMethod(true) != null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,23 +1,18 @@
|
|||||||
using System;
|
namespace AntiAntiSwearingBot;
|
||||||
using System.Collections.Generic;
|
public static class IListExtensions
|
||||||
|
|
||||||
namespace AntiAntiSwearingBot
|
|
||||||
{
|
{
|
||||||
public static class IListExtensions
|
public static void Move<T>(this IList<T> list, int from, int to)
|
||||||
{
|
{
|
||||||
public static void Move<T>(this IList<T> list, int from, int to)
|
if (from < 0 || from > list.Count)
|
||||||
{
|
throw new ArgumentOutOfRangeException("from");
|
||||||
if (from < 0 || from > list.Count)
|
if (to < 0 || to > list.Count)
|
||||||
throw new ArgumentOutOfRangeException("from");
|
throw new ArgumentOutOfRangeException("to");
|
||||||
if (to < 0 || to > list.Count)
|
if (from == to)
|
||||||
throw new ArgumentOutOfRangeException("to");
|
return;
|
||||||
if (from == to)
|
|
||||||
return;
|
|
||||||
|
|
||||||
var item = list[from];
|
var item = list[from];
|
||||||
list.RemoveAt(from);
|
list.RemoveAt(from);
|
||||||
if (to > from) --to; // the actual index could have shifted due to the removal
|
if (to > from) --to; // the actual index could have shifted due to the removal
|
||||||
list.Insert(to, item);
|
list.Insert(to, item);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,15 +0,0 @@
|
|||||||
using System.Collections.Generic;
|
|
||||||
|
|
||||||
namespace AntiAntiSwearingBot
|
|
||||||
{
|
|
||||||
public static class IReadOnlyDictionaryExtensions
|
|
||||||
{
|
|
||||||
public static TValue GetOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dict, TKey key)
|
|
||||||
{
|
|
||||||
TValue res = default(TValue);
|
|
||||||
if (key != null)
|
|
||||||
dict.TryGetValue(key, out res);
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
6
AntiAntiSwearingBot/GlobalSuppressions.cs
Normal file
6
AntiAntiSwearingBot/GlobalSuppressions.cs
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
// This file is used by Code Analysis to maintain SuppressMessage
|
||||||
|
// attributes that are applied to this project.
|
||||||
|
// Project-level suppressions either have no target or are given
|
||||||
|
// a specific target and scoped to a namespace, type, member, etc.
|
||||||
|
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
5
AntiAntiSwearingBot/GlobalUsings.cs
Normal file
5
AntiAntiSwearingBot/GlobalUsings.cs
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
global using System;
|
||||||
|
global using System.Text;
|
||||||
|
global using System.Linq;
|
||||||
|
global using System.Collections.Generic;
|
||||||
|
|
||||||
@ -1,76 +1,69 @@
|
|||||||
using System;
|
using System.Text.RegularExpressions;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Text;
|
|
||||||
using System.Text.RegularExpressions;
|
|
||||||
|
|
||||||
namespace AntiAntiSwearingBot
|
namespace AntiAntiSwearingBot;
|
||||||
|
public static class Language
|
||||||
{
|
{
|
||||||
public static class Language
|
static int min(int a, int b, int c) { return Math.Min(Math.Min(a, b), c); }
|
||||||
|
|
||||||
|
public static int HammingDistance(string a, string b)
|
||||||
{
|
{
|
||||||
static int min(int a, int b, int c) { return Math.Min(Math.Min(a, b), c); }
|
if (string.IsNullOrEmpty(a))
|
||||||
|
|
||||||
public static int HammingDistance(string a, string b)
|
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(a))
|
if (string.IsNullOrEmpty(b))
|
||||||
{
|
return 0;
|
||||||
if (string.IsNullOrEmpty(b))
|
return b.Length;
|
||||||
return 0;
|
|
||||||
return b.Length;
|
|
||||||
}
|
|
||||||
|
|
||||||
int dist = 0;
|
|
||||||
int len = Math.Min(a.Length, b.Length);
|
|
||||||
int leftover = Math.Max(a.Length, b.Length) - len;
|
|
||||||
for (int i = 0; i < len; ++i)
|
|
||||||
if (!CharMatch(a[i], b[i]))
|
|
||||||
++dist;
|
|
||||||
|
|
||||||
return leftover + dist;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static int LevenshteinDistance(string a, string b)
|
int dist = 0;
|
||||||
{
|
int len = Math.Min(a.Length, b.Length);
|
||||||
int[] prevRow = new int[b.Length + 1];
|
int leftover = Math.Max(a.Length, b.Length) - len;
|
||||||
int[] thisRow = new int[b.Length + 1];
|
for (int i = 0; i < len; ++i)
|
||||||
|
if (!CharMatch(a[i], b[i]))
|
||||||
// init thisRow as
|
++dist;
|
||||||
for (int i = 0; i < prevRow.Length; i++) prevRow[i] = i;
|
|
||||||
|
|
||||||
for (int i = 0; i < a.Length; i++)
|
|
||||||
{
|
|
||||||
thisRow[0] = i + 1;
|
|
||||||
for (int j = 0; j < b.Length; j++)
|
|
||||||
{
|
|
||||||
var cost = CharMatch(a[i], b[j]) ? 0 : 1;
|
|
||||||
thisRow[j + 1] = min(thisRow[j] + 1, prevRow[j + 1] + 1, prevRow[j] + cost);
|
|
||||||
}
|
|
||||||
|
|
||||||
var t = prevRow;
|
|
||||||
prevRow = thisRow;
|
|
||||||
thisRow = t;
|
|
||||||
}
|
|
||||||
return prevRow[b.Length];
|
|
||||||
}
|
|
||||||
|
|
||||||
public static bool CharMatch(char a, char b)
|
|
||||||
=> a == b || !char.IsLetterOrDigit(a) || !char.IsLetterOrDigit(b);
|
|
||||||
|
|
||||||
static readonly Regex MentionRegex = new Regex("^@[a-zA-Z0-9_]+$", RegexOptions.Compiled);
|
|
||||||
static readonly Regex EmailPartRegex = new Regex("^\\w+@\\w+$", RegexOptions.Compiled);
|
|
||||||
|
|
||||||
static readonly Regex HashTagRegex = new Regex("^#\\w+$", RegexOptions.Compiled);
|
|
||||||
|
|
||||||
public static bool IsTelegramMention(string word) => MentionRegex.IsMatch(word);
|
|
||||||
|
|
||||||
public static bool IsEmailPart(string word) => EmailPartRegex.IsMatch(word);
|
|
||||||
|
|
||||||
public static bool IsHashTag(string word) => HashTagRegex.IsMatch(word);
|
|
||||||
|
|
||||||
public static bool HasNonWordChars(string arg) => arg.Any(c => !char.IsLetterOrDigit(c));
|
|
||||||
|
|
||||||
public static bool HasWordChars(string arg) => arg.Any(char.IsLetter);
|
|
||||||
|
|
||||||
|
|
||||||
|
return leftover + dist;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static int LevenshteinDistance(string a, string b)
|
||||||
|
{
|
||||||
|
int[] prevRow = new int[b.Length + 1];
|
||||||
|
int[] thisRow = new int[b.Length + 1];
|
||||||
|
|
||||||
|
// init thisRow as
|
||||||
|
for (int i = 0; i < prevRow.Length; i++) prevRow[i] = i;
|
||||||
|
|
||||||
|
for (int i = 0; i < a.Length; i++)
|
||||||
|
{
|
||||||
|
thisRow[0] = i + 1;
|
||||||
|
for (int j = 0; j < b.Length; j++)
|
||||||
|
{
|
||||||
|
var cost = CharMatch(a[i], b[j]) ? 0 : 1;
|
||||||
|
thisRow[j + 1] = min(thisRow[j] + 1, prevRow[j + 1] + 1, prevRow[j] + cost);
|
||||||
|
}
|
||||||
|
|
||||||
|
var t = prevRow;
|
||||||
|
prevRow = thisRow;
|
||||||
|
thisRow = t;
|
||||||
|
}
|
||||||
|
return prevRow[b.Length];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool CharMatch(char a, char b)
|
||||||
|
=> a == b || !char.IsLetterOrDigit(a) || !char.IsLetterOrDigit(b);
|
||||||
|
|
||||||
|
static readonly Regex MentionRegex = new Regex("^@[a-zA-Z0-9_]+$", RegexOptions.Compiled);
|
||||||
|
static readonly Regex EmailPartRegex = new Regex("^\\w+@\\w+$", RegexOptions.Compiled);
|
||||||
|
|
||||||
|
static readonly Regex HashTagRegex = new Regex("^#\\w+$", RegexOptions.Compiled);
|
||||||
|
|
||||||
|
public static bool IsTelegramMention(string word) => MentionRegex.IsMatch(word);
|
||||||
|
|
||||||
|
public static bool IsEmailPart(string word) => EmailPartRegex.IsMatch(word);
|
||||||
|
|
||||||
|
public static bool IsHashTag(string word) => HashTagRegex.IsMatch(word);
|
||||||
|
|
||||||
|
public static bool HasNonWordChars(string arg) => arg.Any(c => !char.IsLetterOrDigit(c));
|
||||||
|
|
||||||
|
public static bool HasWordChars(string arg) => arg.Any(char.IsLetter);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,59 +1,31 @@
|
|||||||
using System;
|
using System.Threading;
|
||||||
using System.Threading;
|
using AntiAntiSwearingBot;
|
||||||
|
|
||||||
namespace AntiAntiSwearingBot
|
static void Log(string m) => Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}|{m}");
|
||||||
|
|
||||||
|
Log("AntiAntiSwearBot starting....");
|
||||||
|
|
||||||
|
var cfg = Config.Load<Config>("aasb.cfg.json", "aasb.cfg.secret.json");
|
||||||
|
var dict = new SearchDictionary(cfg);
|
||||||
|
Log($"{dict.Count} words loaded.");
|
||||||
|
var bot = new AntiAntiSwearingBot.AntiAntiSwearingBot(cfg, dict);
|
||||||
|
bot.Init().Wait();
|
||||||
|
Log($"Connected to Telegram as @{bot.Me.Username}");
|
||||||
|
Log("AntiAntiSwearBot started! Press Ctrl-C to exit.");
|
||||||
|
|
||||||
|
ManualResetEvent quitEvent = new ManualResetEvent(false);
|
||||||
|
try
|
||||||
{
|
{
|
||||||
public static class Program
|
Console.CancelKeyPress += (sender, eArgs) => // ctrl-c
|
||||||
{
|
{
|
||||||
public enum ExitCode : int
|
eArgs.Cancel = true;
|
||||||
{
|
quitEvent.Set();
|
||||||
Ok = 0,
|
};
|
||||||
ErrorNotStarted = 0x80,
|
|
||||||
ErrorRunning = 0x81,
|
|
||||||
ErrorException = 0x82,
|
|
||||||
ErrorInvalidCommandLine = 0x100
|
|
||||||
};
|
|
||||||
|
|
||||||
static void Log(string m) => Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}|{m}");
|
|
||||||
|
|
||||||
public static int Main(string[] args)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
Log("AntiAntiSwearBot starting....");
|
|
||||||
|
|
||||||
var cfg = Config.Load<Config>("aasb.cfg.json", "aasb.cfg.secret.json");
|
|
||||||
var dict = new SearchDictionary(cfg);
|
|
||||||
Log($"{dict.Count} words loaded.");
|
|
||||||
var bot = new AntiAntiSwearingBot(cfg, dict);
|
|
||||||
bot.Init().Wait();
|
|
||||||
Log($"Connected to Telegram as @{bot.Me.Username}");
|
|
||||||
Log("AntiAntiSwearBot started! Press Ctrl-C to exit.");
|
|
||||||
Environment.ExitCode = (int)ExitCode.ErrorRunning;
|
|
||||||
|
|
||||||
ManualResetEvent quitEvent = new ManualResetEvent(false);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
Console.CancelKeyPress += (sender, eArgs) => // ctrl-c
|
|
||||||
{
|
|
||||||
eArgs.Cancel = true;
|
|
||||||
quitEvent.Set();
|
|
||||||
};
|
|
||||||
}
|
|
||||||
catch { }
|
|
||||||
|
|
||||||
quitEvent.WaitOne(Timeout.Infinite);
|
|
||||||
|
|
||||||
Console.WriteLine("Waiting for exit...");
|
|
||||||
bot.Stop().Wait();
|
|
||||||
dict.Save();
|
|
||||||
return (int)ExitCode.Ok;
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Console.WriteLine(ex);
|
|
||||||
return (int)ExitCode.ErrorException;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
catch { }
|
||||||
|
|
||||||
|
quitEvent.WaitOne(Timeout.Infinite);
|
||||||
|
|
||||||
|
Console.WriteLine("Waiting for exit...");
|
||||||
|
dict.Save();
|
||||||
|
|
||||||
|
|||||||
@ -1,86 +1,81 @@
|
|||||||
using System;
|
using System.IO;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.IO;
|
|
||||||
using System.Linq;
|
|
||||||
|
|
||||||
namespace AntiAntiSwearingBot
|
namespace AntiAntiSwearingBot;
|
||||||
|
public class SearchDictionary
|
||||||
{
|
{
|
||||||
public class SearchDictionary
|
public SearchDictionary(Config cfg)
|
||||||
{
|
{
|
||||||
public SearchDictionary(Config cfg)
|
var s = cfg.SearchDictionary;
|
||||||
{
|
path = s.DictionaryPath;
|
||||||
var s = cfg.SearchDictionary;
|
tmppath = path + ".tmp";
|
||||||
path = s.DictionaryPath;
|
|
||||||
tmppath = path + ".tmp";
|
|
||||||
|
|
||||||
words = File.ReadAllLines(path).ToList();
|
words = File.ReadAllLines(path).ToList();
|
||||||
}
|
|
||||||
|
|
||||||
public int Count => words.Count;
|
|
||||||
|
|
||||||
public void Save()
|
|
||||||
{
|
|
||||||
if (File.Exists(tmppath))
|
|
||||||
File.Delete(tmppath);
|
|
||||||
File.WriteAllLines(tmppath, words);
|
|
||||||
if (File.Exists(path))
|
|
||||||
File.Delete(path);
|
|
||||||
File.Move(tmppath, path);
|
|
||||||
}
|
|
||||||
|
|
||||||
public struct WordMatch
|
|
||||||
{
|
|
||||||
public string Word;
|
|
||||||
public int Distance;
|
|
||||||
public int Rating;
|
|
||||||
}
|
|
||||||
|
|
||||||
public WordMatch Match(string pattern)
|
|
||||||
=> AllMatches(pattern).First();
|
|
||||||
|
|
||||||
public IEnumerable<WordMatch> AllMatches(string pattern)
|
|
||||||
{
|
|
||||||
lock (SyncRoot)
|
|
||||||
{
|
|
||||||
pattern = pattern.ToLowerInvariant();
|
|
||||||
return words
|
|
||||||
.Select((w, i) => new WordMatch { Word = w, Distance = Language.LevenshteinDistance(pattern, w), Rating = i })
|
|
||||||
.OrderBy(m => m.Distance)
|
|
||||||
.ThenBy(m => m.Rating);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public bool Learn(string word)
|
|
||||||
{
|
|
||||||
lock (SyncRoot)
|
|
||||||
{
|
|
||||||
int index = words.IndexOf(word);
|
|
||||||
if (index > 0)
|
|
||||||
{
|
|
||||||
words.Move(index, 0);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
words.Insert(0, word);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public bool Unlearn(string word)
|
|
||||||
{
|
|
||||||
lock (SyncRoot)
|
|
||||||
return words.Remove(word);
|
|
||||||
}
|
|
||||||
|
|
||||||
#region service
|
|
||||||
|
|
||||||
readonly string path, tmppath;
|
|
||||||
|
|
||||||
object SyncRoot = new object();
|
|
||||||
List<string> words;
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public int Count => words.Count;
|
||||||
|
|
||||||
|
public void Save()
|
||||||
|
{
|
||||||
|
if (File.Exists(tmppath))
|
||||||
|
File.Delete(tmppath);
|
||||||
|
File.WriteAllLines(tmppath, words);
|
||||||
|
if (File.Exists(path))
|
||||||
|
File.Delete(path);
|
||||||
|
File.Move(tmppath, path);
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct WordMatch
|
||||||
|
{
|
||||||
|
public string Word;
|
||||||
|
public int Distance;
|
||||||
|
public int Rating;
|
||||||
|
}
|
||||||
|
|
||||||
|
public WordMatch Match(string pattern)
|
||||||
|
=> AllMatches(pattern).First();
|
||||||
|
|
||||||
|
public IEnumerable<WordMatch> AllMatches(string pattern)
|
||||||
|
{
|
||||||
|
lock (SyncRoot)
|
||||||
|
{
|
||||||
|
pattern = pattern.ToLowerInvariant();
|
||||||
|
return words
|
||||||
|
.Select((w, i) => new WordMatch { Word = w, Distance = Language.LevenshteinDistance(pattern, w), Rating = i })
|
||||||
|
.OrderBy(m => m.Distance)
|
||||||
|
.ThenBy(m => m.Rating);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Learn(string word)
|
||||||
|
{
|
||||||
|
lock (SyncRoot)
|
||||||
|
{
|
||||||
|
int index = words.IndexOf(word);
|
||||||
|
if (index > 0)
|
||||||
|
{
|
||||||
|
words.Move(index, 0);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
words.Insert(0, word);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Unlearn(string word)
|
||||||
|
{
|
||||||
|
lock (SyncRoot)
|
||||||
|
return words.Remove(word);
|
||||||
|
}
|
||||||
|
|
||||||
|
#region service
|
||||||
|
|
||||||
|
readonly string path, tmppath;
|
||||||
|
|
||||||
|
object SyncRoot = new object();
|
||||||
|
List<string> words;
|
||||||
|
|
||||||
|
#endregion
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,62 +1,57 @@
|
|||||||
using System;
|
using System.Text.RegularExpressions;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Text;
|
|
||||||
using System.Text.RegularExpressions;
|
|
||||||
|
|
||||||
namespace AntiAntiSwearingBot
|
namespace AntiAntiSwearingBot;
|
||||||
|
|
||||||
|
public class Unbleeper
|
||||||
{
|
{
|
||||||
public class Unbleeper
|
SearchDictionary Dict { get; }
|
||||||
|
UnbleeperSettings Cfg { get; }
|
||||||
|
|
||||||
|
public Unbleeper(SearchDictionary dict, UnbleeperSettings cfg)
|
||||||
{
|
{
|
||||||
SearchDictionary Dict { get; }
|
Dict = dict;
|
||||||
UnbleeperSettings Cfg { get; }
|
Cfg = cfg;
|
||||||
|
BleepedSwearsRegex = new Regex("^" + Cfg.BleepedSwearsRegex + "$", RegexOptions.Compiled);
|
||||||
|
}
|
||||||
|
|
||||||
public Unbleeper(SearchDictionary dict, UnbleeperSettings cfg)
|
Regex BleepedSwearsRegex { get; }
|
||||||
|
|
||||||
|
static readonly char[] WORD_SEPARATORS = { ' ', '\t', '\r', '\n', '.', ',', '!', '?', ';', ':', '-', '—' };
|
||||||
|
|
||||||
|
public string UnbleepSwears(string text)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(text))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
text = text.Trim();
|
||||||
|
|
||||||
|
if (text.StartsWith('/')) // is chat command
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var words = text.Split(WORD_SEPARATORS, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
var candidates = words
|
||||||
|
.Where(w =>
|
||||||
|
!Language.IsTelegramMention(w)
|
||||||
|
&& !Language.IsEmailPart(w)
|
||||||
|
&& Language.HasNonWordChars(w)
|
||||||
|
&& !Language.IsHashTag(w)
|
||||||
|
&& (Language.HasWordChars(w) || w.Length >= Cfg.MinAmbiguousWordLength)
|
||||||
|
&& w.Length >= Cfg.MinWordLength
|
||||||
|
&& BleepedSwearsRegex.IsMatch(w)
|
||||||
|
)
|
||||||
|
.ToArray();
|
||||||
|
|
||||||
|
if (candidates.Any())
|
||||||
{
|
{
|
||||||
Dict = dict;
|
var response = new StringBuilder();
|
||||||
Cfg = cfg;
|
for (int i = 0; i < candidates.Length; ++i)
|
||||||
BleepedSwearsRegex = new Regex("^" + Cfg.BleepedSwearsRegex + "$", RegexOptions.Compiled);
|
|
||||||
}
|
|
||||||
|
|
||||||
Regex BleepedSwearsRegex { get; }
|
|
||||||
|
|
||||||
static readonly char[] WORD_SEPARATORS = { ' ', '\t', '\r', '\n', '.', ',', '!', '?', ';', ':', '-', '—' };
|
|
||||||
|
|
||||||
public string UnbleepSwears(string text)
|
|
||||||
{
|
|
||||||
if (string.IsNullOrWhiteSpace(text))
|
|
||||||
return null;
|
|
||||||
|
|
||||||
text = text.Trim();
|
|
||||||
|
|
||||||
if (text.StartsWith('/')) // is chat command
|
|
||||||
return null;
|
|
||||||
|
|
||||||
var words = text.Split(WORD_SEPARATORS, StringSplitOptions.RemoveEmptyEntries);
|
|
||||||
var candidates = words
|
|
||||||
.Where(w =>
|
|
||||||
!Language.IsTelegramMention(w)
|
|
||||||
&& !Language.IsEmailPart(w)
|
|
||||||
&& Language.HasNonWordChars(w)
|
|
||||||
&& !Language.IsHashTag(w)
|
|
||||||
&& (Language.HasWordChars(w) || w.Length >= Cfg.MinAmbiguousWordLength)
|
|
||||||
&& w.Length >= Cfg.MinWordLength
|
|
||||||
&& BleepedSwearsRegex.IsMatch(w)
|
|
||||||
)
|
|
||||||
.ToArray();
|
|
||||||
|
|
||||||
if (candidates.Any())
|
|
||||||
{
|
{
|
||||||
var response = new StringBuilder();
|
var m = Dict.Match(candidates[i]);
|
||||||
for (int i = 0; i < candidates.Length; ++i)
|
response.AppendLine(new string('*', i + 1) + m.Word + new string('?', m.Distance));
|
||||||
{
|
|
||||||
var m = Dict.Match(candidates[i]);
|
|
||||||
response.AppendLine(new string('*', i + 1) + m.Word + new string('?', m.Distance));
|
|
||||||
}
|
|
||||||
return response.ToString();
|
|
||||||
}
|
}
|
||||||
else
|
return response.ToString();
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
else
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user