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,18 +1,16 @@
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
{
public class AntiAntiSwearingBot : IDisposable
namespace AntiAntiSwearingBot;
public class AntiAntiSwearingBot
{
Config Config { get; }
SearchDictionary Dict { 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();
}
#endregion
Console.WriteLine(e);
}
}
}

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,13 +1,11 @@
using System;
using System.Collections.Generic;
using Telegram.Bot.Args;
using Telegram.Bot.Types;
using AntiAntiSwearingBot.Commands;
namespace AntiAntiSwearingBot
{
namespace AntiAntiSwearingBot;
public interface IChatCommand
{
string Execute(CommandString cmd, MessageEventArgs messageEventArgs);
string Execute(CommandString cmd, Update messageEventArgs);
}
public class ChatCommandRouter
@ -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);
@ -44,4 +42,3 @@ namespace AntiAntiSwearingBot
}
}
}
}

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 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' };
@ -41,4 +38,3 @@ namespace AntiAntiSwearingBot.Commands
return true;
}
}
}

View File

@ -1,9 +1,7 @@
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
{
SearchDictionary Dict { get; }
@ -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,4 +24,3 @@ namespace AntiAntiSwearingBot.Commands
return newWord ? $"Принято слово \"{word}\"" : $"Поднял рейтинг слову \"{word}\"";
}
}
}

View File

@ -1,9 +1,7 @@
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
{
SearchDictionary Dict { get; }
@ -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))
@ -27,4 +25,3 @@ namespace AntiAntiSwearingBot.Commands
return $"Не нашел слово \"{word}\"";
}
}
}

View File

@ -1,5 +1,5 @@
namespace AntiAntiSwearingBot
{
namespace AntiAntiSwearingBot;
public class Config : ConfigBase
{
public string ApiKey { get; private set; }
@ -27,6 +27,3 @@
public string Login { get; private set; }
public string Password { get; private set; }
}
}

View File

@ -1,11 +1,11 @@
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 static T Load<T>(params string[] paths) where T : ConfigBase, new()
@ -73,4 +73,3 @@ namespace AntiAntiSwearingBot
return property?.GetSetMethod(true) != null;
}
}
}

View File

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
namespace AntiAntiSwearingBot
{
namespace AntiAntiSwearingBot;
public static class IListExtensions
{
public static void Move<T>(this IList<T> list, int from, int to)
@ -20,4 +16,3 @@ namespace AntiAntiSwearingBot
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,11 +1,6 @@
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
{
static int min(int a, int b, int c) { return Math.Min(Math.Min(a, b), c); }
@ -71,6 +66,4 @@ namespace AntiAntiSwearingBot
public static bool HasWordChars(string arg) => arg.Any(char.IsLetter);
}
}

View File

@ -1,35 +1,17 @@
using System;
using System.Threading;
namespace AntiAntiSwearingBot
{
public static class Program
{
public enum ExitCode : int
{
Ok = 0,
ErrorNotStarted = 0x80,
ErrorRunning = 0x81,
ErrorException = 0x82,
ErrorInvalidCommandLine = 0x100
};
using System.Threading;
using AntiAntiSwearingBot;
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);
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.");
Environment.ExitCode = (int)ExitCode.ErrorRunning;
ManualResetEvent quitEvent = new ManualResetEvent(false);
try
@ -45,15 +27,5 @@ namespace AntiAntiSwearingBot
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;
}
}
}
}

View File

@ -1,10 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.IO;
namespace AntiAntiSwearingBot
{
namespace AntiAntiSwearingBot;
public class SearchDictionary
{
public SearchDictionary(Config cfg)
@ -83,4 +79,3 @@ namespace AntiAntiSwearingBot
#endregion
}
}

View File

@ -1,11 +1,7 @@
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
{
SearchDictionary Dict { get; }
@ -59,4 +55,3 @@ namespace AntiAntiSwearingBot
return null;
}
}
}