我应该如何从电报中下载收到的文件 api

How should I download received files from telegram api

我只想用 nodejs 下载我的电报机器人接收到的图像,但我不知道 的使用方法。我正在使用 node-telegram-bot-api 并尝试了此代码:

bot.on('message', (msg) => {
    const img = bot.getFileLink(msg.photo[0].file_id);

    console.log(img);
});

这是结果:

Promise [Object] {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined,
  _cancellationParent:
   Promise [Object] {
     _bitField: 1,
     _fulfillmentHandler0: [Function],
     _rejectionHandler0: undefined,
     _promise0: [Circular],
     _receiver0: undefined,
     _cancellationParent:
      Promise [Object] {
        _bitField: 1,
        _fulfillmentHandler0: undefined,
        _rejectionHandler0: [Function],
        _promise0: [Circular],
        _receiver0: undefined,
        _cancellationParent: [Promise],
        _branchesRemainingToCancel: 1 },
     _branchesRemainingToCancel: 1 } }
bot.on('message', async (msg) => {
    if (msg.photo && msg.photo[0]) {
        const image = await bot.getFile({ file_id: msg.photo[0].file_id });
        console.log(image);
    }
});

https://github.com/mast/telegram-bot-api/blob/master/lib/telegram-bot.js#L1407

  bot.getFile(msg.document.file_id).then((resp) => {
             console.log(resp)
         })

共有三个步骤: api 请求获取 Telegram 上的“文件目录”。使用该“文件目录”创建“下载 URL”。使用“请求”模块下载文件。

const fs = require('fs');
const request = require('request');
require('dotenv').config();
const path = require('path');
const fetch = require('node-fetch');

// this is used to download the file from the link
const download = (url, path, callback) => {
    request.head(url, (err, res, body) => {
    request(url).pipe(fs.createWriteStream(path)).on('close', callback);
  });
};
// handling incoming photo or any other file
bot.on('photo', async (doc) => {

    // there's other ways to get the file_id we just need it to get the download link
    const fileId = doc.update.message.photo[0].file_id;

    // an api request to get the "file directory" (file path)
    const res = await fetch(
      `https://api.telegram.org/bot${process.env.BOT_TOKEN}/getFile?file_id=${fileId}`
    );
    // extract the file path
    const res2 = await res.json();
    const filePath = res2.result.file_path;

    // now that we've "file path" we can generate the download link
    const downloadURL = 
      `https://api.telegram.org/file/bot${process.env.BOT_TOKEN}/${filePath}`;

    // download the file (in this case it's an image)
    download(downloadURL, path.join(__dirname, `${fileId}.jpg`), () =>
      console.log('Done!')
     );
});    

可能有帮助的链接:https://core.telegram.org/bots/api#file and https://core.telegram.org/bots/api#getfile