0

I need my bot to save photos to my computer, where it is running, to a specified path. The function for this:

const fs = require('fs');
const path = require('path');

...

bot.on('photo', (msg) => {
  const chatId = msg.chat.id;
  const photo = msg.photo[0]; 
  const fileId = photo.file_id;

  const fileName = `${chatId}.jpg`;
  const filePath = `D:/bot/${fileName}`;

  bot.downloadFile(fileId, filePath)
    .then(() => {
      bot.sendMessage(chatId, 'Done!');
    })
    .catch((downloadErr) => {
      console.error('Error downloading photo:', downloadErr);
      bot.sendMessage(chatId, 'Error while saving.');
    });
});

I get an error

Error downloading photo: [Error: ENOENT: no such file or directory, open 'D:\bot\248408814.jpg\file_12.jpg']

Why does he leave the name of the file it downloads from telegram? I want the photo to be in this file path: 'D:\bot\248408814.jpg'

1 Answers1

0
const fileName = `${chatId}.jpg`;
const filePath = `D:/bot/${fileName}`;

bot.downloadFile(fileId, filePath)

The second argument should be the folder were the image should be saved, not the full path. That's why you get the 'no such file or directory' since it's trying to find that folder, which doesn't exists.


Set filePath to the the directory path, for example:

bot.downloadFile(fileId, 'D:\Bot\someFolder')

You'll need to make sure that the folder passed as second argument exists;
How to create a directory if it doesn't exist using Node.js


Regarding OP's comment about changing the file name, this issue asks the same, there does not seem an option for this.

Looking at the source of downloadFile, there is no option to change the name.

However, downloadFile returns a Promise, that holds the filePath, you then can use fs to rename the file: Renaming files using node.js

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • But the fileId of the file given by Telegram should be in the first place, not the filename? `downloadFile(fileId, path )` Otherwise I get an error `Error downloading photo: TelegramError: ETELEGRAM: 400 Bad Request: wrong file_id or the file is temporarily unavailable` – Leaverk Vands May 24 '23 at 18:52
  • It works fine this way. It saves the file in the bot folder, but with the name file_12.jpg `const filePath = "D:/bot"; bot.downloadFile(fileId, filePath)` But then how do I change the file name when saving to `${chatId}.jpg` ? – Leaverk Vands May 24 '23 at 18:59
  • You are right, please see my improved answer. Hope it helps @LeaverkVands. – 0stone0 May 25 '23 at 11:48