我需要將相冊打包發送給電報機器人。照片數量事先未知。我寫的代碼:
List<IAlbumInputMedia> streamArray = new List<IAlbumInputMedia> {};
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using var stream = formFile.OpenReadStream();
streamArray.Add(stream); // there is a mistake here. cannot convert to System.IO.Stream to Telegram.Bot.Types.IAlbumInputmedia
//await clientTg.SendPhotoAsync(groupId,stream); // it works fine
}
}
await clientTg.SendMediaGroupAsync(groupId, streamArray);
我無法將流添加到 List arrayStream,錯誤“無法轉換為 System.IO.Stream 到 Telegram.Bot.Types.IAlbumInputmedia ” 在單個實體中,流通常通過 SendPhotoAsync 方法發送,在代碼中注釋掉。如何轉換這些型別并發送合影?
uj5u.com熱心網友回復:
根據檔案:
Message[] messages = await botClient.SendMediaGroupAsync(
chatId: chatId,
media: new IAlbumInputMedia[]
{
new InputMediaPhoto("https://cdn.pixabay.com/photo/2017/06/20/19/22/fuchs-2424369_640.jpg"),
new InputMediaPhoto("https://cdn.pixabay.com/photo/2017/04/11/21/34/giraffe-2222908_640.jpg"),
}
);
您必須明確設定檔案的型別。
在您的情況下,它將類似于:
streamArray.Add(new InputMediaPhoto(stream, $"file{DateTime.Now.ToString("s").Replace(":", ".")}")
uj5u.com熱心網友回復:
@Vadim 的回答沒有用,可能是因為Add在這種情況下我不能。但他們的回答確實將我推向了正確的方向。我決定為程式不同分支的不同數量的照片撰寫代碼。
if (files.Count == 2) // <<<< 2 photos
{
await using var stream1 = files[0].OpenReadStream();
await using var stream2 = files[1].OpenReadStream();
IAlbumInputMedia[] streamArray =
{
new InputMediaPhoto(new InputMedia(stream1, "111"))
{
Caption = "Cap 111"
},
new InputMediaPhoto(new InputMedia(stream2, "222"))
{
Caption = "Cap 222"
},
};
await clientTg.SendMediaGroupAsync(groupId, streamArray);
}
我不確定我await using是否正確使用,但至少它有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/360405.html
下一篇:將模板傳遞給異步函式
