JDA 向私人频道发送通知

JDA send notification to private channels

我希望能够向我组中所有用户的私人频道发送通知 这是我的代码

public static void main(String[] args) throws LoginException {          
    final JDA bot =
                new JDABuilder(AccountType.BOT)
                        .setToken("secret")
                        .addEventListener(new DemoApplication())
                        .build();
}

@Override
public void onPrivateMessageReceived(final PrivateMessageReceivedEvent event) {
    if (event.getAuthor().isBot()) {
        return;
    }
    event.getJDA().getGuilds().get(0).getMembers().forEach(user->user.getUser().openPrivateChannel().queue());
    event.getJDA().getPrivateChannels().forEach(privateChannel -> privateChannel.sendMessage("ZDAROVA").queue());
}

但是只有这条私信的发件人才能收到消息。我错过了什么 ? 我使用版本为 3.8.3_462

的 JDA

您的代码使用了异步操作。异步任务是在另一个线程上启动并可能在稍后时间发生的任务。

Discord 具有操作客户端必须遵守的速率限制。由于这个原因以及 HTTP 请求需要一些时间的原因,请求在后台发生。您正在使用的称为 queue() 的方法只是将请求放在由工作线程耗尽的队列中。

openPrivateChannel() returns RestAction<PrivateChannel> 这意味着它将收到一个私有频道实例作为响应。可以使用 queue(Consumer<PrivateChannel> callback).

的回调参数与此响应进行交互
static void sendMessage(User user, String content) {
    user.openPrivateChannel().queue(channel -> { // this is a lambda expression
        // the channel is the successful response
        channel.sendMessage(content).queue();
    });
}

guild.getMembers().stream()
    .map(Member::getUser)
    .forEach(user -> sendMessage(user, "ZDAROVA"));

有关 RestAction 的更多信息,请参阅 JDA Wiki and Documentation