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

标签 javascript node.js bots

我目前正在使用 TMI.js,它是一个用于在 Twitch 中构建机器人的 Node 包。不过我真的可以使用冷却系统〜一旦你执行一个命令 !test 这是一个测试命令。 您需要等待 10 秒才能再次触发,如果您尝试在这 10 秒内使用它,我希望什么也不会发生。
谢谢。

最佳答案

编写冷却包装函数:

// 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

关于javascript - 使用 Node/TMI.js 命令的冷却时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41746916/

相关文章:

javascript - 如何缩小 KendoUI 饼图的大小?

javascript - 使用node js上传文件并将表单信息存储在数据库(mysql)中

python - 如何让 Discord 机器人在 on_message 中使用自定义表情符号响应消息

javascript - 简单的固定小部件

javascript - 将焦点放在其中包含 <a> 标记的第一个子 <li> 项目

javascript - jQuery 查找最接近的元素不起作用

javascript - Node.js Express 应用程序 : if cookie is present, 从服务器端向元素添加 CSS 类

javascript - 使用 JavaScript 返回数据

azure - Microsoft Bot Framework Composer 是否与 Dot Net 6.0 或 Dot Net 7.0 SDK 安装兼容?

Python IRC 机器人 : Set variables from channel reading