[code-watcher] init module.

This commit is contained in:
West14
2022-04-20 00:38:47 +03:00
parent 166363cd50
commit b58fe8b6e9
7 changed files with 128 additions and 1 deletions
+9
View File
@@ -0,0 +1,9 @@
using Kruzya.TelegramBot.Core;
namespace West.TelegramBot.CodeWatcher
{
public class CodeWatcher : Module
{
public CodeWatcher(Core core) : base(core) {}
}
}
+15
View File
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AssemblyName>TelegramBot.CodeWatcher</AssemblyName>
<RootNamespace>West.TelegramBot.CodeWatcher</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Core\Core.csproj" />
</ItemGroup>
</Project>
+67
View File
@@ -0,0 +1,67 @@
using BotFramework;
using BotFramework.Attributes;
using BotFramework.Enums;
using BotFramework.Utils;
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 static readonly string ResponseMessage = new HtmlString()
.Text(", не стоит публиковать столь большой код прямо в чат. Вместо этого загрузите его на ")
.Url("https://pastebin.com", "https://pastebin.com")
.Text(" и отправьте в виде ссылки.")
.ToString();
[Message(InChat.Public, MessageFlag.HasText)]
public async Task HandleMessage()
{
var message = RawUpdate.Message!;
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 >= 10)
{
await DeleteAndNotifyAsync(message);
return;
}
if (entityLines.Any(line => line.Length > 80))
{
await DeleteAndNotifyAsync(message);
return;
}
}
}
}
public async Task DeleteAndNotifyAsync(Message message)
{
await Bot.DeleteMessageAsync(Chat.Id, message.MessageId);
await Bot.SendTextMessageAsync(Chat.Id,
(message.From?.ToHtml() ?? "") + ResponseMessage,
ParseMode.Html);
}
}
+17
View File
@@ -0,0 +1,17 @@
namespace West.TelegramBot.CodeWatcher;
public static class StringExtension
{
// https://stackoverflow.com/a/23408020
public static IEnumerable<string> SplitToLines(this string input)
{
using (var reader = new StringReader(input))
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
}