#nullable enable using System; using System.Collections.Generic; using System.Threading.Tasks; using BotFramework; 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 { public class Handler : BotEventHandler { private readonly 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) { // var groupName = group.Text; var repliedMessage = RawUpdate.Message!.ReplyToMessage; if (repliedMessage == null || repliedMessage.From!.IsBot || !(await Bot.CanPunishMember(Chat, From)) || string.IsNullOrEmpty(groupName)) { return; } var from = repliedMessage.From; var fromId = from.Id; var chatId = Chat!.Id; var userGroupOption = await _db.UserValues.FindOrCreateOption(Chat.Id, "userGroups"); var tagDictionary = userGroupOption.GetValue(new Dictionary>()); var memberList = tagDictionary.GetValueOrDefault(groupName, new List()); if (memberList.Contains(fromId)) { await Bot.SendTextMessageAsync(chatId, $"{from.ToHtml()} уже находится в группе {groupName}", parseMode: ParseMode.Html); return; } memberList.Add(repliedMessage.From.Id); tagDictionary[groupName] = memberList; userGroupOption.SetValue(tagDictionary); _db.AddOrUpdate(userGroupOption); _userCache.SetValue(repliedMessage.From.Id, repliedMessage.From, Int32.MaxValue); await Bot.SendTextMessageAsync(chatId, $"{from.ToHtml()} добавлен в группу {groupName}", parseMode: ParseMode.Html); } [ParametrizedCommand(InChat.Public, "tag_group", CommandParseMode.Both)] public async Task HandleTagGroup(string groupName) { if (string.IsNullOrEmpty(groupName)) { return; } var userGroupOption = await _db.UserValues.FindOption(Chat.Id, "userGroups"); var userList = userGroupOption?.GetValue>>()?[groupName]; if (userList == null || userList.Count == 0) { return; } var msg = new HtmlString() .Text("Пользователь ") .UserMention(From) .Text($" призывает группу пользователей {groupName}: "); foreach (var userId in userList) { msg.UserMention(await GetUser(userId, Chat)).Text(", "); } await Bot.SendTextMessageAsync(Chat.Id, msg.ToString().TrimEnd(',', ' '), parseMode: ParseMode.Html); } protected async Task GetUser(long userId, Chat chat) { User user; if (!_userCache.TryGetValue(userId, out user)) { user = (await Bot.GetChatMemberAsync(Chat.Id, userId)).User; _userCache.SetValue(userId, user, Int32.MaxValue); } return user; } } }