如何让Twitch Bot各触发条件独立定时执行且不阻塞
实现独立冷却的Twitch Bot触发控制
你可以通过维护一个冷却状态对象,为每个触发规则单独记录上次执行时间,这样就能实现各规则冷却互不干扰,且不会阻塞Bot的正常运行。
修改后的完整代码
const tmi = require("tmi.js"); const client = new tmi.Client({ options: { debug: true, messagesLogLevel: "info" }, connection: { reconnect: true, secure: true }, identity: { username: `${process.env.TWITCH_BOT_USERNAME}`, password: `oauth:${process.env.TWITCH_OAUTH_TOKEN}` }, channels: ["channelName"] }); client.connect().catch(console.error); // 定义各规则的冷却配置:键是规则标识,值是冷却时长(毫秒)+上次执行时间 const cooldowns = { emojiParty: { cooldownMs: 100 * 1000, // 100秒 lastExecuted: 0 }, lulSpam: { cooldownMs: 50 * 1000, // 可给LUL设置独立冷却,比如50秒 lastExecuted: 0 } }; // 检查冷却的辅助函数 function canExecute(ruleKey) { const now = Date.now(); const rule = cooldowns[ruleKey]; if (now - rule.lastExecuted >= rule.cooldownMs) { rule.lastExecuted = now; return true; } return false; } client.on("message", (channel, tags, message, self) => { if (self) return; // emoji触发规则:先检查冷却 if (message.indexOf("emoji") !== -1 && canExecute("emojiParty")) { client.say(channel, `emoji party`); } // LUL触发规则:独立冷却判断 if (message.indexOf("LUL") !== -1 && canExecute("lulSpam")) { client.say(channel, `LUL LUL LUL LUL`); } });
关键说明
- 冷却状态对象:
cooldowns里每个条目对应一个触发规则,你可以自由调整每个规则的冷却时长,相互完全独立。 - 辅助函数
canExecute:负责判断当前时间是否超过上次执行的冷却间隔,满足条件就更新上次执行时间并返回true,否则返回false。 - 非阻塞逻辑:整个过程都是异步的,不会暂停Bot的其他事件处理,其他消息和规则依然能正常响应。
后续如果要加新的触发规则,只需要在cooldowns里新增条目,然后在message事件里调用canExecute做检查即可。
内容的提问来源于stack exchange,提问作者Cooxy
相关产品推荐
相关产品推荐

