59 lines
2.1 KiB
C#
59 lines
2.1 KiB
C#
using BotPages.Core;
|
|
using Telegram.Bot;
|
|
|
|
namespace BotPages.Telegram
|
|
{
|
|
/// <summary>
|
|
/// FileService для Telegram: загрузка по FileId.
|
|
/// </summary>
|
|
public sealed class TelegramFileService : IFileService
|
|
{
|
|
private readonly ITelegramBotClient _bot;
|
|
|
|
/// <summary>
|
|
/// Создаёт файловый сервис для Telegram.
|
|
/// </summary>
|
|
public TelegramFileService(ITelegramBotClient bot) => _bot = bot;
|
|
|
|
/// <summary>
|
|
/// Загружает файл по идентификатору Telegram FileId.
|
|
/// </summary>
|
|
public async Task<FileDescriptor> DownloadAsync(string fileId, CancellationToken ct)
|
|
{
|
|
var file = await _bot.GetFile(fileId, ct);
|
|
var ms = new MemoryStream();
|
|
await _bot.DownloadFile(file.FilePath!, ms, ct);
|
|
ms.Position = 0;
|
|
var name = System.IO.Path.GetFileName(file.FilePath!);
|
|
return new FileDescriptor(file.FileId, name, "application/octet-stream", ms);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Загружает несколько файлов по их идентификаторам.
|
|
/// </summary>
|
|
public async Task<IReadOnlyList<FileDescriptor>> DownloadManyAsync(IEnumerable<string> fileIds, CancellationToken ct)
|
|
{
|
|
var res = new List<FileDescriptor>();
|
|
foreach (var id in fileIds)
|
|
res.Add(await DownloadAsync(id, ct));
|
|
return res;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Отправляет один файл в чат.
|
|
/// </summary>
|
|
public async Task SendAsync(IChatClient client, long chatId, FileDescriptor file, CancellationToken ct)
|
|
{
|
|
await client.SendFilesAsync(chatId, new[] { file }, ct);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Отправляет несколько файлов в чат.
|
|
/// </summary>
|
|
public Task SendManyAsync(IChatClient client, long chatId, IEnumerable<FileDescriptor> files, CancellationToken ct)
|
|
{
|
|
return client.SendFilesAsync(chatId, files, ct);
|
|
}
|
|
}
|
|
|
|
} |