Files
Andriy a4f05bacab [code-watcher] handle message edit & message delayed delete service
Message delayed deleter service deals with issue when you need to delete some message with delay without blocking the execution. This is replacement for dumb Task.Delay call. Use of it could be used before as exploit, to stop responding for a long time.
2022-07-07 17:15:40 +03:00

75 lines
2.3 KiB
C#

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<DeleteRequest> _requests;
public Handler(ConcurrentBag<DeleteRequest> 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)
});
}
}