我创建了一个 bot js 命令,该命令每 5 秒更新一次网站上的状态,无论其是否在线。时间戳也显示当前时间,但由于某种原因,一段时间后它开始延迟两分钟,最后你知道它延迟了几个小时。我认为这与那 5 秒的状态检查有关。
const tcpp = require('tcp-ping');
const { EmbedBuilder } = require('discord.js');
let statusMessage = null;
module.exports = {
checkWeb: async (client) => {
try {
const website = {
name: "mysite",
url: "mysite.com",
port: 80
};
tcpp.probe(website.url, website.port, function(err, available) {
if (err) {
throw new Error(`Error probing website: ${err}`);
}
const status = available ? "🟢 Online" : "🔴 Offline";
const color = available ? "#00FF00" : "#FF0000";
const description = available ? `The ${website.url} is up and running.` : `The ${website.url} is offline.`;
const embed = new EmbedBuilder()
.setTitle(`Status of ${website.name}`)
.setDescription(`${description}\n\nStatus: ${status}\n\u200B`)
.setThumbnail('https://i.imgur.com/AfFp7pu.png')
.setTimestamp()
.setColor(color);
if (!statusMessage) {
client.channels.cache.get('1232582546932633610').send({ embeds: [embed] })
.then(message => {
statusMessage = message.id;
});
} else {
client.channels.cache.get('1232582546932633610').messages.fetch(statusMessage)
.then(message => {
message.edit({ embeds: [embed] });
})
.catch(console.error);
}
});
} catch (error) {
console.error(`Error checking website status: ${error}`);
} finally {
setTimeout(() => module.exports.checkWeb(client), 5 * 1000);
}
}
};
以下这些情况可能会导致出现延迟问题。
setTimeout
安排每 5 秒更新一次状态,JavaScript 可能会带来轻微的延迟。