简体   繁体   中英

Upload files with telegram bot - NodeJS

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

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'))    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM