【问题标题】:Send a pdf file using telegram bot api使用电报机器人 api 发送 pdf 文件
【发布时间】:2019-02-25 21:04:20
【问题描述】:

我正在尝试使用文件的 url 并使用“sendDocument”方法发送 pdf 文件,问题是由于存储文件的服务器,我无法直接访问该文件。我尝试使用这篇文章中提供的答案: readFileSync from an URL for Twitter media - node.js

它可以工作,但文件作为“file.doc”发送。如果我将扩展名更改为 pdf,则它是正确的文件。我需要做任何额外的步骤来发送具有正确名称和扩展名的文件,还是有其他方法可以实现我所需要的?

编辑: 我用来获取 pdf 的代码看起来与我提供的帖子的答案中的代码一模一样:

function getImage(url, callback) {
https.get(url, res => {
    // Initialise an array
    const bufs = [];

    // Add the data to the buffer collection
    res.on('data', function (chunk) {
        bufs.push(chunk)
    });

    // This signifies the end of a request
    res.on('end', function () {
        // We can join all of the 'chunks' of the image together
        const data = Buffer.concat(bufs);

        // Then we can call our callback.
        callback(null, data);
    });
})
// Inform the callback of the error.
.on('error', callback);
}

要发送文件我使用这样的东西:

getImage(url, function(err, data){
    if(err){
        throw new Error(err);
    }

    bot.sendDocument(
        msg.chat.id,
        data,
    );
})

【问题讨论】:

  • 你能添加你的示例代码吗!?
  • 嗨,我在帖子中添加了一些代码

标签: javascript node.js telegram-bot


【解决方案1】:

您可以使用以下代码指定文件名和文件类型:

const fileOptions = {
  // Explicitly specify the file name.
  filename: 'mypdf.pdf',
  // Explicitly specify the MIME type.
  contentType: 'application/pdf',
};

全功能:

 getImage("https://your.url/yourfile.pdf", function(err, data){
  if(err){
      throw new Error(err);
  }

      const fileOptions = {
        // Explicitly specify the file name.
        filename: 'mypdf.pdf',
        // Explicitly specify the MIME type.
        contentType: 'application/pdf',
      };
      bot.sendDocument(msg.chat.id, data, {}, fileOptions);
}); 

注意:如果您没有要指定的查询选项,您必须提供一个空对象 ({}) 来代替 Additional Telegram 查询选项。例如,

// 错了! // 'fileOptions' 将作为额外的 Telegram 查询选项!!!

bot.sendAudio(chatId, data, fileOptions);

// 对!

bot.sendAudio(chatId, data, {}, fileOptions);

更多信息在这里: https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md#sending-files

【讨论】:

  • 谢谢你的回答@mrblue。我尝试了代码,但它一直将文件作为“file.doc”发送
  • 这很奇怪,因为我已经测试了这段代码并且它对我来说工作正常。也许是因为网址?
  • 我不确定,我尝试使用存储在同一服务器中的图片的 getImage 方法,它按预期唤醒了
【解决方案2】:

找到了解决办法。我正在使用 Telebot api(抱歉没有提到那个细节,但我不知道,我没有做这个项目)。

我使用以下行来发送文件:

bot.sendDocument(chat_id, data, {fileName: 'file.pdf'});

【讨论】:

    猜你喜欢
    • 2017-06-16
    • 1970-01-01
    • 2020-10-08
    • 2019-06-02
    • 2021-10-25
    • 1970-01-01
    • 2015-07-21
    • 2017-03-19
    • 1970-01-01
    相关资源
    最近更新 更多