为我的 JDA Music Bot

问题描述

这是我第一次在这里提问,所以请原谅我在发布时犯的任何错误。另外我对编程有点陌生,所以请原谅我所做的任何不好的做法。

所以我想要做的是创建一个投票跳过命令来跳过我的 JDA discord 音乐机器人的当前歌曲。我的问题是我找不到计算选票的方法在这种情况下,我的机器人发送的消息中添加了反应)。

以下代码片段显示了我的尝试:

channel.sendMessage( builder.build() ).queue( (message) -> {
            message.addReaction(Emojis.upVote).queue();
            message.addReaction(Emojis.downVote).queue();

            this.waiter.waitForEvent(
                    
                    // The class the EventWaiter should listen for
                    GuildMessageReactionAddEvent.class,// Conditions
                    
                    // Todo Change event as GuildMessageReactionAddEvent doesn't provide a count for reactions
                    (evt) -> ((GuildMessageReactionAddEvent) evt).getReaction().getCount() >= 10
                    
                            && ((GuildMessageReactionAddEvent) evt).getReaction().getReactionEmote().getEmoji().equals(Emojis.upVote)
                            && evt.getMessageIdLong() == context.getMessage().getIdLong(),// Action if the conditions are fulfilled
                    (evt) -> skip(context),// Timeout after 1 minute
                    1L,TimeUnit.MINUTES,// Action after timeout
                    () -> channel.sendMessage("Not enough Votes! Track will be continued").queue());
        } );

我意识到 GuildMessageReactionAddEvent 不提供对消息的反应计数,因为它只检查添加到消息中的单个反应,这意味着我的尝试完全没有意义。

我对解决此问题的想法是使用一个 int 变量作为计数器,每次 GuildMessageReactionAddEvent 事件触发时,该计数器都会递增。现在,只要计数器达到所需的票数,歌曲就会被跳过,如果没有,则会出现超时,导致机器人发送“票数不足!”留言。

如果你们中的一些人能写一些关于如何解决这个问题的建议或只是提示,我真的很感激。

解决方法

你需要做这样的事情(这是一个草图,不是可编译的代码)

你需要记录投票数,所以你的谓词需要有副作用。

您可以在谓词 lambda 的范围内使用 AtomicInteger 执行此操作。

谓词的返回值取决于投票数。

       channel.sendMessage( builder.build() ).queue( (message) -> {
            final AtomicInteger voteCounter = new AtomicInteger();
            message.addReaction(Emojis.upvote).queue();
            message.addReaction(Emojis.downvote).queue();

            this.waiter.waitForEvent(

                    // The class the EventWaiter should listen for
                    GuildMessageReactionAddEvent.class,// Conditions

                    (evt) -> {
                        if (((GuildMessageReactionAddEvent) evt).getReaction().getReactionEmote().getEmoji().equals(Emojis.upvote)
                            && evt.getMessageIdLong() == context.getMessage().getIdLong()) {
                            voteCounter.incrementAndGet();
                        }
                        return voteCounter.get() > 10;
                    },// Action if the conditions are fullfilled
                    (evt) -> skip(context),// Timeout after 1 minute
                    1L,TimeUnit.MINUTES,// Action after timeout
                    () -> channel.sendMessage("Not enough votes! Track will be continued").queue());
        } );
    }