Reputation: 3161
I'm trying to send an audio file to a Telegram bot using node and Telegram Api (sendAudio in this case)
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);
});
console result is a big obj with:
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 } },
what am I doing wrong? I tried send same file using a simple form, and PHP and it worked, I don't get what's wrong in this code.
Upvotes: 1
Views: 4564
Reputation: 11
I recommend you to use getHeaders() function of FormData module. This solved my problem with sending photo to telegram bot
payload.append('photo', fs.createReadStream(`./audio.jpg`));
...
headers: payload.getHeaders()
...
Upvotes: 1
Reputation: 40444
You're not sending an audio file, but a string containing a local path to a file, which Telegram of course doesn't have access.
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.
The telegram documentation is clear, audio
must be:
You can try this:
payload.append('audio', fs.createReadStream('./audio.mp3'));
I recommend using telegraf which will do all the heavy lifting, and will allow you to use a local file path.
const bot = new Telegraf(process.env.BOT_TOKEN);
bot.on('message', (ctx) => {
// send file
ctx.replyWithAudio({ source: './audio.mp3' })
});
bot.startPolling();
Upvotes: 1