【问题标题】:Awaiting for message using discordJDA not working as intended使用 discordJDA 等待消息未按预期工作
【发布时间】:2019-05-25 07:46:28
【问题描述】:

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

我也尝试过阅读关于在此处使用 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) 任何帮助将不胜感激!

【问题讨论】:

    标签: java discord


    【解决方案1】:

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

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

    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()));
    

    【讨论】:

    • 我忘记添加的其他内容:您必须将 EventWaiter 添加为 JDA 的事件侦听器。 jda.addEventListener(waiter);
    • 是的,我意识到,在阅读了有关该问题的更多信息后,我将它实现到了我的 EventListener 类中。非常感谢!
    猜你喜欢
    • 2021-08-20
    • 2019-04-19
    • 2020-03-04
    • 2013-12-10
    • 2019-04-07
    • 2019-08-31
    • 2022-01-22
    • 2018-12-02
    • 1970-01-01
    相关资源
    最近更新 更多