Update dependencies

This commit is contained in:
jetsparrow 2023-11-19 19:13:22 +03:00
parent dc879e2984
commit ed7346c16d
10 changed files with 72 additions and 56 deletions

View File

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

View File

@ -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)
{
Log.Error(exception, "Exception while handling API message");
return Task.CompletedTask;
}
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
{
var message = args.Message;
if (message == null || message.Type != MessageType.Text)
return;
if (!CommandString.TryParse(args.Message.Text, out var cmd))
if (!CommandString.TryParse(message.Text, out var cmd))
return;
if (cmd.UserName != null && cmd.UserName != Commands.Me.Username)
return;
RequestContext ctx = new RequestContext(Client, args, cmd);
_ = Chain.Handle(ctx);
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)

View File

@ -1,18 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.4">
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.14">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.2.0" />
<PackageReference Include="Telegram.Bot" Version="14.12.0" />
<PackageReference Include="NLog" Version="4.6.5" />
<PackageReference Include="NLog.Config" Version="4.6.5" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="7.0.0" />
<PackageReference Include="Telegram.Bot" Version="19.0.0" />
<PackageReference Include="NLog" Version="5.2.5" />
<ProjectReference Include="..\perfusion\Perfusion\Perfusion.csproj" />
</ItemGroup>
<ItemGroup>

View File

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

View File

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

View File

@ -12,7 +12,7 @@ namespace JetKarmaBot.Models
AwardsTo = new HashSet<Award>();
}
public int UserId { get; set; }
public long UserId { get; set; }
public string Username { get; set; }
public DateTime CooldownDate { get; set; }
[InverseProperty("From")]

View File

@ -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<KarmaContext>()
.UseMySql(cfg.ConnectionString + (cfg.ConnectionString.EndsWith(";") ? "" : ";") + "TreatTinyAsBoolean=false");
.UseMySql(connStr, serverVersion);
c.AddInfo<Logger>(new LogInfo());
if (cfg.SqlDebug)
{

View File

@ -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<Type, object> Features { get; } = new Dictionary<Type, object>();
public RequestContext(ITelegramBotClient client, MessageEventArgs args, CommandString cmd)
public RequestContext(ITelegramBotClient client, Update args, CommandString cmd)
{
Client = client;
EventArgs = args;

View File

@ -26,7 +26,7 @@ namespace JetKarmaBot.Services.Handling
public async Task Handle(RequestContext ctx, Func<RequestContext, Task> 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<int, TimeoutStats> TimeoutCache = new Dictionary<int, TimeoutStats>();
private async Task ApplyCost(string name, bool succeded, int uid, KarmaContext db, Feature feature)
public Dictionary<long, TimeoutStats> 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<RequestContext, Task> next)
{
int uid = ctx.EventArgs.Message.From.Id;
var uid = ctx.EventArgs.Message.From.Id;
KarmaContext db = ctx.GetFeature<KarmaContext>();
await PopulateStats(uid, db);
DateTime debtLimit = DateTime.Now.AddSeconds(cfg.Timeout.DebtLimitSeconds);

@ -1 +1 @@
Subproject commit 5913a7e44f7e9ac63a5bfd04c837a9968cf1fe88
Subproject commit e4c448c0505ae081d23e46151b6628ec5a9f3a42