mirror of
https://github.com/Bubuni-Team/telegram-bot.git
synced 2026-07-31 00:29:24 +03:00
73 lines
2.2 KiB
C#
73 lines
2.2 KiB
C#
using Kruzya.TelegramBot.Core.Data;
|
|
using Kruzya.TelegramBot.Core.Extensions;
|
|
using Kruzya.TelegramBot.Core.Service;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Telegram.Bot.Types;
|
|
using West.TelegramBot.Reputation.Data;
|
|
|
|
namespace West.TelegramBot.Reputation.Service;
|
|
|
|
public class ReputationService : IReputation
|
|
{
|
|
private readonly ReputationContext _reputationContext;
|
|
|
|
public ReputationService(ReputationContext reputationContext)
|
|
{
|
|
_reputationContext = reputationContext;
|
|
}
|
|
|
|
public async Task<double> GetUserReputationAsync(Chat chat, User user)
|
|
{
|
|
var rep = await FindUserReputation(chat, user);
|
|
|
|
return rep?.Value ?? 0;
|
|
}
|
|
|
|
public async Task<double> SetUserReputationAsync(Chat chat, User user, double value)
|
|
{
|
|
var rep = await FindUserReputation(chat, user) ?? new UserReputation
|
|
{
|
|
ChatId = chat.Id,
|
|
UserId = user.Id
|
|
};
|
|
|
|
rep.Value = Math.Round(value, 2);
|
|
_reputationContext.AddOrUpdate(rep);
|
|
|
|
return rep.Value;
|
|
}
|
|
|
|
public async Task<double> IncrementReputationAsync(Chat chat, User user, double diff)
|
|
{
|
|
return await SetUserReputationAsync(chat, user, await GetUserReputationAsync(chat, user) + diff);
|
|
}
|
|
|
|
public async Task<double> GetReputationDiffAsync(Chat chat, User sender, User receiver)
|
|
{
|
|
var senderRep = await FindUserReputation(chat, sender);
|
|
|
|
if (senderRep == null)
|
|
{
|
|
return 1;
|
|
}
|
|
|
|
var senderValue = senderRep.Value;
|
|
return Math.Round(senderValue == 0 ? 1 : Math.Sqrt(senderValue), 2);
|
|
}
|
|
|
|
public async Task<IEnumerable<IReputationEntity>> GetChatRatingAsync(Chat chat, int limit = 10, int offset = 0)
|
|
{
|
|
return await _reputationContext.UserReputation
|
|
.Where(r => r.ChatId == chat.Id && r.Value > 0D)
|
|
.OrderByDescending(r => r.Value)
|
|
.Skip(offset)
|
|
.Take(limit)
|
|
.ToListAsync();
|
|
}
|
|
|
|
private async Task<UserReputation?> FindUserReputation(Chat chat, User user)
|
|
{
|
|
return await _reputationContext.UserReputation.SingleOrDefaultAsync(
|
|
e => e.ChatId == chat.Id && e.UserId == user.Id);
|
|
}
|
|
} |