使用 SendMediaGroupAsync 方法 c#

问题描述 投票:0回答:3

我需要将相册捆绑发送到电报机器人。照片数量事先未知。 我写了代码:

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);

我无法将 stream 添加到 List arrayStream,错误“无法转换为 System.IO.Stream 到 Telegram.Bot.Types.IAlbumInputmedia” 在单个实例中,流通常通过 SendPhotoAsync 方法发送,并在代码中注释掉。 如何转换这些类型并发送合影?

c# visual-studio telegram telegram-bot
3个回答
0
投票

根据文档

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(":", ".")}")

0
投票

@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
,但至少它有效。


0
投票
// This Correct One
string[] files = Directory.GetFiles(photofolder);
List<IAlbumInputMedia> mediaItems = new List<IAlbumInputMedia>();
// Loop through each file path and create an InputMediaPhoto for each file
foreach (string singleFilePath in files)
{
// Get the safe file name from the file path
string safeFileName = Path.GetFileName(singleFilePath);
// Open a file stream for the current file
var localPhotoStream = new FileStream(singleFilePath, FileMode.Open, FileAccess.Read);
// Create an InputMediaPhoto object and add it to the list
var inputMedia = new InputMediaPhoto(new InputMedia(localPhotoStream, safeFileName))
{
Caption = $"Caption for {safeFileName}" // Example caption, customize as needed
};
mediaItems.Add(inputMedia);
}
// Assuming botClient is initialized with your Telegram Bot API token
botClient.SendMediaGroupAsync(
chatId: chatId,
media: mediaItems);
© www.soinside.com 2019 - 2024. All rights reserved.