简体   繁体   English

如何在JDA事件监听器中访问数据?

[英]How do I access Data inside a JDA event Listener?

I'm trying to do a discordBOT using Java and JDA. 我正在尝试使用Java和JDA做一个discordBOT。 I've tried to work with them for several hours now and I don't get it to work. 我已经尝试与他们合作了几个小时,但我没有让它起作用。 My Bot needs to process data which depends on the user. 我的机器人程序需要处理取决于用户的数据。 In JDA's event Handlers you cannot return any data types since they extend the ListenerAdapter. 在JDA的事件处理程序中,您不能返回任何数据类型,因为它们扩展了ListenerAdapter。 Its my first time working with Eventlisteners and I already googled a lot. 这是我第一次与Eventlisteners合作,而我已经在Google上搜索了很多。

Create a ListenerAdapter and associate it to the JDA instance. 创建一个ListenerAdapter并将其关联到JDA实例。 I'll show you an example code so you can understand: 我将向您展示一个示例代码,以便您可以理解:

    /**
     * Logs the bot into Discord and sets the event listeners.
     */
    public static void launchJDA(String botToken) {
        try {
            jdaInstance = new JDABuilder(AccountType.BOT).setToken(loadToken()).build().awaitReady();
            jdaInstance.addEventListener(new EventsManager());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
public class EventsManager extends ListenerAdapter {

    @Override
    public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
        //Do what you want with the event here, for example replying with the message received:
        String msg = event.getMessage().getContentDisplay();
        event.getChannel().sendMessage(msg).queue();
    }
}

I'm not sure if this is what you are asking for, but your class needs to extend from ListenerAdapter. 我不确定这是否是您要的,但是您的类需要从ListenerAdapter扩展。

public class yourClass extends ListenerAdapter { 
    //Your code. 
}

Inside a class you can use the method you need for doing what you want. 在类内部,您可以使用所需的方法来执行所需的操作。 eg 例如

@Override
public void onMessageReceived(MessageReceivedEvent event) {
    //Your code again.
}

If you want to transfer data between two classes, you can use your own methods and just give the event to it. 如果要在两个类之间传输数据,则可以使用自己的方法并将事件赋予它。

[Method1]
public static void yourMethod(MessageReceivedEvent event) {
    //Your code.
}

[Method2]
@Override
public void onMessageReceived(MessageReceivedEvent event) {
    yourMethod(event);
}

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

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