如何使机器人充电硬币,而不管用户在语音通道中的状态如何



我正在用硬币系统制作一个机器人,一个人已经帮助了我(非常感谢,@Federico格兰迪 (,以便机器人检查语音通道中的用户以及他在那里的数量。现在我不知道如何在一分钟后立即让机器人列出硬币,而不是在用户注销时。

let coins = require("./coins.json");
let voiceStates = {}
bot.on('voiceStateUpdate', (oldState, newState) => {
let { id } = oldState
if (!oldState.channel) {
console.log('user joined voice channel');
voiceStates[id] = new Date()
} else if (!newState.channel) {
console.log('user left voice channel')
let now = new Date()
let joined = voiceStates[id] || new Date()
let dateDiff = now.getTime() - joined.getTime();
if (oldState.selfMute === true && newState.selfMute === true){
console.log('2');
}
if (dateDiff > 60 * 1000) {
console.log('user earned 200 coins');
coins[message.author.id] = {
coins: coins[message.author.id].coins + 200
};
}
}
});

试试这个:

let coins = require("./coins.json");
let voiceStates = {};
bot.on('voiceStateUpdate', (oldState, newState) => {
let { id } = oldState;
if (!oldState.channel) {
console.log('user joined voice channel');
voiceStates[id] = { joined: new Date() };
// If the user is not muted...
if (!newState.selfMute) {
// ...execute a callback a minute later (this may be cancelled: see below)
voiceStates[id].timeout = setTimeout(() => {
// charge the coins
// do whatever after the user has been on the channel unmuted for a minute
}, 60000);
}
} else if (!newState.channel || newState.selfMute) {
// If the user left the channel or muted themselves and there is a timeout...
if (voiceStates[id].timeout) {
// ...cancel the timeout
clearTimeout(voiceStates[id].timeout);
voiceStates[id].timeout = undefined;
}
if (!newState.channel) {
// rest of your code for if the user left the channel...
console.log('user left voice channel');
let now = new Date();
// Only difference from your code is here
let joined = voiceStates[id] && voiceStates[id].joined || new Date();
let dateDiff = now.getTime() - joined.getTime();
if (oldState.selfMute === true && newState.selfMute === true) {
console.log('2');
}
if (dateDiff > 60 * 1000) {
console.log('user earned 200 coins');
coins[message.author.id] = {
coins: coins[message.author.id].coins + 200
};
}
}
}
});

这使用setTimeout在一分钟后为硬币充电。如果用户离开频道或自行静音,此计时器将被取消/清除。

最新更新