cleartimeout函数,用于在与discord.js一起使用时不工作

nsc4cvqm  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(283)

我试图创建一个bot,在调用execcmd()函数10分钟后删除一个通道(“常规”),但如果 msg 由具有“idofsomeuser”的人发送,则应取消上一次超时并再次启动计时器。但它不起作用。

function execcmd(msg) {
  let ID = msg.author.id
  let chan = msg.guild.channels.cache.find(
    (channel) => channel.name === 'general'
  );
  x = 'idofsomeuser'
  if (ID == x) {
    clearTimeout(x);
    ID = setTimeout(() => {
      chan.delete();
    }, 600000); //10min 
  } else {
    x = setTimeout(() => {
      chan.delete();
    }, 600000);
  }
}
execcmd(msg); //msg is received by client and passed here
toiithl6

toiithl61#

创建一个闭包函数,在其中存储超时变量。这样做使您能够存储 timeout 安全无需创建全局变量来存储它。
在回调函数中,首先检查作者的id是否匹配。如果超时,请清除超时并将其设置为 null . 然后检查 timeout 等于 null 然后启动计时器。
因此,现在计时器将在第一次调用函数时启动,并在每次找到您要查找的id为的用户时重新启动。

function createClearChannel(channelName, authorId) {
  let timeout = null;
  const timeoutDuration = 1000 * 60 * 10;

  return function (msg) {
    const isAuthor = authorId === msg.author.id;
    const channel = msg.guild.channels.cache.find(
      channel => channel.name === channelName
    );

    if (isAuthor) {
      clearTimeout(timeout);
      timeout = null;
    }

    if (timeout === null) {
      timeout = setTimeout(channel.delete, timoutDuration);
    }
  };
}

要设置此设置,请首先调用 createClearChannel 函数并传递下面的参数。将结果存储在 execcmd 并在消息进入时调用该函数。
(您可以忽略这些参数,只需对用户的频道名称和id进行硬编码,但通过这样做,您可以使函数更灵活,以便也可以用于其他情况。)
重要提示: createClearChannel 应该只调用一次。所以不要创建一个新的 execcmd 当收到每条消息时,但每次都使用相同的消息。

const execcmd = createClearChannel('general', 'idofsomeuser');
execcmd(msg);

相关问题