Telegram Bot download image file

∥☆過路亽.° 提交于 2020-05-13 14:45:31

问题


I'm trying to download file (image ) using my bot, but when I download the image ( which is done successfully ) after using getFile, the image I received is very small 1.7 kb while it's bigger than that on my mobile phone


回答1:


  1. the getFile Method present a JSON object (the 1.7 KB response) that contain the data for accessing your image file.

  2. also note that telegram create an array of image for any image. the first element of this array contain the small thumbnail of your original image and the latest element of the array contain your original image.




回答2:


This is an old post. But since there is not a good documentation on how you should download file in telegram bot, for anyone wondering, that's how you should do it(One way of it):

DownloadFile(message.Photo[message.Photo.Length - 1].FileId, @"c:\photo.jpg");

in which:

    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);
        }
    }

The message.Photo[message.Photo.Length - 1] is the last element in message.Photo array, which contains the highest quality image data. Obviously you can use DownloadFile to download other kind of files(for example message.Document) as well.




回答3:


I use telegram.bot v14.10.0 but I can't find file.FileStream so I find alternative way to get image from telegram. my way is to use telegram api directly for this case.

                    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



回答4:


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();


来源:https://stackoverflow.com/questions/33082572/telegram-bot-download-image-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!