skip to Main Content

I need to send a photo album in a bundle to the telegram bot. The number of photos is unknown in advance.
I wrote the code:

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

I can’t add stream to List arrayStream, error "cannot convert to System.IO.Stream to Telegram.Bot.Types.IAlbumInputmedia"
In a single instance, the stream is normally sent via the SendPhotoAsync method, commented out in the code.
How do I convert these types and send a group photo?

2

Answers


  1. Chosen as BEST ANSWER

    @Vadim's answer didn't work, probably because I can't Add in this case. But their answer did push me in the right direction. I decided to write code for a different number of photos of different branches of the program.

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

    I'm not sure that I'm using await using correctly, but at least it works.


  2. According to the docs:

    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"),
        }
    );
    

    You must explicitly set the type of files.

    In your case it will be like:

    streamArray.Add(new InputMediaPhoto(stream, $"file{DateTime.Now.ToString("s").Replace(":", ".")}")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search