Search code examples
c#telegramwtelegramclient

C# how to send a file via Telegram API


I am using WTelegramClient library.

Here is how I send messages:

var client = new WTelegram.Client(Config);
await client.LoginUserIfNeeded();
var contacts = await client.Contacts_ImportContacts(new[]
{
   new InputPhoneContact { phone = "+998901234567" } 
});

if (contacts.imported.Length > 0)
await client.SendMessageAsync(contacts.users[contacts.imported[0].user_id], "Hello, world!");

How to send multiple files? or at least one file.

I need to send files from a list or from a folder. I will be glad for any help.

List<byte[]> file = new List<byte[]>();

Solution

  • Sample from the official documentation

    1.Get upload folder path, like this.

    const string Filepath = @"C:\...\photo.jpg";
    

    2.Upload file using client and path

    var inputFile = await client.UploadFileAsync(Filepath);
    

    3.Send file to peer (chats.chats[ChatId])

    await client.SendMediaAsync(peer, "Here is the photo", inputFile);
    

    Sample code

    const int ChatId = 1234567890; // the chat we want
    const string Filepath = @"C:\...\photo.jpg";
    
    using var client = new WTelegram.Client(Environment.GetEnvironmentVariable);
    await client.LoginUserIfNeeded();
    var chats = await client.Messages_GetAllChats(null);
    InputPeer peer = chats.chats[ChatId];
    var inputFile = await client.UploadFileAsync(Filepath);
    await client.SendMediaAsync(peer, "Here is the photo", inputFile);