有人知道如何使用 NodeJs 将 audio/image 发送到 Telegram 机器人吗?

Anybody knows how to send a audio/image using NodeJs to a Telegram bot?

我正在尝试使用 nodeTelegram Api 将音频文件发送到 Telegram 机器人(sendAudio in这种情况)

const axios = require('axios');
const FormData = require('form-data');

let payload = new FormData();
payload.append('chat_id', 'ID');
payload.append('audio', './audio.mp3');
// OR  payload.append('photo', fs.createReadStream(`./audio.jpg`));

axios.post(
    'https://api.telegram.org/botMyToken/sendAudio',
    payload,
    {
        headers: {
            'accept': 'application/json',
            'Content-Type': `multipart/form-data;`
        }
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });

控制台结果是一个大对象:

Error: Request failed with status code 400
at createError (/Users/username/TelegramBot/MyBot/node_modules/axios/lib/core/createError.js:16:15)
at settle (/Users/username/TelegramBot/MyBot/node_modules/axios/lib/core/settle.js:18:12)
at IncomingMessage.handleStreamEnd (/Users/username/TelegramBot/MyBot/node_modules/axios/lib/adapters/http.js:201:11)
at IncomingMessage.emit (events.js:185:15)
at endReadableNT (_stream_readable.js:1101:12)
at process._tickCallback (internal/process/next_tick.js:114:19) 

headers:
  { Accept: 'application/json, text/plain, */*',
    'Content-Type': 'multipart/form-data;',
    accept: 'application/json',
    'Accept-Language': 'en-US,en;q=0.8',
    'User-Agent': 'axios/0.18.0' },
  method: 'post',
  url: 'https://api.telegram.org/botMyToken/sendAudio',
  data:
   FormData {
    _overheadLength: 210,
    _valueLength: 89,
    _valuesToMeasure: [],
    writable: false,
    readable: true,
    dataSize: 0,
    maxDataSize: 2097152,
    pauseStreams: true,
    _released: true,
    _streams: [],
    _currentStream: null,
    _boundary: '--------------------------432591578870565694802709',
    _events: {},
    _eventsCount: 0 } },

我做错了什么? 我尝试使用一个简单的表单发送相同的文件,并且 PHP 并且成功了,我不明白这段代码有什么问题。

您发送的不是音频文件,而是包含 local 文件路径的字符串,Telegram 当然没有访问权限。

Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data.

电报文档很清楚,audio必须是:

  • file_id
  • url
  • Post 文件使用 multipart/form-data

你可以试试这个:

payload.append('audio', fs.createReadStream('./audio.mp3'));

我建议使用 telegraf,它将完成所有繁重的工作,并允许您使用 local 文件路径。

const bot = new Telegraf(process.env.BOT_TOKEN);

bot.on('message', (ctx) => {

  // send file
  ctx.replyWithAudio({ source: './audio.mp3' })

});

bot.startPolling();

我推荐你使用 FormData 模块的 getHeaders() 函数。这解决了我将照片发送到电报机器人的问题

payload.append('photo', fs.createReadStream(`./audio.jpg`));
... 
headers: payload.getHeaders()
...