refactor: add final to all method/constructor parameters (MethodArgumentCouldBeFinal)

- Add final to every method/constructor parameter that is not assigned in the method body
- Handle annotations, varargs, generics, throws clauses
- Skip record components, lambdas, catch clauses, enum constructors
- Skip parameters that are reassigned in the method body
This commit is contained in:
loki5512344 2026-07-29 19:18:32 +02:00
parent 040870770d
commit 61150c5063
Signed by: boba
GPG key ID: 253067914055423B
253 changed files with 1009 additions and 1210 deletions

View file

@ -13,7 +13,7 @@ public class App {
private static final Logger logger = LoggerFactory.getLogger(App.class); private static final Logger logger = LoggerFactory.getLogger(App.class);
private static volatile boolean shutdownRequested = false; private static volatile boolean shutdownRequested = false;
public static void main(String[] args) { public static void main(final String[] args) {
Thread shutdownHook = Thread shutdownHook =
new Thread( new Thread(
() -> { () -> {

View file

@ -12,7 +12,7 @@ public class ReadyListener extends ListenerAdapter {
private static final Logger logger = LoggerFactory.getLogger(ReadyListener.class); private static final Logger logger = LoggerFactory.getLogger(ReadyListener.class);
@Override @Override
public void onReady(ReadyEvent event) { public void onReady(final ReadyEvent event) {
LoggerDecorator.success( LoggerDecorator.success(
logger, "Бот " + event.getJDA().getSelfUser().getName() + " успешно запущен!"); logger, "Бот " + event.getJDA().getSelfUser().getName() + " успешно запущен!");
LoggerDecorator.bot(logger, "Подключен к " + event.getGuildTotalCount() + " серверам"); LoggerDecorator.bot(logger, "Подключен к " + event.getGuildTotalCount() + " серверам");

View file

@ -19,12 +19,12 @@ public final class ConfigLoader {
Boolean.parseBoolean(getEnv(dotenv, "LAVALINK_ENABLED", "true"))); Boolean.parseBoolean(getEnv(dotenv, "LAVALINK_ENABLED", "true")));
} }
private static String getEnv(Dotenv dotenv, String key, String defaultValue) { private static String getEnv(Dotenv dotenv, final String key, final String defaultValue) {
String value = dotenv.get(key); String value = dotenv.get(key);
return (value != null && !value.isBlank()) ? value : defaultValue; return (value != null && !value.isBlank()) ? value : defaultValue;
} }
private static int parsePort(String raw, String key) { private static int parsePort(String raw, final String key) {
if (raw == null || raw.isBlank()) return 0; if (raw == null || raw.isBlank()) return 0;
try { try {
int port = Integer.parseInt(raw.trim()); int port = Integer.parseInt(raw.trim());

View file

@ -120,7 +120,7 @@ public class BotInitializer {
return buildWithLavalink(builder, ml); return buildWithLavalink(builder, ml);
} }
private JDA createRadioJDA(LavalinkManager radioLavalink) { private JDA createRadioJDA(final LavalinkManager radioLavalink) {
if (config.getRadioToken() == null || config.getRadioToken().isBlank()) return null; if (config.getRadioToken() == null || config.getRadioToken().isBlank()) return null;
LoggerDecorator.startup(logger, "Инициализация radio бота..."); LoggerDecorator.startup(logger, "Инициализация radio бота...");
var builder = var builder =
@ -134,7 +134,7 @@ public class BotInitializer {
return buildWithLavalink(builder, radioLavalink); return buildWithLavalink(builder, radioLavalink);
} }
private static JDA buildWithLavalink(JDABuilder builder, LavalinkManager ll) { private static JDA buildWithLavalink(final JDABuilder builder, final LavalinkManager ll) {
if (ll.getClient() != null) { if (ll.getClient() != null) {
builder.setVoiceDispatchInterceptor(new JDAVoiceUpdateListener(ll.getClient())); builder.setVoiceDispatchInterceptor(new JDAVoiceUpdateListener(ll.getClient()));
} }

View file

@ -9,19 +9,19 @@ public class BotJdaRegistry {
private JDA music; private JDA music;
private JDA radio; private JDA radio;
public void setMain(JDA jda) { public void setMain(final JDA jda) {
this.main = jda; this.main = jda;
} }
public void setMusic(JDA jda) { public void setMusic(final JDA jda) {
this.music = jda; this.music = jda;
} }
public void setRadio(JDA jda) { public void setRadio(final JDA jda) {
this.radio = jda; this.radio = jda;
} }
public JDA getByPersonality(String personality) { public JDA getByPersonality(final String personality) {
return switch (personality) { return switch (personality) {
case "windows" -> music != null ? music : main; case "windows" -> music != null ? music : main;
case "gentoo" -> radio != null ? radio : main; case "gentoo" -> radio != null ? radio : main;

View file

@ -39,7 +39,7 @@ public class EventDispatcher implements Lifecycle {
this.metrics = metrics; this.metrics = metrics;
} }
public void handleMessage(MessageReceivedEvent event) { public void handleMessage(final MessageReceivedEvent event) {
// Игнорируем ботов // Игнорируем ботов
if (event.getAuthor().isBot()) { if (event.getAuthor().isBot()) {
return; return;

View file

@ -12,7 +12,7 @@ import net.dv8tion.jda.api.utils.cache.CacheFlag;
public final class JdaFactory { public final class JdaFactory {
private JdaFactory() {} private JdaFactory() {}
public static JDABuilder createBuilder(String token, String activity, GatewayIntent... intents) { public static JDABuilder createBuilder(final String token, final String activity, final GatewayIntent... intents) {
return JDABuilder.createDefault(token) return JDABuilder.createDefault(token)
.setStatus(OnlineStatus.ONLINE) .setStatus(OnlineStatus.ONLINE)
.setActivity(Activity.playing(activity)) .setActivity(Activity.playing(activity))
@ -20,7 +20,7 @@ public final class JdaFactory {
.enableCache(CacheFlag.VOICE_STATE); .enableCache(CacheFlag.VOICE_STATE);
} }
public static JDA awaitJda(JDA jda) { public static JDA awaitJda(final JDA jda) {
try { try {
jda.awaitReady(); jda.awaitReady();
} catch (InterruptedException e) { } catch (InterruptedException e) {

View file

@ -7,8 +7,7 @@ import creator.loki.feature.music.repository.QueueRepository;
public final class LavalinkManagerFactory { public final class LavalinkManagerFactory {
private LavalinkManagerFactory() {} private LavalinkManagerFactory() {}
public static LavalinkManager create( public static LavalinkManager create(final BotConfig config, final QueueRepository queueRepository, final String token) {
BotConfig config, QueueRepository queueRepository, String token) {
return new LavalinkManager(config, queueRepository, token); return new LavalinkManager(config, queueRepository, token);
} }
} }

View file

@ -31,31 +31,7 @@ public class ListenerAggregator {
private final Object[] listeners; private final Object[] listeners;
@Inject @Inject
public ListenerAggregator( public ListenerAggregator(final ReadyListener readyListener, final MessageListener messageListener, final VoiceTracker voiceTracker, final VoiceChannelListener voiceChannelListener, final MemberCounterListener memberCounterListener, final VoiceButtonHandler voiceButtonHandler, final VoiceModalHandler voiceModalHandler, final VoiceSyncListener voiceSyncListener, final WelcomeListener welcomeListener, final ModerationLogger moderationLogger, final HelpMenuHandler helpMenuHandler, final ResetLevelsButtonHandler resetLevelsButtonHandler, final LeaderboardButtonListener leaderboardButtonListener, final MessageCache messageCache, final MusicSlashCommands musicSlashCommands, final PlaySelectHandler playSelectHandler, final FishMessageListener fishMessageListener, final AndrertListener andrertListener, final ClearSlashCommands clearSlashCommands, final HelperListener helperListener, final ImageNavigationHandler imageNavigationHandler, final SetupSlashHandler setupSlashHandler, final TicketListener ticketListener, final ReactionRoleListener reactionRoleListener) {
ReadyListener readyListener,
MessageListener messageListener,
VoiceTracker voiceTracker,
VoiceChannelListener voiceChannelListener,
MemberCounterListener memberCounterListener,
VoiceButtonHandler voiceButtonHandler,
VoiceModalHandler voiceModalHandler,
VoiceSyncListener voiceSyncListener,
WelcomeListener welcomeListener,
ModerationLogger moderationLogger,
HelpMenuHandler helpMenuHandler,
ResetLevelsButtonHandler resetLevelsButtonHandler,
LeaderboardButtonListener leaderboardButtonListener,
MessageCache messageCache,
MusicSlashCommands musicSlashCommands,
PlaySelectHandler playSelectHandler,
FishMessageListener fishMessageListener,
AndrertListener andrertListener,
ClearSlashCommands clearSlashCommands,
HelperListener helperListener,
ImageNavigationHandler imageNavigationHandler,
SetupSlashHandler setupSlashHandler,
TicketListener ticketListener,
ReactionRoleListener reactionRoleListener) {
this.listeners = this.listeners =
new Object[] { new Object[] {
readyListener, readyListener,

View file

@ -16,7 +16,7 @@ public class MessageCache extends ListenerAdapter {
} }
@Override @Override
public void onMessageReceived(MessageReceivedEvent event) { public void onMessageReceived(final MessageReceivedEvent event) {
if (event.getAuthor().isBot()) return; if (event.getAuthor().isBot()) return;
String content = event.getMessage().getContentRaw(); String content = event.getMessage().getContentRaw();
if (!content.isBlank()) { if (!content.isBlank()) {
@ -24,7 +24,7 @@ public class MessageCache extends ListenerAdapter {
} }
} }
public String getContent(String messageId) { public String getContent(final String messageId) {
return cache.getIfPresent(messageId); return cache.getIfPresent(messageId);
} }
} }

View file

@ -27,7 +27,7 @@ public class ShutdownManager {
this.radioManager = radioManager; this.radioManager = radioManager;
} }
public void shutdown(JDA jda) { public void shutdown(final JDA jda) {
shutdown(new BotCluster(jda, null, null)); shutdown(new BotCluster(jda, null, null));
} }
@ -35,7 +35,7 @@ public class ShutdownManager {
shutdown(new BotCluster(null, null, null)); shutdown(new BotCluster(null, null, null));
} }
public void shutdown(BotCluster cluster) { public void shutdown(final BotCluster cluster) {
logger.info("========================================"); logger.info("========================================");
logger.info("Получен сигнал завершения работы ботов..."); logger.info("Получен сигнал завершения работы ботов...");
logger.info("========================================"); logger.info("========================================");
@ -70,7 +70,7 @@ public class ShutdownManager {
LoggerDecorator.success(logger, "Боты успешно завершены!"); LoggerDecorator.success(logger, "Боты успешно завершены!");
} }
private void shutdownJDA(JDA jda, String name) { private void shutdownJDA(final JDA jda, final String name) {
LoggerDecorator.bot(logger, "Отключение " + name + " JDA..."); LoggerDecorator.bot(logger, "Отключение " + name + " JDA...");
jda.shutdown(); jda.shutdown();
try { try {

View file

@ -10,7 +10,7 @@ public class CommandException extends Exception {
this.userMessage = userMessage; this.userMessage = userMessage;
} }
public CommandException(String userMessage, Throwable cause) { public CommandException(String userMessage, final Throwable cause) {
super(userMessage, cause); super(userMessage, cause);
this.userMessage = userMessage; this.userMessage = userMessage;
} }

View file

@ -14,7 +14,7 @@ public class CommandExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(CommandExceptionHandler.class); private static final Logger logger = LoggerFactory.getLogger(CommandExceptionHandler.class);
/** Обрабатывает исключение и отправляет сообщение пользователю */ /** Обрабатывает исключение и отправляет сообщение пользователю */
public static void handle(Throwable throwable, MessageChannel channel, String commandName) { public static void handle(final Throwable throwable, final MessageChannel channel, final String commandName) {
LoggerDecorator.error(logger, "Ошибка при выполнении команды: " + commandName, throwable); LoggerDecorator.error(logger, "Ошибка при выполнении команды: " + commandName, throwable);
String userMessage; String userMessage;
@ -43,8 +43,7 @@ public class CommandExceptionHandler {
} }
/** Обрабатывает исключение с кастомным сообщением */ /** Обрабатывает исключение с кастомным сообщением */
public static void handle( public static void handle(final Throwable throwable, final MessageChannel channel, final String commandName, final String customMessage) {
Throwable throwable, MessageChannel channel, String commandName, String customMessage) {
LoggerDecorator.error(logger, "Ошибка при выполнении команды: " + commandName, throwable); LoggerDecorator.error(logger, "Ошибка при выполнении команды: " + commandName, throwable);
MessageEmbed errorEmbed = MessageEmbed errorEmbed =

View file

@ -2,5 +2,5 @@ package creator.loki.core.registry;
@FunctionalInterface @FunctionalInterface
public interface CommandRegistrar { public interface CommandRegistrar {
void register(CommandRegistry registry); void register(final CommandRegistry registry);
} }

View file

@ -14,7 +14,7 @@ public class CommandRegistry {
private static final Logger logger = LoggerFactory.getLogger(CommandRegistry.class); private static final Logger logger = LoggerFactory.getLogger(CommandRegistry.class);
private final Map<String, Command> commands = new HashMap<>(); private final Map<String, Command> commands = new HashMap<>();
public void register(Command command) { public void register(final Command command) {
String key = command.getName().toLowerCase(); String key = command.getName().toLowerCase();
Command previous = commands.put(key, command); Command previous = commands.put(key, command);
if (previous != null) { if (previous != null) {
@ -31,7 +31,7 @@ public class CommandRegistry {
} }
} }
public Command getCommand(String name) { public Command getCommand(final String name) {
return commands.get(name.toLowerCase()); return commands.get(name.toLowerCase());
} }

View file

@ -20,7 +20,7 @@ public class CooldownManager implements Lifecycle {
} }
/** Проверяет, находится ли пользователь на cooldown для команды */ /** Проверяет, находится ли пользователь на cooldown для команды */
public boolean isOnCooldown(String userId, String commandName) { public boolean isOnCooldown(final String userId, final String commandName) {
String key = userId + ":" + commandName; String key = userId + ":" + commandName;
Instant cooldownEnd = cooldowns.get(key); Instant cooldownEnd = cooldowns.get(key);
@ -37,7 +37,7 @@ public class CooldownManager implements Lifecycle {
} }
/** Возвращает оставшееся время cooldown в секундах */ /** Возвращает оставшееся время cooldown в секундах */
public long getRemainingSeconds(String userId, String commandName) { public long getRemainingSeconds(final String userId, final String commandName) {
String key = userId + ":" + commandName; String key = userId + ":" + commandName;
Instant cooldownEnd = cooldowns.get(key); Instant cooldownEnd = cooldowns.get(key);
@ -50,7 +50,7 @@ public class CooldownManager implements Lifecycle {
} }
/** Применяет cooldown для пользователя на команду */ /** Применяет cooldown для пользователя на команду */
public void applyCooldown(String userId, String commandName, int seconds) { public void applyCooldown(final String userId, final String commandName, final int seconds) {
String key = userId + ":" + commandName; String key = userId + ":" + commandName;
Instant cooldownEnd = Instant.now().plusSeconds(seconds); Instant cooldownEnd = Instant.now().plusSeconds(seconds);
cooldowns.put(key, cooldownEnd); cooldowns.put(key, cooldownEnd);

View file

@ -33,7 +33,7 @@ public class RateLimiter implements Lifecycle {
} }
/** Проверяет, может ли пользователь выполнить действие */ /** Проверяет, может ли пользователь выполнить действие */
public boolean allowUser(String userId) { public boolean allowUser(final String userId) {
TokenBucket bucket = TokenBucket bucket =
userBuckets.computeIfAbsent( userBuckets.computeIfAbsent(
userId, k -> new TokenBucket(DEFAULT_USER_CAPACITY, DEFAULT_USER_REFILL_RATE)); userId, k -> new TokenBucket(DEFAULT_USER_CAPACITY, DEFAULT_USER_REFILL_RATE));
@ -41,7 +41,7 @@ public class RateLimiter implements Lifecycle {
} }
/** Проверяет, может ли гильдия выполнить действие */ /** Проверяет, может ли гильдия выполнить действие */
public boolean allowGuild(String guildId) { public boolean allowGuild(final String guildId) {
TokenBucket bucket = TokenBucket bucket =
guildBuckets.computeIfAbsent( guildBuckets.computeIfAbsent(
guildId, k -> new TokenBucket(DEFAULT_GUILD_CAPACITY, DEFAULT_GUILD_REFILL_RATE)); guildId, k -> new TokenBucket(DEFAULT_GUILD_CAPACITY, DEFAULT_GUILD_REFILL_RATE));
@ -49,12 +49,12 @@ public class RateLimiter implements Lifecycle {
} }
/** Проверяет оба лимита: пользователя и гильдии */ /** Проверяет оба лимита: пользователя и гильдии */
public boolean allow(String userId, String guildId) { public boolean allow(final String userId, final String guildId) {
return allowUser(userId) && allowGuild(guildId); return allowUser(userId) && allowGuild(guildId);
} }
/** Возвращает оставшееся время до восстановления для пользователя (в секундах) */ /** Возвращает оставшееся время до восстановления для пользователя (в секундах) */
public long getUserWaitTime(String userId) { public long getUserWaitTime(final String userId) {
TokenBucket bucket = userBuckets.get(userId); TokenBucket bucket = userBuckets.get(userId);
if (bucket == null) { if (bucket == null) {
return 0; return 0;

View file

@ -40,7 +40,7 @@ public class Database implements Lifecycle {
+ config.getMaximumPoolSize() + config.getMaximumPoolSize()
+ ")"); + ")");
try (Connection conn = dataSource.getConnection(); try (final Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement()) { Statement stmt = conn.createStatement()) {
stmt.execute("PRAGMA foreign_keys = ON"); stmt.execute("PRAGMA foreign_keys = ON");
} catch (SQLException e) { } catch (SQLException e) {
@ -57,8 +57,8 @@ public class Database implements Lifecycle {
} }
} }
public void execute(String sql) { public void execute(final String sql) {
try (Connection conn = getConnection(); try (final Connection conn = getConnection();
Statement stmt = conn.createStatement()) { Statement stmt = conn.createStatement()) {
stmt.execute(sql); stmt.execute(sql);
} catch (SQLException e) { } catch (SQLException e) {
@ -67,7 +67,7 @@ public class Database implements Lifecycle {
} }
} }
public PreparedStatement prepare(String sql) { public PreparedStatement prepare(final String sql) {
Connection conn = null; Connection conn = null;
try { try {
conn = getConnection(); conn = getConnection();

View file

@ -22,7 +22,7 @@ public class DatabaseMigration {
this.database = database; this.database = database;
} }
public void migrateFromJson(String jsonPath) { public void migrateFromJson(final String jsonPath) {
LoggerDecorator.database(logger, "Начало миграции данных из JSON: " + jsonPath); LoggerDecorator.database(logger, "Начало миграции данных из JSON: " + jsonPath);
if (!new java.io.File(jsonPath).exists()) { if (!new java.io.File(jsonPath).exists()) {
logger.info("No legacy data file found at {}, skipping migration", jsonPath); logger.info("No legacy data file found at {}, skipping migration", jsonPath);
@ -49,7 +49,7 @@ public class DatabaseMigration {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private Map<String, Object> parseJson(String path) { private Map<String, Object> parseJson(final String path) {
try (var reader = new InputStreamReader(new FileInputStream(path), UTF_8)) { try (var reader = new InputStreamReader(new FileInputStream(path), UTF_8)) {
var type = new TypeToken<Map<String, Object>>() {}.getType(); var type = new TypeToken<Map<String, Object>>() {}.getType();
return (Map<String, Object>) gson.fromJson(reader, type); return (Map<String, Object>) gson.fromJson(reader, type);
@ -60,7 +60,7 @@ public class DatabaseMigration {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void migrateUserStats(Map<String, Object> data) { private void migrateUserStats(final Map<String, Object> data) {
var userStats = (Map<String, Object>) data.get("userStats"); var userStats = (Map<String, Object>) data.get("userStats");
if (userStats == null) return; if (userStats == null) return;
LoggerDecorator.database(logger, "Миграция userStats: " + userStats.size() + " записей"); LoggerDecorator.database(logger, "Миграция userStats: " + userStats.size() + " записей");
@ -85,7 +85,7 @@ public class DatabaseMigration {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void migrateReputation(Map<String, Object> data) { private void migrateReputation(final Map<String, Object> data) {
var reputation = (Map<String, Object>) data.get("reputation"); var reputation = (Map<String, Object>) data.get("reputation");
if (reputation == null) return; if (reputation == null) return;
LoggerDecorator.database(logger, "Миграция reputation: " + reputation.size() + " записей"); LoggerDecorator.database(logger, "Миграция reputation: " + reputation.size() + " записей");
@ -103,7 +103,7 @@ public class DatabaseMigration {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void migrateShipPairs(Map<String, Object> data) { private void migrateShipPairs(final Map<String, Object> data) {
var shipPairs = (Map<String, Object>) data.get("shipPairs"); var shipPairs = (Map<String, Object>) data.get("shipPairs");
if (shipPairs == null) return; if (shipPairs == null) return;
LoggerDecorator.database(logger, "Миграция shipPairs: " + shipPairs.size() + " записей"); LoggerDecorator.database(logger, "Миграция shipPairs: " + shipPairs.size() + " записей");
@ -126,7 +126,7 @@ public class DatabaseMigration {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void migrateCustomRoles(Map<String, Object> data) { private void migrateCustomRoles(final Map<String, Object> data) {
var customRoles = (Map<String, Object>) data.get("custom_roles"); var customRoles = (Map<String, Object>) data.get("custom_roles");
if (customRoles == null) return; if (customRoles == null) return;
LoggerDecorator.database(logger, "Миграция custom_roles"); LoggerDecorator.database(logger, "Миграция custom_roles");

View file

@ -15,7 +15,7 @@ import creator.loki.feature.ship.repository.ShipPairRepository;
public class DatabaseModule extends AbstractModule { public class DatabaseModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
Database provideDatabase(BotConfig config) { Database provideDatabase(final BotConfig config) {
Database database = new Database(config.getDbPath()); Database database = new Database(config.getDbPath());
database.connect(); database.connect();
new DatabaseSchema(database).createTables(); new DatabaseSchema(database).createTables();
@ -25,37 +25,37 @@ public class DatabaseModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
ConfigRepository provideConfigRepository(Database database) { ConfigRepository provideConfigRepository(final Database database) {
return new ConfigRepository(database); return new ConfigRepository(database);
} }
@Provides @Provides
@Singleton @Singleton
GuildConfigRepository provideGuildConfigRepository(ConfigRepository cr) { GuildConfigRepository provideGuildConfigRepository(final ConfigRepository cr) {
return new PrefixedGuildConfigRepository(cr); return new PrefixedGuildConfigRepository(cr);
} }
@Provides @Provides
@Singleton @Singleton
RatingsRepository provideRatingsRepository(Database database) { RatingsRepository provideRatingsRepository(final Database database) {
return new RatingsRepository(database); return new RatingsRepository(database);
} }
@Provides @Provides
@Singleton @Singleton
ReputationRepository provideReputationRepository(Database database) { ReputationRepository provideReputationRepository(final Database database) {
return new ReputationRepository(database); return new ReputationRepository(database);
} }
@Provides @Provides
@Singleton @Singleton
ShipPairRepository provideShipPairRepository(Database database) { ShipPairRepository provideShipPairRepository(final Database database) {
return new ShipPairRepository(database); return new ShipPairRepository(database);
} }
@Provides @Provides
@Singleton @Singleton
QueueRepository provideQueueRepository(Database database) { QueueRepository provideQueueRepository(final Database database) {
return new QueueRepository(database); return new QueueRepository(database);
} }
} }

View file

@ -4,7 +4,7 @@ import creator.loki.database.Database;
public final class CoreTables { public final class CoreTables {
public static void create(Database database) { public static void create(final Database database) {
createConfig(database); createConfig(database);
createUserStats(database); createUserStats(database);
createReputation(database); createReputation(database);
@ -12,7 +12,7 @@ public final class CoreTables {
createIndexes(database); createIndexes(database);
} }
private static void createConfig(Database database) { private static void createConfig(final Database database) {
database.execute( database.execute(
""" """
CREATE TABLE IF NOT EXISTS config ( CREATE TABLE IF NOT EXISTS config (
@ -22,7 +22,7 @@ public final class CoreTables {
"""); """);
} }
private static void createUserStats(Database database) { private static void createUserStats(final Database database) {
database.execute( database.execute(
""" """
CREATE TABLE IF NOT EXISTS user_stats ( CREATE TABLE IF NOT EXISTS user_stats (
@ -37,7 +37,7 @@ public final class CoreTables {
"""); """);
} }
private static void createReputation(Database database) { private static void createReputation(final Database database) {
database.execute( database.execute(
""" """
CREATE TABLE IF NOT EXISTS reputation ( CREATE TABLE IF NOT EXISTS reputation (
@ -47,7 +47,7 @@ public final class CoreTables {
"""); """);
} }
private static void createShipPairs(Database database) { private static void createShipPairs(final Database database) {
database.execute( database.execute(
""" """
CREATE TABLE IF NOT EXISTS ship_pairs ( CREATE TABLE IF NOT EXISTS ship_pairs (
@ -59,7 +59,7 @@ public final class CoreTables {
"""); """);
} }
private static void createIndexes(Database database) { private static void createIndexes(final Database database) {
database.execute("CREATE INDEX IF NOT EXISTS idx_user_stats_level ON user_stats(level DESC)"); database.execute("CREATE INDEX IF NOT EXISTS idx_user_stats_level ON user_stats(level DESC)");
database.execute( database.execute(
"CREATE INDEX IF NOT EXISTS idx_user_stats_total_xp ON user_stats(total_xp DESC)"); "CREATE INDEX IF NOT EXISTS idx_user_stats_total_xp ON user_stats(total_xp DESC)");

View file

@ -134,7 +134,7 @@ public final class FeatureTables {
PRIMARY KEY (guild_id, user_id, rating_type) PRIMARY KEY (guild_id, user_id, rating_type)
)"""; )""";
public static void create(Database database) { public static void create(final Database database) {
database.execute(ECONOMY); database.execute(ECONOMY);
database.execute(MUSIC_QUEUE); database.execute(MUSIC_QUEUE);
database.execute(WARNINGS); database.execute(WARNINGS);
@ -150,7 +150,7 @@ public final class FeatureTables {
createIndexes(database); createIndexes(database);
} }
private static void createIndexes(Database database) { private static void createIndexes(final Database database) {
for (var sql : for (var sql :
new String[] { new String[] {
"CREATE INDEX IF NOT EXISTS idx_ratings_guild_type ON ratings(guild_id, rating_type)", "CREATE INDEX IF NOT EXISTS idx_ratings_guild_type ON ratings(guild_id, rating_type)",

View file

@ -80,11 +80,7 @@ public class BotModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
EventDispatcher provideEventDispatcher( EventDispatcher provideEventDispatcher(final BotConfig config, final CommandRegistry registry, final RateLimiter rateLimiter, final MetricsCollector metrics) {
BotConfig config,
CommandRegistry registry,
RateLimiter rateLimiter,
MetricsCollector metrics) {
return new EventDispatcher(config, registry, rateLimiter, metrics); return new EventDispatcher(config, registry, rateLimiter, metrics);
} }
} }

View file

@ -17,57 +17,57 @@ public class EmbedFactory {
return new EmbedFactory(); return new EmbedFactory();
} }
public EmbedFactory withTitle(String title) { public EmbedFactory withTitle(final String title) {
builder.setTitle(title); builder.setTitle(title);
return this; return this;
} }
public EmbedFactory withDescription(String description) { public EmbedFactory withDescription(final String description) {
builder.setDescription(description); builder.setDescription(description);
return this; return this;
} }
public EmbedFactory withColor(Color color) { public EmbedFactory withColor(final Color color) {
builder.setColor(color); builder.setColor(color);
return this; return this;
} }
public EmbedFactory addField(String name, String value, boolean inline) { public EmbedFactory addField(final String name, final String value, final boolean inline) {
builder.addField(name, value, inline); builder.addField(name, value, inline);
return this; return this;
} }
public EmbedFactory withFooter(String text) { public EmbedFactory withFooter(final String text) {
builder.setFooter(text); builder.setFooter(text);
return this; return this;
} }
public EmbedFactory withFooter(String text, String iconUrl) { public EmbedFactory withFooter(final String text, final String iconUrl) {
builder.setFooter(text, iconUrl); builder.setFooter(text, iconUrl);
return this; return this;
} }
public EmbedFactory withThumbnail(String url) { public EmbedFactory withThumbnail(final String url) {
builder.setThumbnail(url); builder.setThumbnail(url);
return this; return this;
} }
public EmbedFactory withImage(String url) { public EmbedFactory withImage(final String url) {
builder.setImage(url); builder.setImage(url);
return this; return this;
} }
public EmbedFactory withAuthor(String name) { public EmbedFactory withAuthor(final String name) {
builder.setAuthor(name); builder.setAuthor(name);
return this; return this;
} }
public EmbedFactory withAuthor(String name, String url) { public EmbedFactory withAuthor(final String name, final String url) {
builder.setAuthor(name, url); builder.setAuthor(name, url);
return this; return this;
} }
public EmbedFactory withAuthor(String name, String url, String iconUrl) { public EmbedFactory withAuthor(final String name, final String url, final String iconUrl) {
builder.setAuthor(name, url, iconUrl); builder.setAuthor(name, url, iconUrl);
return this; return this;
} }

View file

@ -12,7 +12,7 @@ public final class EmbedTemplates {
// Запрет создания экземпляров // Запрет создания экземпляров
} }
public static MessageEmbed success(String title, String description) { public static MessageEmbed success(final String title, final String description) {
return new EmbedBuilder() return new EmbedBuilder()
.setColor(Color.GREEN) .setColor(Color.GREEN)
.setTitle("✅ " + title) .setTitle("✅ " + title)
@ -21,7 +21,7 @@ public final class EmbedTemplates {
.build(); .build();
} }
public static MessageEmbed error(String title, String description) { public static MessageEmbed error(final String title, final String description) {
return new EmbedBuilder() return new EmbedBuilder()
.setColor(Color.RED) .setColor(Color.RED)
.setTitle("❌ " + title) .setTitle("❌ " + title)
@ -30,7 +30,7 @@ public final class EmbedTemplates {
.build(); .build();
} }
public static MessageEmbed info(String title, String description) { public static MessageEmbed info(final String title, final String description) {
return new EmbedBuilder() return new EmbedBuilder()
.setColor(Color.CYAN) .setColor(Color.CYAN)
.setTitle("ℹ️ " + title) .setTitle("ℹ️ " + title)
@ -39,7 +39,7 @@ public final class EmbedTemplates {
.build(); .build();
} }
public static MessageEmbed warning(String title, String description) { public static MessageEmbed warning(final String title, final String description) {
return new EmbedBuilder() return new EmbedBuilder()
.setColor(Color.ORANGE) .setColor(Color.ORANGE)
.setTitle("⚠️ " + title) .setTitle("⚠️ " + title)

View file

@ -69,20 +69,19 @@ public final class HelpCategories {
private HelpCategories() {} private HelpCategories() {}
public static String getEmoji(String category) { public static String getEmoji(final String category) {
return EMOJIS.getOrDefault(category, "📌"); return EMOJIS.getOrDefault(category, "📌");
} }
public static Color getColor(String category) { public static Color getColor(final String category) {
return COLORS.getOrDefault(category, new Color(88, 101, 242)); return COLORS.getOrDefault(category, new Color(88, 101, 242));
} }
public static String getDescription(String category) { public static String getDescription(final String category) {
return DESCRIPTIONS.getOrDefault(category, "Команды категории"); return DESCRIPTIONS.getOrDefault(category, "Команды категории");
} }
public static boolean isCategoryVisible( public static boolean isCategoryVisible(final String category, final boolean isAdmin, final boolean isSuper, final boolean isNsfwChannel) {
String category, boolean isAdmin, boolean isSuper, boolean isNsfwChannel) {
if (CommandCategories.SETTINGS.equals(category) && !isAdmin) { if (CommandCategories.SETTINGS.equals(category) && !isAdmin) {
return false; return false;
} }

View file

@ -46,7 +46,7 @@ public class GenerateRatingsCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
if (!config.getSuperAdminId().equals(context.getAuthor().getUser().getId())) { if (!config.getSuperAdminId().equals(context.getAuthor().getUser().getId())) {
context context
.getChannel() .getChannel()
@ -95,7 +95,7 @@ public class GenerateRatingsCommand implements Command {
} }
} }
private void generateRatingForUser(String guildId, String userId, String ratingType) { private void generateRatingForUser(final String guildId, final String userId, final String ratingType) {
if (ratingsRepository.hasRating(guildId, userId, ratingType)) return; if (ratingsRepository.hasRating(guildId, userId, ratingType)) return;
var value = var value =
switch (ratingType) { switch (ratingType) {
@ -110,7 +110,7 @@ public class GenerateRatingsCommand implements Command {
ratingsRepository.setRating(guildId, userId, ratingType, value); ratingsRepository.setRating(guildId, userId, ratingType, value);
} }
private MessageEmbed errorEmbed(String title, String description) { private MessageEmbed errorEmbed(final String title, final String description) {
return EmbedFactory.create() return EmbedFactory.create()
.withTitle(title) .withTitle(title)
.withDescription(description) .withDescription(description)
@ -118,7 +118,7 @@ public class GenerateRatingsCommand implements Command {
.build(); .build();
} }
private MessageEmbed warnEmbed(String title, String description) { private MessageEmbed warnEmbed(final String title, final String description) {
return EmbedFactory.create() return EmbedFactory.create()
.withTitle(title) .withTitle(title)
.withDescription(description) .withDescription(description)
@ -126,7 +126,7 @@ public class GenerateRatingsCommand implements Command {
.build(); .build();
} }
private MessageEmbed successEmbed(CommandContext context, int memberCount, int generatedCount) { private MessageEmbed successEmbed(final CommandContext context, final int memberCount, final int generatedCount) {
return EmbedFactory.create() return EmbedFactory.create()
.withTitle("✅ Генерация завершена") .withTitle("✅ Генерация завершена")
.withDescription( .withDescription(

View file

@ -42,7 +42,7 @@ public class SetupSlashHandler extends ListenerAdapter {
} }
@Override @Override
public void onGuildReady(@NotNull GuildReadyEvent event) { public void onGuildReady(@NotNull final GuildReadyEvent event) {
if (registered) return; if (registered) return;
registered = true; registered = true;
event.getJDA().updateCommands() event.getJDA().updateCommands()
@ -51,14 +51,14 @@ public class SetupSlashHandler extends ListenerAdapter {
} }
@Override @Override
public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) { public void onSlashCommandInteraction(@NotNull final SlashCommandInteractionEvent event) {
if (!event.getName().equals("setup")) return; if (!event.getName().equals("setup")) return;
event.deferReply().queue(); event.deferReply().queue();
showDashboard(event.getGuild(), event.getHook()); showDashboard(event.getGuild(), event.getHook());
} }
@Override @Override
public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { public void onButtonInteraction(@NotNull final ButtonInteractionEvent event) {
String id = event.getComponentId(); String id = event.getComponentId();
if (!id.startsWith("setup_")) return; if (!id.startsWith("setup_")) return;
event.deferEdit().queue(); event.deferEdit().queue();
@ -76,7 +76,7 @@ public class SetupSlashHandler extends ListenerAdapter {
} }
@Override @Override
public void onEntitySelectInteraction(@NotNull EntitySelectInteractionEvent event) { public void onEntitySelectInteraction(@NotNull final EntitySelectInteractionEvent event) {
String id = event.getComponentId(); String id = event.getComponentId();
if (!id.startsWith("setup_")) return; if (!id.startsWith("setup_")) return;
event.deferEdit().queue(); event.deferEdit().queue();
@ -109,7 +109,7 @@ public class SetupSlashHandler extends ListenerAdapter {
} }
@Override @Override
public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent event) { public void onStringSelectInteraction(@NotNull final StringSelectInteractionEvent event) {
String id = event.getComponentId(); String id = event.getComponentId();
if (!id.startsWith("setup_")) return; if (!id.startsWith("setup_")) return;
event.deferEdit().queue(); event.deferEdit().queue();
@ -122,7 +122,7 @@ public class SetupSlashHandler extends ListenerAdapter {
} }
@Override @Override
public void onModalInteraction(@NotNull ModalInteractionEvent event) { public void onModalInteraction(@NotNull final ModalInteractionEvent event) {
String id = event.getModalId(); String id = event.getModalId();
if (!id.startsWith("setup_")) return; if (!id.startsWith("setup_")) return;
event.deferEdit().queue(); event.deferEdit().queue();
@ -143,13 +143,13 @@ public class SetupSlashHandler extends ListenerAdapter {
} }
} }
private void showDashboard(Guild guild, InteractionHook hook) { private void showDashboard(Guild guild, final InteractionHook hook) {
hook.editOriginalEmbeds(buildDashboardEmbed(guild).build()) hook.editOriginalEmbeds(buildDashboardEmbed(guild).build())
.setComponents(buildDashboardButtons()) .setComponents(buildDashboardButtons())
.queue(); .queue();
} }
private void showVoicePanel(Guild guild, InteractionHook hook) { private void showVoicePanel(Guild guild, final InteractionHook hook) {
EmbedBuilder embed = new EmbedBuilder() EmbedBuilder embed = new EmbedBuilder()
.setTitle("🎤 Настройка голосовых каналов") .setTitle("🎤 Настройка голосовых каналов")
.setColor(BLURPLE); .setColor(BLURPLE);
@ -183,7 +183,7 @@ public class SetupSlashHandler extends ListenerAdapter {
.queue(); .queue();
} }
private void showCounterPanel(Guild guild, InteractionHook hook) { private void showCounterPanel(Guild guild, final InteractionHook hook) {
EmbedBuilder embed = new EmbedBuilder() EmbedBuilder embed = new EmbedBuilder()
.setTitle("📊 Настройка счётчика участников") .setTitle("📊 Настройка счётчика участников")
.setColor(BLURPLE); .setColor(BLURPLE);
@ -210,7 +210,7 @@ public class SetupSlashHandler extends ListenerAdapter {
.queue(); .queue();
} }
private void showLoggingPanel(Guild guild, InteractionHook hook) { private void showLoggingPanel(Guild guild, final InteractionHook hook) {
EmbedBuilder embed = new EmbedBuilder() EmbedBuilder embed = new EmbedBuilder()
.setTitle("📝 Настройка логирования") .setTitle("📝 Настройка логирования")
.setColor(BLURPLE); .setColor(BLURPLE);
@ -235,7 +235,7 @@ public class SetupSlashHandler extends ListenerAdapter {
.queue(); .queue();
} }
private void showLevelRolesPanel(Guild guild, InteractionHook hook) { private void showLevelRolesPanel(Guild guild, final InteractionHook hook) {
Map<String, String> allConfig = configRepo.getAll(); Map<String, String> allConfig = configRepo.getAll();
var levelRoles = allConfig.entrySet().stream() var levelRoles = allConfig.entrySet().stream()
.filter(e -> e.getKey().startsWith("level_role_")) .filter(e -> e.getKey().startsWith("level_role_"))
@ -269,7 +269,7 @@ public class SetupSlashHandler extends ListenerAdapter {
.queue(); .queue();
} }
private void openCounterFormatModal(ButtonInteractionEvent event) { private void openCounterFormatModal(final ButtonInteractionEvent event) {
String currentFormat = configRepo.get("counter.format"); String currentFormat = configRepo.get("counter.format");
if (currentFormat == null) { if (currentFormat == null) {
currentFormat = "【👥】Участники: {count}"; currentFormat = "【👥】Участники: {count}";
@ -288,7 +288,7 @@ public class SetupSlashHandler extends ListenerAdapter {
event.replyModal(modal).queue(); event.replyModal(modal).queue();
} }
private void openLevelRoleAddModal(ButtonInteractionEvent event) { private void openLevelRoleAddModal(final ButtonInteractionEvent event) {
TextInput levelInput = TextInput.create("level", TextInputStyle.SHORT) TextInput levelInput = TextInput.create("level", TextInputStyle.SHORT)
.setPlaceholder("10") .setPlaceholder("10")
.setRequired(true) .setRequired(true)
@ -306,7 +306,7 @@ public class SetupSlashHandler extends ListenerAdapter {
event.replyModal(modal).queue(); event.replyModal(modal).queue();
} }
private void openLevelRoleRemoveSelect(ButtonInteractionEvent event) { private void openLevelRoleRemoveSelect(final ButtonInteractionEvent event) {
Map<String, String> allConfig = configRepo.getAll(); Map<String, String> allConfig = configRepo.getAll();
var options = allConfig.entrySet().stream() var options = allConfig.entrySet().stream()
.filter(e -> e.getKey().startsWith("level_role_")) .filter(e -> e.getKey().startsWith("level_role_"))

View file

@ -21,7 +21,7 @@ public class ConfigRepository implements StringConfigStore {
/** Получить значение конфигурации */ /** Получить значение конфигурации */
public String get(String key) { public String get(String key) {
try (PreparedStatement stmt = database.prepare("SELECT value FROM config WHERE key = ?")) { try (final PreparedStatement stmt = database.prepare("SELECT value FROM config WHERE key = ?")) {
stmt.setString(1, key); stmt.setString(1, key);
ResultSet rs = stmt.executeQuery(); ResultSet rs = stmt.executeQuery();
@ -36,8 +36,8 @@ public class ConfigRepository implements StringConfigStore {
} }
/** Установить значение конфигурации */ /** Установить значение конфигурации */
public void set(String key, String value) { public void set(String key, final String value) {
try (PreparedStatement stmt = try (final PreparedStatement stmt =
database.prepare("INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)")) { database.prepare("INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)")) {
stmt.setString(1, key); stmt.setString(1, key);
stmt.setString(2, value); stmt.setString(2, value);
@ -50,7 +50,7 @@ public class ConfigRepository implements StringConfigStore {
public Map<String, String> getAll() { public Map<String, String> getAll() {
Map<String, String> result = new HashMap<>(); Map<String, String> result = new HashMap<>();
try (PreparedStatement stmt = database.prepare("SELECT key, value FROM config")) { try (final PreparedStatement stmt = database.prepare("SELECT key, value FROM config")) {
ResultSet rs = stmt.executeQuery(); ResultSet rs = stmt.executeQuery();
while (rs.next()) { while (rs.next()) {
result.put(rs.getString("key"), rs.getString("value")); result.put(rs.getString("key"), rs.getString("value"));
@ -63,7 +63,7 @@ public class ConfigRepository implements StringConfigStore {
/** Удалить значение конфигурации */ /** Удалить значение конфигурации */
public void delete(String key) { public void delete(String key) {
try (PreparedStatement stmt = database.prepare("DELETE FROM config WHERE key = ?")) { try (final PreparedStatement stmt = database.prepare("DELETE FROM config WHERE key = ?")) {
stmt.setString(1, key); stmt.setString(1, key);
stmt.executeUpdate(); stmt.executeUpdate();
logger.info("Конфигурация удалена: {}", key); logger.info("Конфигурация удалена: {}", key);

View file

@ -12,22 +12,22 @@ public final class PrefixedGuildConfigRepository implements GuildConfigRepositor
this.store = store; this.store = store;
} }
private static String storageKey(String guildId, String key) { private static String storageKey(final String guildId, final String key) {
return guildId + ":" + key; return guildId + ":" + key;
} }
@Override @Override
public String get(String guildId, String key) { public String get(final String guildId, final String key) {
return store.get(storageKey(guildId, key)); return store.get(storageKey(guildId, key));
} }
@Override @Override
public void set(String guildId, String key, String value) { public void set(final String guildId, final String key, final String value) {
store.set(storageKey(guildId, key), value); store.set(storageKey(guildId, key), value);
} }
@Override @Override
public void delete(String guildId, String key) { public void delete(final String guildId, final String key) {
store.delete(storageKey(guildId, key)); store.delete(storageKey(guildId, key));
} }
} }

View file

@ -15,14 +15,13 @@ public class CounterModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
CounterStatsRepository provideCounterStatsRepository(Database database) { CounterStatsRepository provideCounterStatsRepository(final Database database) {
return new CounterStatsRepository(database); return new CounterStatsRepository(database);
} }
@Provides @Provides
@Singleton @Singleton
CounterManager provideCounterManager( CounterManager provideCounterManager(final CounterStatsRepository statsRepo, final ConfigRepository configRepo) {
CounterStatsRepository statsRepo, ConfigRepository configRepo) {
return new CounterManager(statsRepo, configRepo); return new CounterManager(statsRepo, configRepo);
} }
} }

View file

@ -25,10 +25,10 @@ public class CounterStatsRepository {
public DailyStats getStats(String date) { public DailyStats getStats(String date) {
String sql = "SELECT * FROM counter_stats WHERE date = ?"; String sql = "SELECT * FROM counter_stats WHERE date = ?";
try (PreparedStatement stmt = database.prepare(sql)) { try (final PreparedStatement stmt = database.prepare(sql)) {
stmt.setString(1, date); stmt.setString(1, date);
try (ResultSet rs = stmt.executeQuery()) { try (final ResultSet rs = stmt.executeQuery()) {
if (rs.next()) { if (rs.next()) {
DailyStats stats = new DailyStats(); DailyStats stats = new DailyStats();
stats.setDate(rs.getString("date")); stats.setDate(rs.getString("date"));
@ -70,7 +70,7 @@ public class CounterStatsRepository {
difference = excluded.difference difference = excluded.difference
"""; """;
try (PreparedStatement stmt = database.prepare(sql)) { try (final PreparedStatement stmt = database.prepare(sql)) {
stmt.setString(1, stats.getDate()); stmt.setString(1, stats.getDate());
stmt.setInt(2, stats.getJoined()); stmt.setInt(2, stats.getJoined());
stmt.setInt(3, stats.getLeft()); stmt.setInt(3, stats.getLeft());
@ -82,14 +82,14 @@ public class CounterStatsRepository {
} }
/** Получить историю за последние N дней */ /** Получить историю за последние N дней */
public List<DailyStats> getHistory(int days) { public List<DailyStats> getHistory(final int days) {
List<DailyStats> history = new ArrayList<>(); List<DailyStats> history = new ArrayList<>();
String sql = "SELECT * FROM counter_stats ORDER BY date DESC LIMIT ?"; String sql = "SELECT * FROM counter_stats ORDER BY date DESC LIMIT ?";
try (PreparedStatement stmt = database.prepare(sql)) { try (final PreparedStatement stmt = database.prepare(sql)) {
stmt.setInt(1, days); stmt.setInt(1, days);
try (ResultSet rs = stmt.executeQuery()) { try (final ResultSet rs = stmt.executeQuery()) {
while (rs.next()) { while (rs.next()) {
DailyStats stats = new DailyStats(); DailyStats stats = new DailyStats();
stats.setDate(rs.getString("date")); stats.setDate(rs.getString("date"));
@ -107,14 +107,14 @@ public class CounterStatsRepository {
} }
/** Удалить старую статистику (старше N дней) */ /** Удалить старую статистику (старше N дней) */
public void cleanOldStats(int daysToKeep) { public void cleanOldStats(final int daysToKeep) {
String sql = String sql =
""" """
DELETE FROM counter_stats DELETE FROM counter_stats
WHERE date < date('now', '-' || ? || ' days') WHERE date < date('now', '-' || ? || ' days')
"""; """;
try (PreparedStatement stmt = database.prepare(sql)) { try (final PreparedStatement stmt = database.prepare(sql)) {
stmt.setInt(1, daysToKeep); stmt.setInt(1, daysToKeep);
int deleted = stmt.executeUpdate(); int deleted = stmt.executeUpdate();
if (deleted > 0) { if (deleted > 0) {

View file

@ -62,7 +62,7 @@ public class CounterManager {
} }
/** Обновить счетчик участников */ /** Обновить счетчик участников */
public void updateCounter(Guild guild) { public void updateCounter(final Guild guild) {
if (counterChannelId == null || counterChannelId.isEmpty()) { if (counterChannelId == null || counterChannelId.isEmpty()) {
return; return;
} }
@ -88,7 +88,7 @@ public class CounterManager {
} }
/** Получить историю статистики */ /** Получить историю статистики */
public List<DailyStats> getHistory(int days) { public List<DailyStats> getHistory(final int days) {
return statsRepo.getHistory(days); return statsRepo.getHistory(days);
} }

View file

@ -41,7 +41,7 @@ public class CounterSetupPrefixCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
if (!context.getAuthor().hasPermission(Permission.ADMINISTRATOR)) { if (!context.getAuthor().hasPermission(Permission.ADMINISTRATOR)) {
context.getChannel().sendMessage("❌ У вас нет прав администратора!").queue(); context.getChannel().sendMessage("❌ У вас нет прав администратора!").queue();
return; return;
@ -61,7 +61,7 @@ public class CounterSetupPrefixCommand implements Command {
} }
} }
private void handleChannel(CommandContext context, List<String> args) { private void handleChannel(final CommandContext context, final List<String> args) {
if (args.size() < 2) { if (args.size() < 2) {
context context
.getChannel() .getChannel()
@ -98,7 +98,7 @@ public class CounterSetupPrefixCommand implements Command {
CounterConfigFormatter.sendChannelSetConfirmation(channel, memberCount, context.getChannel()); CounterConfigFormatter.sendChannelSetConfirmation(channel, memberCount, context.getChannel());
} }
private void handleFormat(CommandContext context, List<String> args) { private void handleFormat(final CommandContext context, final List<String> args) {
if (args.size() < 2) { if (args.size() < 2) {
context context
.getChannel() .getChannel()
@ -130,7 +130,7 @@ public class CounterSetupPrefixCommand implements Command {
CounterConfigFormatter.sendFormatUpdated(format, context.getChannel()); CounterConfigFormatter.sendFormatUpdated(format, context.getChannel());
} }
private void handleInfo(CommandContext context) { private void handleInfo(final CommandContext context) {
String channelId = configRepo.get("counter.channel_id"); String channelId = configRepo.get("counter.channel_id");
String format = configRepo.get("counter.format"); String format = configRepo.get("counter.format");
CounterConfigFormatter.sendInfo(context.getGuild(), channelId, format, context.getChannel()); CounterConfigFormatter.sendInfo(context.getGuild(), channelId, format, context.getChannel());

View file

@ -6,10 +6,7 @@ import creator.loki.embed.EmbedFactory;
public class CounterConfigFormatter { public class CounterConfigFormatter {
public static void sendChannelSetConfirmation( public static void sendChannelSetConfirmation(final net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel channel, final int memberCount, final net.dv8tion.jda.api.entities.channel.middleman.MessageChannel textChannel) {
net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel channel,
int memberCount,
net.dv8tion.jda.api.entities.channel.middleman.MessageChannel textChannel) {
textChannel textChannel
.sendMessageEmbeds( .sendMessageEmbeds(
EmbedFactory.create() EmbedFactory.create()
@ -22,8 +19,7 @@ public class CounterConfigFormatter {
.queue(); .queue();
} }
public static void sendFormatUpdated( public static void sendFormatUpdated(final String format, final net.dv8tion.jda.api.entities.channel.middleman.MessageChannel channel) {
String format, net.dv8tion.jda.api.entities.channel.middleman.MessageChannel channel) {
channel channel
.sendMessageEmbeds( .sendMessageEmbeds(
EmbedFactory.create() EmbedFactory.create()
@ -35,11 +31,7 @@ public class CounterConfigFormatter {
.queue(); .queue();
} }
public static void sendInfo( public static void sendInfo(final net.dv8tion.jda.api.entities.Guild guild, final String channelId, final String format, final net.dv8tion.jda.api.entities.channel.middleman.MessageChannel channel) {
net.dv8tion.jda.api.entities.Guild guild,
String channelId,
String format,
net.dv8tion.jda.api.entities.channel.middleman.MessageChannel channel) {
var embed = var embed =
EmbedFactory.create() EmbedFactory.create()
.withTitle("📊 Конфигурация счетчика участников") .withTitle("📊 Конфигурация счетчика участников")
@ -59,8 +51,7 @@ public class CounterConfigFormatter {
channel.sendMessageEmbeds(embed.build()).queue(); channel.sendMessageEmbeds(embed.build()).queue();
} }
public static void sendHelp( public static void sendHelp(final net.dv8tion.jda.api.entities.channel.middleman.MessageChannel channel) {
net.dv8tion.jda.api.entities.channel.middleman.MessageChannel channel) {
channel channel
.sendMessageEmbeds( .sendMessageEmbeds(
EmbedFactory.create() EmbedFactory.create()

View file

@ -50,7 +50,7 @@ public class MemberCounterListener extends ListenerAdapter implements Lifecycle
} }
@Override @Override
public void onGuildMemberJoin(GuildMemberJoinEvent event) { public void onGuildMemberJoin(final GuildMemberJoinEvent event) {
// Игнорируем ботов // Игнорируем ботов
if (event.getUser().isBot()) { if (event.getUser().isBot()) {
return; return;
@ -64,7 +64,7 @@ public class MemberCounterListener extends ListenerAdapter implements Lifecycle
} }
@Override @Override
public void onGuildMemberRemove(GuildMemberRemoveEvent event) { public void onGuildMemberRemove(final GuildMemberRemoveEvent event) {
// Игнорируем ботов // Игнорируем ботов
if (event.getUser().isBot()) { if (event.getUser().isBot()) {
return; return;

View file

@ -46,7 +46,7 @@ public class EconomyCommandRegistrar implements CommandRegistrar {
} }
@Override @Override
public void register(CommandRegistry registry) { public void register(final CommandRegistry registry) {
registry.register(new BalanceCommand(economyService)); registry.register(new BalanceCommand(economyService));
registry.register(new BaltopCommand(economyService)); registry.register(new BaltopCommand(economyService));
registry.register(new PayCommand(economyService)); registry.register(new PayCommand(economyService));

View file

@ -26,44 +26,43 @@ public class EconomyModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
EconomyRepository provideEconomyRepository(Database database) { EconomyRepository provideEconomyRepository(final Database database) {
return new SqlEconomyRepository(database); return new SqlEconomyRepository(database);
} }
@Provides @Provides
@Singleton @Singleton
EconomyService provideEconomyService( EconomyService provideEconomyService(final EconomyRepository repository, final CooldownManager cooldownManager) {
EconomyRepository repository, CooldownManager cooldownManager) {
return new EconomyService(repository, cooldownManager); return new EconomyService(repository, cooldownManager);
} }
@Provides @Provides
@Singleton @Singleton
FishingService provideFishingService(EconomyRepository repository) { FishingService provideFishingService(final EconomyRepository repository) {
return new FishingService(repository); return new FishingService(repository);
} }
@Provides @Provides
@Singleton @Singleton
BlackjackService provideBlackjackService(EconomyRepository repository) { BlackjackService provideBlackjackService(final EconomyRepository repository) {
return new BlackjackService(repository); return new BlackjackService(repository);
} }
@Provides @Provides
@Singleton @Singleton
SlotService provideSlotService(EconomyRepository repository) { SlotService provideSlotService(final EconomyRepository repository) {
return new SlotService(repository); return new SlotService(repository);
} }
@Provides @Provides
@Singleton @Singleton
JobService provideJobService(EconomyRepository repository) { JobService provideJobService(final EconomyRepository repository) {
return new JobService(repository); return new JobService(repository);
} }
@Provides @Provides
@Singleton @Singleton
FishMessageListener provideFishMessageListener(FishingService fishingService) { FishMessageListener provideFishMessageListener(final FishingService fishingService) {
return new FishMessageListener(fishingService); return new FishMessageListener(fishingService);
} }
} }

View file

@ -21,7 +21,7 @@ public class FishMessageListener extends ListenerAdapter {
} }
@Override @Override
public void onMessageReceived(@NotNull MessageReceivedEvent event) { public void onMessageReceived(@NotNull final MessageReceivedEvent event) {
if (event.getAuthor().isBot()) return; if (event.getAuthor().isBot()) return;
String content = event.getMessage().getContentRaw().trim(); String content = event.getMessage().getContentRaw().trim();

View file

@ -39,7 +39,7 @@ public class BankCommand implements Command {
} }
@Override @Override
public void execute(CommandContext ctx) { public void execute(final CommandContext ctx) {
List<String> args = ctx.getArgs(); List<String> args = ctx.getArgs();
String uid = ctx.getAuthor().getId(); String uid = ctx.getAuthor().getId();
if (args.isEmpty() || args.get(0).equalsIgnoreCase("balance")) { if (args.isEmpty() || args.get(0).equalsIgnoreCase("balance")) {

View file

@ -39,7 +39,7 @@ public class BalanceCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
List<Member> mentioned = context.getMessage().getMentions().getMembers(); List<Member> mentioned = context.getMessage().getMentions().getMembers();
Member target = mentioned.isEmpty() ? context.getAuthor() : mentioned.get(0); Member target = mentioned.isEmpty() ? context.getAuthor() : mentioned.get(0);

View file

@ -33,7 +33,7 @@ public class BaltopCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
List<EconomyAccount> top = economyService.getTopBalances(10); List<EconomyAccount> top = economyService.getTopBalances(10);
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();

View file

@ -32,7 +32,7 @@ public class DailyCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
EconomyService.DailyResult result = economyService.claimDaily(context.getAuthor().getId()); EconomyService.DailyResult result = economyService.claimDaily(context.getAuthor().getId());
if (result == null) { if (result == null) {

View file

@ -37,7 +37,7 @@ public class PayCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
List<Member> mentioned = context.getMessage().getMentions().getMembers(); List<Member> mentioned = context.getMessage().getMentions().getMembers();
if (mentioned.isEmpty()) { if (mentioned.isEmpty()) {
context context

View file

@ -39,7 +39,7 @@ public class JobCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
var args = context.getArgs(); var args = context.getArgs();
var userId = context.getAuthor().getId(); var userId = context.getAuthor().getId();
@ -67,7 +67,7 @@ public class JobCommand implements Command {
} }
} }
private void handleCurrent(CommandContext context, String userId) { private void handleCurrent(final CommandContext context, final String userId) {
String current = jobService.getCurrentJob(userId); String current = jobService.getCurrentJob(userId);
if (current == null) { if (current == null) {
context context
@ -102,7 +102,7 @@ public class JobCommand implements Command {
.queue(); .queue();
} }
private void handleList(CommandContext context) { private void handleList(final CommandContext context) {
var jobs = jobService.listJobs(); var jobs = jobService.listJobs();
var desc = new StringBuilder(); var desc = new StringBuilder();
@ -131,7 +131,7 @@ public class JobCommand implements Command {
.queue(); .queue();
} }
private void handleJoin(CommandContext context, String userId, String name) { private void handleJoin(final CommandContext context, final String userId, final String name) {
var jobs = jobService.listJobs(); var jobs = jobService.listJobs();
JobService.JobInfo target = null; JobService.JobInfo target = null;
@ -168,7 +168,7 @@ public class JobCommand implements Command {
.queue(); .queue();
} }
private JobService.JobInfo findJob(String name) { private JobService.JobInfo findJob(final String name) {
for (var job : jobService.listJobs()) { for (var job : jobService.listJobs()) {
if (job.name().equalsIgnoreCase(name) || job.displayName().equalsIgnoreCase(name)) { if (job.name().equalsIgnoreCase(name) || job.displayName().equalsIgnoreCase(name)) {
return job; return job;

View file

@ -34,7 +34,7 @@ public class WorkCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
var userId = context.getAuthor().getId(); var userId = context.getAuthor().getId();
String currentJob = jobService.getCurrentJob(userId); String currentJob = jobService.getCurrentJob(userId);
@ -77,7 +77,7 @@ public class WorkCommand implements Command {
.queue(); .queue();
} }
private JobService.JobInfo findJob(String name) { private JobService.JobInfo findJob(final String name) {
for (var job : jobService.listJobs()) { for (var job : jobService.listJobs()) {
if (job.name().equalsIgnoreCase(name) || job.displayName().equalsIgnoreCase(name)) { if (job.name().equalsIgnoreCase(name) || job.displayName().equalsIgnoreCase(name)) {
return job; return job;

View file

@ -45,7 +45,7 @@ public class BlackjackCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
var args = context.getArgs(); var args = context.getArgs();
var userId = context.getAuthor().getId(); var userId = context.getAuthor().getId();
if (args.isEmpty()) { if (args.isEmpty()) {
@ -66,7 +66,7 @@ public class BlackjackCommand implements Command {
} }
} }
private void handleStart(CommandContext context, String userId, String betStr) { private void handleStart(final CommandContext context, final String userId, final String betStr) {
if (activeGames.contains(userId)) { if (activeGames.contains(userId)) {
context context
.getChannel() .getChannel()
@ -110,7 +110,7 @@ public class BlackjackCommand implements Command {
context.getChannel().sendMessageEmbeds(buildGameEmbed(state)).queue(); context.getChannel().sendMessageEmbeds(buildGameEmbed(state)).queue();
} }
private void handleAction(CommandContext context, String userId, boolean isHit) { private void handleAction(final CommandContext context, final String userId, final boolean isHit) {
if (!activeGames.contains(userId)) { if (!activeGames.contains(userId)) {
context context
.getChannel() .getChannel()
@ -125,7 +125,7 @@ public class BlackjackCommand implements Command {
context.getChannel().sendMessageEmbeds(buildGameEmbed(state)).queue(); context.getChannel().sendMessageEmbeds(buildGameEmbed(state)).queue();
} }
private MessageEmbed buildGameEmbed(BlackjackService.BlackjackState state) { private MessageEmbed buildGameEmbed(final BlackjackService.BlackjackState state) {
var embed = var embed =
EmbedFactory.create() EmbedFactory.create()
.withTitle("🃏 Блэкджек") .withTitle("🃏 Блэкджек")
@ -143,17 +143,17 @@ public class BlackjackCommand implements Command {
return embed.addField("Ставка", state.bet() + " LC", false).build(); return embed.addField("Ставка", state.bet() + " LC", false).build();
} }
private String formatCards(String[] cards, int sum) { private String formatCards(final String[] cards, final int sum) {
return String.join(" + ", cards) + " = " + sum; return String.join(" + ", cards) + " = " + sum;
} }
private String formatHiddenDealerCards(String[] cards) { private String formatHiddenDealerCards(final String[] cards) {
var sb = new StringBuilder("?"); var sb = new StringBuilder("?");
for (int i = 1; i < cards.length; i++) sb.append(" + ").append(cards[i]); for (int i = 1; i < cards.length; i++) sb.append(" + ").append(cards[i]);
return sb.toString(); return sb.toString();
} }
private String formatResult(BlackjackService.BlackjackState state) { private String formatResult(final BlackjackService.BlackjackState state) {
long payout = state.payout(); long payout = state.payout();
if (payout > state.bet()) return "🎉 Блэкджек! +" + payout + " LC"; if (payout > state.bet()) return "🎉 Блэкджек! +" + payout + " LC";
if (payout > 0) return "✅ Ты выиграл +" + payout + " LC"; if (payout > 0) return "✅ Ты выиграл +" + payout + " LC";

View file

@ -38,7 +38,7 @@ public class FishCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
var args = context.getArgs(); var args = context.getArgs();
var userId = context.getAuthor().getId(); var userId = context.getAuthor().getId();

View file

@ -41,7 +41,7 @@ public class SlotCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
var args = context.getArgs(); var args = context.getArgs();
var userId = context.getAuthor().getId(); var userId = context.getAuthor().getId();

View file

@ -46,7 +46,7 @@ public class RobCommand implements Command {
} }
@Override @Override
public void execute(CommandContext ctx) { public void execute(final CommandContext ctx) {
List<Member> mentioned = ctx.getMessage().getMentions().getMembers(); List<Member> mentioned = ctx.getMessage().getMentions().getMembers();
if (mentioned.isEmpty()) { if (mentioned.isEmpty()) {
ctx.getChannel() ctx.getChannel()

View file

@ -31,7 +31,7 @@ public class EconomyAccount {
this.lastWork = null; this.lastWork = null;
} }
EconomyAccount(EconomyAccountBuilder builder) { EconomyAccount(final EconomyAccountBuilder builder) {
this.userId = builder.userId; this.userId = builder.userId;
this.cash = builder.cash; this.cash = builder.cash;
this.bank = builder.bank; this.bank = builder.bank;
@ -98,27 +98,27 @@ public class EconomyAccount {
return cash + bank; return cash + bank;
} }
public EconomyAccount withCash(long cash) { public EconomyAccount withCash(final long cash) {
return new EconomyAccountBuilder(this).cash(cash).build(); return new EconomyAccountBuilder(this).cash(cash).build();
} }
public EconomyAccount withBank(long bank) { public EconomyAccount withBank(final long bank) {
return new EconomyAccountBuilder(this).bank(bank).build(); return new EconomyAccountBuilder(this).bank(bank).build();
} }
public EconomyAccount withAddedEarned(long amount) { public EconomyAccount withAddedEarned(final long amount) {
return new EconomyAccountBuilder(this).totalEarned(this.totalEarned + amount).build(); return new EconomyAccountBuilder(this).totalEarned(this.totalEarned + amount).build();
} }
public EconomyAccount withAddedSpent(long amount) { public EconomyAccount withAddedSpent(final long amount) {
return new EconomyAccountBuilder(this).totalSpent(this.totalSpent + amount).build(); return new EconomyAccountBuilder(this).totalSpent(this.totalSpent + amount).build();
} }
public EconomyAccount withFishingLuck(int level) { public EconomyAccount withFishingLuck(final int level) {
return new EconomyAccountBuilder(this).fishingLuck(level).build(); return new EconomyAccountBuilder(this).fishingLuck(level).build();
} }
public EconomyAccount withEfficiency(int level) { public EconomyAccount withEfficiency(final int level) {
return new EconomyAccountBuilder(this).efficiency(level).build(); return new EconomyAccountBuilder(this).efficiency(level).build();
} }

View file

@ -16,7 +16,7 @@ public class EconomyAccountBuilder {
public EconomyAccountBuilder() {} public EconomyAccountBuilder() {}
public EconomyAccountBuilder(EconomyAccount existing) { public EconomyAccountBuilder(final EconomyAccount existing) {
this.userId = existing.getUserId(); this.userId = existing.getUserId();
this.cash = existing.getCash(); this.cash = existing.getCash();
this.bank = existing.getBank(); this.bank = existing.getBank();

View file

@ -42,7 +42,7 @@ public enum Job {
return emoji; return emoji;
} }
public static Job fromName(String name) { public static Job fromName(final String name) {
for (Job j : values()) { for (Job j : values()) {
if (j.name().equalsIgnoreCase(name) || j.getDisplayName().equalsIgnoreCase(name)) { if (j.name().equalsIgnoreCase(name) || j.getDisplayName().equalsIgnoreCase(name)) {
return j; return j;

View file

@ -29,7 +29,7 @@ public enum SlotCombination {
return chance; return chance;
} }
public static SlotCombination match(String e1, String e2, String e3) { public static SlotCombination match(final String e1, final String e2, final String e3) {
if (!e1.equals(e2) || !e2.equals(e3)) return null; if (!e1.equals(e2) || !e2.equals(e3)) return null;
for (SlotCombination sc : values()) { for (SlotCombination sc : values()) {
if (sc.emojis[0].equals(e1)) return sc; if (sc.emojis[0].equals(e1)) return sc;

View file

@ -6,15 +6,15 @@ import java.util.Optional;
import creator.loki.feature.economy.domain.EconomyAccount; import creator.loki.feature.economy.domain.EconomyAccount;
public interface EconomyRepository { public interface EconomyRepository {
Optional<EconomyAccount> findById(String userId); Optional<EconomyAccount> findById(final String userId);
void save(EconomyAccount account); void save(final EconomyAccount account);
boolean exists(String userId); boolean exists(final String userId);
List<EconomyAccount> findTopByBalance(int limit); List<EconomyAccount> findTopByBalance(final int limit);
default EconomyAccount getAccount(String userId) { default EconomyAccount getAccount(final String userId) {
return findById(userId).orElse(new EconomyAccount(userId)); return findById(userId).orElse(new EconomyAccount(userId));
} }
} }

View file

@ -43,7 +43,7 @@ public class SqlEconomyRepository implements EconomyRepository {
+ "job = excluded.job, last_work = excluded.last_work"; + "job = excluded.job, last_work = excluded.last_work";
} }
private static void setNullableString(PreparedStatement stmt, int index, String value) private static void setNullableString(PreparedStatement stmt, final int index, final String value)
throws SQLException { throws SQLException {
if (value != null) { if (value != null) {
stmt.setString(index, value); stmt.setString(index, value);
@ -53,7 +53,7 @@ public class SqlEconomyRepository implements EconomyRepository {
} }
@Override @Override
public Optional<EconomyAccount> findById(String userId) { public Optional<EconomyAccount> findById(final String userId) {
var sql = selectSql(); var sql = selectSql();
try (var stmt = database.prepare(sql)) { try (var stmt = database.prepare(sql)) {
stmt.setString(1, userId); stmt.setString(1, userId);
@ -69,7 +69,7 @@ public class SqlEconomyRepository implements EconomyRepository {
} }
@Override @Override
public void save(EconomyAccount account) { public void save(final EconomyAccount account) {
var sql = upsertSql(); var sql = upsertSql();
try (var stmt = database.prepare(sql)) { try (var stmt = database.prepare(sql)) {
stmt.setString(1, account.getUserId()); stmt.setString(1, account.getUserId());
@ -91,7 +91,7 @@ public class SqlEconomyRepository implements EconomyRepository {
} }
@Override @Override
public boolean exists(String userId) { public boolean exists(final String userId) {
var sql = "SELECT 1 FROM economy WHERE user_id = ?"; var sql = "SELECT 1 FROM economy WHERE user_id = ?";
try (var stmt = database.prepare(sql)) { try (var stmt = database.prepare(sql)) {
stmt.setString(1, userId); stmt.setString(1, userId);
@ -105,7 +105,7 @@ public class SqlEconomyRepository implements EconomyRepository {
} }
@Override @Override
public List<EconomyAccount> findTopByBalance(int limit) { public List<EconomyAccount> findTopByBalance(final int limit) {
var lim = clampLimit(limit); var lim = clampLimit(limit);
var sql = var sql =
"SELECT " "SELECT "
@ -125,12 +125,12 @@ public class SqlEconomyRepository implements EconomyRepository {
return Collections.unmodifiableList(list); return Collections.unmodifiableList(list);
} }
private static int clampLimit(int limit) { private static int clampLimit(final int limit) {
if (limit <= 0) return 1; if (limit <= 0) return 1;
return Math.min(limit, MAX_TOP); return Math.min(limit, MAX_TOP);
} }
private EconomyAccount mapResultSetToAccount(ResultSet rs) throws SQLException { private EconomyAccount mapResultSetToAccount(final ResultSet rs) throws SQLException {
return new EconomyAccountBuilder() return new EconomyAccountBuilder()
.userId(rs.getString("user_id")) .userId(rs.getString("user_id"))
.cash(rs.getLong("cash")) .cash(rs.getLong("cash"))

View file

@ -22,11 +22,11 @@ public class EconomyService {
this.cooldownManager = cooldownManager; this.cooldownManager = cooldownManager;
} }
public EconomyAccount getAccount(String userId) { public EconomyAccount getAccount(final String userId) {
return repository.getAccount(userId); return repository.getAccount(userId);
} }
public boolean transfer(String fromId, String toId, long amount) { public boolean transfer(final String fromId, final String toId, long amount) {
if (amount <= 0) return false; if (amount <= 0) return false;
EconomyAccount from = repository.getAccount(fromId); EconomyAccount from = repository.getAccount(fromId);
if (from.getCash() < amount) return false; if (from.getCash() < amount) return false;
@ -36,7 +36,7 @@ public class EconomyService {
return true; return true;
} }
public boolean deposit(String userId, long amount) { public boolean deposit(final String userId, long amount) {
if (amount <= 0) return false; if (amount <= 0) return false;
EconomyAccount account = repository.getAccount(userId); EconomyAccount account = repository.getAccount(userId);
if (account.getCash() < amount) return false; if (account.getCash() < amount) return false;
@ -45,7 +45,7 @@ public class EconomyService {
return true; return true;
} }
public boolean withdraw(String userId, long amount) { public boolean withdraw(final String userId, long amount) {
if (amount <= 0) return false; if (amount <= 0) return false;
EconomyAccount account = repository.getAccount(userId); EconomyAccount account = repository.getAccount(userId);
if (account.getBank() < amount) return false; if (account.getBank() < amount) return false;
@ -54,14 +54,14 @@ public class EconomyService {
return true; return true;
} }
public long earnCash(String userId, long amount) { public long earnCash(final String userId, long amount) {
EconomyAccount account = repository.getAccount(userId); EconomyAccount account = repository.getAccount(userId);
EconomyAccount updated = account.withCash(account.getCash() + amount).withAddedEarned(amount); EconomyAccount updated = account.withCash(account.getCash() + amount).withAddedEarned(amount);
repository.save(updated); repository.save(updated);
return updated.getCash(); return updated.getCash();
} }
public boolean spendCash(String userId, long amount) { public boolean spendCash(final String userId, long amount) {
if (amount <= 0) return false; if (amount <= 0) return false;
EconomyAccount account = repository.getAccount(userId); EconomyAccount account = repository.getAccount(userId);
if (account.getCash() < amount) return false; if (account.getCash() < amount) return false;
@ -69,7 +69,7 @@ public class EconomyService {
return true; return true;
} }
public DailyResult claimDaily(String userId) { public DailyResult claimDaily(final String userId) {
EconomyAccount account = repository.getAccount(userId); EconomyAccount account = repository.getAccount(userId);
String today = LocalDate.now().toString(); String today = LocalDate.now().toString();
if (today.equals(account.getLastDaily())) return null; if (today.equals(account.getLastDaily())) return null;
@ -93,7 +93,7 @@ public class EconomyService {
return new DailyResult(amount, streak, newCash); return new DailyResult(amount, streak, newCash);
} }
public int upgradeFishingLuck(String userId) { public int upgradeFishingLuck(final String userId) {
EconomyAccount account = repository.getAccount(userId); EconomyAccount account = repository.getAccount(userId);
if (account.getFishingLuck() >= 5) return -1; if (account.getFishingLuck() >= 5) return -1;
long cost = 800L * (account.getFishingLuck() + 1); long cost = 800L * (account.getFishingLuck() + 1);
@ -104,7 +104,7 @@ public class EconomyService {
return newLevel; return newLevel;
} }
public int upgradeEfficiency(String userId) { public int upgradeEfficiency(final String userId) {
EconomyAccount account = repository.getAccount(userId); EconomyAccount account = repository.getAccount(userId);
if (account.getEfficiency() >= 5) return -1; if (account.getEfficiency() >= 5) return -1;
long cost = 800L * (account.getEfficiency() + 1); long cost = 800L * (account.getEfficiency() + 1);
@ -115,7 +115,7 @@ public class EconomyService {
return newLevel; return newLevel;
} }
public List<EconomyAccount> getTopBalances(int limit) { public List<EconomyAccount> getTopBalances(final int limit) {
return repository.findTopByBalance(limit); return repository.findTopByBalance(limit);
} }

View file

@ -30,7 +30,7 @@ public class FishingService {
private record ActiveFish( private record ActiveFish(
String targetFish, int correctCount, long startTime, String difficulty, String[] grid) {} String targetFish, int correctCount, long startTime, String difficulty, String[] grid) {}
public FishResult startFishing(String userId, String difficulty) { public FishResult startFishing(final String userId, final String difficulty) {
EconomyAccount account = repository.getAccount(userId); EconomyAccount account = repository.getAccount(userId);
if (account.getLastFish() != null) { if (account.getLastFish() != null) {
long elapsed = System.currentTimeMillis() - Long.parseLong(account.getLastFish()); long elapsed = System.currentTimeMillis() - Long.parseLong(account.getLastFish());
@ -98,13 +98,13 @@ public class FishingService {
return new FishResult(rows, targetFish, correctCount, 0, account.getCash()); return new FishResult(rows, targetFish, correctCount, 0, account.getCash());
} }
public FishResult checkAnswer(String userId, int answer) { public FishResult checkAnswer(final String userId, int answer) {
ActiveFish session = activeFishing.get(userId); ActiveFish session = activeFishing.get(userId);
if (session == null) return null; if (session == null) return null;
return checkAnswer(userId, answer, session.startTime(), session.difficulty()); return checkAnswer(userId, answer, session.startTime(), session.difficulty());
} }
public FishResult checkAnswer(String userId, int answer, long startTime, String difficulty) { public FishResult checkAnswer(final String userId, int answer, final long startTime, final String difficulty) {
ActiveFish session = activeFishing.remove(userId); ActiveFish session = activeFishing.remove(userId);
if (session == null) return null; if (session == null) return null;
if (session.startTime() != startTime || !session.difficulty().equals(difficulty)) return null; if (session.startTime() != startTime || !session.difficulty().equals(difficulty)) return null;

View file

@ -27,7 +27,7 @@ public class BlackjackService {
private record ActiveBlackjack( private record ActiveBlackjack(
List<String> playerCards, List<String> dealerCards, long bet, String userId) {} List<String> playerCards, List<String> dealerCards, long bet, String userId) {}
public BlackjackState startGame(String userId, long bet) { public BlackjackState startGame(final String userId, final long bet) {
if (bet <= 0 || activeGames.containsKey(userId)) return null; if (bet <= 0 || activeGames.containsKey(userId)) return null;
var account = repository.getAccount(userId); var account = repository.getAccount(userId);
if (account.getCash() < bet) return null; if (account.getCash() < bet) return null;
@ -52,7 +52,7 @@ public class BlackjackService {
return buildState(playerCards, dealerCards, playerSum, dealerSum, bet, false, 0); return buildState(playerCards, dealerCards, playerSum, dealerSum, bet, false, 0);
} }
public BlackjackState hit(String userId) { public BlackjackState hit(final String userId) {
var game = activeGames.get(userId); var game = activeGames.get(userId);
if (game == null) return null; if (game == null) return null;
@ -72,7 +72,7 @@ public class BlackjackService {
0); 0);
} }
public BlackjackState stand(String userId) { public BlackjackState stand(final String userId) {
var game = activeGames.remove(userId); var game = activeGames.remove(userId);
if (game == null) return null; if (game == null) return null;
@ -91,7 +91,7 @@ public class BlackjackService {
game.playerCards(), dealerCards, playerSum, dealerSum, game.bet(), true, payout); game.playerCards(), dealerCards, playerSum, dealerSum, game.bet(), true, payout);
} }
private void creditUser(String userId, long amount) { private void creditUser(final String userId, final long amount) {
if (amount <= 0) return; if (amount <= 0) return;
var account = repository.getAccount(userId); var account = repository.getAccount(userId);
repository.save(account.withCash(account.getCash() + amount)); repository.save(account.withCash(account.getCash() + amount));
@ -101,7 +101,7 @@ public class BlackjackService {
return DECK[ThreadLocalRandom.current().nextInt(DECK.length)]; return DECK[ThreadLocalRandom.current().nextInt(DECK.length)];
} }
private int calculateSum(List<String> cards) { private int calculateSum(final List<String> cards) {
var sum = 0; var sum = 0;
var aces = 0; var aces = 0;
for (var c : cards) { for (var c : cards) {
@ -121,14 +121,7 @@ public class BlackjackService {
return sum; return sum;
} }
private BlackjackState buildState( private BlackjackState buildState(final List<String> playerCards, final List<String> dealerCards, final int playerSum, final int dealerSum, final long bet, final boolean isOver, final long payout) {
List<String> playerCards,
List<String> dealerCards,
int playerSum,
int dealerSum,
long bet,
boolean isOver,
long payout) {
return new BlackjackState( return new BlackjackState(
playerCards.toArray(String[]::new), playerCards.toArray(String[]::new),
dealerCards.toArray(String[]::new), dealerCards.toArray(String[]::new),

View file

@ -23,7 +23,7 @@ public class JobService {
this.repository = repository; this.repository = repository;
} }
public void setJob(String userId, String jobName) { public void setJob(final String userId, String jobName) {
Job job = Job.fromName(jobName); Job job = Job.fromName(jobName);
if (job == null) return; if (job == null) return;
EconomyAccount account = repository.getAccount(userId); EconomyAccount account = repository.getAccount(userId);
@ -31,7 +31,7 @@ public class JobService {
repository.save(updated); repository.save(updated);
} }
public WorkResult work(String userId, int userLevel) { public WorkResult work(final String userId, final int userLevel) {
EconomyAccount account = repository.getAccount(userId); EconomyAccount account = repository.getAccount(userId);
String jobName = account.getJob(); String jobName = account.getJob();
if (jobName == null) return null; if (jobName == null) return null;
@ -76,7 +76,7 @@ public class JobService {
return infos; return infos;
} }
public String getCurrentJob(String userId) { public String getCurrentJob(final String userId) {
EconomyAccount account = repository.getAccount(userId); EconomyAccount account = repository.getAccount(userId);
String jobName = account.getJob(); String jobName = account.getJob();
if (jobName == null) return null; if (jobName == null) return null;

View file

@ -24,7 +24,7 @@ public class SlotService {
this.repository = repository; this.repository = repository;
} }
public SlotResult spin(String userId, long bet) { public SlotResult spin(final String userId, final long bet) {
if (bet <= 0) return null; if (bet <= 0) return null;
EconomyAccount account = repository.getAccount(userId); EconomyAccount account = repository.getAccount(userId);
if (account.getCash() < bet) return null; if (account.getCash() < bet) return null;

View file

@ -55,7 +55,7 @@ public class EntertainmentCommandRegistrar implements CommandRegistrar {
} }
@Override @Override
public void register(CommandRegistry registry) { public void register(final CommandRegistry registry) {
registry.register(new EightBallCommand()); registry.register(new EightBallCommand());
registry.register(new CoinCommand()); registry.register(new CoinCommand());
registry.register(new DiceCommand()); registry.register(new DiceCommand());

View file

@ -34,7 +34,7 @@ public class GlazbobaCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
List<Member> mentioned = context.getMessage().getMentions().getMembers(); List<Member> mentioned = context.getMessage().getMentions().getMembers();
if (mentioned.isEmpty()) { if (mentioned.isEmpty()) {
context.getChannel().sendMessage("Укажи пользователя через @").queue(); context.getChannel().sendMessage("Укажи пользователя через @").queue();

View file

@ -37,7 +37,7 @@ public class MemeCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
context context
.getChannel() .getChannel()
.sendMessage("🔍 Ищу мем...") .sendMessage("🔍 Ищу мем...")

View file

@ -51,7 +51,7 @@ public class RandomChoiceCommand implements Command {
this.templates = templates; this.templates = templates;
} }
String randomLine(String pick) { String randomLine(final String pick) {
var rnd = ThreadLocalRandom.current(); var rnd = ThreadLocalRandom.current();
return String.format(templates[rnd.nextInt(templates.length)], pick); return String.format(templates[rnd.nextInt(templates.length)], pick);
} }
@ -88,7 +88,7 @@ public class RandomChoiceCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
String p = config.getPrefix(); String p = config.getPrefix();
String tail = String tail =
ChoiceOptionParser.tailAfterCommand(context.getMessage().getContentRaw(), p, commandName); ChoiceOptionParser.tailAfterCommand(context.getMessage().getContentRaw(), p, commandName);
@ -123,11 +123,11 @@ public class RandomChoiceCommand implements Command {
reply(context, embed.build()); reply(context, embed.build());
} }
private static void reply(CommandContext ctx, net.dv8tion.jda.api.entities.MessageEmbed embed) { private static void reply(final CommandContext ctx, final net.dv8tion.jda.api.entities.MessageEmbed embed) {
ctx.getChannel().sendMessageEmbeds(embed).queue(); ctx.getChannel().sendMessageEmbeds(embed).queue();
} }
private String usageExamples(String p) { private String usageExamples(final String p) {
return "**Примеры:**\n" return "**Примеры:**\n"
+ "`" + "`"
+ p + p

View file

@ -32,7 +32,7 @@ public class CoinCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
boolean isHeads = random.nextBoolean(); boolean isHeads = random.nextBoolean();
String result = isHeads ? "Орёл" : "Решка"; String result = isHeads ? "Орёл" : "Решка";
String emoji = isHeads ? "🦅" : "🪙"; String emoji = isHeads ? "🦅" : "🪙";

View file

@ -32,7 +32,7 @@ public class DiceCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
int maxValue = 6; int maxValue = 6;
if (!context.getArgs().isEmpty()) { if (!context.getArgs().isEmpty()) {

View file

@ -54,7 +54,7 @@ public class EightBallCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
if (context.getArgs().isEmpty()) { if (context.getArgs().isEmpty()) {
context.getChannel().sendMessage("Задай вопрос!").queue(); context.getChannel().sendMessage("Задай вопрос!").queue();
return; return;

View file

@ -22,18 +22,18 @@ public class RatingService {
this.cooldownManager = cooldownManager; this.cooldownManager = cooldownManager;
} }
public int getDeterministicValue(String userId, int salt, int min, int max) { public int getDeterministicValue(final String userId, final int salt, final int min, final int max) {
long seed = Long.parseLong(userId) + salt; long seed = Long.parseLong(userId) + salt;
RANDOM.setSeed(seed); RANDOM.setSeed(seed);
return RANDOM.nextInt(max - min + 1) + min; return RANDOM.nextInt(max - min + 1) + min;
} }
public Member resolveTarget(CommandContext context) { public Member resolveTarget(final CommandContext context) {
List<Member> mentioned = context.getMessage().getMentions().getMembers(); List<Member> mentioned = context.getMessage().getMentions().getMembers();
return mentioned.isEmpty() ? context.getAuthor() : mentioned.get(0); return mentioned.isEmpty() ? context.getAuthor() : mentioned.get(0);
} }
public boolean checkAndApplyCooldown(CommandContext context, String commandName) { public boolean checkAndApplyCooldown(final CommandContext context, final String commandName) {
if (cooldownManager.isOnCooldown(context.getAuthor().getId(), commandName)) { if (cooldownManager.isOnCooldown(context.getAuthor().getId(), commandName)) {
long remaining = long remaining =
cooldownManager.getRemainingSeconds(context.getAuthor().getId(), commandName); cooldownManager.getRemainingSeconds(context.getAuthor().getId(), commandName);

View file

@ -31,7 +31,7 @@ public class HelpMenuHandler extends ListenerAdapter {
} }
@Override @Override
public void onStringSelectInteraction(StringSelectInteractionEvent event) { public void onStringSelectInteraction(final StringSelectInteractionEvent event) {
if (!event.getComponentId().equals("help:category")) { if (!event.getComponentId().equals("help:category")) {
return; return;
} }
@ -100,8 +100,7 @@ public class HelpMenuHandler extends ListenerAdapter {
event.editMessageEmbeds(embed.build()).setComponents(ActionRow.of(menuBuilder.build())).queue(); event.editMessageEmbeds(embed.build()).setComponents(ActionRow.of(menuBuilder.build())).queue();
} }
private EmbedFactory createCategoryEmbed( private EmbedFactory createCategoryEmbed(final String category, final List<Command> commands, final StringSelectInteractionEvent event) {
String category, List<Command> commands, StringSelectInteractionEvent event) {
String emoji = HelpCategories.getEmoji(category); String emoji = HelpCategories.getEmoji(category);
Color color = HelpCategories.getColor(category); Color color = HelpCategories.getColor(category);
@ -153,7 +152,7 @@ public class HelpMenuHandler extends ListenerAdapter {
return embed; return embed;
} }
private static boolean isNsfw(StringSelectInteractionEvent event) { private static boolean isNsfw(final StringSelectInteractionEvent event) {
return event.getChannel() instanceof IAgeRestrictedChannel arc && arc.isNSFW(); return event.getChannel() instanceof IAgeRestrictedChannel arc && arc.isNSFW();
} }
} }

View file

@ -38,7 +38,7 @@ public class HelpCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
var commands = registry.getAllCommands(); var commands = registry.getAllCommands();
Map<String, List<Command>> commandsByCategory = Map<String, List<Command>> commandsByCategory =
commands.stream().collect(Collectors.groupingBy(Command::getCategory)); commands.stream().collect(Collectors.groupingBy(Command::getCategory));
@ -86,16 +86,11 @@ public class HelpCommand implements Command {
.queue(); .queue();
} }
private static boolean isNsfw(CommandContext context) { private static boolean isNsfw(final CommandContext context) {
return context.getChannel() instanceof IAgeRestrictedChannel arc && arc.isNSFW(); return context.getChannel() instanceof IAgeRestrictedChannel arc && arc.isNSFW();
} }
private EmbedFactory createMainPage( private EmbedFactory createMainPage(final CommandContext context, final Map<String, List<Command>> commandsByCategory, final boolean isAdmin, final boolean isSuper, final boolean isNsfwChannel) {
CommandContext context,
Map<String, List<Command>> commandsByCategory,
boolean isAdmin,
boolean isSuper,
boolean isNsfwChannel) {
int totalCommands = int totalCommands =
commandsByCategory.entrySet().stream() commandsByCategory.entrySet().stream()
.filter( .filter(

View file

@ -25,7 +25,7 @@ public class ImageModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
ImageService provideImageService(BotConfig config) { ImageService provideImageService(final BotConfig config) {
return new ImageService(config); return new ImageService(config);
} }
} }

View file

@ -47,7 +47,7 @@ public abstract class AbstractImageCommand implements Command {
// ── Общая логика execute ───────────────────────────────────────────────────── // ── Общая логика execute ─────────────────────────────────────────────────────
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
if (!isNsfwChannel(context)) { if (!isNsfwChannel(context)) {
context context
.getChannel() .getChannel()
@ -101,7 +101,7 @@ public abstract class AbstractImageCommand implements Command {
// ── Вспомогательное ────────────────────────────────────────────────────────── // ── Вспомогательное ──────────────────────────────────────────────────────────
protected static ParseResult parseArgs(List<String> args) { protected static ParseResult parseArgs(final List<String> args) {
if (args.isEmpty()) return new ParseResult(DEFAULT_FETCH, ""); if (args.isEmpty()) return new ParseResult(DEFAULT_FETCH, "");
try { try {
int count = Integer.parseInt(args.get(0)); int count = Integer.parseInt(args.get(0));
@ -113,7 +113,7 @@ public abstract class AbstractImageCommand implements Command {
} }
} }
protected boolean isNsfwChannel(CommandContext context) { protected boolean isNsfwChannel(final CommandContext context) {
return context.getChannel() instanceof IAgeRestrictedChannel arc && arc.isNSFW(); return context.getChannel() instanceof IAgeRestrictedChannel arc && arc.isNSFW();
} }

View file

@ -10,7 +10,7 @@ import creator.loki.feature.image.commands.AbstractImageCommand;
public class GelbooruCommand extends AbstractImageCommand { public class GelbooruCommand extends AbstractImageCommand {
public GelbooruCommand(ImageService imageService, ImageSessionManager sessionManager) { public GelbooruCommand(final ImageService imageService, final ImageSessionManager sessionManager) {
super(imageService, sessionManager); super(imageService, sessionManager);
} }
@ -50,7 +50,7 @@ public class GelbooruCommand extends AbstractImageCommand {
} }
@Override @Override
protected List<String> fetchUrls(String tags, int limit) { protected List<String> fetchUrls(final String tags, final int limit) {
return imageService.fetchGelbooru(tags, limit); return imageService.fetchGelbooru(tags, limit);
} }
} }

View file

@ -10,7 +10,7 @@ import creator.loki.feature.image.commands.AbstractImageCommand;
public class YandereCommand extends AbstractImageCommand { public class YandereCommand extends AbstractImageCommand {
public YandereCommand(ImageService imageService, ImageSessionManager sessionManager) { public YandereCommand(final ImageService imageService, final ImageSessionManager sessionManager) {
super(imageService, sessionManager); super(imageService, sessionManager);
} }
@ -50,7 +50,7 @@ public class YandereCommand extends AbstractImageCommand {
} }
@Override @Override
protected List<String> fetchUrls(String tags, int limit) { protected List<String> fetchUrls(final String tags, final int limit) {
return imageService.fetchYandere(tags, limit); return imageService.fetchYandere(tags, limit);
} }
} }

View file

@ -10,7 +10,7 @@ import creator.loki.feature.image.commands.AbstractImageCommand;
public class E621Command extends AbstractImageCommand { public class E621Command extends AbstractImageCommand {
public E621Command(ImageService imageService, ImageSessionManager sessionManager) { public E621Command(final ImageService imageService, final ImageSessionManager sessionManager) {
super(imageService, sessionManager); super(imageService, sessionManager);
} }
@ -50,7 +50,7 @@ public class E621Command extends AbstractImageCommand {
} }
@Override @Override
protected List<String> fetchUrls(String tags, int limit) { protected List<String> fetchUrls(final String tags, final int limit) {
return imageService.fetchE621(tags, limit); return imageService.fetchE621(tags, limit);
} }
} }

View file

@ -14,7 +14,7 @@ import creator.loki.feature.image.commands.AbstractImageCommand;
public class E621RandomCommand extends AbstractImageCommand { public class E621RandomCommand extends AbstractImageCommand {
public E621RandomCommand(ImageService imageService, ImageSessionManager sessionManager) { public E621RandomCommand(final ImageService imageService, final ImageSessionManager sessionManager) {
super(imageService, sessionManager); super(imageService, sessionManager);
} }
@ -54,13 +54,13 @@ public class E621RandomCommand extends AbstractImageCommand {
} }
@Override @Override
protected List<String> fetchUrls(String tags, int limit) { protected List<String> fetchUrls(final String tags, int limit) {
return imageService.fetchE621("", limit); // теги игнорируются — всегда случайные return imageService.fetchE621("", limit); // теги игнорируются — всегда случайные
} }
/** Переопределяем execute: теги не нужны, лимит берём из первого аргумента. */ /** Переопределяем execute: теги не нужны, лимит берём из первого аргумента. */
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
if (!isNsfwChannel(context)) { if (!isNsfwChannel(context)) {
context context
.getChannel() .getChannel()

View file

@ -30,7 +30,7 @@ public class ImageNavigationHandler extends ListenerAdapter {
} }
@Override @Override
public void onButtonInteraction(ButtonInteractionEvent event) { public void onButtonInteraction(final ButtonInteractionEvent event) {
String id = event.getComponentId(); String id = event.getComponentId();
if (!id.startsWith(PREFIX)) return; if (!id.startsWith(PREFIX)) return;
@ -57,7 +57,7 @@ public class ImageNavigationHandler extends ListenerAdapter {
// ── Вперёд ─────────────────────────────────────────────────────────────────── // ── Вперёд ───────────────────────────────────────────────────────────────────
private void handleNext(ButtonInteractionEvent event, ImageSession session, String messageId) { private void handleNext(final ButtonInteractionEvent event, final ImageSession session, final String messageId) {
if (session.hasNext()) { if (session.hasNext()) {
// Есть готовая следующая страница в кеше // Есть готовая следующая страница в кеше
logger.debug("nav: next in cache page={}/{}", session.page() + 1, session.totalPages()); logger.debug("nav: next in cache page={}/{}", session.page() + 1, session.totalPages());
@ -76,7 +76,7 @@ public class ImageNavigationHandler extends ListenerAdapter {
// ── Назад ──────────────────────────────────────────────────────────────────── // ── Назад ────────────────────────────────────────────────────────────────────
private void handlePrev(ButtonInteractionEvent event, ImageSession session, String messageId) { private void handlePrev(final ButtonInteractionEvent event, final ImageSession session, final String messageId) {
if (!session.hasPrev()) return; if (!session.hasPrev()) return;
logger.debug("nav: prev page={}/{}", session.page() - 1, session.totalPages()); logger.debug("nav: prev page={}/{}", session.page() - 1, session.totalPages());
ImageSession updated = session.withPage(session.page() - 1); ImageSession updated = session.withPage(session.page() - 1);
@ -86,7 +86,7 @@ public class ImageNavigationHandler extends ListenerAdapter {
// ── Подгрузка с API ────────────────────────────────────────────────────────── // ── Подгрузка с API ──────────────────────────────────────────────────────────
private void loadMore(ButtonInteractionEvent event, ImageSession session, String messageId) { private void loadMore(final ButtonInteractionEvent event, final ImageSession session, final String messageId) {
int nextApiPage = session.apiPage() + 1; int nextApiPage = session.apiPage() + 1;
logger.debug( logger.debug(
"loadMore: site={} tags='{}' apiPage={}", session.site(), session.tags(), nextApiPage); "loadMore: site={} tags='{}' apiPage={}", session.site(), session.tags(), nextApiPage);
@ -105,7 +105,7 @@ public class ImageNavigationHandler extends ListenerAdapter {
.queue(); .queue();
} }
private List<String> fetchPage(String site, String tags, int apiPage) { private List<String> fetchPage(final String site, final String tags, final int apiPage) {
return switch (site) { return switch (site) {
case "e621.net" -> imageService.fetchE621(tags, PAGE_FETCH, apiPage); case "e621.net" -> imageService.fetchE621(tags, PAGE_FETCH, apiPage);
case "gelbooru.com" -> imageService.fetchGelbooru(tags, PAGE_FETCH, apiPage); case "gelbooru.com" -> imageService.fetchGelbooru(tags, PAGE_FETCH, apiPage);
@ -116,7 +116,7 @@ public class ImageNavigationHandler extends ListenerAdapter {
// ── Вспомогательное ────────────────────────────────────────────────────────── // ── Вспомогательное ──────────────────────────────────────────────────────────
private static void editMessage(ButtonInteractionEvent event, ImageSession session) { private static void editMessage(final ButtonInteractionEvent event, final ImageSession session) {
event event
.editMessageEmbeds(ImageEmbedHelper.buildEmbeds(session)) .editMessageEmbeds(ImageEmbedHelper.buildEmbeds(session))
.setComponents(ImageEmbedHelper.buildActionRow(session)) .setComponents(ImageEmbedHelper.buildActionRow(session))

View file

@ -26,7 +26,7 @@ public class ImageService {
private final OkHttpClient client; private final OkHttpClient client;
@Inject @Inject
public ImageService(BotConfig config) { public ImageService(final BotConfig config) {
this.client = this.client =
new OkHttpClient.Builder() new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS) .connectTimeout(15, TimeUnit.SECONDS)
@ -44,7 +44,7 @@ public class ImageService {
Request request = Request request =
new Request.Builder().url(url).header("User-Agent", "LokiBot/1.0 (by loki)").get().build(); new Request.Builder().url(url).header("User-Agent", "LokiBot/1.0 (by loki)").get().build();
try (Response response = client.newCall(request).execute()) { try (final Response response = client.newCall(request).execute()) {
if (!response.isSuccessful() || response.body() == null) { if (!response.isSuccessful() || response.body() == null) {
logger.error("e621 API error: {} {}", response.code(), response.message()); logger.error("e621 API error: {} {}", response.code(), response.message());
return List.of(); return List.of();
@ -107,11 +107,11 @@ public class ImageService {
return fetchBooruJson(url, limit); return fetchBooruJson(url, limit);
} }
private List<String> fetchBooruJson(String url, int limit) { private List<String> fetchBooruJson(final String url, final int limit) {
Request request = Request request =
new Request.Builder().url(url).header("User-Agent", "LokiBot/1.0 (by loki)").get().build(); new Request.Builder().url(url).header("User-Agent", "LokiBot/1.0 (by loki)").get().build();
try (Response response = client.newCall(request).execute()) { try (final Response response = client.newCall(request).execute()) {
if (!response.isSuccessful() || response.body() == null) { if (!response.isSuccessful() || response.body() == null) {
logger.error("Booru API error: {} {}", response.code(), response.message()); logger.error("Booru API error: {} {}", response.code(), response.message());
return List.of(); return List.of();

View file

@ -28,14 +28,7 @@ public record ImageSession(
// ── Фабричный метод ────────────────────────────────────────────────────────── // ── Фабричный метод ──────────────────────────────────────────────────────────
public static ImageSession create( public static ImageSession create(final List<String> urls, final int pageSize, final String site, final java.awt.Color color, final String tags, final long userId, final long guildId) {
List<String> urls,
int pageSize,
String site,
java.awt.Color color,
String tags,
long userId,
long guildId) {
return new ImageSession( return new ImageSession(
urls, urls,
0, 0,
@ -73,7 +66,7 @@ public record ImageSession(
// ── Мутации (возвращают новый экземпляр) ──────────────────────────────────── // ── Мутации (возвращают новый экземпляр) ────────────────────────────────────
public ImageSession withPage(int newPage) { public ImageSession withPage(final int newPage) {
return new ImageSession( return new ImageSession(
urls, urls,
newPage, newPage,
@ -92,7 +85,7 @@ public record ImageSession(
* Добавляем новые URL из следующей API-страницы и переходим на следующую внутреннюю страницу. * Добавляем новые URL из следующей API-страницы и переходим на следующую внутреннюю страницу.
* Если newUrls пустой — помечаем сессию как exhausted. * Если newUrls пустой — помечаем сессию как exhausted.
*/ */
public ImageSession withMoreUrls(List<String> newUrls) { public ImageSession withMoreUrls(final List<String> newUrls) {
if (newUrls.isEmpty()) { if (newUrls.isEmpty()) {
// API больше ничего не отдал — остаёмся на месте, ставим флаг // API больше ничего не отдал — остаёмся на месте, ставим флаг
return new ImageSession( return new ImageSession(

View file

@ -11,12 +11,12 @@ public class ImageSessionManager {
private static final long SESSION_TTL = 5 * 60 * 1000; private static final long SESSION_TTL = 5 * 60 * 1000;
private final Map<String, ImageSession> sessions = new ConcurrentHashMap<>(); private final Map<String, ImageSession> sessions = new ConcurrentHashMap<>();
public void put(String messageId, ImageSession session) { public void put(final String messageId, ImageSession session) {
cleanup(); cleanup();
sessions.put(messageId, session); sessions.put(messageId, session);
} }
public ImageSession get(String messageId) { public ImageSession get(final String messageId) {
ImageSession session = sessions.get(messageId); ImageSession session = sessions.get(messageId);
if (session == null) return null; if (session == null) return null;
if (System.currentTimeMillis() - session.createdAt() > SESSION_TTL) { if (System.currentTimeMillis() - session.createdAt() > SESSION_TTL) {
@ -26,11 +26,11 @@ public class ImageSessionManager {
return session; return session;
} }
public void update(String messageId, ImageSession session) { public void update(final String messageId, final ImageSession session) {
sessions.put(messageId, session); sessions.put(messageId, session);
} }
public void remove(String messageId) { public void remove(final String messageId) {
sessions.remove(messageId); sessions.remove(messageId);
} }
@ -39,7 +39,7 @@ public class ImageSessionManager {
sessions.values().removeIf(s -> now - s.createdAt() > SESSION_TTL); sessions.values().removeIf(s -> now - s.createdAt() > SESSION_TTL);
} }
public static Color parseColor(String hex) { public static Color parseColor(final String hex) {
try { try {
return Color.decode(hex); return Color.decode(hex);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {

View file

@ -21,7 +21,7 @@ public class ImageCommandRegistrar implements CommandRegistrar {
} }
@Override @Override
public void register(CommandRegistry registry) { public void register(final CommandRegistry registry) {
registry.register(new E621Command(imageService, sessionManager)); registry.register(new E621Command(imageService, sessionManager));
registry.register(new E621RandomCommand(imageService, sessionManager)); registry.register(new E621RandomCommand(imageService, sessionManager));
registry.register(new GelbooruCommand(imageService, sessionManager)); registry.register(new GelbooruCommand(imageService, sessionManager));

View file

@ -18,7 +18,7 @@ public final class ImageEmbedHelper {
private ImageEmbedHelper() {} private ImageEmbedHelper() {}
public static MessageEmbed[] buildEmbeds(ImageSession session) { public static MessageEmbed[] buildEmbeds(final ImageSession session) {
String tagsStr = formatTags(session.tags()); String tagsStr = formatTags(session.tags());
List<MessageEmbed> embeds = new ArrayList<>(); List<MessageEmbed> embeds = new ArrayList<>();
List<String> pageUrls = session.currentPageUrls(); List<String> pageUrls = session.currentPageUrls();
@ -84,7 +84,7 @@ public final class ImageEmbedHelper {
return embeds.toArray(new MessageEmbed[0]); return embeds.toArray(new MessageEmbed[0]);
} }
public static ActionRow buildActionRow(ImageSession session) { public static ActionRow buildActionRow(final ImageSession session) {
boolean noPrev = !session.hasPrev(); boolean noPrev = !session.hasPrev();
boolean noNext = !session.hasNext() && session.exhausted(); boolean noNext = !session.hasNext() && session.exhausted();
return ActionRow.of( return ActionRow.of(
@ -111,7 +111,7 @@ public final class ImageEmbedHelper {
return (tags == null || tags.isBlank()) ? "" : " `" + tags + "`"; return (tags == null || tags.isBlank()) ? "" : " `" + tags + "`";
} }
private static String extension(String url) { private static String extension(final String url) {
int dot = url.lastIndexOf('.'); int dot = url.lastIndexOf('.');
if (dot < 0 || dot >= url.length() - 1) return ""; if (dot < 0 || dot >= url.length() - 1) return "";
int end = url.indexOf('?', dot); int end = url.indexOf('?', dot);
@ -119,7 +119,7 @@ public final class ImageEmbedHelper {
return url.substring(dot + 1, end).toLowerCase(); return url.substring(dot + 1, end).toLowerCase();
} }
private static boolean isVideoExt(String ext) { private static boolean isVideoExt(final String ext) {
return VIDEO_EXTS.contains(ext); return VIDEO_EXTS.contains(ext);
} }
} }

View file

@ -33,7 +33,7 @@ public class AvatarCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
User targetUser; User targetUser;
// Если упомянут пользователь - показываем его аватар // Если упомянут пользователь - показываем его аватар

View file

@ -32,7 +32,7 @@ public class InfoCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
String type = context.getArgs().isEmpty() ? "server" : context.getArgs().get(0).toLowerCase(); String type = context.getArgs().isEmpty() ? "server" : context.getArgs().get(0).toLowerCase();
switch (type) { switch (type) {
@ -47,7 +47,7 @@ public class InfoCommand implements Command {
} }
} }
private void showServerInfo(CommandContext context) { private void showServerInfo(final CommandContext context) {
Guild guild = context.getGuild(); Guild guild = context.getGuild();
if (guild == null) return; if (guild == null) return;
@ -78,7 +78,7 @@ public class InfoCommand implements Command {
.queue(); .queue();
} }
private void showUserInfo(CommandContext context) { private void showUserInfo(final CommandContext context) {
Member member = context.getAuthor(); Member member = context.getAuthor();
if (member == null) return; if (member == null) return;

View file

@ -20,7 +20,7 @@ public class PingCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
context context

View file

@ -39,7 +39,7 @@ public class ServerStatsCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
Guild guild = context.getGuild(); Guild guild = context.getGuild();
if (guild == null) { if (guild == null) {
context.getChannel().sendMessage("Только на сервере.").queue(); context.getChannel().sendMessage("Только на сервере.").queue();
@ -55,7 +55,7 @@ public class ServerStatsCommand implements Command {
} }
} }
private void handleEmbed(CommandContext context, Guild guild) { private void handleEmbed(final CommandContext context, final Guild guild) {
guild guild
.loadMembers() .loadMembers()
.onSuccess( .onSuccess(
@ -144,7 +144,7 @@ public class ServerStatsCommand implements Command {
}); });
} }
private void handleCsv(CommandContext context, Guild guild) { private void handleCsv(final CommandContext context, final Guild guild) {
context context
.getChannel() .getChannel()
.sendMessage("⏳ Генерирую CSV...") .sendMessage("⏳ Генерирую CSV...")
@ -165,7 +165,7 @@ public class ServerStatsCommand implements Command {
}); });
} }
private void handleChart(CommandContext context, Guild guild) { private void handleChart(final CommandContext context, final Guild guild) {
context context
.getChannel() .getChannel()
.sendMessage("⏳ Генерирую график...") .sendMessage("⏳ Генерирую график...")

View file

@ -17,7 +17,7 @@ public class LeaderboardButtonListener extends ListenerAdapter {
} }
@Override @Override
public void onButtonInteraction(ButtonInteractionEvent event) { public void onButtonInteraction(final ButtonInteractionEvent event) {
String buttonId = event.getComponentId(); String buttonId = event.getComponentId();
if (!buttonId.startsWith("lb_")) { if (!buttonId.startsWith("lb_")) {
@ -36,19 +36,19 @@ public class LeaderboardButtonListener extends ListenerAdapter {
} }
} }
private void showLevelLeaderboard(ButtonInteractionEvent event) { private void showLevelLeaderboard(final ButtonInteractionEvent event) {
var top = leaderboardService.getTopByLevel(10); var top = leaderboardService.getTopByLevel(10);
var embed = LeaderboardFormatter.formatLevelLeaderboard(top); var embed = LeaderboardFormatter.formatLevelLeaderboard(top);
event.getHook().editOriginalEmbeds(embed).queue(); event.getHook().editOriginalEmbeds(embed).queue();
} }
private void showMessageLeaderboard(ButtonInteractionEvent event) { private void showMessageLeaderboard(final ButtonInteractionEvent event) {
var top = leaderboardService.getTopByMessages(10); var top = leaderboardService.getTopByMessages(10);
var embed = LeaderboardFormatter.formatMessageLeaderboard(top); var embed = LeaderboardFormatter.formatMessageLeaderboard(top);
event.getHook().editOriginalEmbeds(embed).queue(); event.getHook().editOriginalEmbeds(embed).queue();
} }
private void showVoiceLeaderboard(ButtonInteractionEvent event) { private void showVoiceLeaderboard(final ButtonInteractionEvent event) {
var top = leaderboardService.getTopByVoice(10); var top = leaderboardService.getTopByVoice(10);
var embed = LeaderboardFormatter.formatVoiceLeaderboard(top); var embed = LeaderboardFormatter.formatVoiceLeaderboard(top);
event.getHook().editOriginalEmbeds(embed).queue(); event.getHook().editOriginalEmbeds(embed).queue();

View file

@ -37,7 +37,7 @@ public class LeaderboardCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
var top = leaderboardService.getTopByLevel(10); var top = leaderboardService.getTopByLevel(10);
if (top.isEmpty()) { if (top.isEmpty()) {

View file

@ -12,7 +12,7 @@ import net.dv8tion.jda.api.entities.MessageEmbed;
/** Форматирование таблиц лидеров (DRY принцип) */ /** Форматирование таблиц лидеров (DRY принцип) */
public class LeaderboardFormatter { public class LeaderboardFormatter {
public static MessageEmbed formatLevelLeaderboard(List<Map.Entry<String, UserStats>> top) { public static MessageEmbed formatLevelLeaderboard(final List<Map.Entry<String, UserStats>> top) {
return formatLeaderboard( return formatLeaderboard(
top, top,
"🏆 Топ-10 по уровням", "🏆 Топ-10 по уровням",
@ -23,7 +23,7 @@ public class LeaderboardFormatter {
}); });
} }
public static MessageEmbed formatMessageLeaderboard(List<Map.Entry<String, UserStats>> top) { public static MessageEmbed formatMessageLeaderboard(final List<Map.Entry<String, UserStats>> top) {
return formatLeaderboard( return formatLeaderboard(
top, top,
"💬 Топ-10 по сообщениям", "💬 Топ-10 по сообщениям",
@ -31,7 +31,7 @@ public class LeaderboardFormatter {
entry -> "**" + entry.getValue().getMessageCount() + "** сообщений"); entry -> "**" + entry.getValue().getMessageCount() + "** сообщений");
} }
public static MessageEmbed formatVoiceLeaderboard(List<Map.Entry<String, UserStats>> top) { public static MessageEmbed formatVoiceLeaderboard(final List<Map.Entry<String, UserStats>> top) {
return formatLeaderboard( return formatLeaderboard(
top, top,
"🎤 Топ-10 по времени в войсе", "🎤 Топ-10 по времени в войсе",
@ -44,11 +44,7 @@ public class LeaderboardFormatter {
}); });
} }
private static MessageEmbed formatLeaderboard( private static MessageEmbed formatLeaderboard(final List<Map.Entry<String, UserStats>> top, final String title, final Color color, final Function<Map.Entry<String, UserStats>, String> statFormatter) {
List<Map.Entry<String, UserStats>> top,
String title,
Color color,
Function<Map.Entry<String, UserStats>, String> statFormatter) {
StringBuilder description = new StringBuilder(); StringBuilder description = new StringBuilder();
int position = 1; int position = 1;
@ -79,7 +75,7 @@ public class LeaderboardFormatter {
.build(); .build();
} }
private static String getPositionEmoji(int position) { private static String getPositionEmoji(final int position) {
return switch (position) { return switch (position) {
case 1 -> "🥇"; case 1 -> "🥇";
case 2 -> "🥈"; case 2 -> "🥈";

View file

@ -35,7 +35,7 @@ public class LevelModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
UserStatsRepository provideUserStatsRepository(Database database) { UserStatsRepository provideUserStatsRepository(final Database database) {
return new SqlUserStatsRepository(database); return new SqlUserStatsRepository(database);
} }
@ -47,40 +47,37 @@ public class LevelModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
MessageCooldownService provideMessageCooldownService(UserStatsRepository repository) { MessageCooldownService provideMessageCooldownService(final UserStatsRepository repository) {
return new MessageCooldownService(repository); return new MessageCooldownService(repository);
} }
@Provides @Provides
@Singleton @Singleton
LeaderboardService provideLeaderboardService(UserStatsRepository repository) { LeaderboardService provideLeaderboardService(final UserStatsRepository repository) {
return new LeaderboardService(repository); return new LeaderboardService(repository);
} }
@Provides @Provides
@Singleton @Singleton
LevelService provideLevelService( LevelService provideLevelService(final UserStatsRepository repository, final XpFormula xpFormula, final MessageCooldownService cooldownService) {
UserStatsRepository repository, XpFormula xpFormula, MessageCooldownService cooldownService) {
return new LevelService(repository, xpFormula, cooldownService); return new LevelService(repository, xpFormula, cooldownService);
} }
@Provides @Provides
@Singleton @Singleton
LevelRoleService provideLevelRoleService(ConfigRepository configRepository) { LevelRoleService provideLevelRoleService(final ConfigRepository configRepository) {
return new LevelRoleService(configRepository); return new LevelRoleService(configRepository);
} }
@Provides @Provides
@Singleton @Singleton
LevelUpNotifier provideLevelUpNotifier( LevelUpNotifier provideLevelUpNotifier(final ConfigRepository configRepo, final LevelService levelService, final LevelRoleService levelRoleService) {
ConfigRepository configRepo, LevelService levelService, LevelRoleService levelRoleService) {
return new LevelUpNotifier(configRepo, levelService, levelRoleService); return new LevelUpNotifier(configRepo, levelService, levelRoleService);
} }
@Provides @Provides
@Singleton @Singleton
ResetLevelsCommand provideResetLevelsCommand( ResetLevelsCommand provideResetLevelsCommand(final UserStatsRepository userStatsRepository, final GuildConfigRepository guildConfigRepository) {
UserStatsRepository userStatsRepository, GuildConfigRepository guildConfigRepository) {
return new ResetLevelsCommand(userStatsRepository, guildConfigRepository); return new ResetLevelsCommand(userStatsRepository, guildConfigRepository);
} }
} }

View file

@ -34,7 +34,7 @@ public class LevelCommandRegistrar implements CommandRegistrar {
} }
@Override @Override
public void register(CommandRegistry registry) { public void register(final CommandRegistry registry) {
registry.register(new LeaderboardCommand(leaderboardService)); registry.register(new LeaderboardCommand(leaderboardService));
registry.register(new StatsCommand()); registry.register(new StatsCommand());
registry.register(resetLevelsCommand); registry.register(resetLevelsCommand);

View file

@ -42,7 +42,7 @@ public class LevelRoleCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
if (context.getAuthor() == null if (context.getAuthor() == null
|| !context.getAuthor().hasPermission(Permission.ADMINISTRATOR)) { || !context.getAuthor().hasPermission(Permission.ADMINISTRATOR)) {
context context
@ -77,7 +77,7 @@ public class LevelRoleCommand implements Command {
} }
} }
private void handleSet(CommandContext context, List<String> args) { private void handleSet(final CommandContext context, final List<String> args) {
if (args.size() < 3) { if (args.size() < 3) {
context context
.getChannel() .getChannel()
@ -127,7 +127,7 @@ public class LevelRoleCommand implements Command {
.queue(); .queue();
} }
private void handleRemove(CommandContext context, List<String> args) { private void handleRemove(final CommandContext context, final List<String> args) {
if (args.size() < 2) { if (args.size() < 2) {
context context
.getChannel() .getChannel()
@ -158,7 +158,7 @@ public class LevelRoleCommand implements Command {
.queue(); .queue();
} }
private void handleClear(CommandContext context) { private void handleClear(final CommandContext context) {
Map<String, String> allConfig = configRepository.getAll(); Map<String, String> allConfig = configRepository.getAll();
int removed = 0; int removed = 0;
for (String key : allConfig.keySet()) { for (String key : allConfig.keySet()) {

View file

@ -53,7 +53,7 @@ public class ResetLevelsCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
// Проверка прав администратора // Проверка прав администратора
if (context.getAuthor() == null if (context.getAuthor() == null
|| !context.getAuthor().hasPermission(Permission.ADMINISTRATOR)) { || !context.getAuthor().hasPermission(Permission.ADMINISTRATOR)) {
@ -127,7 +127,7 @@ public class ResetLevelsCommand implements Command {
} }
/** Выполняет сброс уровней (вызывается из ButtonHandler) */ /** Выполняет сброс уровней (вызывается из ButtonHandler) */
public void executeReset(String guildId, String userId) { public void executeReset(final String guildId, final String userId) {
try { try {
LoggerDecorator.warn(logger, "Начало сброса уровней для гильдии: " + guildId); LoggerDecorator.warn(logger, "Начало сброса уровней для гильдии: " + guildId);
LoggerDecorator.warn(logger, "Инициатор: " + userId); LoggerDecorator.warn(logger, "Инициатор: " + userId);

View file

@ -32,7 +32,7 @@ public class StatsCommand implements Command {
} }
@Override @Override
public void execute(CommandContext context) { public void execute(final CommandContext context) {
if (context.getGuild() == null) { if (context.getGuild() == null) {
context.getChannel().sendMessage("Команда доступна только на сервере").queue(); context.getChannel().sendMessage("Команда доступна только на сервере").queue();
return; return;

View file

@ -9,8 +9,7 @@ import net.dv8tion.jda.api.EmbedBuilder;
public class LevelRoleFormatter { public class LevelRoleFormatter {
public static EmbedBuilder buildMappingsEmbed( public static EmbedBuilder buildMappingsEmbed(final ConfigRepository configRepository, final LevelRoleService levelRoleService) {
ConfigRepository configRepository, LevelRoleService levelRoleService) {
Map<String, String> allConfig = configRepository.getAll(); Map<String, String> allConfig = configRepository.getAll();
Map<Integer, String> customRoles = Map<Integer, String> customRoles =
allConfig.entrySet().stream() allConfig.entrySet().stream()

View file

@ -21,7 +21,7 @@ public class UserStats {
this.lastVoiceJoin = 0; this.lastVoiceJoin = 0;
} }
private UserStats(Builder builder) { private UserStats(final Builder builder) {
this.userId = builder.userId; this.userId = builder.userId;
this.level = builder.level; this.level = builder.level;
this.totalXP = builder.totalXP; this.totalXP = builder.totalXP;
@ -63,15 +63,15 @@ public class UserStats {
return new Builder(this).level(level).build(); return new Builder(this).level(level).build();
} }
public UserStats withAddedXP(int xp) { public UserStats withAddedXP(final int xp) {
return new Builder(this).totalXP(this.totalXP + xp).build(); return new Builder(this).totalXP(this.totalXP + xp).build();
} }
public UserStats withRecordedMessage(long timestamp) { public UserStats withRecordedMessage(final long timestamp) {
return new Builder(this).messageCount(this.messageCount + 1).lastMessageTime(timestamp).build(); return new Builder(this).messageCount(this.messageCount + 1).lastMessageTime(timestamp).build();
} }
public UserStats withAddedVoiceMinutes(long minutes) { public UserStats withAddedVoiceMinutes(final long minutes) {
return new Builder(this).voiceMinutes(this.voiceMinutes + minutes).build(); return new Builder(this).voiceMinutes(this.voiceMinutes + minutes).build();
} }
@ -106,7 +106,7 @@ public class UserStats {
public Builder() {} public Builder() {}
public Builder(UserStats existing) { public Builder(final UserStats existing) {
this.userId = existing.userId; this.userId = existing.userId;
this.level = existing.level; this.level = existing.level;
this.totalXP = existing.totalXP; this.totalXP = existing.totalXP;

View file

@ -10,7 +10,7 @@ public class XpFormula {
* @param level целевой уровень * @param level целевой уровень
* @return общее количество XP * @return общее количество XP
*/ */
public int getTotalXPForLevel(int level) { public int getTotalXPForLevel(final int level) {
if (level <= 0) { if (level <= 0) {
return 0; return 0;
} }
@ -23,7 +23,7 @@ public class XpFormula {
* @param xp текущее количество XP * @param xp текущее количество XP
* @return текущий уровень * @return текущий уровень
*/ */
public int calculateLevel(int xp) { public int calculateLevel(final int xp) {
if (xp <= 0) { if (xp <= 0) {
return 0; return 0;
} }
@ -37,7 +37,7 @@ public class XpFormula {
* @param currentLevel текущий уровень * @param currentLevel текущий уровень
* @return XP для следующего уровня * @return XP для следующего уровня
*/ */
public int getXpForNextLevel(int currentLevel) { public int getXpForNextLevel(final int currentLevel) {
return XP_PER_LEVEL * (currentLevel + 1); return XP_PER_LEVEL * (currentLevel + 1);
} }
@ -48,7 +48,7 @@ public class XpFormula {
* @param currentLevel текущий уровень * @param currentLevel текущий уровень
* @return прогресс от 0.0 до 1.0 * @return прогресс от 0.0 до 1.0
*/ */
public double getProgressToNextLevel(int currentXp, int currentLevel) { public double getProgressToNextLevel(final int currentXp, final int currentLevel) {
int xpForCurrentLevel = getTotalXPForLevel(currentLevel); int xpForCurrentLevel = getTotalXPForLevel(currentLevel);
int xpForNextLevel = getTotalXPForLevel(currentLevel + 1); int xpForNextLevel = getTotalXPForLevel(currentLevel + 1);
int xpNeeded = xpForNextLevel - xpForCurrentLevel; int xpNeeded = xpForNextLevel - xpForCurrentLevel;

View file

@ -35,7 +35,7 @@ public class MessageListener extends ListenerAdapter {
} }
@Override @Override
public void onMessageReceived(MessageReceivedEvent event) { public void onMessageReceived(final MessageReceivedEvent event) {
try { try {
if (!event.getAuthor().isBot()) { if (!event.getAuthor().isBot()) {
String userId = event.getAuthor().getId(); String userId = event.getAuthor().getId();

View file

@ -26,7 +26,7 @@ public class ResetLevelsButtonHandler extends ListenerAdapter {
} }
@Override @Override
public void onButtonInteraction(ButtonInteractionEvent event) { public void onButtonInteraction(final ButtonInteractionEvent event) {
String buttonId = event.getComponentId(); String buttonId = event.getComponentId();
if (buttonId.startsWith(PREFIX_CONFIRM)) { if (buttonId.startsWith(PREFIX_CONFIRM)) {

Some files were not shown because too many files have changed in this diff Show more