[reputation] Move reputation to separate module.

This commit is contained in:
West14
2022-02-14 00:18:53 +02:00
parent 6f02031e65
commit a4a44198c5
20 changed files with 595 additions and 228 deletions
+2 -1
View File
@@ -3,13 +3,14 @@
using System.Threading.Tasks;
using BotFramework.Attributes;
using BotFramework.Enums;
using Kruzya.TelegramBot.Core;
using Kruzya.TelegramBot.Core.Data;
using Telegram.Bot;
using Telegram.Bot.Types;
namespace West.TelegramBot.ChatManagement.Handler
{
public class Ban : ManagementHandler
public class Ban : CommonHandler
{
public Ban(CoreContext db) : base(db) {}
@@ -1,71 +0,0 @@
#nullable enable
using System;
using System.Threading.Tasks;
using BotFramework;
using Kruzya.TelegramBot.Core.Data;
using Kruzya.TelegramBot.Core.Extensions;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace West.TelegramBot.ChatManagement.Handler
{
public abstract class ManagementHandler : BotEventHandler
{
protected readonly CoreContext Db;
protected Message? Message => RawUpdate.Message;
protected User? RepliedUser => Message?.ReplyToMessage?.From;
protected ManagementHandler(CoreContext db)
{
Db = db;
}
protected async Task<Message> Reply(string text)
{
return await Bot.SendTextMessageAsync(Chat.Id, text,
replyToMessageId: Message?.MessageId, parseMode: ParseMode.Html);
}
protected async Task<bool> CanPunish()
{
return RepliedUser != null && await Bot.CanPunishMember(Chat, From, RepliedUser);
}
#region Bans
protected async Task BanMember(User user, DateTime? banEnd = null, bool sendMessage = true)
{
await BanMember(user.Id, banEnd);
if (sendMessage)
{
await Bot.SendTextMessageAsync(
Chat.Id,
$"{From.ToHtml()} <code>заблокировал</code> {user.ToHtml()} <code>на 7 дней</code>",
disableNotification: true, parseMode: ParseMode.Html);
}
}
protected async Task BanMember(long userId, DateTime? banEnd = null)
{
await Bot.RestrictChatMemberAsync(
Chat.Id,
userId,
new ChatPermissions
{
CanSendMessages = false
},
banEnd ?? DateTime.Now.AddDays(7)
);
}
#endregion
protected async Task<BotUserValue> GetWarnOption(User user)
{
return await Db.UserValues.FindOrCreateOption(Chat.Id, user.Id, "warnCount");
}
}
}
@@ -1,183 +0,0 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using BotFramework.Attributes;
using BotFramework.Enums;
using BotFramework.Utils;
using Kruzya.TelegramBot.Core.Data;
using Kruzya.TelegramBot.Core.Extensions;
using Kruzya.TelegramBot.Core.Service;
using Microsoft.Extensions.Logging;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace West.TelegramBot.ChatManagement.Handler
{
public class Reputation : ManagementHandler
{
private readonly UserService _userService;
private readonly ILogger _logger;
private static readonly List<string> RepUpChars = new()
{
"+",
"👍",
"👍🏼",
"👍🏽",
"👍🏾",
"👍🏿",
"👍🏻"
};
private static readonly List<string> RepDownChars = new()
{
"-",
"👎",
"👎🏼",
"👎🏽",
"👎🏾",
"👎🏿",
"👎🏻"
};
public Reputation(CoreContext db, UserService userService, ILogger<Reputation> logger) : base(db)
{
_userService = userService;
_logger = logger;
}
[Command("whois", CommandParseMode.Both)]
public async Task HandleWhois()
{
var user = RepliedUser ?? From;
var message = $"{user.ToHtml()}\n";
if (user.IsBot)
{
message += "<code>Бот</code>";
}
else
{
message += $"<code>{await GetChatMemberStatusString(user)}</code>\n";
message += $"<code>Репутация: {await GetUserReputation(user)}\n";
message += $"Предупреждения: {(await GetWarnOption(user)).GetValue<int>()}</code>";
}
await Reply(message);
}
[Message(InChat.Public, MessageFlag.HasText | MessageFlag.HasSticker)]
public async Task HandleReputation()
{
var text = Message?.Text;
if (string.IsNullOrEmpty(text))
{
text = Message?.Sticker?.Emoji;
}
if (text == null)
{
return;
}
var receiver = RepliedUser;
var canChangeRep = receiver is { IsBot: false } && !From.IsBot && receiver.Id != From.Id;
if (canChangeRep && (RepUpChars.Contains(text) || RepDownChars.Contains(text)))
{
var receiverRepOption = await GetReputationOption(receiver!);
var receiverRepCount = receiverRepOption.GetValue<double>();
var senderRepCount = (await GetReputationOption(From)).GetValue<double>();
if (senderRepCount < 0)
{
await Reply(new HtmlString()
.Code("Ты не можешь голосовать с отрицательной репутацией.")
.ToString()
);
return;
}
var diff = Math.Round(senderRepCount == 0 ? 1 : Math.Sqrt(senderRepCount), 2);
_logger.LogDebug("Calculated diff: {Diff}", diff);
string action;
if (RepUpChars.Contains(text))
{
receiverRepCount += diff;
action = "увеличил";
}
else
{
receiverRepCount -= diff;
action = "уменьшил";
}
_logger.LogDebug("Saving receiver rep with value: {Value}", receiverRepCount);
receiverRepOption.SetValue(receiverRepCount);
Db.AddOrUpdate(receiverRepOption);
_logger.LogDebug("Updated value: {Value}", receiverRepOption.GetValue<double>());
await Reply($"{From.ToHtml()}<code>({await GetUserReputation(From)}) " +
$"{action} репутацию </code>{receiver.ToHtml()}<code>({Math.Round(receiverRepCount, 2)})</code>");
}
}
[ParametrizedCommand(InChat.Public, "setrep", CommandParseMode.Both)]
public async Task HandleSetRep(double reputation)
{
if (!_userService.IsUserSuper(From))
{
_logger.LogInformation("{User} attempted to call /setrep in {Chat}", From, Chat.Title);
return;
}
if (RepliedUser == null || RepliedUser.IsBot)
{
return;
}
reputation = Math.Round(reputation, 2);
var opt = await GetReputationOption(RepliedUser);
opt.SetValue(reputation);
Db.AddOrUpdate(opt);
await Reply(
new HtmlString()
.Code("Пользователю ")
.UserMention(RepliedUser)
.Code($" установлена репутация: {reputation}")
.ToString()
);
}
private async Task<double> GetUserReputation(User user)
{
return Math.Round((await GetReputationOption(user)).GetValue<double>(), 2);
}
private async Task<BotUserValue> GetReputationOption(User user)
{
return await Db.UserValues.FindOrCreateOption(Chat.Id, user.Id, "reputation");
}
private async Task<string> GetChatMemberStatusString(User user)
{
var customStatus = _userService.GetUserCustomStatus(user.Id);
if (customStatus != null)
{
return customStatus;
}
var chatMember = await Bot.GetChatMemberAsync(Chat.Id, user.Id);
return chatMember.Status switch
{
ChatMemberStatus.Creator => "Владелец",
ChatMemberStatus.Restricted => "Заблокированный",
ChatMemberStatus.Administrator => "Администратор",
_ => "Пользователь"
};
}
}
}
+33 -33
View File
@@ -1,47 +1,47 @@
using System.Threading.Tasks;
using BotFramework.Attributes;
using BotFramework.Enums;
using Kruzya.TelegramBot.Core;
using Kruzya.TelegramBot.Core.Data;
using Kruzya.TelegramBot.Core.Extensions;
using Telegram.Bot;
using Telegram.Bot.Exceptions;
namespace West.TelegramBot.ChatManagement.Handler
namespace West.TelegramBot.ChatManagement.Handler;
class Rules : CommonHandler
{
class Rules : ManagementHandler
[Command(InChat.Public, "setrules", CommandParseMode.Both)]
public async Task HandleSetRules()
{
[Command(InChat.Public, "setrules", CommandParseMode.Both)]
public async Task HandleSetRules()
{
var replyToMessage = Message?.ReplyToMessage;
var replyToMessage = Message?.ReplyToMessage;
if (replyToMessage == null || !await Bot.IsUserAdminAsync(Chat, From)) return;
if (replyToMessage == null || !await Bot.IsUserAdminAsync(Chat, From)) return;
var opt = await Db.UserValues.FindOrCreateOption(Chat.Id, "rulesMsgId");
opt.SetValue(replyToMessage.MessageId);
Db.AddOrUpdate(opt);
}
[Command(InChat.Public, "rules", CommandParseMode.Both)]
public async Task HandleRules()
{
var opt = await Db.UserValues.FindOption(Chat.Id, "rulesMsgId");
if (opt == null)
{
return;
}
try
{
await Bot.CopyMessageAsync(Chat.Id, Chat.Id, opt.GetValue<int>());
}
catch (ApiRequestException)
{
Db.UserValues.Remove(opt);
throw;
}
}
public Rules(CoreContext db) : base(db) {}
var opt = await Db.UserValues.FindOrCreateOption(Chat.Id, "rulesMsgId");
opt.SetValue(replyToMessage.MessageId);
Db.AddOrUpdate(opt);
}
[Command(InChat.Public, "rules", CommandParseMode.Both)]
public async Task HandleRules()
{
var opt = await Db.UserValues.FindOption(Chat.Id, "rulesMsgId");
if (opt == null)
{
return;
}
try
{
await Bot.CopyMessageAsync(Chat.Id, Chat.Id, opt.GetValue<int>());
}
catch (ApiRequestException)
{
Db.UserValues.Remove(opt);
throw;
}
}
public Rules(CoreContext db) : base(db) {}
}
+2 -1
View File
@@ -4,6 +4,7 @@ using System;
using System.Threading.Tasks;
using BotFramework.Attributes;
using BotFramework.Enums;
using Kruzya.TelegramBot.Core;
using Kruzya.TelegramBot.Core.Data;
using Kruzya.TelegramBot.Core.Extensions;
using Telegram.Bot;
@@ -11,7 +12,7 @@ using Telegram.Bot.Types.Enums;
namespace West.TelegramBot.ChatManagement.Handler
{
public class Warn : ManagementHandler
public class Warn : CommonHandler
{
public Warn(CoreContext db) : base(db) {}