0

I want to upload a .txt file to telegram with my javascript bot. I've seen a few examples in php and python but didn't understand, so I just need a js example to find out.

Should I upload a file first and then sendDocmuent or should input in sendDocmuent?

I've tried sendDocument with document: 'file.txt' but didn't work.

Also read about form-data but got nothing!

call("sendDocument",{
chat_id: owner,
document: 'file.txt' // or /file.txt or full address (C:...)
});

I'm not using any library, here is my call function:

const botUrl = "https://api.telegram.org/bot" + token + "/";
const request = require('request');
function call(method, params, onResponse)
{

var requestData = params;

var data = {
    url: botUrl+method,
    json: true,
    body: requestData
};


request.post(data, function(error, httpResponse, body){
    if (onResponse) {
            if(body)
            {
                onResponse(body.result);
            }
        }
});

}

Telegram bot API

S.s.
  • 33
  • 2
  • 10

1 Answers1

0

EDITED: This is the code that works for me.

It seems that what the Telegram API never requires a file name for the sendDocument method:

File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data

Instead of just sending out the string 'file.txt', you need to actually send the contents of the file, as a multipart/form-data, as you had guessed. Building on this answer, you just need to modify the form field of the request object:

const request = require('request')
const fs = require('fs')
const token = '752511654:AAGnu88dyi7YsmpZfcaA6XvR26Fy7f2moGo'
const url = 'https://api.telegram.org/bot'+token+'/sendDocument'
const chat_id = "741718736"

let r = request(url, (err, res, body) => {
    if(err) console.log(err)
    console.log(body)
})

let f = r.form()
f.append('chat_id', chat_id)
f.append('document', fs.createReadStream('file.txt'))    
pierre
  • 151
  • 8
  • I've updated my post, I prefer not using telegram-bot-api – S.s. Jan 03 '19 at 11:44
  • Updated my post as well, based on the telegram API! – pierre Jan 03 '19 at 12:47
  • Does `let document_to_be_sent = fs.createReadStream('path/to/file.txt')` return anything? You could also try with `form.append('custom_file', fs.createReadStream('path/to/file'), {filename: 'file.txt'});`, all in one line – pierre Jan 03 '19 at 15:05
  • My file is in root folder, so `fs.createReadStream('file.txt')`.At first I use fs.readFile('file.txt',... and I'm sure the file is ok – S.s. Jan 03 '19 at 15:10
  • I think should change botUrl+method, tried botUrl+"sendDocument" and that was the respond – S.s. Jan 03 '19 at 15:11
  • hey @S.s. the code i edited is working for me now. let me know if it does the job for you. the problem was to set the form field as `document` and not `file` or `custom_file` – pierre Jan 04 '19 at 10:32