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">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>

View File

@ -1,19 +1,17 @@
using System;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using AntiAntiSwearingBot.Commands;
using Telegram.Bot;
using Telegram.Bot.Args;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Extensions.Polling;
using Telegram.Bot.Types;
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; }
@ -25,72 +23,75 @@ namespace AntiAntiSwearingBot
Unbleeper = new Unbleeper(dict, cfg.Unbleeper);
}
TelegramBotClient Client { get; set; }
TelegramBotClient TelegramBot { get; set; }
ChatCommandRouter Router { get; set; }
public User Me { get; private set; }
public async Task Init()
{
var httpProxy = new WebProxy($"{Config.Proxy.Url}:{Config.Proxy.Port}")
{
Credentials = new NetworkCredential(Config.Proxy.Login, Config.Proxy.Password)
};
if (string.IsNullOrWhiteSpace(Config.ApiKey))
return;
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.Add(new LearnCommand(Dict), "learn");
Router.Add(new UnlearnCommand(Dict), "unlearn");
Client.OnMessage += BotOnMessageReceived;
Client.StartReceiving();
var receiverOptions = new ReceiverOptions { AllowedUpdates = new[] { UpdateType.Message } };
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
void BotOnMessageReceived(object sender, MessageEventArgs args)
async Task HandleUpdateAsync(ITelegramBotClient sender, Update update, CancellationToken cancellationToken)
{
var msg = args.Message;
if (msg == null || msg.Type != MessageType.Text)
if (update.Type != UpdateType.Message || update?.Message?.Type != MessageType.Text)
return;
var msg = update.Message!;
try
{
string commandResponse = null;
try { commandResponse = Router.Execute(sender, args); }
try { commandResponse = Router.Execute(sender, update); }
catch { }
if (commandResponse != null)
{
Client.SendTextMessageAsync(
args.Message.Chat.Id,
await TelegramBot.SendTextMessageAsync(
msg.Chat.Id,
commandResponse,
replyToMessageId: args.Message.MessageId);
replyToMessageId: msg.MessageId);
}
else
{
var unbleepResponse = Unbleeper.UnbleepSwears(msg.Text);
if (unbleepResponse != null)
Client.SendTextMessageAsync(
args.Message.Chat.Id,
await TelegramBot.SendTextMessageAsync(
msg.Chat.Id,
unbleepResponse,
replyToMessageId: args.Message.MessageId);
}
replyToMessageId: msg.MessageId);
}
#endregion
#region IDisposable
public void Dispose()
}
catch (Exception e)
{
Client.StopReceiving();
Console.WriteLine(e);
}
#endregion
}
}

View File

@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
@ -10,8 +10,8 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
<PackageReference Include="Telegram.Bot" Version="14.10.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Telegram.Bot.Extensions.Polling" Version="2.0.0-alpha.1" />
</ItemGroup>
<ItemGroup>

View File

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

View File

@ -1,21 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
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)
{
Command = command;
Username = username;
Parameters = parameters;
}
public string Command { get; }
public string UserName { get; }
public string Username { get; }
public string[] Parameters { get; }
static readonly char[] WS_CHARS = new[] { ' ', '\r', '\n', '\n' };
@ -40,5 +37,4 @@ namespace AntiAntiSwearingBot.Commands
result = new CommandString(cmd, username, parameters);
return true;
}
}
}

View File

@ -1,11 +1,9 @@
using System.Linq;
using System.Text.RegularExpressions;
using Telegram.Bot.Args;
using System.Text.RegularExpressions;
using Telegram.Bot.Types;
namespace AntiAntiSwearingBot.Commands
namespace AntiAntiSwearingBot.Commands;
public class LearnCommand : IChatCommand
{
public class LearnCommand : IChatCommand
{
SearchDictionary Dict { get; }
public LearnCommand(SearchDictionary dict)
@ -13,7 +11,7 @@ namespace AntiAntiSwearingBot.Commands
Dict = dict;
}
public string Execute(CommandString cmd, MessageEventArgs args)
public string Execute(CommandString cmd, Update args)
{
var word = cmd.Parameters.FirstOrDefault();
if (string.IsNullOrWhiteSpace(word))
@ -25,5 +23,4 @@ namespace AntiAntiSwearingBot.Commands
bool newWord = Dict.Learn(word);
return newWord ? $"Принято слово \"{word}\"" : $"Поднял рейтинг слову \"{word}\"";
}
}
}

View File

@ -1,11 +1,9 @@
using System.Linq;
using System.Text.RegularExpressions;
using Telegram.Bot.Args;
using System.Text.RegularExpressions;
using Telegram.Bot.Types;
namespace AntiAntiSwearingBot.Commands
namespace AntiAntiSwearingBot.Commands;
public class UnlearnCommand : IChatCommand
{
public class UnlearnCommand : IChatCommand
{
SearchDictionary Dict { get; }
public UnlearnCommand(SearchDictionary dict)
@ -13,7 +11,7 @@ namespace AntiAntiSwearingBot.Commands
Dict = dict;
}
public string Execute(CommandString cmd, MessageEventArgs args)
public string Execute(CommandString cmd, Update args)
{
var word = cmd.Parameters.FirstOrDefault();
if (string.IsNullOrWhiteSpace(word))
@ -26,5 +24,4 @@ namespace AntiAntiSwearingBot.Commands
else
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 ProxySettings Proxy { get; private set; }
public SearchDictionarySettings SearchDictionary { get; private set; }
public UnbleeperSettings Unbleeper { get; private set; }
}
}
public struct UnbleeperSettings
{
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 struct SearchDictionarySettings
{
public string DictionaryPath { get; private set; }
}
}
public struct ProxySettings
{
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; }
}
}

View File

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

View File

@ -1,10 +1,6 @@
using System;
using System.Collections.Generic;
namespace AntiAntiSwearingBot
namespace AntiAntiSwearingBot;
public static class IListExtensions
{
public static class IListExtensions
{
public static void Move<T>(this IList<T> list, int from, int to)
{
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
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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
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)
@ -71,6 +66,4 @@ namespace AntiAntiSwearingBot
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
{
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();

View File

@ -1,12 +1,8 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.IO;
namespace AntiAntiSwearingBot
namespace AntiAntiSwearingBot;
public class SearchDictionary
{
public class SearchDictionary
{
public SearchDictionary(Config cfg)
{
var s = cfg.SearchDictionary;
@ -82,5 +78,4 @@ namespace AntiAntiSwearingBot
List<string> words;
#endregion
}
}

View File

@ -1,13 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Text.RegularExpressions;
namespace AntiAntiSwearingBot
namespace AntiAntiSwearingBot;
public class Unbleeper
{
public class Unbleeper
{
SearchDictionary Dict { get; }
UnbleeperSettings Cfg { get; }
@ -58,5 +54,4 @@ namespace AntiAntiSwearingBot
else
return null;
}
}
}