【发布时间】:2021-01-19 22:05:55
【问题描述】:
我正在尝试在 discord jda 中的最后一条消息之前获取消息。
我已经尝试过了,但它给了我一个 IndexOutOfBounds 异常。
event.getChannel().getHistory().getRetrievedHistory().get(1)
您能否向我解释一下为什么要这样做并指出正确的方向,以便我可以完成我的项目?谢谢。
【问题讨论】:
我正在尝试在 discord jda 中的最后一条消息之前获取消息。
我已经尝试过了,但它给了我一个 IndexOutOfBounds 异常。
event.getChannel().getHistory().getRetrievedHistory().get(1)
您能否向我解释一下为什么要这样做并指出正确的方向,以便我可以完成我的项目?谢谢。
【问题讨论】:
根据getRetrievedHistory()的documentation:
使用
retrievePast(int)、retrieveFuture(int)和MessageChannel.getHistoryAround(String, int)方法使用此 MessageHistory 对象从 Discord 检索到的所有消息的消息列表,从最新到最旧排序。如果它只是使用 MessageChannel.getHistory() 或类似方法创建的,则该字段将为空。 您首先必须检索消息。
所以你必须使用retrievePast(2) 来获取第二条最新消息:
channel.getHistory().retrievePast(2)
.map(messages -> messages.get(1)) // this assumes that the channel has at least 2 messages
.queue(message -> { // success callback
System.out.println("The second most recent message is: " + message.getContentDisplay();
});
请记住,队列是异步。这意味着这样的代码无法工作:
MessageHistory history = channel.getHistory();
history.retrievePast(2).queue(); // <-- schedules the request, its not done when it returns
List<Message> message = history.getRetrievedHistory(); // <-- this is still empty
【讨论】: