mirror of
https://github.com/Bubuni-Team/telegram-bot.git
synced 2026-07-31 00:29:24 +03:00
91 lines
2.7 KiB
C#
91 lines
2.7 KiB
C#
#nullable enable
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using BotFramework.Abstractions;
|
|
using Kruzya.TelegramBot.Core.Cache;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.Logging;
|
|
using Telegram.Bot;
|
|
using Telegram.Bot.Types;
|
|
|
|
namespace Kruzya.TelegramBot.Core.Service
|
|
{
|
|
public class UserService
|
|
{
|
|
private readonly List<long> _superUsers;
|
|
private readonly Dictionary<long, string> _statusMap;
|
|
private readonly ICacheStorage<long, User> _userCache;
|
|
private readonly ITelegramBotClient _bot;
|
|
private readonly ILogger<UserService> _logger;
|
|
|
|
|
|
public UserService(
|
|
IConfiguration configuration,
|
|
IBotInstance bot,
|
|
ICacheStorage<long, User> userCache,
|
|
ILogger<UserService> logger)
|
|
{
|
|
_superUsers = configuration.GetSection("SuperUsers")
|
|
.GetChildren()
|
|
.Select(q => Convert.ToInt64(q.Value))
|
|
.ToList();
|
|
|
|
_statusMap = configuration.GetSection("CustomMemberStatus")
|
|
.GetChildren()
|
|
.ToDictionary(x => Convert.ToInt64(x.Key), x => x.Value);
|
|
|
|
_userCache = userCache;
|
|
_bot = bot.BotClient;
|
|
_logger = logger;
|
|
}
|
|
|
|
public async Task<User> GetUser(long userId, long chatId, bool bypassCache = false)
|
|
{
|
|
if (bypassCache || !_userCache.TryGetValue(userId, out var user))
|
|
{
|
|
if (bypassCache)
|
|
{
|
|
_logger.LogDebug("Bypassing cache for {UserId}.", userId);
|
|
}
|
|
else
|
|
{
|
|
_logger.LogDebug("User {UserId} is not found in cache. Fetching from Telegram API.", userId);
|
|
}
|
|
|
|
user = await GetUserByChat(chatId, userId);
|
|
CacheUser(user);
|
|
}
|
|
|
|
return user;
|
|
}
|
|
|
|
private void CacheUser(User user)
|
|
{
|
|
// TODO: config entry for TTL
|
|
_userCache.SetValue(user.Id, user, Convert.ToInt32(TimeSpan.FromHours(1).TotalSeconds));
|
|
}
|
|
|
|
private async Task<User> GetUserByChat(long chatId, long userId)
|
|
{
|
|
return (await _bot.GetChatMemberAsync(chatId, userId)).User;
|
|
}
|
|
|
|
public bool IsUserSuper(User user)
|
|
{
|
|
return IsUserSuper(user.Id);
|
|
}
|
|
|
|
public bool IsUserSuper(long userId)
|
|
{
|
|
return _superUsers.Contains(userId);
|
|
}
|
|
|
|
public string? GetUserCustomStatus(long userId)
|
|
{
|
|
return _statusMap.ContainsKey(userId) ? _statusMap[userId] : null;
|
|
}
|
|
}
|
|
} |