我试图创建一个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
1条答案
按热度按时间toiithl61#
创建一个闭包函数,在其中存储超时变量。这样做使您能够存储
timeout
安全无需创建全局变量来存储它。在回调函数中,首先检查作者的id是否匹配。如果超时,请清除超时并将其设置为
null
. 然后检查timeout
等于null
然后启动计时器。因此,现在计时器将在第一次调用函数时启动,并在每次找到您要查找的id为的用户时重新启动。
要设置此设置,请首先调用
createClearChannel
函数并传递下面的参数。将结果存储在execcmd
并在消息进入时调用该函数。(您可以忽略这些参数,只需对用户的频道名称和id进行硬编码,但通过这样做,您可以使函数更灵活,以便也可以用于其他情况。)
重要提示:
createClearChannel
应该只调用一次。所以不要创建一个新的execcmd
当收到每条消息时,但每次都使用相同的消息。