如何在嵌入式 Discord JDA 中添加多个反应

huangapple go评论65阅读模式
英文:

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");

huangapple
  • 本文由 发表于 2020年8月8日 15:55:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63313055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定