mirror of
https://github.com/Bubuni-Team/telegram-bot.git
synced 2026-07-31 00:29:24 +03:00
94 lines
2.8 KiB
C#
94 lines
2.8 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 && message?.CaptionEntities == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var text = message.Caption ?? message.Text;
|
|
if (text == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
|
|
if (!await Bot.CanDeleteMessagesAsync(Chat))
|
|
{
|
|
return;
|
|
}
|
|
|
|
var entities = new List<MessageEntity>();
|
|
|
|
if (message.Entities != null)
|
|
{
|
|
entities.AddRange(message.Entities);
|
|
}
|
|
|
|
if (message.CaptionEntities != null)
|
|
{
|
|
entities.AddRange(message.CaptionEntities);
|
|
}
|
|
|
|
foreach (var entity in entities)
|
|
{
|
|
if (entity.Type is MessageEntityType.Code or MessageEntityType.Pre)
|
|
{
|
|
var entityLines = 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)
|
|
});
|
|
}
|
|
} |