使用telegram.bot发送照片
本文关键字:照片 bot telegram 使用 | 更新日期: 2023-09-27 18:22:11
我想在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:[Error]:错误请求:文件到发送必须是非空
根据源代码方法文档,您应该将"file_id作为字符串传递,以重新发送Telegram服务器上已经存在的照片,或使用多部分/表单数据上传新照片"。我的猜测是,参数注释是通用的,并且这个重载只接受服务器上现有文件的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)
接受保存文件名和流的CCD_ 2。使用第二个过载上传新照片。
免责声明:我没有使用API,所以这些纯粹是从检查源代码中扣除的。
您也可以这样尝试=>
Bot.SendPhotoAsync(Chatid , new FileToSend(FileName,Streaminput),Caption);
此api是telegram bot上带有标题的发送照片的默认api。
如果需要,也可以这样尝试。
Bot.SendPhoto(int channelId,photo : "http://abc.jpeg",caption:"hii");
在telegram bot上,你可以通过2种方式发送图像、视频。第一个是你可以发送,比如将你的图像转换为流,然后发送,第二个是我给出的,比如只传递照片:"这里给出字符串形式的url",然后telegram bot服务器自动从url下载这个图像。