问题描述
这个问题混合了 discord js 和 javascript 混淆。我正在为 discord 服务器制作一个机器人,它需要接收当天的最后一条消息(在凌晨 12 点之前发送)并用 cookie 对其做出反应。我目前的方法是使用 setInterval()
每隔几秒检查一天中的时间,如果正好是凌晨 12 点,则获取最后一条消息并使用 cookie 对其做出反应。但是,出于某种原因,机器人会多次做出反应(因为它每次都可以对随机 cookie 表情符号做出反应),这并非有意为之。我的解决方案是检查当前对消息的反应,然后仅在没有反应时才作出反应,但不知何故,我无法使该解决方案起作用。
代码:
function cookieReaction(messages,cookies) {
let cookieCount;
let cookieMessage = messages.first();
const filter = (reaction,user) => user.id === client.user.id
// Check for "cookie" reactions (reactions from bot that are cookie emojis)
cookieMessage.awaitReactions(filter,{time: 1000}).then(collected => {
console.log(`${cookieMessage.content} has ${collected.size} cookies`);
this.cookieCount = collected.size;
console.log(`Cookie count inside is: ${this.cookieCount}`);
}).catch(console.error);
// If the message has no "cookie" reactions,then react with a random cookie emoji
console.log(`Cookie count outside is: ${cookieCount}`);
if(!this.cookieCount) cookieMessage.react(cookies[Math.floor(Math.random() * cookies.length)]).catch(console.error);
}
当我尝试在匿名函数(cookieCount
之后的函数)之外获取 cookieMessage.awaitReactions()
的值时,它一直返回 undefined。我也尝试过使用和不使用 this
关键字,并尝试在匿名函数中移动 cookieMessage.react()
语句,但这只会导致更奇怪的行为。简而言之,我似乎无法将 collected.size
的值作为匿名函数之外的 if 语句的条件。欢迎任何解决此问题的方法。
编辑 - 更新代码:
async function cookieReaction(messages,user) => user.id === client.user.id
// Check for "cookie" reactions (reactions from bot that are cookie emojis)
await cookieMessage.awaitReactions(filter,{time: 1000}).then(collected => {
console.log(`${cookieMessage.content} has ${collected.size} cookies`);
cookieCount = collected.size;
console.log(`Cookie count inside is: ${cookieCount}`);
}).catch(console.error);
// If the message has no "cookie" reactions,then react with a random cookie emoji
console.log(`Cookie count outside is: ${cookieCount}`);
if(cookieCount == 0) cookieMessage.react(cookies[Math.floor(Math.random() * cookies.length)]).catch(console.error);
}
cookieCount
现在存储了正确的值,但即使 if 语句说它不应该,机器人仍然对消息做出反应。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)