Upload and send string as file via telegram bot
Asked Answered
M

1

6

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.org/bots/api#sending-files). Inspired by https://mcmap.net/q/297026/-javascript-uploading-a-file-without-a-file 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.org/bot<token>/sendDocument');
request.send(FormData);

but I only get a generic error POST https://api.telegram.org/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 welcome.

Mend answered 17/5, 2019 at 12:58 Comment(0)
C
8

Your 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.org/bot${token}/sendDocument`);
request.send(formData);
Cimon answered 20/5, 2019 at 10:51 Comment(1)
worked like a charm, can't believe it was such a trivial mistake!Mend

© 2022 - 2024 — McMap. All rights reserved.