【问题标题】:JDA send notification to private channelsJDA 向私人渠道发送通知
【发布时间】:2019-09-09 16:42:39
【问题描述】:

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

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

【问题讨论】:

    标签: java discord discord-jda


    【解决方案1】:

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

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

    openPrivateChannel() 返回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 WikiDocumentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多