简体   繁体   English

如何等待反应然后才发送消息 [discord.js]

[英]How to wait for reaction and only then send message [discord.js]

I have a message that my bots sends (ban command) and then reacts to, then the bot checks the reaction and sends another message and reacts to it as well.我有一条消息,我的机器人发送(禁止命令)然后做出反应,然后机器人检查反应并发送另一条消息并对其做出反应。 Anyway, after that the bot should send a confirmation messages and that's it.无论如何,在那之后机器人应该发送确认消息,就是这样。 But, the bot sends the message right after it sends the first messages, without waiting for a reaction.但是,机器人在发送第一条消息后立即发送消息,无需等待反应。 How can I fix this?我怎样才能解决这个问题?

(the last message [and GuildMember#ban] being sent right after the first message that although it should wait for a reaction): (最后一条消息 [和 GuildMember#ban] 在第一条消息之后立即发送,尽管它应该等待反应):

bannedUser.ban({ days: banDuration, reason: banReason }).catch(err => {

    console.log(err)
    message.channel.send(`An error occured: ${err}`)
})

message.channel.send({ embed: banConfirmation })

the whole thing:整个东西:

        let bannedUser = message.mentions.members.first()
        let banDuration;
        let banReason;

        const noPermsEmbed = new Discord.MessageEmbed()
            .setTitle(":x: You do not have permission to perform this command!")
            .setColor(botconfig.colors.err)

        const UserDoesNotExistEmbed = new Discord.MessageEmbed()
            .setTitle(":warning: This user is not a member of this server.")
            .setColor(botconfig.colors.warn)

        const banEmbedReason = new Discord.MessageEmbed()
            .setTitle(`You are about to ban ${bannedUser.username}, first pick a reason for the ban.`)
            .setDescription("Please pick a reason for your ban first")
            .addFields({ name: ':regional_indicator_a: Use of bad language', value: 'Ban the user for use of inappropriate language in the server' }, { name: ':regional_indicator_b: Insulting a member', value: 'Ban the user for insulting memebers on the server for any reason' }, { name: ':regional_indicator_c: Spamming in the server', value: 'Ban the user for spamming messages on the server' }, { name: ':regional_indicator_d: NSFW/harmful/inappropriate content', value: 'Ban the user for sending inappropriate content on the server' }, { name: ':regional_indicator_e: Other..', value: 'For a differnet reason, write the reason in chat, like "$banreason <reason>"' }, { name: ':x: None', value: '\u200b' }, )
            .setColor(botconfig.colors.err)

        const banEmbedDuration = new Discord.MessageEmbed()
            .setTitle(`Now, please pick a duration for the ban`)
            .setDescription("Please pick a duration for your ban first")
            .addFields({ name: ':regional_indicator_a: 1 day', value: '\u200b' }, { name: ':regional_indicator_b: 3 days', value: '\u200b' }, { name: ':regional_indicator_c: 7 days', value: '\u200b' }, { name: ':regional_indicator_d: 14 days', value: '\u200b' }, { name: ':regional_indicator_e: 28 days', value: '\u200b' }, { name: ':infinity: Forever', value: '\u200b' }, )
            .setColor(botconfig.colors.err)

        const banConfirmation = new Discord.MessageEmbed()
            .setTitle(`You sucessfully banned ${bannedUser.username}.`)
            .setDescription(`You have sucessfuly banned ${bannedUser} from the server.`)
            .addFields({ name: ':timer: Ban duration:', value: `${banDuration} days. (0 days = forever)` }, { name: ':page_with_curl:', value: `"${banReason}"` })
            .setColor(botconfig.colors.success)

        if (!message.member.hasPermission(['BAN_MEMBERS'])) {
            message.channel.send(noPermsEmbed)
            return
        }

        if (!message.guild.member(bannedUser)) {
            message.channel.send(UserDoesNotExistEmbed)
            return
        }

        message.channel.send({ embed: banEmbedReason }).then(embedMessage => {

            embedMessage.react("🇦");
            embedMessage.react("🇧");
            embedMessage.react("🇨");
            embedMessage.react("🇩");
            embedMessage.react("❌");

            const reasonFilter = (reaction, user) => {
                return ['🇦', '🇧', '🇨', '🇩', '❌'].includes(reaction.emoji.name) && user.id === message.author.id;
            };

            embedMessage.awaitReactions(reasonFilter, { max: 1, time: 120000 }).then(collected => {

                message.channel.send({ embed: banEmbedDuration }).then(embedMessage => {

                    embedMessage.react("🇦");
                    embedMessage.react("🇧");
                    embedMessage.react("🇨");
                    embedMessage.react("🇩");
                    embedMessage.react("🇪");
                    embedMessage.react("♾️");

                    const durationFilter = (reaction, user) => {
                        return ['🇦', '🇧', '🇨', '🇩', '🇪', '♾️'].includes(reaction.emoji.name) && user.id === message.author.id;
                    };

                    embedMessage.awaitReactions(durationFilter, { max: 1, time: 120000 }).then(collected => {

                        const durationReaction = collected.first()

                        if (durationReaction.emoji.name === '🇦') {
                            banDuration = 1
                        } else if (durationReaction.emoji.name === '🇧') {
                            banDuration = 3
                        } else if (durationReaction.emoji.name === '🇨') {
                            banDuration = 7
                        } else if (durationReaction.emoji.name === '🇩') {
                            banDuration = 14
                        } else if (durationReaction.emoji.name === '🇪') {
                            banDuration = 28
                        } else if (durationReaction.emoji.name === '♾️') {
                            banDuration = 0 //infinite
                        }
                    })
                })

                const reasonReaction = collected.first()

                if (reasonReaction.emoji.name === '🇦') {
                    banReason = "Use of bad language"
                } else if (reasonReaction.emoji.name === '🇧') {
                    banReason = "Insulting a member"
                } else if (reasonReaction.emoji.name === '🇨') {
                    banReason = "Spamming in the server"
                } else if (reasonReaction.emoji.name === '🇩') {
                    banReason = "NSFW/harmful/inappropriate content"
                } else if (reasonReaction.emoji.name === '❌') {
                    banReason = "None specified"
                }
            })
        })

        bannedUser.ban({ days: banDuration, reason: banReason }).catch(err => {

            console.log(err)
            message.channel.send(`An error occured: ${err}`)
        })

        message.channel.send({ embed: banConfirmation })

    }

(the undefined(s) in the picture are not related to the problem, it's just that the green stripe message get's sent before the user can react to the first message. i fixed the undefined problem already) (图中的未定义与问题无关,只是在用户对第一条消息做出反应之前发送了绿色条纹消息。我已经修复了未定义的问题)

It results with:结果是:

在此处输入图片说明

updated code:更新代码:

const Discord = require("discord.js")
const botconfig = require("../botconfig.json")

module.exports = {
    name: 'ban',
    description: 'Bans a user from your server.',
    execute(message, args) {

        let bannedUser = message.mentions.members.first()
        let banDuration;
        let banReason;

        const noPermsEmbed = new Discord.MessageEmbed()
            .setTitle(":x: You do not have permission to perform this command!")
            .setColor(botconfig.colors.err)

        const UserDoesNotExistEmbed = new Discord.MessageEmbed()
            .setTitle(":warning: This user is not a member of this server.")
            .setColor(botconfig.colors.warn)

        const banEmbedReason = new Discord.MessageEmbed()
            .setTitle(`You are about to ban ${bannedUser.user.username}, first pick a reason for the ban.`)
            .setDescription("Please pick a reason for your ban first")
            .addFields({ name: ':regional_indicator_a: Use of bad language', value: 'Ban the user for use of inappropriate language in the server' }, { name: ':regional_indicator_b: Insulting a member', value: 'Ban the user for insulting memebers on the server for any reason' }, { name: ':regional_indicator_c: Spamming in the server', value: 'Ban the user for spamming messages on the server' }, { name: ':regional_indicator_d: NSFW/harmful/inappropriate content', value: 'Ban the user for sending inappropriate content on the server' }, { name: ':regional_indicator_e: Other..', value: 'For a differnet reason, write the reason in chat, like "$banreason <reason>"' }, { name: ':x: None', value: '\u200b' }, )
            .setColor(botconfig.colors.err)

        const banEmbedDuration = new Discord.MessageEmbed()
            .setTitle(`Now, please pick a duration for the ban`)
            .setDescription("Please pick a duration for your ban first")
            .addFields({ name: ':regional_indicator_a: 1 day', value: '\u200b' }, { name: ':regional_indicator_b: 3 days', value: '\u200b' }, { name: ':regional_indicator_c: 7 days', value: '\u200b' }, { name: ':regional_indicator_d: 14 days', value: '\u200b' }, { name: ':regional_indicator_e: 28 days', value: '\u200b' }, { name: ':infinity: Forever', value: '\u200b' }, )
            .setColor(botconfig.colors.err)

        const banConfirmation = new Discord.MessageEmbed()
            .setTitle(`You sucessfully banned ${bannedUser.user.username}.`)
            .setDescription(`You have sucessfuly banned ${bannedUser} from the server.`)
            .addFields({ name: ':timer: Ban duration:', value: `${banDuration} days. (0 days = forever)` }, { name: ':page_with_curl: Ban reason:', value: `"${banReason}"` })
            .setColor(botconfig.colors.success)

        if (!message.member.hasPermission(['BAN_MEMBERS'])) {
            message.channel.send(noPermsEmbed)
            return
        }

        if (!message.guild.member(bannedUser)) {
            message.channel.send(UserDoesNotExistEmbed)
            return
        }

        message.channel.send({ embed: banEmbedReason }).then(embedMessage => {

            const reasonFilter = (reaction, user) => {
                return ['🇦', '🇧', '🇨', '🇩', '❌'].includes(reaction.emoji.name) && user.id === message.author.id;
            };

            embedMessage.react("🇦")
                .then(() => embedMessage.react("🇧"))
                .then(() => embedMessage.react("🇨"))
                .then(() => embedMessage.react("🇩"))
                .then(() => embedMessage.react("❌"))
                .then(() => {
                    embedMessage.awaitReactions(reasonFilter, { max: 1, time: 120000 }).then(collected => {

                        message.channel.send({ embed: banEmbedDuration }).then(embedMessage => {

                            embedMessage.react("🇦");
                            embedMessage.react("🇧");
                            embedMessage.react("🇨");
                            embedMessage.react("🇩");
                            embedMessage.react("🇪");
                            embedMessage.react("♾️");

                            const durationFilter = (reaction, user) => {
                                return ['🇦', '🇧', '🇨', '🇩', '🇪', '♾️'].includes(reaction.emoji.name) && user.id === message.author.id;
                            };

                            embedMessage.awaitReactions(durationFilter, { max: 1, time: 120000 }).then(collected => {

                                const durationReaction = collected.first()

                                if (durationReaction.emoji.name === '🇦') {
                                    banDuration = 1
                                } else if (durationReaction.emoji.name === '🇧') {
                                    banDuration = 3
                                } else if (durationReaction.emoji.name === '🇨') {
                                    banDuration = 7
                                } else if (durationReaction.emoji.name === '🇩') {
                                    banDuration = 14
                                } else if (durationReaction.emoji.name === '🇪') {
                                    banDuration = 28
                                } else if (durationReaction.emoji.name === '♾️') {
                                    banDuration = 0 //infinite
                                }
                            })
                        })

                        const reasonReaction = collected.first()

                        if (reasonReaction.emoji.name === '🇦') {
                            banReason = "Use of bad language"
                        } else if (reasonReaction.emoji.name === '🇧') {
                            banReason = "Insulting a member"
                        } else if (reasonReaction.emoji.name === '🇨') {
                            banReason = "Spamming in the server"
                        } else if (reasonReaction.emoji.name === '🇩') {
                            banReason = "NSFW/harmful/inappropriate content"
                        } else if (reasonReaction.emoji.name === '❌') {
                            banReason = "None specified"
                        }
                    })
                })
        }).then(() => {

            bannedUser.ban({ days: banDuration, reason: banReason }).catch(err => {
                console.log(err)
                message.channel.send(`An error occured: ${err}`)
            })

            message.channel.send({ embed: banConfirmation })
        })

    }
}

Be sure to wait for your bot to put on the reactions before waiting for them, otherwise it will detect itself.在等待它们之前一定要等待你的机器人做出反应,否则它会检测到自己。 (Using the .react function is basically sending a promise, and it can finish after your await starts.) (使用 .react 函数基本上是发送一个 promise,它可以在您的 await 开始后完成。)

You can do this in such way:您可以通过以下方式执行此操作:

message.react('🍎')
    .then(() => message.react('🍊'))
    .then(() => message.react('🍇'))
    .then(() => message.awaitReactions(<...>).then((...) => {...})

(It's only some pseudo code.) (这只是一些伪代码。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM