Skip to content

Commit

Permalink
Add support for enforce_nonce (#2614)
Browse files Browse the repository at this point in the history
  • Loading branch information
MinnDevelopment committed Mar 10, 2024
1 parent 184e8bf commit f8bdadb
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
Expand Up @@ -21,6 +21,7 @@
import net.dv8tion.jda.api.entities.sticker.GuildSticker;
import net.dv8tion.jda.api.entities.sticker.Sticker;
import net.dv8tion.jda.api.entities.sticker.StickerSnowflake;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.requests.FluentRestAction;
import net.dv8tion.jda.api.utils.messages.MessageCreateData;
import net.dv8tion.jda.api.utils.messages.MessageCreateRequest;
Expand Down Expand Up @@ -54,14 +55,14 @@ static void setDefaultFailOnInvalidReply(boolean fail)
}

/**
* Unique string/number used to identify messages using {@link Message#getNonce()} in events.
* <br>This can be useful to handle round-trip messages.
* Unique string/number used to identify messages using {@link Message#getNonce()} in {@link MessageReceivedEvent}.
*
* <p>Discord also uses the nonce to dedupe messages for users, but this is not currently supported for bots.
* However, for future proofing, it is highly recommended to use a unique nonce for each message.
* <p>The nonce can be used for deduping messages and marking them for use with {@link MessageReceivedEvent}.
* JDA will automatically generate a unique nonce per message, it is not necessary to do this manually.
*
* @param nonce
* The nonce string to use
* The nonce string to use, must be unique per message.
* A unique nonce will be generated automatically if this is null.
*
* @throws IllegalArgumentException
* If the provided nonce is longer than {@value Message#MAX_NONCE_LENGTH} characters
Expand Down
Expand Up @@ -35,6 +35,7 @@

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
Expand All @@ -43,6 +44,7 @@

public class MessageCreateActionImpl extends RestActionImpl<Message> implements MessageCreateAction, MessageCreateBuilderMixin<MessageCreateAction>
{
protected static final SecureRandom nonceGenerator = new SecureRandom();
protected static boolean defaultFailOnInvalidReply = false;

private final MessageChannel channel;
Expand Down Expand Up @@ -83,8 +85,11 @@ protected RequestBody finalizeData()
try (MessageCreateData data = builder.build())
{
DataObject json = data.toData();
if (nonce != null)
json.put("enforce_nonce", true);
if (nonce != null && !nonce.isEmpty())
json.put("nonce", nonce);
else
json.put("nonce", Long.toUnsignedString(nonceGenerator.nextLong()));
if (stickers != null && !stickers.isEmpty())
json.put("sticker_ids", stickers);
if (messageReferenceId != null)
Expand Down

0 comments on commit f8bdadb

Please sign in to comment.