我正在尝试使用我的机器人下载文件(图像),但是当我在使用 getFile 后下载图像(成功完成)时,我收到的图像非常小 1.7 kb 而它比我的手机大
5 回答
这是一个旧帖子。但是由于没有关于如何在电报机器人中下载文件的好文档,对于任何想知道的人来说,这就是你应该这样做(一种方式):
DownloadFile(message.Photo[message.Photo.Length - 1].FileId, @"c:\photo.jpg");
其中:
private static async void DownloadFile(string fileId, string path)
{
try
{
var file = await Bot.GetFileAsync(fileId);
using (var saveImageStream = new FileStream(path, FileMode.Create))
{
await file.FileStream.CopyToAsync(saveImageStream);
}
}
catch (Exception ex)
{
Console.WriteLine("Error downloading: " + ex.Message);
}
}
message.Photo[message.Photo.Length - 1]
是数组中的最后一个元素,message.Photo
其中包含最高质量的图像数据。显然,您也可以使用DownloadFile
下载其他类型的文件(例如message.Document
)。
该
getFile
方法提供一个 JSON 对象(1.7 KB 响应),其中包含用于访问您的图像文件的数据。另请注意,电报为任何图像创建图像数组。该数组的第一个元素包含原始图像的小缩略图,数组的最新元素包含原始图像。
var file = await Bot.GetFileAsync(message.Document.FileId);
FileStream fs=new FileStream("Your Destination Path And File Name",FileMode.Create);
await Bot.DownloadFileAsync(file.FilePath, fs);
fs.Close();
fs.Dispose();
我使用 telegram.bot v14.10.0 但我找不到 file.FileStream 所以我找到了从电报获取图像的替代方法。我的方法是在这种情况下直接使用电报 api。
var test = _myBot.GetFileAsync(e.Message.Photo[e.Message.Photo.Count() - 1].FileId);
var download_url = @"https://api.telegram.org/file/bot<token>/" + test.Result.FilePath;
using (WebClient client = new WebClient())
{
client.DownloadFile(new Uri(download_url), @"c:\temp\NewCompanyPicure.png");
}
//then do what you want with it
您需要await botClient.DownloadFileAsync(file.FilePath, saveImageStream);
改用await file.FileStream.CopyToAsync(saveImageStream);
您的代码应如下所示:
static async void DownloadFile(ITelegramBotClient botClient, string fileId, string path)
{
try
{
var file = await botClient.GetFileAsync(fileId);
using (var saveImageStream = new FileStream(path, FileMode.Create))
{
await botClient.DownloadFileAsync(file.FilePath, saveImageStream);
}
}
catch (Exception ex)
{
Console.WriteLine("Error downloading: " + ex.Message);
}
}
来自版本 14.2.0 的 Telegram.Bot 在示例中提交:https ://github.com/TelegramBots/Telegram.Bot.Examples/commit/ff5a44133ad3b0d3c1e4a8b82edce959d0ee0d0e