skip to Main Content

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?

2

Answers


  1. From the Telegram api docs

    1. If the file is already stored somewhere on the Telegram servers, you don’t need to reupload it: each file object has a file_id field, simply pass this file_id as a parameter instead of uploading. There are no limits for files sent this way.
    2. Provide Telegram with an HTTP URL for the file to be sent. Telegram will download and send the file. 5 MB max size for photos and 20 MB max for other types of content.
    3. Post the file using multipart/form-data in the usual way that files are uploaded via the browser. 10 MB max size for photos, 50 MB for other files.

    What you want to send is a file via file upload (3.). This is the answer to what you are trying to achieve:
    https://stackoverflow.com/a/59177066/4668136

    Login or Signup to reply.
  2. 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);
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search