首页 > 解决方案 > 为 tmi.js 集成 discord.js 添加全局计时器

问题描述

我正在尝试做一个不和谐的机器人来监听多个抽搐聊天的命令,然后在不和谐上运行它们,同时使用 tmi.js 和 discord.js。目前它正在工作,但我似乎无法在命令本身上添加全局冷却时间以防止垃圾邮件。起初我尝试为每个命令添加一个 cd 计时器,但我无法让它工作,因此决定尝试制作一个全局 cd 但仍然无济于事。我做错了什么吗?

twitch.on('message', (channel, tags, message, self) => {
    if(!message.startsWith(prefix) || self) return;
    const args = (message.slice(prefix.length).trim().split(/ +/));
    const commandName = args.shift().toLowerCase();
    
    if (!twitch.commands.has(commandName)) return;
    const command = twitch.commands.get(commandName);
}
    try {
        command.execute(bot, botChannel, vcChannel, isReady);
    } catch (error){
        console.error(error);
    }
        
});

标签: javascriptnode.jsdiscord.jstwitch

解决方案


只是为了更新,我基本上从这里的异步等待函数中获取了一份传单:https ://stackoverflow.com/a/54772517/14637034 然后,我修改了代码:

const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => {
    setTimeout(() => {
        cb();
        resolve();
    }, timeout);
});
const doStuffAsync = async () => {
    await setAsyncTimeout(() => {
        isReady = true;
        console.log(isReady);
    }, 10000);};

twitch.on('message', (channel, tags, message, self) => {
    if(!message.startsWith(prefix) || self) return;
    const args = (message.slice(prefix.length).trim().split(/ +/));
    const commandName = args.shift().toLowerCase();
    
    if (!twitch.commands.has(commandName)) return;
    if (isReady){
        const command = twitch.commands.get(commandName);
        isReady = false;
        try {
            command.execute(bot, botChannel, vcChannel);
        } catch (error){
            console.error(error);
        }
        doStuffAsync();
    }
});

现在似乎可以工作,因为 10 秒足够长的时间让机器人正确地离开不和谐而不会导致超时。不过,我仍然愿意接受更好的优化建议!


推荐阅读