Telegram Bot API: Photo sending fails with 'no photo in request' error

Hey everyone! I’m stuck with my Node.js Telegram bot. I’m trying to send an image to users, but it’s not working. Here’s my code:

bot.sendPhoto({
  chatId: chatInfo.id,
  caption: 'Check out this pic',
  files: {
    photo: './images/cool-image.jpg'
  }
}, (error, response) => {
  if (error) console.error(error);
  else console.log(response);
});

But I keep getting this error:

Error 400: Bad Request: there is no photo in the request

I’m pretty sure the file path is correct. Any ideas what I’m doing wrong? Has anyone else run into this issue before? I’d really appreciate some help figuring this out. Thanks!

Have you considered using the Telegram Bot API directly instead of a wrapper library? Sometimes these libraries can introduce unexpected issues. You could try making a POST request to the sendPhoto endpoint using a library like axios or node-fetch. Here’s a basic example:

const axios = require('axios');
const fs = require('fs');
const FormData = require('form-data');

const form = new FormData();
form.append('chat_id', chatInfo.id);
form.append('caption', 'Check out this pic');
form.append('photo', fs.createReadStream('./images/cool-image.jpg'));

axios.post(`https://api.telegram.org/bot${YOUR_BOT_TOKEN}/sendPhoto`, form, {
  headers: form.getHeaders()
}).then(response => {
  console.log(response.data);
}).catch(error => {
  console.error(error);
});

This approach gives you more control and might help identify where the issue lies. Make sure to replace YOUR_BOT_TOKEN with your actual bot token.

hey mate, have u checked if the file exists using the fs module? it might be a path issue. also, see if ur bot got proper access to that folder. as a last resort, try using a direct image url instead of a local path. good luck!

I encountered a similar issue when working on a Telegram bot project. The problem might be with how you’re specifying the file path. Instead of using a relative path, try using an absolute path to the image file. Also, make sure the image file actually exists at that location.

Another thing to check is the file format. Telegram supports JPEG, PNG, GIF, and WebP formats for photos. If your image is in a different format, you might need to convert it first.

If those don’t work, you could try reading the file into a buffer first and then sending that:

const fs = require('fs');
const imageBuffer = fs.readFileSync('/absolute/path/to/cool-image.jpg');

bot.sendPhoto({
  chatId: chatInfo.id,
  caption: 'Check out this pic',
  photo: imageBuffer
});

This approach has worked for me in the past when I had similar issues. Hope this helps!