Switching to NET6

This commit is contained in:
jetsparrow 2022-02-27 18:21:35 +03:00
parent a17f40c5f7
commit 354876985d
17 changed files with 487 additions and 557 deletions

View File

@ -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>

View File

@ -1,19 +1,17 @@
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; } Config Config { get; }
SearchDictionary Dict { get; } SearchDictionary Dict { get; }
Unbleeper Unbleeper { get; } Unbleeper Unbleeper { get; }
@ -25,72 +23,75 @@ namespace AntiAntiSwearingBot
Unbleeper = new Unbleeper(dict, cfg.Unbleeper); Unbleeper = new Unbleeper(dict, cfg.Unbleeper);
} }
TelegramBotClient Client { get; set; } TelegramBotClient TelegramBot { get; set; }
ChatCommandRouter Router { get; set; } ChatCommandRouter Router { get; set; }
public User Me { get; private set; } public User Me { get; private set; }
public async Task Init() public async Task Init()
{ {
var httpProxy = new WebProxy($"{Config.Proxy.Url}:{Config.Proxy.Port}") if (string.IsNullOrWhiteSpace(Config.ApiKey))
{ return;
Credentials = new NetworkCredential(Config.Proxy.Login, Config.Proxy.Password)
}; TelegramBot = new TelegramBotClient(Config.ApiKey);
Me = await TelegramBot.GetMeAsync();
Client = new TelegramBotClient(Config.ApiKey, httpProxy);
Me = await Client.GetMeAsync();
Router = new ChatCommandRouter(Me.Username); Router = new ChatCommandRouter(Me.Username);
Router.Add(new LearnCommand(Dict), "learn"); Router.Add(new LearnCommand(Dict), "learn");
Router.Add(new UnlearnCommand(Dict), "unlearn"); Router.Add(new UnlearnCommand(Dict), "unlearn");
Client.OnMessage += BotOnMessageReceived; var receiverOptions = new ReceiverOptions { AllowedUpdates = new[] { UpdateType.Message } };
Client.StartReceiving(); TelegramBot.StartReceiving(
HandleUpdateAsync,
HandleErrorAsync,
receiverOptions);
} }
public async Task Stop() Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
{ {
Dispose(); var ErrorMessage = exception switch
{
ApiRequestException apiRequestException => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
_ => exception.ToString()
};
Console.WriteLine(ErrorMessage);
return Task.CompletedTask;
} }
#region service async Task HandleUpdateAsync(ITelegramBotClient sender, Update update, CancellationToken cancellationToken)
void BotOnMessageReceived(object sender, MessageEventArgs args)
{ {
var msg = args.Message; if (update.Type != UpdateType.Message || update?.Message?.Type != MessageType.Text)
if (msg == null || msg.Type != MessageType.Text)
return; return;
var msg = update.Message!;
try
{
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);
}
} }
#endregion }
catch (Exception e)
#region IDisposable
public void Dispose()
{ {
Client.StopReceiving(); Console.WriteLine(e);
} }
#endregion
} }
} }

View File

@ -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>

View File

@ -1,17 +1,15 @@
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
{
string Execute(CommandString cmd, MessageEventArgs messageEventArgs);
}
public class ChatCommandRouter public interface IChatCommand
{ {
string Execute(CommandString cmd, Update messageEventArgs);
}
public class ChatCommandRouter
{
string Username { get; } string Username { get; }
Dictionary<string, IChatCommand> Commands { get; } Dictionary<string, IChatCommand> Commands { get; }
@ -21,12 +19,12 @@ namespace AntiAntiSwearingBot
Commands = new Dictionary<string, IChatCommand>(); Commands = new Dictionary<string, IChatCommand>();
} }
public string Execute(object sender, MessageEventArgs args) public string Execute(object sender, Update args)
{ {
var text = args.Message.Text; var text = args.Message.Text;
if (CommandString.TryParse(text, out var cmd)) if (CommandString.TryParse(text, out var cmd))
{ {
if (cmd.UserName != null && cmd.UserName != Username) if (cmd.Username != null && cmd.Username != Username)
return null; return null;
if (Commands.ContainsKey(cmd.Command)) if (Commands.ContainsKey(cmd.Command))
return Commands[cmd.Command].Execute(cmd, args); return Commands[cmd.Command].Execute(cmd, args);
@ -43,5 +41,4 @@ namespace AntiAntiSwearingBot
Commands[cmd] = c; Commands[cmd] = c;
} }
} }
}
} }

View File

@ -1,21 +1,18 @@
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; Command = command;
Username = username;
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' };
@ -40,5 +37,4 @@ namespace AntiAntiSwearingBot.Commands
result = new CommandString(cmd, username, parameters); result = new CommandString(cmd, username, parameters);
return true; return true;
} }
}
} }

View File

@ -1,11 +1,9 @@
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; } SearchDictionary Dict { get; }
public LearnCommand(SearchDictionary dict) public LearnCommand(SearchDictionary dict)
@ -13,7 +11,7 @@ namespace AntiAntiSwearingBot.Commands
Dict = dict; Dict = dict;
} }
public string Execute(CommandString cmd, MessageEventArgs args) public string Execute(CommandString cmd, Update args)
{ {
var word = cmd.Parameters.FirstOrDefault(); var word = cmd.Parameters.FirstOrDefault();
if (string.IsNullOrWhiteSpace(word)) if (string.IsNullOrWhiteSpace(word))
@ -25,5 +23,4 @@ namespace AntiAntiSwearingBot.Commands
bool newWord = Dict.Learn(word); bool newWord = Dict.Learn(word);
return newWord ? $"Принято слово \"{word}\"" : $"Поднял рейтинг слову \"{word}\""; return newWord ? $"Принято слово \"{word}\"" : $"Поднял рейтинг слову \"{word}\"";
} }
}
} }

View File

@ -1,11 +1,9 @@
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; } SearchDictionary Dict { get; }
public UnlearnCommand(SearchDictionary dict) public UnlearnCommand(SearchDictionary dict)
@ -13,7 +11,7 @@ namespace AntiAntiSwearingBot.Commands
Dict = dict; Dict = dict;
} }
public string Execute(CommandString cmd, MessageEventArgs args) public string Execute(CommandString cmd, Update args)
{ {
var word = cmd.Parameters.FirstOrDefault(); var word = cmd.Parameters.FirstOrDefault();
if (string.IsNullOrWhiteSpace(word)) if (string.IsNullOrWhiteSpace(word))
@ -26,5 +24,4 @@ namespace AntiAntiSwearingBot.Commands
else else
return $"Не нашел слово \"{word}\""; return $"Не нашел слово \"{word}\"";
} }
}
} }

View File

@ -1,32 +1,29 @@
namespace AntiAntiSwearingBot namespace AntiAntiSwearingBot;
public class Config : ConfigBase
{ {
public class Config : ConfigBase
{
public string ApiKey { get; private set; } public string ApiKey { get; private set; }
public ProxySettings Proxy { get; private set; } public ProxySettings Proxy { get; private set; }
public SearchDictionarySettings SearchDictionary { get; private set; } public SearchDictionarySettings SearchDictionary { get; private set; }
public UnbleeperSettings Unbleeper { get; private set; } public UnbleeperSettings Unbleeper { get; private set; }
} }
public struct UnbleeperSettings public struct UnbleeperSettings
{ {
public string BleepedSwearsRegex { get; private set; } public string BleepedSwearsRegex { get; private set; }
public int MinAmbiguousWordLength { get; private set; } public int MinAmbiguousWordLength { get; private set; }
public int MinWordLength { get; private set; } public int MinWordLength { get; private set; }
} }
public struct SearchDictionarySettings public struct SearchDictionarySettings
{ {
public string DictionaryPath { get; private set; } public string DictionaryPath { get; private set; }
} }
public struct ProxySettings public struct ProxySettings
{ {
public string Url { get; private set; } public string Url { get; private set; }
public int Port { get; private set; } public int Port { get; private set; }
public string Login { get; private set; } public string Login { get; private set; }
public string Password { get; private set; } public string Password { get; private set; }
}
} }

View File

@ -1,13 +1,13 @@
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 result = new T();
@ -34,10 +34,10 @@ namespace AntiAntiSwearingBot
return result; return result;
} }
} }
public class PrivateSetterContractResolver : DefaultContractResolver public class PrivateSetterContractResolver : DefaultContractResolver
{ {
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{ {
var jProperty = base.CreateProperty(member, memberSerialization); var jProperty = base.CreateProperty(member, memberSerialization);
@ -48,10 +48,10 @@ namespace AntiAntiSwearingBot
return jProperty; return jProperty;
} }
} }
public class PrivateSetterCamelCasePropertyNamesContractResolver : CamelCasePropertyNamesContractResolver public class PrivateSetterCamelCasePropertyNamesContractResolver : CamelCasePropertyNamesContractResolver
{ {
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{ {
var jProperty = base.CreateProperty(member, memberSerialization); var jProperty = base.CreateProperty(member, memberSerialization);
@ -62,15 +62,14 @@ namespace AntiAntiSwearingBot
return jProperty; return jProperty;
} }
} }
internal static class MemberInfoExtensions internal static class MemberInfoExtensions
{ {
internal static bool IsPropertyWithSetter(this MemberInfo member) internal static bool IsPropertyWithSetter(this MemberInfo member)
{ {
var property = member as PropertyInfo; var property = member as PropertyInfo;
return property?.GetSetMethod(true) != null; return property?.GetSetMethod(true) != null;
} }
}
} }

View File

@ -1,10 +1,6 @@
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) if (from < 0 || from > list.Count)
@ -19,5 +15,4 @@ namespace AntiAntiSwearingBot
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);
} }
}
} }

View File

@ -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;
}
}
}

View 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;

View File

@ -0,0 +1,5 @@
global using System;
global using System.Text;
global using System.Linq;
global using System.Collections.Generic;

View File

@ -1,13 +1,8 @@
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); } 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) public static int HammingDistance(string a, string b)
@ -71,6 +66,4 @@ namespace AntiAntiSwearingBot
public static bool HasWordChars(string arg) => arg.Any(char.IsLetter); public static bool HasWordChars(string arg) => arg.Any(char.IsLetter);
}
} }

View File

@ -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
{
public enum ExitCode : int
{
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 Console.CancelKeyPress += (sender, eArgs) => // ctrl-c
{ {
eArgs.Cancel = true; eArgs.Cancel = true;
quitEvent.Set(); 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();

View File

@ -1,12 +1,8 @@
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; var s = cfg.SearchDictionary;
@ -82,5 +78,4 @@ namespace AntiAntiSwearingBot
List<string> words; List<string> words;
#endregion #endregion
}
} }

View File

@ -1,13 +1,9 @@
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; } SearchDictionary Dict { get; }
UnbleeperSettings Cfg { get; } UnbleeperSettings Cfg { get; }
@ -58,5 +54,4 @@ namespace AntiAntiSwearingBot
else else
return null; return null;
} }
}
} }