微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何获取消息的当前反应并在 Discord JS 中相应地使用它?

如何解决如何获取消息的当前反应并在 Discord JS 中相应地使用它?

这个问题混合了 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 举报,一经查实,本站将立刻删除。