【问题标题】:Get Uptime of Discord.JS bot获取 Discord.JS 机器人的正常运行时间
【发布时间】:2018-09-29 11:06:33
【问题描述】:
我现在正在为运行时创建一个 Discord 机器人命令,我想知道执行运行时的最紧凑(并且仍然正确)的方式是什么,以捕捉机器人实际在线的时间并以 24 小时格式返回。
【问题讨论】:
-
创建一个全局变量,在机器人启动时将 Date.now() 存储在其中,并在命令中从 Date.now() 中减去它,然后您将有毫秒。然后convert that.
标签:
javascript
node.js
discord
discord.js
【解决方案1】:
这是一个非常简单的解决方案,它返回人类可读的字符串。它使用pretty-ms module。
const prettyMilliseconds = require("pretty-ms");
message.channel.send(`Uptime: ${prettyMilliseconds(client.uptime)}`)
// 15d 11h 23m 20s
【解决方案2】:
更好的解决方案
const moment = require("moment");
require("moment-duration-format");
const duration = moment.duration(client.uptime).format(" D [days], H [hrs], m [mins], s [secs]");
console.log(duration);
//Output = 1 hr, 16 mins, 8 secs
【解决方案3】:
机器人启动时无需手动保存。您可以使用client.uptime,您将获得机器人启动了多少毫秒。
从那里你可以做这样的事情:
let totalSeconds = (client.uptime / 1000);
let days = Math.floor(totalSeconds / 86400);
totalSeconds %= 86400;
let hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
let minutes = Math.floor(totalSeconds / 60);
let seconds = Math.floor(totalSeconds % 60);
然后您就可以使用 days、hours、minutes 和 seconds。
let uptime = `${days} days, ${hours} hours, ${minutes} minutes and ${seconds} seconds`;
【解决方案4】:
你可以使用
var bruh = Date.now();
在代码的开头以及想要使用它时,使用
var bruhAfter = bruh - Date.now();
然后使用接受的代码,但使用 bruhAfter 而不是 client.uptime。
这是针对非 discord.js 的。