最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Upload and send string as file via telegram bot - Stack Overflow

programmeradmin1浏览0评论

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.

Share asked May 17, 2019 at 12:58 EarendilEarendil 1751 silver badge10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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/bot${token}/sendDocument`);
request.send(formData);
发布评论

评论列表(0)

  1. 暂无评论