You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js打卡命令开发需求:实现启动至结束的时长统计

优化Discord.js打卡命令:统计打卡总时长

核心实现思路

给每个用户维护打卡状态,触发命令时:

  • 未开始打卡则记录当前时间戳
  • 已开始打卡则计算时间差,转换为hours: h minutes: m seconds: s格式输出,同时清除打卡状态

完整代码示例

const { Client, GatewayIntentBits } = require('discord.js');
const moment = require('moment'); // 可选:用moment简化时间处理

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent
  ]
});

// 存储用户打卡状态:键为用户ID,值为打卡开始时间
const userClockins = new Map();

client.on('messageCreate', async (message) => {
  // 过滤非目标命令和机器人消息
  if (!message.content.startsWith('!baterponto') || message.author.bot) return;

  const userId = message.author.id;

  if (userClockins.has(userId)) {
    // 结束打卡流程
    const startTime = userClockins.get(userId);
    const endTime = new Date();
    userClockins.delete(userId);

    // 方式1:原生Date计算时长
    const diffMs = endTime.getTime() - startTime.getTime();
    const totalSeconds = Math.floor(diffMs / 1000);
    const hours = Math.floor(totalSeconds / 3600);
    const remainingSeconds = totalSeconds % 3600;
    const minutes = Math.floor(remainingSeconds / 60);
    const seconds = remainingSeconds % 60;

    // 方式2:使用moment计算时长(需安装moment依赖)
    // const duration = moment.duration(moment(endTime).diff(moment(startTime)));
    // const hours = duration.hours();
    // const minutes = duration.minutes();
    // const seconds = duration.seconds();

    // 发送格式化结果
    message.reply(`打卡结束!总时长:hours: ${hours} minutes: ${minutes} seconds: ${seconds}`);
  } else {
    // 启动打卡流程
    userClockins.set(userId, new Date());
    message.reply('打卡已启动,再次发送`!baterponto`即可结束并统计时长!');
  }
});

client.login('你的机器人Token');

关键细节说明

  • 用Map存储打卡状态:相比普通对象,Map更适配用户ID作为键的场景,避免键名冲突
  • 时长计算逻辑:
    • 原生方式通过毫秒差转总秒数,再拆分出小时、分钟、秒,确保数值为整数
    • Moment方式利用moment.duration直接提取时分秒,代码更简洁
  • 格式严格匹配要求:即使某部分为0(如不足1小时显示hours: 0),也保持指定输出格式不变

内容的提问来源于stack exchange,提问作者Kauã4op

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 21:39:19