I have a string that I want to send via a telegram bot, but not as a message (it's rather long) but as a file. However I have some problems in creating and uploading this file to Telegram (since I need to post the file using multipart/form-data as specified in the API docs ). Inspired by I tried the following:
var file = new Blob([enc_data], {type: 'text/plain'});
var formData = new FormData();
formData.append('chat_id', '<id>');
formData.append('document', file);
var request = new XMLHttpRequest();
request.open('POST', ';token>/sendDocument');
request.send(FormData);
but I only get a generic error POST ;token>/sendDocument 400 (Bad Request)
I have never used XMLHttpRequest so I'm probably messing up with its usage but I can't find any solution.
Alternatives (possibly using plain js) are wele.
I have a string that I want to send via a telegram bot, but not as a message (it's rather long) but as a file. However I have some problems in creating and uploading this file to Telegram (since I need to post the file using multipart/form-data as specified in the API docs https://core.telegram/bots/api#sending-files). Inspired by https://stackoverflow./a/22858914/4869973 I tried the following:
var file = new Blob([enc_data], {type: 'text/plain'});
var formData = new FormData();
formData.append('chat_id', '<id>');
formData.append('document', file);
var request = new XMLHttpRequest();
request.open('POST', 'https://api.telegram/bot<token>/sendDocument');
request.send(FormData);
but I only get a generic error POST https://api.telegram/bot<token>/sendDocument 400 (Bad Request)
I have never used XMLHttpRequest so I'm probably messing up with its usage but I can't find any solution.
Alternatives (possibly using plain js) are wele.
1 Answer
Reset to default 8Your variable naming was wrong. You named the formdata as formData
and then when you sent the request you called it FormData
.
Copy and paste this code, it should work. I tested it and it does. Make sure to replace the chat_id and token with valid ones else it won't work.
var chat_id = 3934859345; // replace with yours
var enc_data = "This is my default text";
var token = "45390534dfsdlkjfshldfjsh28453945sdnfnsldfj427956345"; // from botfather
var blob = new Blob([enc_data], { type: 'plain/text' });
var formData = new FormData();
formData.append('chat_id', chat_id);
formData.append('document', blob, 'document.txt');
var request = new XMLHttpRequest();
request.open('POST', `https://api.telegram/bot${token}/sendDocument`);
request.send(formData);