首页 > 解决方案 > 使用 discordJDA 等待消息未按预期工作

问题描述

我目前正在研究我的不和谐机器人。我遇到的一个问题是,我不知道如何让机器人在发送消息后等待用户回复。

我也试过在这里阅读关于使用 RestAction 的 git 文档:https ://github.com/DV8FromTheWorld/JDA/wiki/7)-Using-RestAction但它似乎没有提到任何关于实现类似的“等待”功能到 discord.js

我尝试编写代码来模仿这种效果:

public class EventHandler extends ListenerAdapter {

        private static final String PREFIX = "&";
        public static String[] args;


        public void sendMessage(String s, GuildMessageReceivedEvent event) {
            event
                    .getChannel()
                    .sendMessage(s)
                    .queue();
        }

        public void onGuildMessageReceived (GuildMessageReceivedEvent event) {

            args = event
                    .getMessage()
                    .getContentRaw()
                    .split(" "); 

        if (args[0].equalsIgnoreCase(PREFIX + "any_command")) {
            sendMessage("Type hello!");
            if (args[0].equalsIgnoreCase(PREFIX + "hello") {
               sendMessage("hello there!");
            }
        }
    }
}

主类:

import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;


public class Main {

    public static void main(String[] args) throws Exception {
        JDA jda = new JDABuilder(AccountType.BOT)
                .setToken("token goes here")
                .setAutoReconnect(true).build();

        try {
            jda.addEventListener(new EventHandler());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
} 

这不会注册在给出提示后键入的 hello 命令。我最好的猜测是条件永远不会满足,因为原始条件覆盖了即将到来的条件(args[0] 已经是 any_command)任何帮助将不胜感激!

标签: javadiscord

解决方案


我建议EventWaiter来自 JDA-Utilities ( https://github.com/JDA-Applications/JDA-Utilities/ )

快速查看源代码,看起来你需要这样的东西

EventWaiter waiter = new EventWaiter();
// SO wouldn't let me insert new lines for some reason.
waiter.waitForEvent(GuildMessageReceivedEvent.class, (event) -> event.getMessage().getContentRaw().equalsIgnoreCase("hello"), (event) -> event.getChannel().sendMessage("hello!").queue()));

推荐阅读