mirror of
https://github.com/Bubuni-Team/telegram-bot.git
synced 2026-07-31 00:29:24 +03:00
[cm] warn decomposition
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
#nullable enable
|
||||
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using BotFramework.Abstractions;
|
||||
using Kruzya.TelegramBot.Core.Data;
|
||||
using Kruzya.TelegramBot.Core.Extensions;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
|
||||
namespace West.TelegramBot.ChatManagement.Service;
|
||||
|
||||
public class WarnService
|
||||
{
|
||||
public delegate void WarnHandler(ITelegramBotClient bot, Chat chat, User from, User to, int count, bool isBanned = false);
|
||||
public delegate void UnWarnHandler(ITelegramBotClient bot, Chat chat, User from, User to, int count);
|
||||
|
||||
public static event WarnHandler? WarnEvent;
|
||||
public static event UnWarnHandler? UnWarnEvent;
|
||||
|
||||
private readonly CoreContext _db;
|
||||
private readonly ITelegramBotClient _bot;
|
||||
|
||||
public WarnService(CoreContext db, IBotInstance bot)
|
||||
{
|
||||
_db = db;
|
||||
_bot = bot.BotClient;
|
||||
}
|
||||
|
||||
public async Task WarnChatUserAsync(Chat chat, User from, User to)
|
||||
{
|
||||
var warnOption = await GetWarnOption(chat, to);
|
||||
var warnCount = warnOption.GetValue<int>() + 1;
|
||||
|
||||
if (warnCount >= 3)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _bot.RestrictChatMemberAsync(
|
||||
chat.Id,
|
||||
to.Id,
|
||||
new ChatPermissions
|
||||
{
|
||||
CanSendMessages = false
|
||||
},
|
||||
DateTime.Now.AddDays(7)
|
||||
);
|
||||
warnCount = 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
await _bot.SendTextMessageAsync(chat.Id, "У меня нет прав на блокировку пользователя.");
|
||||
}
|
||||
}
|
||||
|
||||
warnOption.SetValue(warnCount);
|
||||
_db.AddOrUpdate(warnOption);
|
||||
WarnEvent?.Invoke(_bot, chat, from, to, warnCount == 0 ? 3 : warnCount, warnCount == 0);
|
||||
}
|
||||
|
||||
public async Task UnWarnChatUserAsync(Chat chat, User from, User user)
|
||||
{
|
||||
var warnOption = await GetWarnOption(chat, user);
|
||||
var warnCount = warnOption.GetValue<int>();
|
||||
if (warnCount == 0) return;
|
||||
|
||||
warnCount = Math.Max(warnCount - 1, 0);
|
||||
warnOption.SetValue(warnCount);
|
||||
_db.AddOrUpdate(warnOption);
|
||||
|
||||
UnWarnEvent?.Invoke(_bot, chat, from, user, warnCount);
|
||||
}
|
||||
|
||||
protected async Task<BotUserValue> GetWarnOption(Chat chat, User user)
|
||||
{
|
||||
return await _db.UserValues.FindOrCreateOption(chat.Id, user.Id, "warnCount");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user