Search code examples
node.jstelegram-botchatbot

Telegram Bot - How to upload local files with absolute/ dynamic URL


I'm trying to send photos through telegram bot using 'sendPhoto' method with relative url (Image at file level). I'm not using any library, here is my call function:

let axiosImage = async (chatId, caption, res) => {
try {
    await axios.post(`${TELEGRAM_API}/sendPhoto`,
        {
            headers:{'Content-Type': 'multipart/form-data'}
        },{
            body: {
                'chat_id': chatId,
                'caption': caption,
                'photo': './image.jpeg'
            }
        })
    return res.send()
} catch (e) {
    console.log('\nSTATUS RESPONSE: ' + e.response.status)
    console.log('\nMESSAGE RESPONSE: ' + e.response.statusText)
}}

but I'm getting this message back: {"ok":false,"error_code":400,"description":"Bad Request: there is no photo in the request"}

I tried with a web url and it sends normally.

What could I be missing? Do I have to upload the local images in some repository?


Solution

  • I had a similar issue recently, I managed to solve the problem using form-data npm package and built-in fs module.

    const FormData = require('form-data');
    const fs = require('fs');
    
    const axiosImage = async(chatId, caption, res) => {
        try {
            const formData = new FormData();
            
            formData.append('chat_id', chatId);
            formData.append('photo', fs.createReadStream('./image.jpeg'));
            formData.append('caption', caption);
        
            const response = await axios.post(`${TELEGRAM_API}/sendPhoto`, formData, {
                headers: formData.getHeaders(),
            });
    
            return res.send();
        } catch (err) {
            console.log(err);
        }
    }