如何获取discord.js v14.7.2机器人的最后重启时间
获取discord.js v14.7.2机器人的最后重启时间
有两种常用方案,根据你的需求选择:
方案1:基础内存记录(仅当前会话有效)
在机器人启动时直接记录当前时间,后续需要时调用即可,适合只需要查看本次启动时间的场景。
- 在主文件(如
index.js)顶部定义全局变量:
// 记录机器人启动时间 const botStartTime = new Date();
- 在命令中调用该变量,比如创建一个查询重启时间的 slash 命令:
const { SlashCommandBuilder } = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('restart-time') .setDescription('查看机器人最后重启时间'), async execute(interaction) { // 格式化时间为本地可读格式 const formattedTime = botStartTime.toLocaleString(); await interaction.reply(`机器人最后重启时间:${formattedTime}`); }, };
如果需要同时显示在线时长,可以扩展代码:
async execute(interaction) { const uptimeMs = Date.now() - botStartTime.getTime(); const uptime = new Date(uptimeMs); const days = uptime.getUTCDate() - 1; const hours = uptime.getUTCHours(); const minutes = uptime.getUTCMinutes(); const seconds = uptime.getUTCSeconds(); await interaction.reply( `最后重启时间:${botStartTime.toLocaleString()}\n` + `在线时长:${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒` ); }
方案2:持久化记录(保留历史重启记录)
如果需要机器人重启后仍能查看历史重启时间,可以将时间写入本地文件存储。
- 编写记录和读取重启时间的工具函数:
const fs = require('fs').promises; const path = require('path'); // 启动时记录重启时间到文件 async function logRestartTime() { const logPath = path.join(__dirname, 'restart-logs.json'); const newLog = { timestamp: new Date().toISOString() }; try { // 读取现有日志,不存在则创建空数组 let logs = []; try { const rawData = await fs.readFile(logPath, 'utf8'); logs = JSON.parse(rawData); } catch (err) {} logs.push(newLog); await fs.writeFile(logPath, JSON.stringify(logs, null, 2)); } catch (err) { console.error('记录重启时间失败:', err); } } // 获取最后一次重启时间 async function getLastRestart() { const logPath = path.join(__dirname, 'restart-logs.json'); try { const rawData = await fs.readFile(logPath, 'utf8'); const logs = JSON.parse(rawData); if (!logs.length) return null; // 转换为本地可读时间 return new Date(logs[logs.length - 1].timestamp).toLocaleString(); } catch (err) { console.error('读取重启记录失败:', err); return null; } }
- 在机器人登录前调用记录函数:
// 假设你的客户端定义为client client.on('ready', async () => { await logRestartTime(); console.log(`Logged in as ${client.user.tag}!`); });
- 在命令中使用读取函数:
async execute(interaction) { const lastRestart = await getLastRestart(); if (!lastRestart) { return interaction.reply('暂无重启记录'); } await interaction.reply(`机器人最后重启时间:${lastRestart}`); }
注意事项
- 方案1无需额外依赖,实现简单,但机器人重启后会丢失之前的记录。
- 方案2需要确保机器人有文件读写权限,避免因权限问题导致记录失败。
内容的提问来源于stack exchange,提问作者Nikhıł
相关产品推荐
相关产品推荐

