【发布时间】:2021-03-30 06:52:42
【问题描述】:
我有这段代码可以保持命令 !start 和 !end 之间的时间用于时间计数器命令,但我希望它发送类似于“您的时间是 14:23:02(小时、分钟、秒)和花费的全部时间是 27:24:32(小时、分钟、秒)"
这是我的代码:
/**
* A map from user IDs to start timestamps
* @type Map<string, number>
*/
const startTimestamps = new Map()
/**
* Pads a number to 2 digits.
* @param {number} value
* @returns {string}
*/
const pad2Digits = value => String(value).padStart(2, '0')
bot.on('message', async message => {
try {
if (message.content === '!start') {
// Sets the start time. This overrides any existing timers
// Date.now() is equivalent to new Date().getTime()
startTimestamps.set(message.author.id, Date.now())
await message.reply('Timer started.')
} else if (message.content === '!end') {
if (startTimestamps.has(message.author.id)) {
// The user has an existing timer to stop
// Calculate the timer result
const ms = Date.now() - startTimestamps.get(message.author.id)
const totalSecs = Math.floor(ms / 1000)
const totalMins = Math.floor(totalSecs / 60)
const hrs = Math.floor(totalMins / 60)
const mins = totalMins % 60
const secs = totalSecs % 60
// Reply with result
await message.reply(`Your time: ${hrs}:${pad2Digits(mins)}:${pad2Digits(secs)}`)
// Remove timestamp from map
startTimestamps.delete(message.author.id)
} else {
// The user does not have an existing timer
await message.reply('You need to use `!start` first!')
}
}
} catch (error) {
console.error(error)
}
})
【问题讨论】:
-
我不确定我是否能理解它。什么是“你的时间”和“花费的全部时间”?你想有一个总时间,所以当他们第二次启动和结束计时器时,他们可以看到这次花费的时间以及这一次和上一次的总和?
-
我想在使用 !start 然后 !end 计算这些命令之间的时间,例如当我再做一次时,我想制作“!myname time”并显示所有时间我已经在那个命令中花费了
标签: javascript node.js discord discord.js