Skip to content

Commit

Permalink
Replace botUsername with botUsernameSupplier
Browse files Browse the repository at this point in the history
  • Loading branch information
alexengrig committed Oct 20, 2020
1 parent e6b9fd8 commit 30fa92c
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public TelegramLongPollingCommandBot(DefaultBotOptions options) {
*/
public TelegramLongPollingCommandBot(DefaultBotOptions options, boolean allowCommandsWithUsername) {
super(options);
this.commandRegistry = new CommandRegistry(allowCommandsWithUsername, this.getBotUsername());
this.commandRegistry = new CommandRegistry(allowCommandsWithUsername, this::getBotUsername);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
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;

/**
Expand All @@ -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
Expand Down Expand Up @@ -123,6 +125,7 @@ public final boolean executeCommand(AbsSender absSender, Message message) {
*/
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;
Expand Down

0 comments on commit 30fa92c

Please sign in to comment.