4

我想在 Telegram 中创建一个机器人。经过搜索,我在一个 Nuget 包中找到了 telegram.bot。

但我无法发送照片。函数定义就像

Bot.SendPhoto(int channelId, string photo, string caption)

但我不知道string photo参数中的预期内容。我应该将图像转换为 base64 字符串,还是传递图像路径,还是...?

我的代码目前看起来像这样

var Bot = new Telegram.Bot.Api("API KEY");
var b = new System.Net.WebClient().DownloadData(a.DefaultImage());
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(new System.IO.MemoryStream(b));
var z = bmp.GetThumbnailImage(200, (200 * bmp.Height) / bmp.Width, 
   new System.Drawing.Image.GetThumbnailImageAbort(
      delegate { return true; }), IntPtr.Zero);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
z.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
var x = new Telegram.Bot.Types.FileToSend() 
{ 
    Filename = a.DefaultImage().Split('/').LastOrDefault(), Content = ms 
};

var t = Bot.SendPhoto("@Chanel", x, a.Title);

但这导致异常

Telegram.Bot.Types.ApiRequestException:[错误]:错误请求:要发送的文件必须非空

4

3 回答 3

5

根据源代码方法文档,您应该将“file_id 作为字符串传递以重新发送已经在 Telegram 服务器上的照片,或使用 multipart/form-data 上传新照片”。我的猜测是参数注释是通用的,并且这个重载只接受服务器上现有文件的 file_id。

/// <summary>
/// Use this method to send photos. On success, the sent Message is returned.
/// </summary>
/// <param name="chatId">Unique identifier for the target chat</param>
/// <param name="photo">Photo to send. You can either pass a file_id as String to resend a photo that is already on the Telegram servers, or upload a new photo using multipart/form-data.</param>
/// <param name="caption">Optional. Photo caption (may also be used when resending photos by file_id).</param>
/// <param name="replyToMessageId">Optional. If the message is a reply, ID of the original message</param>
/// <param name="replyMarkup">Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param>
/// <returns>On success, the sent Message is returned.</returns>
public async Task<Message> SendPhoto(int chatId, string photo, string caption = "", int replyToMessageId = 0, ReplyMarkup replyMarkup = null)

过载

public async Task<Message> SendPhoto(int chatId, FileToSend photo, 
    string caption = "", int replyToMessageId = 0,
    ReplyMarkup replyMarkup = null)

接受FileToSend包含文件名和流的 a。使用第二个重载上传新照片。

免责声明:我没有使用过 API,所以这些纯粹是从检查源代码中扣除的。

于 2015-11-17T14:21:06.137 回答
1

你也可以这样试试 =>

Bot.SendPhotoAsync(Chatid ,  new FileToSend(FileName,Streaminput),Caption);

此 api 是用于在电报机器人上发送带有标题的照片的默认 api。

于 2017-09-01T07:42:27.793 回答
0

如果你需要的话,你也可以这样尝试。

Bot.SendPhoto(int channelId,photo : "http://abc.jpeg",caption:"hii");

在电报机器人上,您发送图像、视频,如 2 种方式。首先是您可以发送,例如将您的图像转换为流,然后继续发送,第二是我就像传递照片一样:“这里将 url 作为字符串”然后电报机器人服务器自动从 url 下载此图像。

于 2017-09-11T07:08:22.833 回答