电报照片下载文件路径(node,js)

ejk8hzay  于 2023-05-28  发布在  Node.js
关注(0)|答案(1)|浏览(297)

我需要我的机器人保存照片到我的电脑,在那里它正在运行,到指定的路径。此函数:

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.');
    });
});

我得到一个错误

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

为什么他要留下从电报下载的文件名?我希望照片位于此文件路径中:'D:\bot\248408814.jpg'

svgewumm

svgewumm1#

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

bot.downloadFile(fileId, filePath)

第二个参数应该是保存图像的文件夹,而不是完整的路径。这就是为什么你得到'没有这样的文件或目录',因为它试图找到该文件夹,这是不存在的。
filePath设置为目录路径,例如:

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

您需要确保作为第二个参数传递的文件夹存在;
How to create a directory if it doesn't exist using Node.js
关于OP关于更改文件名的评论,this issue也问了同样的问题,似乎没有这个选项。
查看downloadFile的源代码,没有更改名称的选项。
但是,downloadFile返回一个Promise,它包含filePath,然后您可以使用fs重命名文件:Renaming files using node.js

相关问题