【问题标题】:Adding a global timer for tmi.js integrated discord.js为 tmi.js 集成 discord.js 添加全局计时器
【发布时间】:2020-11-15 02:59:11
【问题描述】:

我正在尝试做一个 discord 机器人,它会监听多个 twitch 聊天中的命令,然后在 discord 上运行它们,同时使用 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);
    }
        
});

【问题讨论】:

  • 你可以实现一个throttle function来限制每X毫秒的调用次数。
  • 我已经尝试在try catch区域实现上述节流功能,但它使它不起作用。我错过了什么吗?

标签: javascript node.js discord.js twitch


【解决方案1】:

只是为了更新,我基本上从这里的异步等待函数中获取了一份传单: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 秒足以让机器人正确地离开不和谐而不会导致超时。不过,我仍然愿意接受更好的优化建议!

【讨论】:

    猜你喜欢
    • 2021-04-28
    • 2020-05-09
    • 1970-01-01
    • 2023-04-09
    • 2010-10-29
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    • 2021-06-03
    相关资源
    最近更新 更多