【问题标题】:Telegram BOT Api: how to send a photo using C#?Telegram BOT Api:如何使用 C# 发送照片?
【发布时间】:2016-07-09 08:58:49
【问题描述】:
sendPhoto 命令需要一个定义为 InputFile 或 String 的参数 photo。
API 文档告诉:
要发送的照片。您可以将 file_id 作为字符串传递以重新发送照片
已经在 Telegram 服务器上,或者使用
多部分/表单数据。
和
输入文件
此对象表示要上传的文件的内容。一定是
以文件通常的方式使用 multipart/form-data 发布
通过浏览器上传。
【问题讨论】:
标签:
telegram
telegram-bot
【解决方案1】:
我不是 C# 开发人员,但我使用 Postman 生成此代码,它使用 RestSharp lib
var client = new RestClient("https://api.telegram.org/bot%3Ctoken%3E/sendPhoto");
var request = new RestRequest(Method.POST);
request.AddHeader("postman-token", "7bb24813-8e63-0e5a-aa55-420a7d89a82c");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001");
request.AddParameter("multipart/form-data; boundary=---011000010111000001101001", "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"[object Object]\"\r\nContent-Type: false\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"chat_id\"\r\n\r\n2314123\r\n-----011000010111000001101001--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
只需调整它,它应该可以工作。
【解决方案2】:
这是一个有效的参数化代码示例:
using System.Linq;
using System.IO;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
SendPhoto(args[0], args[1], args[2]).Wait();
}
public async static Task SendPhoto(string chatId, string filePath, string token)
{
var url = string.Format("https://api.telegram.org/bot{0}/sendPhoto", token);
var fileName = filePath.Split('\\').Last();
using (var form = new MultipartFormDataContent())
{
form.Add(new StringContent(chatId.ToString(), Encoding.UTF8), "chat_id");
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
form.Add(new StreamContent(fileStream), "photo", fileName);
using (var client = new HttpClient())
{
await client.PostAsync(url, form);
}
}
}
}
}
}