[英]javascript : I want execute 1 command every X seconds
你好,我创建了一个小的 twitch 机器人,我想每 100 秒只执行一次以下条件,例如:
if (message.indexOf("emoji") !== -1) {
client.say(channel, `emoji party`);
}
但正如您所看到的,我还有其他类似的情况,所以我不希望我的整个机器人被 paralized 100 秒。 我希望每个条件都与时间无关
const tmi = require("tmi.js");
const client = new tmi.Client({
options: { debug: true, messagesLogLevel: "info" },
connection: {
reconnect: true,
secure: true
},
// Lack of the identity tags makes the bot anonymous and able to fetch messages from the channel
// for reading, supervison, spying or viewing purposes only
identity: {
username: `${process.env.TWITCH_BOT_USERNAME}`,
password: `oauth:${process.env.TWITCH_OAUTH_TOKEN}`
},
channels: ["channelName"]
});
client.connect().catch(console.error);
client.on("message", (channel, tags, message, self) => {
if (self) return;
if (message.indexOf("emoji") !== -1) {
client.say(channel, `emoji party`);
}
if (message.indexOf("LUL") !== -1) {
client.say(channel, `LUL LUL LUL LUL`);
}
});
谢谢你的帮助
SetInterval()
var intervalID = setInterval(myCallback, 500, 'Parameter 1', 'Parameter 2');
function myCallback(a, b)
{
// Your code here
// Parameters are purely optional.
console.log(a);
console.log(b);
}
来自 MDN:
setInterval() 是一个异步函数,这意味着定时器函数不会暂停函数堆栈中其他函数的执行。
您还可以使用clearInterval()
停止间隔
clearInterval(intervalID);
我认为这样的事情对你有用。 我不确定如何存储持久变量,但global
可能没问题。
global.lastEmojiPartyMs = null; // lets store last called time (milliseconds)
client.on("message", (channel, tags, message, self) => {
if (self) return;
if (message.indexOf("emoji") !== -1) {
const nowMs = Date.now();
if (
!global.lastEmojiPartyMs ||
nowMs - global.lastEmojiPartyMs >= 100 * 1000 // 100 seconds for example
) {
global.lastEmojiPartyMs = nowMs;
client.say(channel, `emoji party`);
}
}
if (message.indexOf("LUL") !== -1) {
client.say(channel, `LUL LUL LUL LUL`);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.