diff --git a/Core/Startup.cs b/Core/Startup.cs index c66ebe8..e53c10a 100644 --- a/Core/Startup.cs +++ b/Core/Startup.cs @@ -1,4 +1,5 @@ using BotFramework; +using Kruzya.TelegramBot.Core.Cache; using Kruzya.TelegramBot.Core.Data; using Kruzya.TelegramBot.Core.Extensions; using Microsoft.AspNetCore.Builder; @@ -7,6 +8,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Telegram.Bot.Types; namespace Kruzya.TelegramBot.Core { @@ -36,6 +38,9 @@ namespace Kruzya.TelegramBot.Core services.AddDbContext(ctx => ctx.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString))); + // Cache for users. + services.AddSingleton, MemoryCache>(); + // Trigger module handlers. _core.Modules.ConfigureServices(services); } diff --git a/modules/UserGroupTag/Handler.cs b/modules/UserGroupTag/Handler.cs index 0b6b246..dc1cec9 100644 --- a/modules/UserGroupTag/Handler.cs +++ b/modules/UserGroupTag/Handler.cs @@ -8,9 +8,11 @@ using BotFramework.Attributes; using BotFramework.Enums; using BotFramework.Utils; using Castle.Core.Internal; +using Kruzya.TelegramBot.Core.Cache; using Kruzya.TelegramBot.Core.Data; using Kruzya.TelegramBot.Core.Extensions; using Telegram.Bot; +using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; namespace UserGroupTag @@ -18,16 +20,17 @@ namespace UserGroupTag public class Handler : BotEventHandler { private readonly CoreContext _db; - - public Handler(CoreContext db) + private readonly ICacheStorage _userCache; + + public Handler(CoreContext db, ICacheStorage userCache) { _db = db; + _userCache = userCache; } [ParametrizedCommand(InChat.Public, "add_group", CommandParseMode.Both)] public async Task HandleAddGroup(string groupName) { - Console.WriteLine("add_group"); // var groupName = group.Text; var repliedMessage = RawUpdate.Message!.ReplyToMessage; @@ -56,6 +59,7 @@ namespace UserGroupTag userGroupOption.SetValue(tagDictionary); _db.MarkAsModified(userGroupOption); + _userCache.SetValue(repliedMessage.From.Id, repliedMessage.From, Int32.MaxValue); await Bot.SendTextMessageAsync(chatId, $"{from.ToHtml()} добавлен в группу {groupName}", ParseMode.Html); } @@ -79,13 +83,25 @@ namespace UserGroupTag var msg = new HtmlString() .Text("Пользователь ") .UserMention(From) - .Text(" охуел и хочет доебаться к: "); + .Text($" призывает группу пользователей {groupName}: "); foreach (var userId in userList) { - msg.User(userId, userId.ToString()).Text(", "); + msg.UserMention(await GetUser(userId, Chat)).Text(", "); } await Bot.SendTextMessageAsync(Chat.Id, msg.ToString().TrimEnd(',', ' '), ParseMode.Html); } + + protected async Task GetUser(long userId, Chat chat) + { + User user; + if (!_userCache.TryGetValue(userId, out user)) + { + user = (await Bot.GetChatMemberAsync(Chat, userId)).User; + _userCache.SetValue(userId, user, Int32.MaxValue); + } + + return user; + } } } \ No newline at end of file