英文:
How to add multiple reactions to embed Discord JDA
问题
以下是翻译的内容:
我正在使用JDA发送一个Discord嵌入,并使用以下代码:
event.getChannel().sendMessage(image.build()).queue();
如果我想要在消息上添加单个反应,可以将代码更改为:
event.getChannel().sendMessage(image.build()).complete().addReaction("✔").queue();
如何在这个消息上添加多个反应?
英文:
I am sending a discord embed using JDA and the following code:
event.getChannel().sendMessage(image.build()).queue();
I can add a single reaction to the message by changing the code to this:
event.getChannel().sendMessage(image.build()).complete().addReaction("✔").queue();
How can I add multiple reactions to this message?
答案1
得分: 1
你可以使用complete()
返回的Message
对象多次。
所以,你可以依次发送反应:
Message msg = event.getChannel().sendMessage(image.build()).complete();
msg.addReaction("✔").queue();
msg.addReaction("+1").queue();
这使用了complete
,但会等待消息发送完成。在此期间不会执行任何监听器。
这意味着你的机器人会等待,其他用户的命令只会在消息发送后执行。
为了解决这个问题,你可以使用.queue()
与 lambda 表达式:
event.getChannel().sendMessage(image.build()).queue(msg -> {
msg.addReaction("✔").queue();
msg.addReaction("+1").queue();
});
如果你想多次执行这个操作,可以编写一个方法:
public void sendMessageWithReactions(MessageChannel channel, MessageEmbed embed, String... reactions){
channel.sendMessage(embed).queue(msg -> {
for (String reaction : reactions){
msg.addReaction(reaction).queue();
}
});
}
你可以像这样调用这个方法:sendMessageWithReactions(event.getChannel(), image.build(), "✔", "+1");
英文:
You can use the Message
object returned by complete()
multiple times.
So, you can just send the reactions one after another:
Message msg=event.getChannel().sendMessage(image.build()).complete();
msg.addReaction("✔").queue();
msg.addReaction("+1").queue();
This uses complete, however and will wait until the message has been sent. No listeners are executed during that time.
This means that your bot waits and other commands (by other users) are executed only after the message has been sent.
In order to fix that, you can use .queue()
with a lambda:
event.getChannel().sendMessage(image.build()).queue(msg->{
msg.addReaction("✔").queue();
msg.addReaction("+1").queue();
});
If you want to do this multiple times, you can write a method for this:
public void sendMessageWithReactions(MessageChannel channel,MessageEmbed embed, String... reactions){
channel.sendMessage(embed).queue(msg->{
for(String reaction:reactions){
msg.addReaction(reaction).queue();
}
});
}
You can call this method like this: sendMessageWithReactions(event.getChannel(),image.build(),"✔","+1");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论