2

我只想用 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 } }
4

3 回答 3

4
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

于 2019-12-12T21:15:13.677 回答
4

共有三个步骤: 获取 Telegram 上“文件目录”的 api 请求。使用该“文件目录”创建“下载 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和https://core.telegram.org/bots/api#getfile

于 2020-09-13T05:56:28.137 回答
1
  bot.getFile(msg.document.file_id).then((resp) => {
             console.log(resp)
         })
于 2020-07-23T17:32:08.023 回答