You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中从Telegram Bot获取用户发送文件的File ID?

在C#中获取Telegram Bot的文件ID并下载文件

首先确保你已经安装官方的Telegram Bot SDK:

dotnet add package Telegram.Bot

获取文件ID

Telegram Bot收到的不同类型文件(照片、文档、音频等),其File ID存储在不同的消息属性中,需要先判断消息类型再提取:

  • 照片:message.Photo是分辨率从低到高的数组,取最后一个元素的FileId(对应最高分辨率)
  • 文档:message.Document.FileId
  • 音频:message.Audio.FileId
  • 视频/语音/贴纸等类型,对应message.Video.FileId、message.Voice.FileId等属性

完整代码示例

using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;

var botClient = new TelegramBotClient("你的BotToken");

// 启动消息接收
botClient.StartReceiving(
    updateHandler: HandleUpdateAsync,
    pollingErrorHandler: HandlePollingErrorAsync
);

Console.WriteLine("Bot运行中,按任意键退出...");
Console.ReadKey();

async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
    // 跳过非消息类更新
    if (update.Message is not { } message) return;

    string? fileId = null;
    string? fileName = null;

    // 识别文件类型并提取File ID和文件名
    if (message.Photo is not null && message.Photo.Any())
    {
        var highestResPhoto = message.Photo.Last();
        fileId = highestResPhoto.FileId;
        fileName = $"photo_{highestResPhoto.FileUniqueId}.jpg";
    }
    else if (message.Document is not null)
    {
        fileId = message.Document.FileId;
        fileName = message.Document.FileName ?? $"doc_{message.Document.FileUniqueId}";
    }
    else if (message.Audio is not null)
    {
        fileId = message.Audio.FileId;
        fileName = message.Audio.FileName ?? $"audio_{message.Audio.FileUniqueId}.mp3";
    }
    // 可自行扩展视频、语音等其他文件类型的判断逻辑

    if (string.IsNullOrEmpty(fileId))
    {
        await botClient.SendTextMessageAsync(
            chatId: message.Chat.Id,
            text: "请发送照片、文档或音频类文件",
            cancellationToken: cancellationToken
        );
        return;
    }

    // 下载文件到本地
    try
    {
        // 获取文件元数据
        var fileInfo = await botClient.GetFileAsync(fileId, cancellationToken);
        // 拼接本地保存路径
        var savePath = Path.Combine(Directory.GetCurrentDirectory(), "telegram_downloads", fileName);
        
        // 创建保存目录(不存在则自动创建)
        Directory.CreateDirectory(Path.GetDirectoryName(savePath)!);

        // 下载并写入本地文件
        await using var fileStream = new FileStream(savePath, FileMode.Create);
        await botClient.DownloadFileAsync(fileInfo.FilePath!, fileStream, cancellationToken);

        await botClient.SendTextMessageAsync(
            chatId: message.Chat.Id,
            text: $"文件已保存到:{savePath}",
            cancellationToken: cancellationToken
        );
    }
    catch (Exception ex)
    {
        await botClient.SendTextMessageAsync(
            chatId: message.Chat.Id,
            text: $"下载失败:{ex.Message}",
            cancellationToken: cancellationToken
        );
    }
}

// 轮询错误处理
Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
{
    Console.WriteLine($"Bot运行错误:{exception.Message}");
    return Task.CompletedTask;
}

关键说明

  1. 必须根据消息类型匹配对应的属性提取File ID,不同媒体类型的存储位置不统一
  2. GetFileAsync仅获取文件的下载路径元数据,不会直接下载文件
  3. DownloadFileAsync需要传入获取到的fileInfo.FilePath和本地文件流完成下载

内容的提问来源于stack exchange,提问作者علیرضا حریری

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 19:09:57