using System.Collections.Concurrent; using BotFramework; using BotFramework.Attributes; using BotFramework.Enums; using Kruzya.TelegramBot.Core.Extensions; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; namespace West.TelegramBot.CodeWatcher; public class Handler : BotEventHandler { private readonly ConcurrentBag _requests; public Handler(ConcurrentBag requests) { _requests = requests; } [Update(InChat.Public, UpdateFlag.Message | UpdateFlag.EditedMessage)] public async Task HandleMessage() { var message = RawUpdate.Message ?? RawUpdate.EditedMessage; if (message?.Entities == null) { return; } if (!await Bot.CanDeleteMessagesAsync(Chat)) { return; } foreach (var entity in message.Entities) { if (entity.Type is MessageEntityType.Code or MessageEntityType.Pre) { var entityLines = message.Text! .Substring(entity.Offset, entity.Length) .SplitToLines() .ToList(); if (entityLines.Count < 2) { continue; } if (entityLines.Count >= 20 || entityLines.Any(line => line.Length > 160)) { await DeleteAndNotifyAsync(message); return; } } } } public async Task DeleteAndNotifyAsync(Message message) { await Bot.DeleteMessageAsync(Chat.Id, message.MessageId); var notifyMsg = await Bot.SendTextMessageAsync(Chat.Id, (message.From?.ToHtml() ?? "") + ", не стоит публиковать столь большой код прямо в чат. " + "Вместо этого загрузите его на https://pastebin.com и отправьте в виде ссылки.", ParseMode.Html); // TODO: maybe write a wrapper-service around collection to avoid direct interactions with the collection, West, 07.07.2022, 16:53 _requests.Add(new DeleteRequest { ChatId = notifyMsg.Chat.Id, MessageId = notifyMsg.MessageId, DeleteAt = DateTime.Now.AddSeconds(30) }); } }