简体   繁体   English

获取 Discord.JS 机器人的正常运行时间

[英]Get Uptime of Discord.JS bot

I am right now making a Discord bot command for runtime, I was wondering what the most compacted (and still correct) way of doing an runtime to catch how long the bot has actually been online and return it in 24hr format.我现在正在为运行时制作一个 Discord 机器人命令,我想知道执行运行时最紧凑(并且仍然正确)的方式是什么来捕捉机器人实际在线的时间并以 24 小时格式返回它。

You don't need to manually save when the bot started.您无需在机器人启动时手动保存。 You can use client.uptime and you will get how many milliseconds the bot is up.您可以使用client.uptime ,您将获得机器人启动的毫秒数

From there you can do something like this:从那里你可以做这样的事情:

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);

Then you'll have days , hours , minutes and seconds ready to use.然后您就可以使用dayshoursminutesseconds

let uptime = `${days} days, ${hours} hours, ${minutes} minutes and ${seconds} seconds`;

Much better solution更好的解决方案

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

Here's a very simple solution that returns a human-readable string.这是一个非常简单的解决方案,它返回一个人类可读的字符串。 It uses the pretty-ms module .它使用漂亮的 ms 模块

const prettyMilliseconds = require("pretty-ms");
message.channel.send(`Uptime: ${prettyMilliseconds(client.uptime)}`)
// 15d 11h 23m 20s
const pixapi = require("pixapi");
let ms = pixapi.formatTimer(client.uptime);
message.reply(`${ms.daystotal}d ${ms.hours}h ${ms.minutes}m ${ms.seconds}s`);

You could use你可以用

var bruh = Date.now();

at the start of your code and when you want to use it, use在代码的开头以及要使用它时,请使用

var bruhAfter = bruh - Date.now();

Then use the accepted code, but use bruhAfter instead of client.uptime.然后使用接受的代码,但使用 bruhAfter 而不是 client.uptime。 This is for non-discord.js.这是针对非 discord.js 的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM