通过电报机器人上传和发送字符串作为文件
Upload and send string as file via telegram bot
我有一个字符串想通过电报机器人发送,但不是作为消息(相当长)而是作为文件。
但是,我在创建此文件并将其上传到 Telegram 时遇到了一些问题(因为我需要使用 multipart/form-data API 文档 https://core.telegram.org/bots/api#sending-files 中指定的 post 文件。
受到 的启发,我尝试了以下方法:
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);
但我只收到一般错误 POST https://api.telegram.org/bot<token>/sendDocument 400 (Bad Request)
我从未使用过 XMLHttpRequest,所以我可能搞砸了它的用法,但我找不到任何解决方案。
欢迎使用替代方案(可能使用纯 js)。
您的变量命名有误。您将表单数据命名为 formData
,然后在发送请求时将其命名为 FormData
.
复制并粘贴这段代码,它应该可以工作。我测试了它,确实如此。确保将 chat_id 和令牌替换为有效的令牌,否则它将不起作用。
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);
我有一个字符串想通过电报机器人发送,但不是作为消息(相当长)而是作为文件。 但是,我在创建此文件并将其上传到 Telegram 时遇到了一些问题(因为我需要使用 multipart/form-data API 文档 https://core.telegram.org/bots/api#sending-files 中指定的 post 文件。 受到 的启发,我尝试了以下方法:
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);
但我只收到一般错误 POST https://api.telegram.org/bot<token>/sendDocument 400 (Bad Request)
我从未使用过 XMLHttpRequest,所以我可能搞砸了它的用法,但我找不到任何解决方案。
欢迎使用替代方案(可能使用纯 js)。
您的变量命名有误。您将表单数据命名为 formData
,然后在发送请求时将其命名为 FormData
.
复制并粘贴这段代码,它应该可以工作。我测试了它,确实如此。确保将 chat_id 和令牌替换为有效的令牌,否则它将不起作用。
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);