所以,我想使用 Ubuntu 最新版本或最高版本在 Google Cloud VM 实例中发送 Telegram API Bot。我正在使用 NodeJS 程序并 fetch 来运行 API。
但是我收到了这个错误:
TypeError: fetch failed
at node:internal/deps/undici/undici:13185:13
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async exports.sendMessage (/root/anonymous/controller/telegram/sendMessageController.js:19:21) {
[cause]: AggregateError [ETIMEDOUT]:
at internalConnectMultiple (node:net:1117:18)
at internalConnectMultiple (node:net:1185:5)
at Timeout.internalConnectMultipleTimeout (node:net:1711:5)
at listOnTimeout (node:internal/timers:596:11)
at process.processTimers (node:internal/timers:529:7) {
code: 'ETIMEDOUT',
[errors]: [ [Error], [Error] ]
}
}
这是我的代码(sendMessageController.js):
const dotenv = require("dotenv");
dotenv.config();
exports.sendMessage = async (req, res) => {
const { message } = req.body;
if (!req.body || Object.keys(req.body).length === 0) {
return res.status(400).json({
status: 400,
message: "Bad request",
});
}
try {
const token = process.env.TELEGRAM_TOKEN;
const url = process.env.TELEGRAM_API_URL;
const channel = process.env.TELEGRAM_CHANNEL_ID;
const request = await fetch(`${url}/bot${token}/sendMessage`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
chat_id: channel,
text: message.replace(/[_*[\]()~`>#+-=|{}.!-]/g, "\\$&"),
parse_mode: "MarkdownV2",
}),
});
const response = await request.json();
console.log(response);
res.status(200).json({ status: 200, message: "Success", data: response });
} catch (error) {
console.error(error);
res.status(500).json({ status: 500, message: "Internal server error" });
}
};
我使用 REST API 触发,问题出自此代码。
我期望的是提取工作正常,没有像本地主机那样失败。
好吧,显然我必须在正文之后添加
const request = await fetch(`${url}/bot${token}/sendMessage`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
chat_id: channel,
text: message.replace(/[_*[\]()~`>#+-=|{}.!-]/g, "\\$&"),
parse_mode: "MarkdownV2",
},
{
family: 4,
}
),
}
);
代码可以运行,但是安全吗?