Replace botUsername with botUsernameSupplier

This commit is contained in:
Grig Alex 2020-10-20 20:41:34 +03:00
parent e6b9fd892f
commit 30fa92cd8b
No known key found for this signature in database
GPG Key ID: 7176EDB56B1B35CB
2 changed files with 8 additions and 5 deletions

View File

@ -53,7 +53,7 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB
*/
public TelegramLongPollingCommandBot(DefaultBotOptions options, boolean allowCommandsWithUsername) {
super(options);
this.commandRegistry = new CommandRegistry(allowCommandsWithUsername, this.getBotUsername());
this.commandRegistry = new CommandRegistry(allowCommandsWithUsername, this::getBotUsername);
}
@Override

View File

@ -7,7 +7,9 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import java.util.regex.Pattern;
/**
@ -19,17 +21,17 @@ public final class CommandRegistry implements ICommandRegistry {
private final Map<String, IBotCommand> commandRegistryMap = new HashMap<>();
private final boolean allowCommandsWithUsername;
private final String botUsername;
private final Supplier<String> botUsernameSupplier;
private BiConsumer<AbsSender, Message> defaultConsumer;
/**
* Creates a Command registry
* @param allowCommandsWithUsername True to allow commands with username, false otherwise
* @param botUsername Bot username
* @param botUsernameSupplier Bot username supplier
*/
public CommandRegistry(boolean allowCommandsWithUsername, String botUsername) {
public CommandRegistry(boolean allowCommandsWithUsername, Supplier<String> botUsernameSupplier) {
this.allowCommandsWithUsername = allowCommandsWithUsername;
this.botUsername = botUsername;
this.botUsernameSupplier = botUsernameSupplier;
}
@Override
@ -123,6 +125,7 @@ public final class CommandRegistry implements ICommandRegistry {
*/
private String removeUsernameFromCommandIfNeeded(String command) {
if (allowCommandsWithUsername) {
String botUsername = Objects.requireNonNull(botUsernameSupplier.get(), "Bot username must not be null");
return command.replaceAll("(?i)@" + Pattern.quote(botUsername), "").trim();
}
return command;