Refactor Telegram bot configuration and deep link handling
- Removed the `BotUsername` property from `TelegramOptions` and updated the `.env.example` to reflect this change, as the bot's username is now dynamically retrieved via the Bot API. - Introduced `ITelegramBotInfo` to cache the bot's username, improving the handling of deep links in `TelegramEndpoints`. - Updated API documentation to clarify that the deep link is now dependent on the bot's token and its availability through the Bot API, enhancing clarity for developers.
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Infrastructure.Telegram;
|
||||
using Telegram.Bot;
|
||||
|
||||
namespace PnvPanel.Api.Telegram;
|
||||
|
||||
/// <summary>Кэширует username бота на время жизни процесса (getMe не меняется, повторный запрос не нужен).</summary>
|
||||
internal sealed class TelegramBotInfo(ITelegramBotClient botClient, IOptions<TelegramOptions> options) : ITelegramBotInfo
|
||||
{
|
||||
private readonly SemaphoreSlim _lock = new(1, 1);
|
||||
private string? _cachedUsername;
|
||||
|
||||
public async Task<string?> GetUsernameAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_cachedUsername is not null)
|
||||
return _cachedUsername;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(options.Value.BotToken))
|
||||
return null;
|
||||
|
||||
await _lock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
if (_cachedUsername is not null)
|
||||
return _cachedUsername;
|
||||
|
||||
var me = await botClient.GetMe(cancellationToken);
|
||||
_cachedUsername = me.Username;
|
||||
return _cachedUsername;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Telegram недоступен/бот не отвечает — деплинк просто не покажем вызывающей стороне.
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lock.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user