我有个问题。 Ima使用Java Discord API(JDA)制作了一个机器人。因此,当新用户加入服务器时,我需要运行。机器人发送消息。但是我的代码无法正常工作。

码:

public class UserJoinModule extends ListenerAdapter {
    public void onGuildMemberJoined(GuildMemberJoinEvent event) throws LoginException {
        String user = event.getMember().getAsMention();
        JDA client = new JDABuilder("awesome token").build();
        final List<TextChannel> channels = client.getTextChannelsByName("awesome channel name", true);
        for (final TextChannel ch : channels) {
            ch.sendMessage("New member joined: " + user).queue();
        }
    }

}


因此,当新用户加入我的公会时,它不会发送消息是不是正常工作。你能帮助我吗?

我也将其添加到事件监听器

最佳答案

您的代码应如下所示:

public class UserJoinModule extends ListenerAdapter {
    @Override // USE THIS WHEN YOU WANT TO OVERRIDE A METHOD
    public void onGuildMemberJoin(GuildMemberJoinEvent event) {
        String user = event.getMember().getAsMention();
        JDA client = event.getJDA(); // DO NOT CREATE A NEW JDA INSTANCE EVERY TIME
        List<TextChannel> channels = client.getTextChannelsByName("awesome channel name", true);
        for (TextChannel ch : channels) {
            ch.sendMessage("New member joined: " + user).queue();
        }
    }
}


而且,您必须在JDABuilder实例中注册此侦听器,最好在整个代码库中只有一个。请参见addEventListeners

07-26 06:09