How do I correctly send a document using my Telegram bot?

I’m attempting to send a file through my Telegram bot, but I keep encountering a 400 error. It appears that the sendDocument method strictly requires a multipart/form-data format. I implemented a script in PowerShell and received an error, which suggests the request format might not be acceptable by the API. Below is a revised version of my code:

$fileName   = 'E:\example.doc'
$chatID     = 99999
$botKey     = 'DEF456'
$apiEndpoint = "https://api.telegram.org/${botKey}/sendDocument?chat_id=${chatID}"

[Net.ServicePointManager]::SecurityProtocol = 'tls12'
$response  = Invoke-WebRequest -Uri $apiEndpoint -Method Post -InFile $fileName -ContentType "multipart/form-data"
$response.Content

Any suggestions or modifications to ensure the file is sent properly would be greatly appreciated.

hey, i ran in a simlar spot where using -InFile got me in trouble. i fixed mine by building the multipart body manually, passing the file as a stream under ‘document’. sometimes getting boundaries right is key. hope this tipz helps!

I encountered a similar challenge and eventually found that using a file stream within a form submission was a more reliable method. I switched from relying solely on the InFile parameter and instead converted the file into a stream that I then passed with the appropriate field name. In my case, I also opted to use Invoke-RestMethod over Invoke-WebRequest, as I found it provided clearer error messages which made troubleshooting easier. This approach ensured that the file was correctly embedded in the multipart/form-data request, and it resolved the 400 error I’ve seen before.

hey, u might need to post the file as a form field named ‘document’ instead of using -InFile. switching to -Form lets powershell handle multipart boundaries correctly. hope this helps!

I encountered a similar issue when I was attempting to send documents using my Telegram bot. After some trial and error, I discovered that the core problem was how the file was attached to the HTTP request. The solution was to explicitly use a form submission approach and specify the field name as ‘document’. Instead of using the -InFile parameter, which may cause the script to incorrectly format the multipart form data, I modified my request to use -Form with the file stream. This method correctly encoded the file and resolved the 400 error.