如何制作命令时间计数器

How to make a command time counter

我的问题是:如何在 discord.js

const Discord = require('discord.js');

exports.run = (client, message) => {
  var af = 0;

  a = setInterval(function(){
  console.log("Hi");
  af = af+1;

   if(af == 25){
     clearInterval(a);
  }
  console.log(af);
  }, 60000);
};

exports.help = {
  name: 'time',
  description: 'time?',
  usage: 'time'
};

我会这样做:当你执行 !count 时,你会节省服务器时间,当你执行 !time 时,你会发回这两个日期之间的差异。

伪代码:

var date;

if (command == 'count') {
  date = new Date();
  message.reply("Done");
}

if (command == 'time') {
  let result = require('pretty-ms')(date ? (new Date() - date) : 0);
  message.reply(result);
}

我正在使用 pretty-ms npm 包来格式化毫秒:docs & live demo.

当有人呼叫 !count 时,将当前日期存储在某处。 new Date() - date 将为您提供当前时间与您存储的时间之间的差异,以毫秒为单位。
请注意,如果命令位于不同的文件中,就像您发布的代码所显示的那样,您需要将日期存储在两个文件都可以访问的位置:解决方案之一是将日期存储为全局变量。

// by '...' I mean that you can put it wherever you want in the global object
global['...'].date = new Date():
new Date() - global['...'].date

编辑:Date class 解释
当您创建一个新的 Date 时,它会在您创建它时节省时间。这就像说 "!count 是在 04:20" 执行的。当你想检查已经过了多少时间时,你需要计算第一个日期减去当前日期:"!count was executed at 04:20。现在是05:40 ,所以差异是 05:40 - 04:20 = 01:20:从你第一次执行 !count" 开始已经过了 1 小时 20 分钟。转换为 new Date() - past_date = time_passed.
由于日期以毫秒为单位存储,因此差异以毫秒为单位:如果你想让它更具可读性,你可以使用函数作为 'pretty-ms' 包或类似的函数来格式化它。
关键概念是:

  • !count被调用时,你保存一个new Date()来锁定那个时间点
  • 当调用 !time 时,您可以通过 new Date() - past_date
  • 得到不同之处