gpt4 book ai didi

node.js - 有人知道如何使用 NodeJs 将音频/图像发送到 Telegram 机器人吗?

转载 作者:太空宇宙 更新时间:2023-11-04 00:09:51 25 4
gpt4 key购买 nike

我正在尝试使用 nodeTelegram Api 将音频文件发送到 Telegram 机器人(在本例中为 sendAudio)

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 有效,我不明白这段代码有什么问题。

最佳答案

您发送的不是音频文件,而是包含文件本地路径的字符串,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.

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

  • 文件 ID
  • 网址
  • 使用 multipart/form-data 发布文件

你可以试试这个:

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

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

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

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

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

});

bot.startPolling();

关于node.js - 有人知道如何使用 NodeJs 将音频/图像发送到 Telegram 机器人吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50355903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com