使用Telegram Bot Api上传文件

时间:2018-06-08 17:47:01

标签: c# vb.net post httpwebrequest telegram-bot

我想将照片(或任何文件)上传到电报,而不使用现有的电报库(像Telegram.Bot TLsharp ),但我不知道 POST 的方法和参数是什么,我在google中找不到任何东西!

我也不想使用 HttpClient System.Net.Http 因为它需要.net framwork 4.5

  static void Main(string[] args)
    {
        var file = System.IO.File.ReadAllBytes(@"D:\Piture\Logo.png");
        UploadMultipart(file, @"D:\Piture\Logo.png", "chat_id 123456789", "https://api.telegram.org//bot123456789:******************Ru7zouEc/sendPhoto");
        Console.ReadKey(true);
    }
    static void UploadMultipart(byte[] file, string filename, string contentType, string url)
    {
        var webClient = new WebClient();
        string boundary = "--" + DateTime.Now.Ticks.ToString("x");
        webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
        var fileData = webClient.Encoding.GetString(file);
        var package = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n{3}\r\n--{0}--\r\n", boundary, filename, contentType, fileData);

        var nfile = webClient.Encoding.GetBytes(package);

        webClient.UploadData(url, "POST", nfile);
    }

我发现内容的正确发布是:telegram.bot library request details

解码照片中的内容

--5d0b5218-7d9b-4e38-8999-1a05325549db 
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data;name=caption Logo

--5d0b5218-7d9b-4e38-8999-1a05325549db  
Content-Type: text/plain; charset=utf-8  
Content-Disposition: form-data; name=chat_id 123456789

--5d0b5218-7d9b-4e38-8999-1a05325549db  
Content-Type: application/octet-stream  
Content-Disposition: form-data; name="photo";filename="D:\Picture\Logo.png" 
(and other is file data)

如果有人有解决方案,请告诉我并举例说明:(

0 个答案:

没有答案