使用Node / TMI.js的命令冷却时间

时间:2017-01-19 16:30:44

标签: javascript node.js bots

我目前正在使用TMI.js,这是一个用于在Twitch中构建机器人的Node包。但是我可以真正使用冷却系统〜一旦你做了一个命令     !test这是一个测试命令。 你需要等待10秒才能再次触发,如果你试图在10秒内使用它我不想发生任何事情 谢谢。

2 个答案:

答案 0 :(得分:1)

写一个冷却包装函数:

// thisArg - context in which to call the function; 'this' in the function's body
// fn - function to execute on a cooldown
// timeout - number of milliseconds to wait before allowing fn to be called again
var cooldown = function (thisArg, fn, timeout) {
    var onCooldown = false;

    // return a function that can be called the same way as the wrapped function
    return function (/* args */) {

        // only call the original function if it is not on cooldown
        if (!onCooldown) {

            // not on cooldown, so call the function with the correct context
            // and the arguments with which this wrapper was called
            fn.apply(thisArg, arguments);

            // set the cooldown flag so subsequent calls will not execute the function
            onCooldown = true;

            // wait <timeout> milliseconds before allowing the function to be called again
            setTimeout(function () {
                onCooldown = false;
            }, timeout);
        }
    }
}

并像这样使用它:

var cooldownLog = cooldown(console, console.log, 5000);

cooldownLog('hello')   // => 'hello'
cooldownLog('hello')   // nothing happens
cooldownLog('hello')   // nothing happens

// > 5000ms later
cooldownLog('hello')   // => 'hello'
cooldownLog('hello')   // nothing happens

答案 1 :(得分:0)

通过使用 setTimeout({function}, x),您可以让函数在 x 毫秒后运行。

所以我们可以有一个名为 active 的布尔值。设置为 True,在命令运行一次后 10 秒(10000 毫秒)。

如果用户在 active == False 期间尝试使用我们的命令,那么我们可以告诉查看者该命令仍然处于超时状态

var active = False

// Whenever someone uses the command the below code is an example
client.on("message", (channel, userstate, message, self) => {
    if (message[0] == "!" && !(self)) {
        message = message.replace("!", "")
        switch (message){
            case "test":
                if (active) {

                    // Do command stuff

                    active = False
                    setTimeout(() => {
                        active = True
                    }, 10000)
                }
                else {

                    // Do stuff if the command is in cooldown

                }
                break
        }

    }
})