简体   繁体   中英

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.

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.

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.

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 .

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. This is for non-discord.js.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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