From ed7346c16d090ca153e75a662e122d4110f2c3a1 Mon Sep 17 00:00:00 2001 From: jetsparrow Date: Sun, 19 Nov 2023 19:13:22 +0300 Subject: [PATCH] Update dependencies --- JetKarmaBot/Commands/AwardCommand.cs | 4 +- JetKarmaBot/JetKarmaBot.cs | 65 +++++++++++-------- JetKarmaBot/JetKarmaBot.csproj | 15 ++--- JetKarmaBot/Models/Award.cs | 4 +- JetKarmaBot/Models/KarmaContext.cs | 14 ++-- JetKarmaBot/Models/User.cs | 2 +- JetKarmaBot/Program.cs | 5 +- .../Services/Handling/RequestContext.cs | 5 +- .../Services/Handling/TimeoutManager.cs | 12 ++-- perfusion | 2 +- 10 files changed, 72 insertions(+), 56 deletions(-) diff --git a/JetKarmaBot/Commands/AwardCommand.cs b/JetKarmaBot/Commands/AwardCommand.cs index 86de14b..2798f2e 100644 --- a/JetKarmaBot/Commands/AwardCommand.cs +++ b/JetKarmaBot/Commands/AwardCommand.cs @@ -32,7 +32,7 @@ namespace JetKarmaBot.Commands } string awardTypeText = null; - int recipientId = default(int); + long recipientId = default; foreach (string arg in ctx.Command.Parameters) { if (arg.StartsWith('@')) @@ -61,7 +61,7 @@ namespace JetKarmaBot.Commands } } - if (ctx.EventArgs.Message.ReplyToMessage != null && recipientId == default(int)) + if (ctx.EventArgs.Message.ReplyToMessage != null && recipientId == default) { recipientId = ctx.EventArgs.Message.ReplyToMessage.From.Id; } diff --git a/JetKarmaBot/JetKarmaBot.cs b/JetKarmaBot/JetKarmaBot.cs index dd1f69a..b658baf 100644 --- a/JetKarmaBot/JetKarmaBot.cs +++ b/JetKarmaBot/JetKarmaBot.cs @@ -2,14 +2,15 @@ using JetKarmaBot.Commands; using JetKarmaBot.Models; using JetKarmaBot.Services; using JetKarmaBot.Services.Handling; +using NLog; using Perfusion; using System; -using System.Net; using System.Threading; using System.Threading.Tasks; using Telegram.Bot; -using Telegram.Bot.Args; +using Telegram.Bot.Polling; +using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; namespace JetKarmaBot @@ -21,6 +22,8 @@ namespace JetKarmaBot [Inject] KarmaContextFactory Db { get; set; } [Inject] TimeoutManager Timeout { get; set; } [Inject] Localization Locale { get; set; } + [Inject] Logger Log { get; set; } + TelegramBotClient Client { get; set; } ChatCommandRouter Commands; @@ -33,17 +36,8 @@ namespace JetKarmaBot { using (KarmaContext db = Db.GetContext()) await db.Database.EnsureCreatedAsync(); - if (Config.Proxy?.Url == null) - Client = new TelegramBotClient(Config.ApiKey); - else - { - 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); - } + + Client = new TelegramBotClient(Config.ApiKey); Container.AddInstance(Client); timeoutWaitTaskToken = new CancellationTokenSource(); @@ -52,14 +46,17 @@ namespace JetKarmaBot await InitCommands(Container); InitChain(Container); - Client.OnMessage += BotOnMessageReceived; - Client.StartReceiving(); + var receiverOptions = new ReceiverOptions { AllowedUpdates = new[] { UpdateType.Message } }; + Client.StartReceiving( + HandleUpdateAsync, + HandleErrorAsync, + receiverOptions); } public async Task Stop() { if (stopped) return; - Client?.StopReceiving(); + Client?.CloseAsync(); timeoutWaitTaskToken?.Cancel(); try { @@ -74,18 +71,34 @@ namespace JetKarmaBot #region service - void BotOnMessageReceived(object sender, MessageEventArgs args) + Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken) { - var message = args.Message; - if (message == null || message.Type != MessageType.Text) - return; - if (!CommandString.TryParse(args.Message.Text, out var cmd)) - return; - if (cmd.UserName != null && cmd.UserName != Commands.Me.Username) - return; + Log.Error(exception, "Exception while handling API message"); + return Task.CompletedTask; + } - RequestContext ctx = new RequestContext(Client, args, cmd); - _ = Chain.Handle(ctx); + async Task HandleUpdateAsync(ITelegramBotClient sender, Update update, CancellationToken cancellationToken) + { + if (update.Type != UpdateType.Message || update?.Message?.Type != MessageType.Text) + return; + var message = update.Message!; + + try + { + if (message == null || message.Type != MessageType.Text) + return; + if (!CommandString.TryParse(message.Text, out var cmd)) + return; + if (cmd.UserName != null && cmd.UserName != Commands.Me.Username) + return; + + RequestContext ctx = new RequestContext(Client, update, cmd); + await Chain.Handle(ctx); + } + catch (Exception e) + { + Log.Error(e, "Exception while handling message {0}", message); + } } async Task InitCommands(IContainer c) diff --git a/JetKarmaBot/JetKarmaBot.csproj b/JetKarmaBot/JetKarmaBot.csproj index 7128cc2..bbf30eb 100644 --- a/JetKarmaBot/JetKarmaBot.csproj +++ b/JetKarmaBot/JetKarmaBot.csproj @@ -1,18 +1,17 @@ - + Exe - net5.0 + net6.0 - + all runtime; build; native; contentfiles; analyzers - - - - - + + + + diff --git a/JetKarmaBot/Models/Award.cs b/JetKarmaBot/Models/Award.cs index f5e9023..6c7af09 100644 --- a/JetKarmaBot/Models/Award.cs +++ b/JetKarmaBot/Models/Award.cs @@ -8,8 +8,8 @@ namespace JetKarmaBot.Models { public int AwardId { get; set; } public long ChatId { get; set; } - public int FromId { get; set; } - public int ToId { get; set; } + public long FromId { get; set; } + public long ToId { get; set; } public sbyte AwardTypeId { get; set; } public sbyte Amount { get; set; } public DateTime Date { get; set; } diff --git a/JetKarmaBot/Models/KarmaContext.cs b/JetKarmaBot/Models/KarmaContext.cs index 5c47e36..88f4078 100644 --- a/JetKarmaBot/Models/KarmaContext.cs +++ b/JetKarmaBot/Models/KarmaContext.cs @@ -34,20 +34,20 @@ namespace JetKarmaBot.Models entity.ToTable("award"); entity.HasIndex(e => e.AwardId) - .HasName("awardid_UNIQUE") + .HasDatabaseName("awardid_UNIQUE") .IsUnique(); entity.HasIndex(e => e.AwardTypeId) - .HasName("fk_awardtype_idx"); + .HasDatabaseName("fk_awardtype_idx"); entity.HasIndex(e => e.ChatId) - .HasName("fk_chat_idx"); + .HasDatabaseName("fk_chat_idx"); entity.HasIndex(e => e.FromId) - .HasName("fk_from_idx"); + .HasDatabaseName("fk_from_idx"); entity.HasIndex(e => e.ToId) - .HasName("fk_to_idx"); + .HasDatabaseName("fk_to_idx"); entity.Property(e => e.AwardId) .HasColumnName("awardid") @@ -109,11 +109,11 @@ namespace JetKarmaBot.Models entity.ToTable("awardtype"); entity.HasIndex(e => e.AwardTypeId) - .HasName("awardtypeid_UNIQUE") + .HasDatabaseName("awardtypeid_UNIQUE") .IsUnique(); entity.HasIndex(e => e.CommandName) - .HasName("commandname_UNIQUE") + .HasDatabaseName("commandname_UNIQUE") .IsUnique(); entity.Property(e => e.AwardTypeId) diff --git a/JetKarmaBot/Models/User.cs b/JetKarmaBot/Models/User.cs index 4ca90aa..a80c74e 100644 --- a/JetKarmaBot/Models/User.cs +++ b/JetKarmaBot/Models/User.cs @@ -12,7 +12,7 @@ namespace JetKarmaBot.Models AwardsTo = new HashSet(); } - public int UserId { get; set; } + public long UserId { get; set; } public string Username { get; set; } public DateTime CooldownDate { get; set; } [InverseProperty("From")] diff --git a/JetKarmaBot/Program.cs b/JetKarmaBot/Program.cs index 5831310..afb6cde 100644 --- a/JetKarmaBot/Program.cs +++ b/JetKarmaBot/Program.cs @@ -28,8 +28,11 @@ namespace JetKarmaBot var cfg = new Config("karma.cfg.json"); c.AddInstance(cfg); + var connStr = cfg.ConnectionString + (cfg.ConnectionString.EndsWith(";") ? "" : ";") + "TreatTinyAsBoolean=false"; + var serverVersion = ServerVersion.AutoDetect(connStr); + var dbOptions = new DbContextOptionsBuilder() - .UseMySql(cfg.ConnectionString + (cfg.ConnectionString.EndsWith(";") ? "" : ";") + "TreatTinyAsBoolean=false"); + .UseMySql(connStr, serverVersion); c.AddInfo(new LogInfo()); if (cfg.SqlDebug) { diff --git a/JetKarmaBot/Services/Handling/RequestContext.cs b/JetKarmaBot/Services/Handling/RequestContext.cs index b59ce84..0aaea8e 100644 --- a/JetKarmaBot/Services/Handling/RequestContext.cs +++ b/JetKarmaBot/Services/Handling/RequestContext.cs @@ -6,16 +6,17 @@ using JetKarmaBot.Commands; using JetKarmaBot.Models; using Telegram.Bot; using Telegram.Bot.Args; +using Telegram.Bot.Types; namespace JetKarmaBot.Services.Handling { public class RequestContext : IServiceProvider { public ITelegramBotClient Client { get; } - public MessageEventArgs EventArgs { get; } + public Update EventArgs { get; } public CommandString Command { get; } public Dictionary Features { get; } = new Dictionary(); - public RequestContext(ITelegramBotClient client, MessageEventArgs args, CommandString cmd) + public RequestContext(ITelegramBotClient client, Update args, CommandString cmd) { Client = client; EventArgs = args; diff --git a/JetKarmaBot/Services/Handling/TimeoutManager.cs b/JetKarmaBot/Services/Handling/TimeoutManager.cs index 7d75c05..ac7cadf 100644 --- a/JetKarmaBot/Services/Handling/TimeoutManager.cs +++ b/JetKarmaBot/Services/Handling/TimeoutManager.cs @@ -26,7 +26,7 @@ namespace JetKarmaBot.Services.Handling public async Task Handle(RequestContext ctx, Func next) { - int uid = ctx.EventArgs.Message.From.Id; + var uid = ctx.EventArgs.Message.From.Id; if (Timeout.TimeoutCache.TryGetValue(uid, out var stats)) { DateTime debtLimit = DateTime.Now.AddSeconds(Timeout.cfg.Timeout.DebtLimitSeconds); @@ -46,8 +46,8 @@ namespace JetKarmaBot.Services.Handling [Inject] private Config cfg; [Inject] private Localization Locale; [Inject] private Logger log; - public Dictionary TimeoutCache = new Dictionary(); - private async Task ApplyCost(string name, bool succeded, int uid, KarmaContext db, Feature feature) + public Dictionary TimeoutCache = new (); + private async Task ApplyCost(string name, bool succeded, long uid, KarmaContext db, Feature feature) { if (feature.Multiplier == 0) return; @@ -67,7 +67,7 @@ namespace JetKarmaBot.Services.Handling TimeoutCache[uid].TimeoutMessaged = false; } - private async Task PopulateStats(int uid, KarmaContext db) + private async Task PopulateStats(long uid, KarmaContext db) { if (!TimeoutCache.ContainsKey(uid)) { @@ -83,7 +83,7 @@ namespace JetKarmaBot.Services.Handling log.Info("Saving timeout info to database"); using (KarmaContext db = Db.GetContext()) { - foreach (int i in TimeoutCache.Keys) + foreach (var i in TimeoutCache.Keys) { (await db.Users.FindAsync(new object[] { i }, ct)).CooldownDate = TimeoutCache[i].CooldownDate; } @@ -102,7 +102,7 @@ namespace JetKarmaBot.Services.Handling public async Task Handle(RequestContext ctx, Func next) { - int uid = ctx.EventArgs.Message.From.Id; + var uid = ctx.EventArgs.Message.From.Id; KarmaContext db = ctx.GetFeature(); await PopulateStats(uid, db); DateTime debtLimit = DateTime.Now.AddSeconds(cfg.Timeout.DebtLimitSeconds); diff --git a/perfusion b/perfusion index 5913a7e..e4c448c 160000 --- a/perfusion +++ b/perfusion @@ -1 +1 @@ -Subproject commit 5913a7e44f7e9ac63a5bfd04c837a9968cf1fe88 +Subproject commit e4c448c0505ae081d23e46151b6628ec5a9f3a42