Assorted improvements.

- Add UserService.
- Add "setrep" command.
- Rename confusing methods and variables in AbstractAnimationHandler.
- Change Bayan cooldown to Zero.
- Add crappy "cooldowns" command.
This commit is contained in:
West14
2022-01-04 17:45:06 +02:00
parent 8717ef9db9
commit 740527d827
7 changed files with 144 additions and 12 deletions
+31
View File
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Telegram.Bot.Types;
namespace Kruzya.TelegramBot.Core.Service
{
public class UserService
{
private List<long> _superUsers;
public UserService(IConfiguration configuration)
{
_superUsers = configuration.GetSection("SuperUsers")
.GetChildren()
.Select(q => Convert.ToInt64(q.Value))
.ToList();
}
public bool IsUserSuper(User user)
{
return IsUserSuper(user.Id);
}
public bool IsUserSuper(long userId)
{
return _superUsers.Contains(userId);
}
}
}
+3
View File
@@ -2,6 +2,7 @@ using BotFramework;
using Kruzya.TelegramBot.Core.Cache; using Kruzya.TelegramBot.Core.Cache;
using Kruzya.TelegramBot.Core.Data; using Kruzya.TelegramBot.Core.Data;
using Kruzya.TelegramBot.Core.Extensions; using Kruzya.TelegramBot.Core.Extensions;
using Kruzya.TelegramBot.Core.Service;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
@@ -41,6 +42,8 @@ namespace Kruzya.TelegramBot.Core
// Cache for users. // Cache for users.
services.AddSingleton<ICacheStorage<long, User>, MemoryCache<long, User>>(); services.AddSingleton<ICacheStorage<long, User>, MemoryCache<long, User>>();
services.AddSingleton<UserService>();
// Trigger module handlers. // Trigger module handlers.
_core.Modules.ConfigureServices(services); _core.Modules.ConfigureServices(services);
} }
+41 -2
View File
@@ -4,14 +4,22 @@ using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using BotFramework.Attributes; using BotFramework.Attributes;
using BotFramework.Enums; using BotFramework.Enums;
using BotFramework.Utils;
using Kruzya.TelegramBot.Core.Data; using Kruzya.TelegramBot.Core.Data;
using Kruzya.TelegramBot.Core.Extensions; using Kruzya.TelegramBot.Core.Extensions;
using Kruzya.TelegramBot.Core.Service;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Telegram.Bot;
using Telegram.Bot.Types; using Telegram.Bot.Types;
namespace West.TelegramBot.ChatManagement.Handler namespace West.TelegramBot.ChatManagement.Handler
{ {
public class Reputation : ManagementHandler public class Reputation : ManagementHandler
{ {
private readonly UserService _userService;
private readonly ILogger _logger;
private static readonly List<string> RepUpChars = new() private static readonly List<string> RepUpChars = new()
{ {
"+", "+",
@@ -22,7 +30,6 @@ namespace West.TelegramBot.ChatManagement.Handler
"👍🏿", "👍🏿",
"👍🏻" "👍🏻"
}; };
private static readonly List<string> RepDownChars = new() private static readonly List<string> RepDownChars = new()
{ {
"-", "-",
@@ -34,7 +41,11 @@ namespace West.TelegramBot.ChatManagement.Handler
"👎🏻" "👎🏻"
}; };
public Reputation(CoreContext db) : base(db) { } public Reputation(CoreContext db, UserService userService, ILogger<Reputation> logger) : base(db)
{
_userService = userService;
_logger = logger;
}
[Command("whois", CommandParseMode.Both)] [Command("whois", CommandParseMode.Both)]
public async Task HandleWhois() public async Task HandleWhois()
@@ -97,6 +108,34 @@ namespace West.TelegramBot.ChatManagement.Handler
} }
} }
[ParametrizedCommand(InChat.Public, "setrep", CommandParseMode.Both)]
public async Task HandleSetRep(int reputation)
{
if (!_userService.IsUserSuper(From))
{
_logger.LogDebug("{User} attempted to call /setrep in {Chat}", From, Chat.Title);
return;
}
if (RepliedUser == null || RepliedUser.IsBot)
{
return;
}
var opt = await GetReputationOption(RepliedUser);
opt.SetValue(reputation);
Db.MarkAsModified(opt);
await Reply(
new HtmlString()
.Code("Пользователю ")
.UserMention(RepliedUser)
.Code($" установлена репутация: {reputation}")
.ToString()
);
}
private async Task<int> GetUserReputation(User user) private async Task<int> GetUserReputation(User user)
{ {
return (await GetReputationOption(user)).GetValue<int>(); return (await GetReputationOption(user)).GetValue<int>();
@@ -10,10 +10,6 @@
<ProjectReference Include="..\..\Core\Core.csproj" /> <ProjectReference Include="..\..\Core\Core.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="Handler" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent"> <Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Delete Files="$(OutDir)\TelegramBot.dll" /> <Delete Files="$(OutDir)\TelegramBot.dll" />
<Delete Files="$(OutDir)\TelegramBot.ChatManagement.dll" /> <Delete Files="$(OutDir)\TelegramBot.ChatManagement.dll" />
+60
View File
@@ -0,0 +1,60 @@
#nullable enable
using System;
using System.Threading.Tasks;
using BotFramework;
using BotFramework.Attributes;
using BotFramework.Enums;
using BotFramework.Utils;
using Kruzya.TelegramBot.Core.Data;
using Kruzya.TelegramBot.Core.Extensions;
using Kruzya.TelegramBot.Core.Service;
using Microsoft.Extensions.Logging;
using Telegram.Bot;
using Telegram.Bot.Types.Enums;
namespace West.Entertainment.Handler
{
public class Common : BotEventHandler
{
private readonly UserService _userService;
private readonly ILogger _logger;
private readonly CoreContext _db;
public Common(CoreContext db, ILogger<Common> logger, UserService userService)
{
_db = db;
_logger = logger;
_userService = userService;
}
[Command(InChat.Public, "cooldowns", CommandParseMode.Both)]
public async Task HandleCooldowns()
{
if (!_userService.IsUserSuper(From))
{
_logger.LogDebug("{User} attempted to call /cooldowns in \"{Chat}\"", From, Chat.Title);
return;
}
var cds = new[] { "python", "javascript" };
var msg = new HtmlString().Bold("Кулдауны:").Br();
foreach (var cd in cds)
{
var opt = await _db.UserValues.FindOption(Chat.Id, $"{cd}NextUse");
var val = opt.GetValue<DateTime>();
if (val == default)
{
continue;
}
msg.Text($"{cd}: ")
.Code((val - DateTime.Now).Duration().ToString())
.Br();
}
await Bot.SendTextMessageAsync(Chat.Id, msg.ToString(), ParseMode.Html);
}
}
}
@@ -19,7 +19,7 @@ namespace West.Entertainment.Handler.Fun
private readonly ILogger _logger; private readonly ILogger _logger;
private static TimeSpan Cooldown => TimeSpan.FromMinutes(new Random().Next(10, 1337)); protected virtual TimeSpan Cooldown => TimeSpan.FromMinutes(new Random().Next(10, 1337));
protected Message? Message => RawUpdate.Message; protected Message? Message => RawUpdate.Message;
@@ -57,14 +57,14 @@ namespace West.Entertainment.Handler.Fun
if (!AnimationMatch.IsMatch(text.ToLower()) || text.StartsWith("/set") || !CanHandle()) return false; if (!AnimationMatch.IsMatch(text.ToLower()) || text.StartsWith("/set") || !CanHandle()) return false;
var animationFileId = (await GetAnimationFileOption()).GetValue(string.Empty); var animationFileId = (await GetAnimationFileOption()).GetValue(string.Empty);
var lastUseOption = await GetLastUseOption(); var nextUseOption = await GetNextUseOption();
_logger.LogDebug("Animation: {Text}, ToLower: {ToLowerText}", _logger.LogDebug("Animation: {Text}, ToLower: {ToLowerText}",
Message!.Text, Message!.Text!.ToLower()); Message!.Text, Message!.Text!.ToLower());
if (animationFileId.IsNullOrEmpty()) return false; if (animationFileId.IsNullOrEmpty()) return false;
var nextUseDt = lastUseOption.GetValue<DateTime>(); var nextUseDt = nextUseOption.GetValue<DateTime>();
if (nextUseDt > DateTime.Now) if (nextUseDt > DateTime.Now)
{ {
_logger.LogInformation("{Name} is on cooldown for chat \"{ChatTitle}\". Will be available at {Time}", _logger.LogInformation("{Name} is on cooldown for chat \"{ChatTitle}\". Will be available at {Time}",
@@ -76,8 +76,8 @@ namespace West.Entertainment.Handler.Fun
await Bot.SendAnimationAsync(Chat.Id, animationFileId, await Bot.SendAnimationAsync(Chat.Id, animationFileId,
replyToMessageId: GetMessageIdToReply() ?? Message?.MessageId); replyToMessageId: GetMessageIdToReply() ?? Message?.MessageId);
lastUseOption.SetValue(DateTime.Now + Cooldown); nextUseOption.SetValue(DateTime.Now + Cooldown);
_db.MarkAsModified(lastUseOption); _db.MarkAsModified(nextUseOption);
return true; return true;
} }
@@ -87,7 +87,7 @@ namespace West.Entertainment.Handler.Fun
return await _db.UserValues.FindOrCreateOption(Chat.Id, $"{GetAnimationName()}File"); return await _db.UserValues.FindOrCreateOption(Chat.Id, $"{GetAnimationName()}File");
} }
private async Task<BotUserValue> GetLastUseOption() private async Task<BotUserValue> GetNextUseOption()
{ {
return await _db.UserValues.FindOrCreateOption(Chat.Id, $"{GetAnimationName()}NextUse"); return await _db.UserValues.FindOrCreateOption(Chat.Id, $"{GetAnimationName()}NextUse");
} }
@@ -1,5 +1,6 @@
#nullable enable #nullable enable
using System;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using BotFramework.Attributes; using BotFramework.Attributes;
@@ -12,6 +13,8 @@ namespace West.Entertainment.Handler.Fun
{ {
public class Bayan : AbstractAnimationReply public class Bayan : AbstractAnimationReply
{ {
protected override TimeSpan Cooldown => TimeSpan.Zero;
public Bayan(CoreContext db, ILogger<Bayan> logger) : base(db, logger) { } public Bayan(CoreContext db, ILogger<Bayan> logger) : base(db, logger) { }
protected override Regex AnimationMatch protected override Regex AnimationMatch