Omid.Hanjani
Omid.Hanjani

Reputation: 1522

How to send remote mp3 file to Telegram channel using Telegram Bot API's sendAudio method in C#

I create a bot (@mp3lyric_bot_test) in telegram and set it as administrator in my channel (@mp3lyric_test). Now I want to make a request to send an mp3 to channel using telegram api.

my mp3 is in web, something like this: http://bayanbox.ir/download/7028444634071302239/Sound-1.mp3

At first i download mp3 with this method:

    public static Task<byte[]> DownloadAsync(string requestUriSt)
    {
        var requestUri = new Uri(requestUriSt);

        byte[] fileBytes;

        using (var httpClient = new HttpClient())
        {
            using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
            {
                using (var responseMessage = await httpClient.SendAsync(request))
                {
                    fileBytes = await responseMessage.Content.ReadAsByteArrayAsync();
                    var audioString = Encoding.UTF8.GetString(fileBytes, 0, fileBytes.Length);
                }
            }
        }

        return fileBytes;
    }

Then send that byte array (fileBytes) using this code:

I have two error:

  1. "Request Entity Too Large" when my mp3 is about 6mb or 7mb or ... (not using http://bayanbox.ir/download/7028444634071302239/Sound-1.mp3)

  2. error_code:400, description:"Bad Request: URL must be in UTF-8" (after using that mp3 for test that is 28kb)

Upvotes: 1

Views: 5911

Answers (2)

Omid.Hanjani
Omid.Hanjani

Reputation: 1522

I chaged my codes for send the byte array (fileBytes) and now it works:

using (var client = new HttpClient())
{
    var uri = new Uri("https://api.telegram.org/bot247655935:AAEhpYCeoXA5y7V8Z3WrVcNJ3AaChORjfvw/sendAudio?chat_id=@mp3lyric_test");

    using (var multipartFormDataContent = new MultipartFormDataContent())
    {
        var streamContent = new StreamContent(new MemoryStream(fileBytes));
        streamContent.Headers.Add("Content-Type", "application/octet-stream");
        streamContent.Headers.Add("Content-Disposition", "form-data; name=\"audio\"; filename=\"Sound-1.mp3\"");
        multipartFormDataContent.Add(streamContent, "file", "Sound-1.mp3");

        using (var message = await client.PostAsync(uri, multipartFormDataContent))
        {
            var contentString = await message.Content.ReadAsStringAsync();
        }
    }
}

Upvotes: 1

Charles Okwuagwu
Charles Okwuagwu

Reputation: 10866

To send a new AudioFile you use the SendAudio method but with the InputFile field.

First create an InputFile object, then pass those bytes in the audio parameter of the SendAudio method

If you need to resend the same AudioFile to another user, then you can use the String option as the audio parameter in the SendAudio

Upvotes: 1

Related Questions